Skip to content

Commit

Permalink
Serialization also works and tests added
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander Wulf authored and SamboyCoding committed Nov 25, 2021
1 parent 83b07a9 commit 5c98192
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Tomlet.Tests.TestModelClasses
{
public record ComplexTestRecordWithAttributeMapping
{
[TomlProperty("string")]
public string MyString { get; init; }
public WidgetForThisComplexTestRecordWithAttributeMapping MyWidget { get; init; }
}

public record WidgetForThisComplexTestRecordWithAttributeMapping
{
[TomlProperty("my_int")]
public int MyInt { get; init; }
}
}
5 changes: 5 additions & 0 deletions Tomlet.Tests/TestResources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -330,4 +330,9 @@ MyDateTime = 1970-01-01T07:00:00</value>
<data name="LiteralQuotedPathWithBackslashesTestInput" xml:space="preserve">
<value>Args = '"C:\\Something"'</value>
</data>
<data name="ComplexTestRecordForAttributeMapping" xml:space="preserve">
<value>string = "Test"
[MyWidget]
my_int = 42</value>
</data>
</root>
26 changes: 26 additions & 0 deletions Tomlet.Tests/TomlPropertyMappingTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Tomlet.Tests.TestModelClasses;
using Xunit;

namespace Tomlet.Tests
{
public class TomlPropertyMappingTests
{
[Fact]
public void DeserializationWorks()
{
var record = TomletMain.To<ComplexTestRecordWithAttributeMapping>(TestResources.ComplexTestRecordForAttributeMapping);
Assert.Equal("Test", record.MyString);
Assert.IsType<WidgetForThisComplexTestRecordWithAttributeMapping>(record.MyWidget);
Assert.Equal(42, record.MyWidget.MyInt);
}

[Fact]
public void SerializationWorks()
{
var testString = TestResources.ComplexTestRecordForAttributeMapping.Trim();
var record = TomletMain.To<ComplexTestRecordWithAttributeMapping>(testString);
var serialized = TomletMain.TomlStringFrom(record).Trim();
Assert.Equal(testString, serialized);
}
}
}
3 changes: 3 additions & 0 deletions Tomlet/TomlSerializationMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,9 @@ internal static Serialize<object> GetCompositeSerializer(Type type)
if (m.Success)
name = m.Groups[1].Value;

var name1 = name;
name = type.GetProperties().FirstOrDefault(p => p.Name == name1)?.GetCustomAttribute<TomlPropertyAttribute>()?.GetMappedString() ?? name;

if (resultTable.ContainsKey(name))
//Do not overwrite fields if they have the same name as something already in the table
//This fixes serializing types which re-declare a field using the `new` keyword, overwriting a field of the same name
Expand Down

0 comments on commit 5c98192

Please sign in to comment.