Throw tests out, use block-scoped namespaces in new files.

This commit is contained in:
vddCore 2024-03-28 07:34:53 +01:00
parent ba915f824c
commit a9d07ba1db
9 changed files with 134 additions and 482 deletions

View file

@ -4,8 +4,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Saradomin", "Saradomin\Sara
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Glitonea", "Glitonea\Glitonea.csproj", "{D2884654-2246-4AC0-B53B-5F1DF33DEDD7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "UnitTests\UnitTests.csproj", "{6A66E5A7-9297-410F-B061-EB386679E430}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -20,9 +18,5 @@ Global
{D2884654-2246-4AC0-B53B-5F1DF33DEDD7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2884654-2246-4AC0-B53B-5F1DF33DEDD7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2884654-2246-4AC0-B53B-5F1DF33DEDD7}.Release|Any CPU.Build.0 = Release|Any CPU
{6A66E5A7-9297-410F-B061-EB386679E430}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6A66E5A7-9297-410F-B061-EB386679E430}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6A66E5A7-9297-410F-B061-EB386679E430}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6A66E5A7-9297-410F-B061-EB386679E430}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

View file

@ -2,7 +2,6 @@ using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Markup.Xaml;
using Glitonea;
using Glitonea.Mvvm;
using PropertyChanged;
using Saradomin.View.Windows;

View file

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.IO;
using System.Linq;
using System.Net.Http;

View file

@ -3,7 +3,6 @@ using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Win32;
using Mono.Unix;

View file

@ -2,159 +2,159 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
namespace Saradomin.Utilities;
public static class SingleplayerManagement
namespace Saradomin.Utilities
{
private static readonly string[] DirsToBackup =
public static class SingleplayerManagement
{
"game/data/players",
"game/data/serverstore",
"game/worldprops"
};
private static readonly string[] FilesToBackup =
{
"game/data/eco/grandexchange.db"
};
public static void MakeBackup(Action<string> log)
{
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string newBackupDir = Path.Combine(
CrossPlatform.GetSingleplayerBackupsHome(),
timestamp
);
foreach (string dir in DirsToBackup)
private static readonly string[] DirsToBackup =
{
string sourcePath = Path.Combine(CrossPlatform.GetSingleplayerHome(), dir);
if (!Directory.Exists(sourcePath))
"game/data/players",
"game/data/serverstore",
"game/worldprops"
};
private static readonly string[] FilesToBackup =
{
"game/data/eco/grandexchange.db"
};
public static void MakeBackup(Action<string> log)
{
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string newBackupDir = Path.Combine(
CrossPlatform.GetSingleplayerBackupsHome(),
timestamp
);
foreach (string dir in DirsToBackup)
{
log($" Skipping backup of {dir} because it doesn't exist (Full path attempted: {sourcePath})");
continue;
string sourcePath = Path.Combine(CrossPlatform.GetSingleplayerHome(), dir);
if (!Directory.Exists(sourcePath))
{
log($" Skipping backup of {dir} because it doesn't exist (Full path attempted: {sourcePath})");
continue;
}
string destPath = Path.Combine(newBackupDir, dir);
CopyDirectory(sourcePath, destPath);
}
string destPath = Path.Combine(newBackupDir, dir);
CopyDirectory(sourcePath, destPath);
foreach (string file in FilesToBackup)
{
string sourceFilePath = Path.Combine(CrossPlatform.GetSingleplayerHome(), file);
if (!File.Exists(sourceFilePath))
{
log($" Skipping backup of {file} because it doesn't exist (Full path attempted: {sourceFilePath})");
continue;
}
string destFilePath = Path.Combine(newBackupDir, file);
string directoryForFile = Path.GetDirectoryName(destFilePath);
if (!Directory.Exists(directoryForFile))
Directory.CreateDirectory(directoryForFile);
File.Copy(sourceFilePath, destFilePath, true);
}
}
foreach (string file in FilesToBackup)
private static void CopyDirectory(string sourceDir, string destinationDir)
{
string sourceFilePath = Path.Combine(CrossPlatform.GetSingleplayerHome(), file);
if (!File.Exists(sourceFilePath))
if (!Directory.Exists(destinationDir))
Directory.CreateDirectory(destinationDir);
foreach (string filePath in Directory.GetFiles(sourceDir))
{
log($" Skipping backup of {file} because it doesn't exist (Full path attempted: {sourceFilePath})");
continue;
string fileName = Path.GetFileName(filePath);
string destFilePath = Path.Combine(destinationDir, fileName);
File.Copy(filePath, destFilePath, true);
}
string destFilePath = Path.Combine(newBackupDir, file);
string directoryForFile = Path.GetDirectoryName(destFilePath);
if (!Directory.Exists(directoryForFile))
Directory.CreateDirectory(directoryForFile);
File.Copy(sourceFilePath, destFilePath, true);
}
}
private static void CopyDirectory(string sourceDir, string destinationDir)
{
if (!Directory.Exists(destinationDir))
Directory.CreateDirectory(destinationDir);
foreach (string filePath in Directory.GetFiles(sourceDir))
{
string fileName = Path.GetFileName(filePath);
string destFilePath = Path.Combine(destinationDir, fileName);
File.Copy(filePath, destFilePath, true);
}
foreach (string subDirPath in Directory.GetDirectories(sourceDir))
{
string subDirName = Path.GetFileName(subDirPath);
string destSubDirPath = Path.Combine(destinationDir, subDirName);
// Recurse!
CopyDirectory(subDirPath, destSubDirPath);
}
}
public static string FindMostRecentBackupDirectory(IEnumerable<string> directories)
{
return directories.Select(Path.GetFileName).MaxBy(name => name);
}
public static void ApplyLatestBackup(Action<string> log)
{
var backupHome = CrossPlatform.GetSingleplayerBackupsHome();
var singleplayerHome = CrossPlatform.GetSingleplayerHome();
// Get all backup directories
string[] backupDirectories = Directory.Exists(backupHome) ? Directory.GetDirectories(backupHome) : Array.Empty<string>();
string mostRecentBackupDirName = FindMostRecentBackupDirectory(backupDirectories);
if (mostRecentBackupDirName == null)
{
log(" No backups found.");
return;
}
string mostRecentBackupFullPath = Path.Combine(backupHome, mostRecentBackupDirName);
// Get the list of files in the most recent backup
var filesInBackup = Directory.GetFiles(
mostRecentBackupFullPath,
"*",
SearchOption.AllDirectories
);
foreach (var file in filesInBackup)
{
// Calculate the file's destination path in the singleplayer home directory
var relativePath = file.Substring(mostRecentBackupFullPath.Length)
.TrimStart(Path.DirectorySeparatorChar);
var destFilePath = Path.Combine(singleplayerHome, relativePath);
// Ensure the destination directory exists
var destDirectory = Path.GetDirectoryName(destFilePath);
if (!Directory.Exists(destDirectory))
foreach (string subDirPath in Directory.GetDirectories(sourceDir))
{
Directory.CreateDirectory(destDirectory);
string subDirName = Path.GetFileName(subDirPath);
string destSubDirPath = Path.Combine(destinationDir, subDirName);
// Recurse!
CopyDirectory(subDirPath, destSubDirPath);
}
}
public static string FindMostRecentBackupDirectory(IEnumerable<string> directories)
{
return directories.Select(Path.GetFileName).MaxBy(name => name);
}
public static void ApplyLatestBackup(Action<string> log)
{
var backupHome = CrossPlatform.GetSingleplayerBackupsHome();
var singleplayerHome = CrossPlatform.GetSingleplayerHome();
// Get all backup directories
string[] backupDirectories = Directory.Exists(backupHome) ? Directory.GetDirectories(backupHome) : Array.Empty<string>();
string mostRecentBackupDirName = FindMostRecentBackupDirectory(backupDirectories);
if (mostRecentBackupDirName == null)
{
log(" No backups found.");
return;
}
// Copy the file to the destination, overwriting any existing file
File.Copy(file, destFilePath, true);
string mostRecentBackupFullPath = Path.Combine(backupHome, mostRecentBackupDirName);
// Get the list of files in the most recent backup
var filesInBackup = Directory.GetFiles(
mostRecentBackupFullPath,
"*",
SearchOption.AllDirectories
);
foreach (var file in filesInBackup)
{
// Calculate the file's destination path in the singleplayer home directory
var relativePath = file.Substring(mostRecentBackupFullPath.Length)
.TrimStart(Path.DirectorySeparatorChar);
var destFilePath = Path.Combine(singleplayerHome, relativePath);
// Ensure the destination directory exists
var destDirectory = Path.GetDirectoryName(destFilePath);
if (!Directory.Exists(destDirectory))
{
Directory.CreateDirectory(destDirectory);
}
// Copy the file to the destination, overwriting any existing file
File.Copy(file, destFilePath, true);
}
log($" Backup from {mostRecentBackupDirName} has been successfully applied.");
}
log($" Backup from {mostRecentBackupDirName} has been successfully applied.");
}
private static Dictionary<string, string> _confCache;
private static string ConfPath => Path.Combine(CrossPlatform.GetSingleplayerHome(), "game", "worldprops", "default.conf");
public static Dictionary<string, string> GrabConfCache()
{
return File.ReadLines(ConfPath)
.Where(line => line.Contains('=') && !line.TrimStart().StartsWith("#"))
.Select(l => l.Split(new[] { '#', '=' }, 3))
.ToDictionary(parts => parts[0].Trim(), parts => parts[1].Trim());
}
private static Dictionary<string, string> _confCache;
private static string ConfPath => Path.Combine(CrossPlatform.GetSingleplayerHome(), "game", "worldprops", "default.conf");
public static Dictionary<string, string> GrabConfCache()
{
return File.ReadLines(ConfPath)
.Where(line => line.Contains('=') && !line.TrimStart().StartsWith("#"))
.Select(l => l.Split(new[] { '#', '=' }, 3))
.ToDictionary(parts => parts[0].Trim(), parts => parts[1].Trim());
}
public static T ParseConf<T>(string key, T defaultValue = default)
{
if (!File.Exists(ConfPath)) return defaultValue;
_confCache ??= GrabConfCache();
if (!_confCache.TryGetValue(key, out var value)) return defaultValue;
return (T)Convert.ChangeType(value, typeof(T));
}
public static T ParseConf<T>(string key, T defaultValue = default)
{
if (!File.Exists(ConfPath)) return defaultValue;
_confCache ??= GrabConfCache();
if (!_confCache.TryGetValue(key, out var value)) return defaultValue;
return (T)Convert.ChangeType(value, typeof(T));
}
public static void WriteConf(string key, object value)
{
_confCache[key] = value.ToString().ToLowerInvariant(); // Update cache
var lines = File.ReadAllLines(ConfPath).Select(l =>
l.StartsWith(key + " =")
? $"{key} = {_confCache[key]}" + (l.Contains("#") ? " " + l.Substring(l.IndexOf('#')) : "")
: l);
File.WriteAllLines(ConfPath, lines);
public static void WriteConf(string key, object value)
{
_confCache[key] = value.ToString().ToLowerInvariant(); // Update cache
var lines = File.ReadAllLines(ConfPath).Select(l =>
l.StartsWith(key + " =")
? $"{key} = {_confCache[key]}" + (l.Contains("#") ? " " + l.Substring(l.IndexOf('#')) : "")
: l);
File.WriteAllLines(ConfPath, lines);
}
}
}

View file

@ -1,295 +0,0 @@
namespace UnitTests.Saradomin.Utilities.SingleplayerManagement;
[TestFixture]
public class BackupManagerTests
{
[Test]
public void WithValidDirectories_ReturnsMostRecent()
{
// Arrange
var directories = new List<string>
{
"/backups/20230101_120000",
"/backups/20230102_120000",
"/backups/20230103_120000"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230103_120000".Equals(mostRecent));
}
[Test]
public void WithDifferentYears_ReturnsMostRecent()
{
// Arrange
var directories = new List<string>
{
"/backups/20210101_120000",
"/backups/20220101_120000",
"/backups/20230101_120000"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230101_120000".Equals(mostRecent));
}
[Test]
public void WithDifferentMonths_ReturnsMostRecent()
{
// Arrange
var directories = new List<string>
{
"/backups/20230101_120000",
"/backups/20230201_120000",
"/backups/20230301_120000"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230301_120000".Equals(mostRecent));
}
[Test]
public void WithDifferentDays_ReturnsMostRecent()
{
// Arrange
var directories = new List<string>
{
"/backups/20230301_120000",
"/backups/20230302_120000",
"/backups/20230303_120000"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230303_120000".Equals(mostRecent));
}
[Test]
public void WithDifferentHours_ReturnsMostRecent()
{
// Arrange
var directories = new List<string>
{
"/backups/20230301_110000",
"/backups/20230301_120000",
"/backups/20230301_130000"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230301_130000".Equals(mostRecent));
}
[Test]
public void WithDifferentMinutes_ReturnsMostRecent()
{
// Arrange
var directories = new List<string>
{
"/backups/20230301_120100",
"/backups/20230301_120200",
"/backups/20230301_120300"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230301_120300".Equals(mostRecent));
}
[Test]
public void WithDifferentSeconds_ReturnsMostRecent()
{
// Arrange
var directories = new List<string>
{
"/backups/20230301_120000",
"/backups/20230301_120015",
"/backups/20230301_120030"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230301_120030".Equals(mostRecent));
}
[Test]
public void WithMixedDateTimes_ReturnsMostRecent_Case1()
{
// Arrange
var directories = new List<string>
{
"/backups/20210101_235959",
"/backups/20201231_235959",
"/backups/20220228_235959"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20220228_235959".Equals(mostRecent));
}
[Test]
public void WithMixedDateTimes_ReturnsMostRecent_Case2()
{
// Arrange
var directories = new List<string>
{
"/backups/20211001_000001",
"/backups/20211001_000002",
"/backups/20210930_235959"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20211001_000002".Equals(mostRecent));
}
[Test]
public void WithMixedDateTimes_ReturnsMostRecent_Case3()
{
// Arrange
var directories = new List<string>
{
"/backups/20211231_235959",
"/backups/20220101_000000",
"/backups/20211231_235958"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20220101_000000".Equals(mostRecent));
}
[Test]
public void WithMixedDateTimes_ReturnsMostRecent_Case4()
{
// Arrange
var directories = new List<string>
{
"/backups/20230530_123456",
"/backups/20230529_123456",
"/backups/20220530_123457"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230530_123456".Equals(mostRecent));
}
[Test]
public void WithMixedDateTimes_ReturnsMostRecent_Case5()
{
// Arrange
var directories = new List<string>
{
"/backups/20230102_010101",
"/backups/20230101_222222",
"/backups/20221231_235959"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20230102_010101".Equals(mostRecent));
}
[Test]
public void WithMixedDateTimes_ReturnsMostRecent_Case6()
{
// Arrange
var directories = new List<string>
{
"/backups/20240101_120000",
"/backups/20231231_235959",
"/backups/20231231_235958"
};
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That("20240101_120000".Equals(mostRecent));
}
[Test]
public void WithNoDirectories_ReturnsNull()
{
// Arrange
// ReSharper disable once CollectionNeverUpdated.Local
var directories = new List<string>();
// Act
var mostRecent =
global::Saradomin.Utilities.SingleplayerManagement.FindMostRecentBackupDirectory(
directories
);
// Assert
Assert.That(mostRecent, Is.EqualTo(null));
}
}

View file

@ -1,20 +0,0 @@
namespace UnitTests.Saradomin.ViewModel.Controls.SingleplayerViewModel;
[TestFixture]
public class IsServerTerminationLogTests
{
[Test]
[TestCase("[23:43:26]: [SystemTermination] Server successfully terminated!", true)]
[TestCase("[23:00:26]: [SystemTermination] Server successfully terminated!", true)]
[TestCase("[23:43:26]: lol said [SystemTermination] Server successfully terminated!", false)]
[TestCase("[23:00:26]: [SystemTermination] Server successfully terminated! weee exploit", false)]
[TestCase("Gotcha [23:00:26]: [SystemTermination] Server successfully terminated!", false)]
public void ServerTerminationLogTests(string log, bool expectedOutcome)
{
// Act
var result = global::Saradomin.ViewModel.Controls.SingleplayerViewModel.IsServerTerminationLog(log);
// Assert
Assert.That(result, Is.EqualTo(expectedOutcome), $"Failed for log: {log}");
}
}

View file

@ -1,23 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.2"/>
<PackageReference Include="NUnit" Version="3.13.3"/>
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1"/>
<PackageReference Include="NUnit.Analyzers" Version="3.3.0"/>
<PackageReference Include="coverlet.collector" Version="3.1.2"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Saradomin\Saradomin.csproj" />
</ItemGroup>
</Project>

View file

@ -1 +0,0 @@
global using NUnit.Framework;