Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Chorus.merge;
using LibFLExBridgeChorusPlugin.DomainServices;
using LibFLExBridgeChorusPlugin.Infrastructure;
using LibFLExBridgeChorusPluginTests.Infrastructure.RoundTrip;
using LibTriboroughBridgeChorusPlugin;
using NUnit.Framework;
using SIL.Progress;
Expand All @@ -24,8 +24,7 @@ namespace LibFLExBridgeChorusPluginTests.Infrastructure
[TestFixture]
public class CustomPropertyCacheTests
{
private const string LangProjGuid = "c1ed46ba-e382-11de-8a39-0800200c9a66";
private const string EntryGuid = "c1ed46bc-e382-11de-8a39-0800200c9a66";
private static readonly Guid EntryGuid = new Guid("c1ed46bc-e382-11de-8a39-0800200c9a66");

private TemporaryFolder _projectFolder;
private string _fwdataPathname;
Expand All @@ -46,51 +45,12 @@ public void TearDown()
_mdc = MetadataCache.TestOnlyNewCache;
}

/// <summary>
/// The objects LangProject must own for the splitter and unifier to round trip a project:
/// (LangProject property, class of the owned object).
/// </summary>
private static readonly string[,] RequiredLangProjectOwnedObjects =
{
{ "GenreList", "CmPossibilityList" },
{ "LexDb", "LexDb" },
{ "MorphologicalData", "MoMorphData" },
{ "MsFeatureSystem", "FsFeatureSystem" },
{ "PhFeatureSystem", "FsFeatureSystem" },
{ "PhonologicalData", "PhPhonData" },
{ "ResearchNotebook", "RnResearchNbk" },
{ "TextMarkupTags", "CmPossibilityList" },
{ "TranslationTags", "CmPossibilityList" }
};

private static string FwdataWithIntegerCustomField()
{
var langProject = new XElement("rt",
new XAttribute("class", "LangProject"),
new XAttribute("guid", LangProjGuid),
new XElement("AnalyzingAgents"),
new XElement("Styles"));
var ownedObjects = new List<XElement>();
for (var i = 0; i < RequiredLangProjectOwnedObjects.GetLength(0); ++i)
{
var guid = Guid.NewGuid().ToString();
langProject.Add(new XElement(RequiredLangProjectOwnedObjects[i, 0],
new XElement("objsur", new XAttribute("guid", guid), new XAttribute("t", "o"))));
ownedObjects.Add(new XElement("rt",
new XAttribute("class", RequiredLangProjectOwnedObjects[i, 1]),
new XAttribute("guid", guid),
new XAttribute("ownerguid", LangProjGuid)));
}
var entry = XElement.Parse(string.Format(
"<rt class='LexEntry' guid='{0}'><Custom name='Rank' val='3' /></rt>", EntryGuid));

var root = new XElement("languageproject",
new XAttribute("version", MetadataCache.MaximumModelVersion),
XElement.Parse("<AdditionalFields><CustomField name='Rank' class='LexEntry' type='Integer' /></AdditionalFields>"),
langProject,
ownedObjects,
entry);
return new XDocument(new XDeclaration("1.0", "utf-8", null), root).ToString();
return new FwdataBuilder()
.AddCustomField("LexEntry", "Rank", "Integer")
.AddUnownedObject("LexEntry", EntryGuid, new XElement("Custom", new XAttribute("name", "Rank"), new XAttribute("val", "3")))
.ToString();
}

private void Split()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright (c) 2026 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using LibFLExBridgeChorusPlugin.Infrastructure;
using NUnit.Framework;

namespace LibFLExBridgeChorusPluginTests.Infrastructure.RoundTrip
{
/// <summary>
/// Semantic comparisons of two .fwdata documents. Objects are matched by guid, so the order of
/// &lt;rt&gt; elements, the order of properties within an object, and whitespace do not matter.
/// </summary>
internal static class FwdataAssert
{
/// <summary>Both documents hold the same objects: same guids, classes and owners.</summary>
internal static void SameObjects(XDocument expected, XDocument actual)
{
Assert.That(ObjectSummaries(actual), Is.EqualTo(ObjectSummaries(expected)), "objects (guid, class, owner)");
}

/// <summary>Both documents declare the same custom fields with the same attributes.</summary>
internal static void SameCustomFields(XDocument expected, XDocument actual)
{
Assert.That(CustomFieldSummaries(actual), Is.EqualTo(CustomFieldSummaries(expected)), "custom fields");
}

/// <summary>
/// Both documents hold the same objects, each with the same properties and property contents.
/// </summary>
internal static void SameObjectContents(XDocument expected, XDocument actual)
{
SameObjects(expected, actual);
var actualObjects = SplitUnifyHarness.ObjectsByGuid(actual);
foreach (var expectedObject in SplitUnifyHarness.ObjectsByGuid(expected))
{
Assert.That(Normalize(actualObjects[expectedObject.Key]).ToString(),
Is.EqualTo(Normalize(expectedObject.Value).ToString()),
"contents of " + expectedObject.Key);
}
}

private static List<string> ObjectSummaries(XDocument fwdata)
{
return SplitUnifyHarness.ObjectsByGuid(fwdata)
.Select(pair => string.Format("{0} {1} owner={2}",
pair.Key,
pair.Value.Attribute(FlexBridgeConstants.Class).Value,
pair.Value.Attribute(FlexBridgeConstants.OwnerGuid) == null
? "none"
: new Guid(pair.Value.Attribute(FlexBridgeConstants.OwnerGuid).Value).ToString()))
.OrderBy(summary => summary)
.ToList();
}

private static List<string> CustomFieldSummaries(XDocument fwdata)
{
var additionalFields = fwdata.Root.Element(FlexBridgeConstants.AdditionalFieldsTag);
if (additionalFields == null)
return new List<string>();
return additionalFields.Elements(FlexBridgeConstants.CustomField)
.Select(cf => string.Join(" ", cf.Attributes()
.OrderBy(attr => attr.Name.LocalName)
.Select(attr => attr.Name.LocalName + "=" + attr.Value)))
.OrderBy(summary => summary)
.ToList();
}

/// <summary>A copy of an element with attributes and child elements sorted and whitespace-only text dropped.</summary>
private static XElement Normalize(XElement element)
{
var copy = new XElement(element.Name,
element.Attributes().OrderBy(attr => attr.Name.LocalName).Select(attr => new XAttribute(attr)));
if (element.HasElements)
{
// Owning and reference sequences keep their order: only the order of an object's properties is free.
var children = element.Name.LocalName == FlexBridgeConstants.RtTag
? element.Elements().OrderBy(child => child.Name.LocalName).ThenBy(child => (string)child.Attribute(FlexBridgeConstants.Name))
: element.Elements();
copy.Add(children.Select(Normalize));
}
else if (!string.IsNullOrWhiteSpace(element.Value))
{
copy.Add(new XText(element.Value));
}
return copy;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
// Copyright (c) 2026 SIL International
// This software is licensed under the MIT License (http://opensource.org/licenses/MIT)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using LibFLExBridgeChorusPlugin.Infrastructure;

namespace LibFLExBridgeChorusPluginTests.Infrastructure.RoundTrip
{
/// <summary>
/// Builds a small .fwdata document that the splitter and unifier accept.
/// </summary>
/// <remarks>
/// A new builder already holds the stub objects every project needs: a LangProject that owns a LexDb and
/// the other objects listed in <see cref="RequiredLangProjectOwnedObjects"/>. Add what a test cares about:
/// <code>
/// var fwdata = new FwdataBuilder()
/// .AddCustomField("LexEntry", "Rank", "Integer")
/// .AddUnownedObject("LexEntry", EntryGuid, new XElement("Custom", new XAttribute("name", "Rank"), new XAttribute("val", "3")))
/// .AddOwnedObject(EntryGuid, "Senses", "LexSense", SenseGuid);
/// </code>
/// Property content is passed as <see cref="XElement"/>s (or anything else <see cref="XElement.Add(object)"/>
/// takes), so any property the model knows can be added. Use <see cref="AddRt"/> for an object that
/// needs full control.
/// </remarks>
internal sealed class FwdataBuilder
{
internal static readonly Guid LangProjectGuid = new Guid("c1ed46ba-e382-11de-8a39-0800200c9a66");

/// <summary>
/// The objects LangProject must own for the splitter and unifier to round trip a project:
/// (LangProject property, class of the owned object). LangProject must also have an AnalyzingAgents element.
/// </summary>
/// <remarks>
/// Without LexDb, MorphologicalData, MsFeatureSystem, PhFeatureSystem, PhonologicalData or AnalyzingAgents
/// the split throws. Every real project has those. Without GenreList, TextMarkupTags, TranslationTags or
/// ResearchNotebook the split succeeds but the unify throws, because the unifier expects a list file or notebook that the
/// splitter writes only when the object exists.
/// </remarks>
internal static readonly IReadOnlyList<KeyValuePair<string, string>> RequiredLangProjectOwnedObjects = new[]
{
new KeyValuePair<string, string>("GenreList", "CmPossibilityList"),
new KeyValuePair<string, string>("LexDb", "LexDb"),
new KeyValuePair<string, string>("MorphologicalData", "MoMorphData"),
new KeyValuePair<string, string>("MsFeatureSystem", "FsFeatureSystem"),
new KeyValuePair<string, string>("PhFeatureSystem", "FsFeatureSystem"),
new KeyValuePair<string, string>("PhonologicalData", "PhPhonData"),
new KeyValuePair<string, string>("ResearchNotebook", "RnResearchNbk"),
new KeyValuePair<string, string>("TextMarkupTags", "CmPossibilityList"),
new KeyValuePair<string, string>("TranslationTags", "CmPossibilityList")
};

private readonly List<XElement> _customFields = new List<XElement>();
// The <rt> elements, in the order added.
private readonly List<XElement> _objects = new List<XElement>();
private readonly string _modelVersion;

internal FwdataBuilder()
: this(MetadataCache.MaximumModelVersion)
{
}

internal FwdataBuilder(int modelVersion)
{
_modelVersion = modelVersion.ToString();
AddRt(new XElement(FlexBridgeConstants.RtTag,
new XAttribute(FlexBridgeConstants.Class, FlexBridgeConstants.LangProject),
new XAttribute(FlexBridgeConstants.GuidStr, LangProjectGuid),
new XElement(FlexBridgeConstants.AnalyzingAgents)));
// Fixed guids keep the split files (for example, which Lexicon_NN.lexdb bucket a guid lands in) stable from run to run.
var i = 0;
foreach (var owned in RequiredLangProjectOwnedObjects)
AddOwnedObject(LangProjectGuid, owned.Key, owned.Value, new Guid(string.Format("00000000-0000-0000-0000-{0:x12}", ++i)));
}

/// <summary>The guid of the stub LexDb that LangProject owns.</summary>
internal Guid LexDbGuid
{
get { return OwnedGuid(LangProjectGuid, FlexBridgeConstants.LexDb); }
}

/// <summary>
/// Declare a custom field in the AdditionalFields element.
/// <paramref name="type"/> is the fwdata type name, such as "Integer", "String", "MultiUnicode" or "OC".
/// </summary>
internal FwdataBuilder AddCustomField(string className, string name, string type, params object[] extraAttributes)
{
_customFields.Add(new XElement(FlexBridgeConstants.CustomField,
new XAttribute(FlexBridgeConstants.Name, name),
new XAttribute(FlexBridgeConstants.Class, className),
new XAttribute("type", type),
extraAttributes));
return this;
}

/// <summary>Add an object with no owner, such as a LexEntry.</summary>
internal FwdataBuilder AddUnownedObject(string className, Guid guid, params object[] content)
{
return AddRt(NewRt(className, guid, content));
}

/// <summary>
/// Add an object owned by <paramref name="ownerGuid"/> (already added) in its <paramref name="owningProperty"/>.
/// The owner gets an &lt;objsur t='o'/&gt; in that property, after any it already has.
/// </summary>
internal FwdataBuilder AddOwnedObject(Guid ownerGuid, string owningProperty, string className, Guid guid, params object[] content)
{
var owner = GetRt(ownerGuid);
var property = owner.Element(owningProperty);
if (property == null)
{
property = new XElement(owningProperty);
owner.Add(property);
}
property.Add(new XElement(FlexBridgeConstants.Objsur,
new XAttribute(FlexBridgeConstants.GuidStr, guid),
new XAttribute("t", "o")));

var rt = NewRt(className, guid, content);
rt.Add(new XAttribute(FlexBridgeConstants.OwnerGuid, ownerGuid));
return AddRt(rt);
}

/// <summary>Add an &lt;rt&gt; element as is. The caller handles ownerguid and the owner's objsur.</summary>
internal FwdataBuilder AddRt(XElement rt)
{
var guid = SplitUnifyHarness.GuidOf(rt);
if (_objects.Any(obj => SplitUnifyHarness.GuidOf(obj) == guid))
throw new ArgumentException("An object with guid " + guid + " was already added.", "rt");
_objects.Add(rt);
return this;
}

/// <summary>The &lt;rt&gt; element with the given guid, for a test that wants to change a stub object.</summary>
internal XElement GetRt(Guid guid)
{
var rt = _objects.FirstOrDefault(obj => SplitUnifyHarness.GuidOf(obj) == guid);
if (rt == null)
throw new ArgumentException("No object with guid " + guid + " has been added.", "guid");
return rt;
}

internal XDocument Build()
{
var root = new XElement("languageproject", new XAttribute("version", _modelVersion));
if (_customFields.Count > 0)
root.Add(new XElement(FlexBridgeConstants.AdditionalFieldsTag, _customFields.Select(cf => new XElement(cf))));
root.Add(_objects.Select(rt => new XElement(rt)));
return new XDocument(new XDeclaration("1.0", "utf-8", null), root);
}

public override string ToString()
{
var doc = Build();
return doc.Declaration + Environment.NewLine + doc;
}

private Guid OwnedGuid(Guid ownerGuid, string owningProperty)
{
return SplitUnifyHarness.GuidOf(GetRt(ownerGuid).Element(owningProperty).Element(FlexBridgeConstants.Objsur));
}

private static XElement NewRt(string className, Guid guid, object[] content)
{
return new XElement(FlexBridgeConstants.RtTag,
new XAttribute(FlexBridgeConstants.Class, className),
new XAttribute(FlexBridgeConstants.GuidStr, guid),
content);
}
}
}
Loading
Loading