696 lines
39 KiB
C#
696 lines
39 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text.RegularExpressions;
|
|
using System.Xml;
|
|
using BlaxDefaults;
|
|
using RimWorld;
|
|
using UnityEngine;
|
|
using Verse;
|
|
|
|
namespace BlaxDefaultsTests
|
|
{
|
|
/// <summary>
|
|
/// Work package "file". The tests of design.md: Defaults library and settings page (the file tests).
|
|
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
|
|
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech").
|
|
///
|
|
/// Every test runs in a FileSandbox: the files in Config/BlaxDefaults of the test data folder are kept,
|
|
/// the folder is emptied for the test and put back exactly afterwards, so other tests see the file they
|
|
/// left. DefaultsFile.Load and ReadFile never touch the library in memory; tests that change it through
|
|
/// DefaultsLibrary rely on the fixture restore.
|
|
/// </summary>
|
|
public static class FileTests
|
|
{
|
|
private static readonly Regex MainCopyName = new Regex(@"^Defaults\.broken-\d{8}-\d{6}(-\d+)?\.xml$");
|
|
private static readonly Regex BackupCopyName = new Regex(@"^Defaults\.bak\.broken-\d{8}-\d{6}(-\d+)?\.xml$");
|
|
|
|
[BlaxTest("file: a template with a missing name is written and read back, the name is kept and applying logs nothing")]
|
|
public static void MissingNameRoundTrip()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
StorageKind kind = Fixtures.Kind("Shelf");
|
|
StorageTemplate template = Fixtures.Template(kind, StoragePriority.Important, ThingDefOf.Steel);
|
|
template.allowed.Add("BlaxTest_Missing");
|
|
T.Check(DefaultsFile.Write(Entries(template)), "Write returned false");
|
|
NoTemp();
|
|
|
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
|
T.NotNull(back, "ReadFile of the written file");
|
|
T.Equal(1, back.Count, "entries read back");
|
|
var loaded = back[0] as StorageTemplate;
|
|
T.NotNull(loaded, "the entry read back as a StorageTemplate");
|
|
T.Equal(template.Fingerprint(), loaded.Fingerprint(), "fingerprint read back");
|
|
T.Check(loaded.allowed.Contains("Steel") && DefDatabase<ThingDef>.GetNamedSilentFail("Steel") != null, "Steel is not in the loaded template or does not resolve");
|
|
T.Check(loaded.allowed.Contains("BlaxTest_Missing"), "the missing name was dropped");
|
|
List<string> unresolved = loaded.UnresolvedNames().ToList();
|
|
T.Equal(1, unresolved.Count, "unresolved names (" + string.Join(",", unresolved) + ")");
|
|
|
|
var target = new StorageSettings();
|
|
using (var log = new LogCounter())
|
|
{
|
|
kind.LoadDefault(target, loaded);
|
|
T.Check(log.Count == 0, "applying the template logged: " + log.Describe());
|
|
}
|
|
T.Equal(StoragePriority.Important, target.Priority, "priority after applying");
|
|
T.Check(target.filter.Allows(ThingDefOf.Steel), "Steel refused after applying");
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: a stockpile default saved with Biotech loads without it, keeps Wastepack and applies Steel silently")]
|
|
public static void BiotechNameWithoutBiotech()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
// The file as a game with Biotech writes it: strings only, so it is the same with or without the DLC.
|
|
File.WriteAllText(DefaultsFile.FilePath, FileText(
|
|
"\t\t<li Class=\"BlaxDefaults.StorageTemplate\">\n"
|
|
+ "\t\t\t<key>" + DefaultsKeys.Stockpile + "</key>\n"
|
|
+ "\t\t\t<priority>Normal</priority>\n"
|
|
+ "\t\t\t<allowed>\n\t\t\t\t<li>Steel</li>\n\t\t\t</allowed>\n"
|
|
+ "\t\t\t<refused>\n\t\t\t\t<li>Wastepack</li>\n\t\t\t</refused>\n"
|
|
+ "\t\t\t<allowedSpecial />\n\t\t\t<refusedSpecial />\n"
|
|
+ "\t\t</li>\n"));
|
|
|
|
bool biotech = ModsConfig.BiotechActive;
|
|
LoadResult r;
|
|
using (var log = new LogCounter())
|
|
{
|
|
r = DefaultsFile.Load();
|
|
T.Check(log.Count == 0, "loading logged: " + log.Describe());
|
|
}
|
|
T.Equal(DefaultsFile.FilePath, r.LoadedFrom, "loaded from");
|
|
T.Equal(1, r.Entries.Count, "entries loaded");
|
|
var loaded = r.Entries[0] as StorageTemplate;
|
|
T.NotNull(loaded, "the entry loaded as a StorageTemplate");
|
|
T.Check(loaded.refused.Contains("Wastepack"), "Wastepack was dropped from the template");
|
|
List<string> unresolved = loaded.UnresolvedNames().ToList();
|
|
if (biotech)
|
|
{
|
|
T.Info("Biotech is active: Wastepack resolves here; a -NoDlc run checks it as an inactive name");
|
|
T.Equal(0, unresolved.Count, "unresolved names with Biotech (" + string.Join(",", unresolved) + ")");
|
|
}
|
|
else
|
|
{
|
|
T.Check(unresolved.SequenceEqual(new[] { "Wastepack" }), "unresolved names without Biotech: " + string.Join(",", unresolved));
|
|
}
|
|
|
|
StorageKind kind = Fixtures.StockpileKind;
|
|
var target = new StorageSettings();
|
|
using (var log = new LogCounter())
|
|
{
|
|
kind.LoadDefault(target, loaded);
|
|
T.Check(log.Count == 0, "applying the template logged: " + log.Describe());
|
|
}
|
|
T.Check(target.filter.Allows(ThingDefOf.Steel), "Steel refused after applying");
|
|
if (biotech)
|
|
T.Check(!target.filter.Allows(Fixtures.Thing("Wastepack")), "Wastepack allowed after applying");
|
|
|
|
// Saved again, the name stays in the file.
|
|
T.Check(DefaultsFile.Write(r.Entries), "writing the loaded entries failed");
|
|
T.Check(File.ReadAllText(DefaultsFile.FilePath).Contains("<li>Wastepack</li>"), "Wastepack is not in the file after writing it again");
|
|
List<DefaultsEntry> again = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
|
T.Check(again != null && again.Count == 1 && ((StorageTemplate)again[0]).refused.Contains("Wastepack"), "Wastepack did not read back after writing it again");
|
|
NoTemp();
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: every write leaves the previous content in .bak")]
|
|
public static void BackupHoldsPrevious()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "the first write made a .bak");
|
|
byte[] previous = File.ReadAllBytes(DefaultsFile.FilePath);
|
|
|
|
var writes = new List<List<DefaultsEntry>>
|
|
{
|
|
Entries(Bill(20f)),
|
|
Entries(Bill(30f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog)),
|
|
Entries(),
|
|
};
|
|
for (int i = 0; i < writes.Count; i++)
|
|
{
|
|
T.Check(DefaultsFile.Write(writes[i]), "write " + (i + 2) + " failed");
|
|
T.Check(SameBytes(previous, File.ReadAllBytes(DefaultsFile.BackupPath)), ".bak does not hold the content before write " + (i + 2));
|
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
|
T.NotNull(back, "ReadFile after write " + (i + 2));
|
|
T.Equal(Prints(writes[i]), Prints(back), "entries read back after write " + (i + 2));
|
|
previous = File.ReadAllBytes(DefaultsFile.FilePath);
|
|
}
|
|
NoTemp();
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: main file truncated, the .bak loads with one warning and the next save keeps it")]
|
|
public static void MainBrokenBackupGood()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
List<DefaultsEntry> older = Entries(Bill(10f));
|
|
T.Check(DefaultsFile.Write(older), "first write failed");
|
|
T.Check(DefaultsFile.Write(Entries(Bill(20f))), "second write failed");
|
|
byte[] backup = File.ReadAllBytes(DefaultsFile.BackupPath);
|
|
byte[] truncated = Truncate(DefaultsFile.FilePath);
|
|
|
|
LoadResult r;
|
|
using (var log = new LogCounter())
|
|
{
|
|
r = DefaultsFile.Load();
|
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
|
T.Equal(1, log.Ours, "log lines from Blax Defaults (" + log.Describe() + ")");
|
|
}
|
|
T.Equal(DefaultsFile.BackupPath, r.LoadedFrom, "loaded from");
|
|
T.Check(!r.BothFailed, "BothFailed is set although the .bak loaded");
|
|
T.Equal(Prints(older), Prints(r.Entries), "entries loaded from .bak");
|
|
T.Equal(1, r.BrokenCopies.Count, "broken copies");
|
|
T.Check(!File.Exists(DefaultsFile.FilePath), "the broken main file is still Defaults.xml");
|
|
string copy = r.BrokenCopies[0];
|
|
T.Check(MainCopyName.IsMatch(Path.GetFileName(copy)), "broken copy name: " + Path.GetFileName(copy));
|
|
T.Check(File.Exists(copy) && SameBytes(truncated, File.ReadAllBytes(copy)), "the broken copy does not hold the original bytes");
|
|
T.Check(SameBytes(backup, File.ReadAllBytes(DefaultsFile.BackupPath)), "loading changed .bak");
|
|
|
|
// A default saved afterwards: a new main file, .bak untouched.
|
|
DefaultsLibrary.ReplaceInMemory(r.Entries);
|
|
StorageTemplate shelf = Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Important, ThingDefOf.Steel);
|
|
T.Check(DefaultsLibrary.Set(shelf), "saving a default after the load failed");
|
|
T.Check(File.Exists(DefaultsFile.FilePath), "saving a default made no new main file");
|
|
T.Check(SameBytes(backup, File.ReadAllBytes(DefaultsFile.BackupPath)), "saving a default changed .bak");
|
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
|
T.NotNull(back, "ReadFile of the new main file");
|
|
T.Equal(Prints(DefaultsLibrary.All), Prints(back), "the new main file");
|
|
T.Check(File.Exists(copy) && SameBytes(truncated, File.ReadAllBytes(copy)), "saving a default changed the broken copy");
|
|
NoTemp();
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: both files truncated, an empty library and two broken copies, twice without a clash")]
|
|
public static void BothBroken()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
|
T.Check(DefaultsFile.Write(Entries(Bill(20f))), "second write failed");
|
|
byte[] mainBytes = TruncatedBytes(DefaultsFile.FilePath);
|
|
byte[] backupBytes = TruncatedBytes(DefaultsFile.BackupPath);
|
|
var copies = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
for (int round = 1; round <= 2; round++)
|
|
{
|
|
File.WriteAllBytes(DefaultsFile.FilePath, mainBytes);
|
|
File.WriteAllBytes(DefaultsFile.BackupPath, backupBytes);
|
|
LoadResult r;
|
|
using (var log = new LogCounter())
|
|
{
|
|
r = DefaultsFile.Load();
|
|
T.Equal(1, log.OurWarnings, "round " + round + ": warnings from Blax Defaults (" + log.Describe() + ")");
|
|
T.Equal(1, log.Ours, "round " + round + ": log lines from Blax Defaults (" + log.Describe() + ")");
|
|
}
|
|
T.Equal(0, r.Entries.Count, "round " + round + ": entries");
|
|
T.Check(r.BothFailed, "round " + round + ": BothFailed is not set");
|
|
T.Equal(null, r.LoadedFrom, "round " + round + ": loaded from");
|
|
T.Equal(2, r.BrokenCopies.Count, "round " + round + ": broken copies");
|
|
string mainCopy = r.BrokenCopies.FirstOrDefault(p => MainCopyName.IsMatch(Path.GetFileName(p)));
|
|
string backupCopy = r.BrokenCopies.FirstOrDefault(p => BackupCopyName.IsMatch(Path.GetFileName(p)));
|
|
T.Check(mainCopy != null && backupCopy != null, "round " + round + ": copy names " + string.Join(", ", r.BrokenCopies.Select(Path.GetFileName)));
|
|
T.Check(SameBytes(mainBytes, File.ReadAllBytes(mainCopy)), "round " + round + ": the main file's copy does not hold the original bytes");
|
|
T.Check(SameBytes(backupBytes, File.ReadAllBytes(backupCopy)), "round " + round + ": the .bak's copy does not hold the original bytes");
|
|
foreach (string c in r.BrokenCopies)
|
|
T.Check(copies.Add(c), "round " + round + ": the copy name " + Path.GetFileName(c) + " was used before");
|
|
|
|
// Nothing written: the folder holds the broken copies and nothing else.
|
|
List<string> files = Directory.GetFiles(DefaultsFile.FolderPath).ToList();
|
|
T.Check(files.Count == copies.Count && files.All(copies.Contains),
|
|
"round " + round + ": files in the folder: " + string.Join(", ", files.Select(Path.GetFileName)));
|
|
}
|
|
T.Equal(4, copies.Count, "broken copies after two loads");
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: an entry that throws while saving leaves both files untouched, no .tmp and one error")]
|
|
public static void ThrowingEntry()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
|
T.Check(DefaultsFile.Write(Entries(Bill(20f))), "second write failed");
|
|
byte[] main = File.ReadAllBytes(DefaultsFile.FilePath);
|
|
byte[] backup = File.ReadAllBytes(DefaultsFile.BackupPath);
|
|
List<DefaultsEntry> before = DefaultsLibrary.Snapshot();
|
|
|
|
T.AllowErrors();
|
|
bool ok = DefaultsLibrary.Set(new BlaxTestThrowingEntry("blaxtest:throws"));
|
|
List<string> errors = T.ErrorsSoFar();
|
|
foreach (string e in errors)
|
|
T.Info("logged: " + (e.Length > 300 ? e.Substring(0, 300) + "..." : e));
|
|
T.Check(!ok, "Set returned true for an entry that throws");
|
|
T.Check(!DefaultsLibrary.LastWriteOk, "LastWriteOk is true after the failed write");
|
|
T.Check(SameBytes(main, File.ReadAllBytes(DefaultsFile.FilePath)), "Defaults.xml changed");
|
|
T.Check(SameBytes(backup, File.ReadAllBytes(DefaultsFile.BackupPath)), "Defaults.xml.bak changed");
|
|
NoTemp();
|
|
T.Equal(1, errors.Count, "errors logged by the failed write");
|
|
T.Check(errors[0].Contains("Blax Defaults"), "the error is not from Blax Defaults");
|
|
|
|
// The library back as it was, and LastWriteOk as a good write leaves it for the tests after this one.
|
|
DefaultsLibrary.ReplaceInMemory(before);
|
|
var probe = new BillValues("blaxtest:probe");
|
|
T.Check(DefaultsLibrary.Set(probe) && DefaultsLibrary.Forget(probe.key), "a write after the failed one failed");
|
|
T.Check(DefaultsLibrary.LastWriteOk, "LastWriteOk is false after a good write");
|
|
NoTemp();
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: the format version is in the root node")]
|
|
public static void FormatVersion()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "Write returned false");
|
|
var doc = new XmlDocument();
|
|
doc.Load(DefaultsFile.FilePath);
|
|
XmlElement root = doc.DocumentElement;
|
|
T.Equal(DefaultsFile.RootNode, root?.Name, "root node");
|
|
T.Equal(DefaultsLibrary.FormatVersion.ToString(), root["formatVersion"]?.InnerText, "formatVersion in the root node");
|
|
T.Equal(1, root["entries"]?.ChildNodes.Count ?? -1, "entries in the file");
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: another root node or a keyless entry fails the read, without an error")]
|
|
public static void ReadRejects()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
string path = DefaultsFile.FilePath;
|
|
File.WriteAllText(path, FileText("", root: "SettingsBlock"));
|
|
T.Check(DefaultsFile.ReadFile(path) == null, "a file with another root node loaded");
|
|
|
|
File.WriteAllText(path, FileText("\t\t<li Class=\"BlaxDefaults.BillValues\">\n\t\t\t<storeMode>DropOnFloor</storeMode>\n\t\t</li>\n"));
|
|
T.Check(DefaultsFile.ReadFile(path) == null, "a keyless entry loaded");
|
|
|
|
File.WriteAllText(path, FileText("\t\t<li Class=\"BlaxDefaults.BillValues\">\n\t\t\t<key>bill:*</key>\n\t\t\t<storeMode>DropOnFloor</storeMode>\n\t\t</li>\n"));
|
|
List<DefaultsEntry> good = DefaultsFile.ReadFile(path);
|
|
T.Check(good != null && good.Count == 1 && good[0] is BillValues b && b.storeMode == "DropOnFloor", "the same entry with a key did not load");
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: a lone broken main file without a backup gives one broken copy and the one-file line")]
|
|
public static void LoneBrokenMain()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "the first write made a .bak");
|
|
byte[] truncated = Truncate(DefaultsFile.FilePath);
|
|
LoadResult r;
|
|
using (var log = new LogCounter())
|
|
{
|
|
r = DefaultsFile.Load();
|
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
|
}
|
|
T.Check(r.BothFailed, "BothFailed is not set");
|
|
T.Equal(1, r.BrokenCopies.Count, "broken copies");
|
|
T.Equal(0, r.Unread.Count, "unread files");
|
|
T.Check(SameBytes(truncated, File.ReadAllBytes(r.BrokenCopies[0])), "the broken copy does not hold the original bytes");
|
|
string line = SettingsPage.BrokenFilesLine(r);
|
|
T.Check(line != null && line.Contains(Path.GetFileName(r.BrokenCopies[0])), "the line doesn't name the copy: " + line);
|
|
T.Check(!line.Contains("backup"), "the line refers to a backup that never existed: " + line);
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: a default of a class this version doesn't have is skipped without an error, and every write keeps it")]
|
|
public static void UnknownClassKept()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
const string future = "\t\t<li Class=\"BlaxDefaults.BlaxTestFutureEntry\">\n\t\t\t<key>bench:BlaxTest</key>\n"
|
|
+ "\t\t\t<bills>\n\t\t\t\t<li>Make & mend</li>\n\t\t\t</bills>\n\t\t</li>\n";
|
|
const string noClass = "\t\t<li>\n\t\t\t<key>bench:NoClass</key>\n\t\t</li>\n";
|
|
File.WriteAllText(DefaultsFile.FilePath, FileText(BillLi + future + noClass));
|
|
byte[] before = File.ReadAllBytes(DefaultsFile.FilePath);
|
|
|
|
LoadResult r;
|
|
using (var log = new LogCounter())
|
|
{
|
|
r = DefaultsFile.Load();
|
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
|
T.Equal(1, log.Ours, "log lines from Blax Defaults (" + log.Describe() + ")");
|
|
}
|
|
T.Check(T.ErrorsSoFar().Count == 0, "loading logged errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
T.Equal(DefaultsFile.FilePath, r.LoadedFrom, "loaded from");
|
|
T.Equal(0, r.BrokenCopies.Count, "broken copies");
|
|
T.Equal(1, r.Entries.Count, "entries this version loads");
|
|
T.Equal(2, r.Unknown.Count, "defaults skipped");
|
|
T.Equal("bench:BlaxTest", r.Unknown[0].Key, "key of the first skipped default");
|
|
T.Equal("BlaxDefaults.BlaxTestFutureEntry", r.Unknown[0].ClassName, "class of the first skipped default");
|
|
T.Equal(null, r.Unknown[1].ClassName, "class of the default without one");
|
|
T.Check(SameBytes(before, File.ReadAllBytes(DefaultsFile.FilePath)), "loading changed the file");
|
|
|
|
// Through the library, as after a startup load: two writes keep both after the library's entries.
|
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
|
try
|
|
{
|
|
DefaultsLibrary.InstallLoadForTests(r, retry: false);
|
|
T.Check(DefaultsLibrary.Set(Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.Steel)), "saving a default failed");
|
|
T.Check(DefaultsLibrary.Set(Bill(30f)), "saving a second default failed");
|
|
FileContent back = DefaultsFile.Read(DefaultsFile.FilePath, out string problem);
|
|
T.NotNull(back, "Read of the written file (" + problem + ")");
|
|
T.Equal(2, back.Entries.Count, "entries this version loads after two writes");
|
|
T.Equal(2, back.Unknown.Count, "skipped defaults in the file after two writes");
|
|
T.Equal(r.Unknown[0].Xml, back.Unknown[0].Xml, "the first skipped default after two writes");
|
|
T.Equal(r.Unknown[1].Xml, back.Unknown[1].Xml, "the second skipped default after two writes");
|
|
T.Check(File.ReadAllText(DefaultsFile.FilePath).Contains("<li>Make & mend</li>"), "the escaped text in the skipped default changed");
|
|
FileContent bak = DefaultsFile.Read(DefaultsFile.BackupPath, out problem);
|
|
T.Check(bak != null && bak.Unknown.Count == 2, ".bak lost the skipped defaults (" + problem + ")");
|
|
NoTemp();
|
|
}
|
|
finally
|
|
{
|
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
|
}
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: a file of a newer format version loads with one warning, and the library never writes it")]
|
|
public static void NewerVersionReadOnly()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
int newer = DefaultsLibrary.FormatVersion + 1;
|
|
File.WriteAllText(DefaultsFile.FilePath, FileText(BillLi, version: newer));
|
|
byte[] before = File.ReadAllBytes(DefaultsFile.FilePath);
|
|
LoadResult r;
|
|
using (var log = new LogCounter())
|
|
{
|
|
r = DefaultsFile.Load();
|
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
|
}
|
|
T.Equal(DefaultsFile.FilePath, r.LoadedFrom, "loaded from");
|
|
T.Equal(newer, r.FormatVersion, "format version read");
|
|
T.Check(r.FromNewerVersion, "FromNewerVersion is false");
|
|
T.Equal(1, r.Entries.Count, "entries loaded");
|
|
|
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
|
try
|
|
{
|
|
DefaultsLibrary.InstallLoadForTests(r, retry: false);
|
|
T.Check(DefaultsLibrary.ReadOnly, "ReadOnly is false for a newer version's file");
|
|
StorageTemplate shelf = Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.Steel);
|
|
using (var log = new LogCounter())
|
|
{
|
|
T.Check(!DefaultsLibrary.Set(shelf), "Set reports a write of a newer version's file");
|
|
T.Check(DefaultsLibrary.Forget(DefaultsKeys.EveryBill), "Forget of the loaded bill values");
|
|
T.Equal(1, log.OurWarnings, "warnings for two refused writes (" + log.Describe() + ")");
|
|
}
|
|
T.Check(!DefaultsLibrary.LastWriteOk, "LastWriteOk is true after a refused write");
|
|
T.Check(DefaultsLibrary.Get(shelf.key) == shelf, "the default is not kept in memory");
|
|
T.Check(SameBytes(before, File.ReadAllBytes(DefaultsFile.FilePath)), "the newer version's file changed");
|
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "a .bak was made");
|
|
NoTemp();
|
|
}
|
|
finally
|
|
{
|
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
|
// LastWriteOk back as a good write leaves it, for the tests after this one.
|
|
var probe = new BillValues("blaxtest:probe");
|
|
DefaultsLibrary.Set(probe);
|
|
DefaultsLibrary.Forget(probe.key);
|
|
}
|
|
T.Check(DefaultsLibrary.LastWriteOk, "LastWriteOk is false after a good write");
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: a read skipped at startup is retried on first use, and the next write rotates the file as usual")]
|
|
public static void SkippedReadRetried()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
List<DefaultsEntry> two = Entries(Bill(10f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog));
|
|
T.Check(DefaultsFile.Write(two), "first write failed");
|
|
byte[] original = File.ReadAllBytes(DefaultsFile.FilePath);
|
|
|
|
LoadResult r = SkippedLoad();
|
|
T.Equal(0, r.Entries.Count, "entries of the skipped read");
|
|
T.Equal(null, r.LoadedFrom, "loaded from");
|
|
T.Check(!r.BothFailed && r.BrokenCopies.Count == 0, "the skipped read called the file broken");
|
|
T.Check(r.Unread.Contains(DefaultsFile.FilePath), "Defaults.xml is not listed as unread: " + string.Join(", ", r.Unread));
|
|
T.Check(SameBytes(original, File.ReadAllBytes(DefaultsFile.FilePath)), "the skipped read changed the file");
|
|
|
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
|
try
|
|
{
|
|
DefaultsLibrary.InstallLoadForTests(r, retry: true);
|
|
T.Check(DefaultsLibrary.RetryPending, "no retry pending after a skipped read");
|
|
T.Equal(2, DefaultsLibrary.Count, "entries after the first use");
|
|
T.Check(!DefaultsLibrary.RetryPending, "the retry is still pending after the first use");
|
|
T.Equal(DefaultsFile.FilePath, DefaultsLibrary.LastLoad.LoadedFrom, "loaded from on the retry");
|
|
T.Equal(0, DefaultsLibrary.LastLoad.Unread.Count, "unread files after the retry");
|
|
|
|
T.Check(DefaultsLibrary.Set(Bill(20f)), "saving a default after the retry failed");
|
|
T.Check(SameBytes(original, File.ReadAllBytes(DefaultsFile.BackupPath)), ".bak does not hold the file read on the retry");
|
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
|
T.Check(back != null && back.Count == 2, "the new file does not hold the shelf and the new bill values");
|
|
NoTemp();
|
|
}
|
|
finally
|
|
{
|
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
|
}
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
[BlaxTest("file: files left unread are moved aside before the first write, and later writes never touch them")]
|
|
public static void UnreadMovedAside()
|
|
{
|
|
using (new FileSandbox())
|
|
{
|
|
T.Check(DefaultsFile.Write(Entries(Bill(10f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog))), "first write failed");
|
|
T.Check(DefaultsFile.Write(Entries(Bill(20f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog))), "second write failed");
|
|
byte[] originalMain = File.ReadAllBytes(DefaultsFile.FilePath);
|
|
byte[] originalBak = File.ReadAllBytes(DefaultsFile.BackupPath);
|
|
|
|
LoadResult r = SkippedLoad();
|
|
T.Equal(2, r.Unread.Count, "unread files (" + string.Join(", ", r.Unread) + ")");
|
|
|
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
|
try
|
|
{
|
|
// As if the retry could not read them either.
|
|
DefaultsLibrary.InstallLoadForTests(r, retry: false);
|
|
StorageTemplate shelf = Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Important, ThingDefOf.Steel);
|
|
T.Check(DefaultsLibrary.Set(shelf), "saving a default failed");
|
|
T.Equal(0, DefaultsLibrary.LastLoad.Unread.Count, "unread files after the first write");
|
|
List<string> moved = DefaultsLibrary.LastLoad.UnreadCopies;
|
|
T.Equal(2, moved.Count, "files moved aside");
|
|
string mainCopy = moved.FirstOrDefault(p => UnreadMainName.IsMatch(Path.GetFileName(p)));
|
|
string bakCopy = moved.FirstOrDefault(p => UnreadBackupName.IsMatch(Path.GetFileName(p)));
|
|
T.Check(mainCopy != null && bakCopy != null, "names of the moved files: " + string.Join(", ", moved.Select(Path.GetFileName)));
|
|
T.Check(SameBytes(originalMain, File.ReadAllBytes(mainCopy)), "the moved main file does not hold the original bytes");
|
|
T.Check(SameBytes(originalBak, File.ReadAllBytes(bakCopy)), "the moved .bak does not hold the original bytes");
|
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "the first write left a .bak");
|
|
T.Equal(Prints(Entries(shelf)), Prints(DefaultsFile.ReadFile(DefaultsFile.FilePath)), "the new main file");
|
|
|
|
T.Check(DefaultsLibrary.Set(Bill(40f)), "saving a second default failed");
|
|
T.Check(DefaultsFile.ReadFile(DefaultsFile.BackupPath)?.Count == 1, ".bak does not hold the first write");
|
|
T.Check(SameBytes(originalMain, File.ReadAllBytes(mainCopy)) && SameBytes(originalBak, File.ReadAllBytes(bakCopy)), "the second write changed a moved file");
|
|
|
|
string line = SettingsPage.BrokenFilesLine(DefaultsLibrary.LastLoad);
|
|
T.Check(line != null && line.Contains(Path.GetFileName(mainCopy)) && line.Contains(Path.GetFileName(bakCopy)), "the page line doesn't name the moved files: " + line);
|
|
NoTemp();
|
|
}
|
|
finally
|
|
{
|
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
|
}
|
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
|
}
|
|
}
|
|
|
|
// ---- helpers ----------------------------------------------------------------------
|
|
|
|
private static readonly Regex UnreadMainName = new Regex(@"^Defaults\.unread-\d{8}-\d{6}(-\d+)?\.xml$");
|
|
private static readonly Regex UnreadBackupName = new Regex(@"^Defaults\.bak\.unread-\d{8}-\d{6}(-\d+)?\.xml$");
|
|
|
|
private const string BillLi = "\t\t<li Class=\"BlaxDefaults.BillValues\">\n\t\t\t<key>bill:*</key>\n\t\t\t<storeMode>DropOnFloor</storeMode>\n\t\t</li>\n";
|
|
|
|
/// <summary>DefaultsFile.Load while the Scribe looks busy, as when the game saves or loads: one warning, nothing read.</summary>
|
|
private static LoadResult SkippedLoad()
|
|
{
|
|
LoadResult r;
|
|
using (var log = new LogCounter())
|
|
{
|
|
Scribe.mode = LoadSaveMode.LoadingVars;
|
|
try
|
|
{
|
|
r = DefaultsFile.Load();
|
|
}
|
|
finally
|
|
{
|
|
Scribe.mode = LoadSaveMode.Inactive;
|
|
}
|
|
T.Equal(1, log.OurWarnings, "warnings from the skipped read (" + log.Describe() + ")");
|
|
}
|
|
return r;
|
|
}
|
|
|
|
private static BillValues Bill(float radius) =>
|
|
new BillValues(DefaultsKeys.EveryBill) { setIngredientSearchRadius = true, ingredientSearchRadius = radius };
|
|
|
|
private static List<DefaultsEntry> Entries(params DefaultsEntry[] entries) => entries.ToList();
|
|
|
|
private static string Prints(IEnumerable<DefaultsEntry> entries) => string.Join("\n", entries.Select(e => e.Fingerprint()));
|
|
|
|
private static bool SameBytes(byte[] a, byte[] b) => a != null && b != null && a.SequenceEqual(b);
|
|
|
|
/// <summary>Cuts the file to half its length and returns the bytes now in it.</summary>
|
|
private static byte[] Truncate(string path)
|
|
{
|
|
byte[] half = TruncatedBytes(path);
|
|
File.WriteAllBytes(path, half);
|
|
return half;
|
|
}
|
|
|
|
private static byte[] TruncatedBytes(string path)
|
|
{
|
|
byte[] bytes = File.ReadAllBytes(path);
|
|
return bytes.Take(bytes.Length / 2).ToArray();
|
|
}
|
|
|
|
private static string FileText(string entries, string root = DefaultsFile.RootNode, int version = 1) =>
|
|
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<" + root + ">\n\t<formatVersion>" + version + "</formatVersion>\n"
|
|
+ (entries.Length == 0 ? "\t<entries />\n" : "\t<entries>\n" + entries + "\t</entries>\n")
|
|
+ "</" + root + ">\n";
|
|
|
|
private static void NoTemp()
|
|
{
|
|
string[] temps = Directory.GetFiles(DefaultsFile.FolderPath, "*.tmp");
|
|
T.Check(temps.Length == 0, ".tmp left in Config/BlaxDefaults: " + string.Join(", ", temps.Select(Path.GetFileName)));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Keeps the files of Config/BlaxDefaults, empties the folder for the test and puts them back exactly
|
|
/// afterwards. Refuses to run outside a -savedatafolder run, so the player's own file is never touched.
|
|
/// </summary>
|
|
private sealed class FileSandbox : IDisposable
|
|
{
|
|
private readonly Dictionary<string, byte[]> kept = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
public FileSandbox()
|
|
{
|
|
if (!GenCommandLine.TryGetCommandLineArg("savedatafolder", out string dataFolder) || dataFolder.NullOrEmpty())
|
|
T.Fail("refusing to touch Config/BlaxDefaults outside a test data folder (no -savedatafolder)");
|
|
Directory.CreateDirectory(DefaultsFile.FolderPath);
|
|
foreach (string f in Directory.GetFiles(DefaultsFile.FolderPath))
|
|
kept[Path.GetFileName(f)] = File.ReadAllBytes(f);
|
|
Empty();
|
|
}
|
|
|
|
private static void Empty()
|
|
{
|
|
foreach (string f in Directory.GetFiles(DefaultsFile.FolderPath))
|
|
File.Delete(f);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
try
|
|
{
|
|
Empty();
|
|
foreach (var kv in kept)
|
|
File.WriteAllBytes(Path.Combine(DefaultsFile.FolderPath, kv.Key), kv.Value);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
T.Info("putting Config/BlaxDefaults back failed: " + e.Message);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The log lines (message, warning, error) while it is open: Count those of the test's own thread, so a
|
|
/// line another thread happens to log meanwhile doesn't count; OurWarnings those of Blax Defaults.
|
|
/// </summary>
|
|
private sealed class LogCounter : IDisposable
|
|
{
|
|
private static LogCounter open;
|
|
private readonly int thread = Environment.CurrentManagedThreadId;
|
|
private readonly List<(LogType type, string text, bool sameThread)> lines = new List<(LogType, string, bool)>();
|
|
|
|
public LogCounter()
|
|
{
|
|
open = this;
|
|
Application.logMessageReceivedThreaded += OnLog;
|
|
}
|
|
|
|
private static void OnLog(string text, string stack, LogType type)
|
|
{
|
|
LogCounter c = open;
|
|
if (c == null) return;
|
|
lock (c.lines) c.lines.Add((type, text ?? "", Environment.CurrentManagedThreadId == c.thread));
|
|
}
|
|
|
|
public int Count
|
|
{
|
|
get { lock (lines) return lines.Count(l => l.sameThread); }
|
|
}
|
|
|
|
public int OurWarnings
|
|
{
|
|
get { lock (lines) return lines.Count(l => l.type == LogType.Warning && l.text.Contains("[Blax Defaults]")); }
|
|
}
|
|
|
|
public int Ours
|
|
{
|
|
get { lock (lines) return lines.Count(l => l.text.Contains("[Blax Defaults]")); }
|
|
}
|
|
|
|
public string Describe()
|
|
{
|
|
lock (lines)
|
|
return lines.Count == 0 ? "nothing" : string.Join(" | ", lines.Take(5).Select(l => l.type + ": " + l.text.Replace('\n', ' ')));
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Application.logMessageReceivedThreaded -= OnLog;
|
|
open = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>A test-only entry whose ExposeData throws while saving (the "file" tests).</summary>
|
|
public class BlaxTestThrowingEntry : DefaultsEntry
|
|
{
|
|
public BlaxTestThrowingEntry()
|
|
{
|
|
}
|
|
|
|
public BlaxTestThrowingEntry(string key)
|
|
{
|
|
this.key = key;
|
|
}
|
|
|
|
public override void ExposeData()
|
|
{
|
|
base.ExposeData();
|
|
if (Scribe.mode == LoadSaveMode.Saving)
|
|
throw new InvalidOperationException("BlaxTest: this entry refuses to be saved");
|
|
}
|
|
|
|
public override DefaultsEntry Clone() => new BlaxTestThrowingEntry(key);
|
|
|
|
public override string Fingerprint() => key ?? "";
|
|
}
|
|
}
|