Skip to content
Merged
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
18 changes: 18 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,11 @@ PublishScripts/
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# and except a Unity project's Packages/, which is source: Unity's package manifest and its
# resolved lock file are both meant to be committed, and a NuGet restore folder never contains
# a file by either name.
!**/[Pp]ackages/manifest.json
!**/[Pp]ackages/packages-lock.json
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
Expand Down Expand Up @@ -651,3 +656,16 @@ Temporary Items

# ImGui.ini files
imgui.ini

# Game engine projects
#
# Godot: the import cache, and the mono/temp bin+obj a C# build writes.
.godot/

# Unity: .meta files are source, not the Visual Studio C++ build artifact that the `*.meta` rule
# further up targets. Unity generates one per asset and it carries the GUID that scenes, prefabs
# and serialized references point at, so ignoring them gives every clone fresh GUIDs and silently
# breaks those references - including for a plug-in whose .dll is itself a build output. This
# negation has to come after that rule to win, and is scoped to the asset tree so the Visual
# Studio artifact stays ignored everywhere else.
!**/[Aa]ssets/**/*.meta
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ public bool TrySerialize(object obj, TextWriter writer)

try
{
using JsonTextWriter jsonWriter = new(writer);
// The caller owns the writer, so disposing the JSON writer must not close it.
using JsonTextWriter jsonWriter = new(writer) { CloseOutput = false };
JsonSerializer serializer = JsonSerializer.Create(settings);
serializer.Serialize(jsonWriter, obj);
jsonWriter.Flush();
return true;
}
catch (JsonSerializationException)
Expand All @@ -48,6 +50,14 @@ public bool TrySerialize(object obj, TextWriter writer)
{
return false;
}
catch (IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
}

/// <summary>
Expand All @@ -72,6 +82,10 @@ public bool TrySerialize(object obj, TextWriter writer)
{
return default;
}
catch (JsonSerializationException)
{
return default;
}
catch (ArgumentException)
{
return default;
Expand Down
41 changes: 41 additions & 0 deletions Essentials.Tests/NewtonsoftJsonSerializationProviderTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) 2023-2026 ktsu-dev contributors

namespace ktsu.Essentials.Tests;

using System.IO;
using ktsu.Essentials.SerializationProviders.NewtonsoftJson;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class NewtonsoftJsonSerializationProviderTests
{
[TestMethod]
public void TrySerialize_DisposedWriter_ReturnsFalse()
{
NewtonsoftJsonSerializationProvider provider = new();
StringWriter writer = new();
writer.Dispose();

Assert.IsFalse(provider.TrySerialize(new { A = 1 }, writer));
}

[TestMethod]
public void TrySerialize_WriterThrowingIOException_ReturnsFalse()
{
NewtonsoftJsonSerializationProvider provider = new();
using FailingWriter writer = new();

Assert.IsFalse(provider.TrySerialize(new { A = 1 }, writer));
}

private sealed class FailingWriter : StringWriter
{
public override void Write(char value) => throw new IOException("disk full");

public override void Write(char[] buffer, int index, int count) => throw new IOException("disk full");

public override void Write(string? value) => throw new IOException("disk full");

public override void Flush() => throw new IOException("disk full");
}
}
33 changes: 33 additions & 0 deletions Essentials.Tests/RoundTripTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
namespace ktsu.Essentials.Tests;

using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ktsu.Essentials;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -24,6 +26,9 @@ private static ServiceProvider BuildProvider()

public static IEnumerable<object[]> SerializationProviders => BuildProvider().EnumerateProviders<ISerializationProvider>();

public static IEnumerable<object[]> JsonSerializationProviders =>
SerializationProviders.Where(row => ((ISerializationProvider)row[0]).FileExtension == ".json");

public TestContext TestContext { get; set; } = null!;

#region Compression Tests
Expand Down Expand Up @@ -230,6 +235,34 @@ public void Serialization_Async_Variants(ISerializationProvider serializer, stri
Assert.AreEqual(original.Value, deserialized.Value, $"{providerName} async should preserve Value property");
}

[TestMethod]
[DynamicData(nameof(SerializationProviders))]
public void Serialization_TrySerialize_Twice_Into_One_StreamWriter_Leaves_It_Open(ISerializationProvider serializer, string providerName)
{
using MemoryStream stream = new();
using StreamWriter writer = new(stream);

bool first = serializer.TrySerialize(new TestObject { Name = "first", Value = 1 }, writer);
bool second = serializer.TrySerialize(new TestObject { Name = "second", Value = 2 }, writer);

Assert.IsTrue(first, $"{providerName} should serialize the first object");
Assert.IsTrue(second, $"{providerName} should serialize the second object into the same writer");
Assert.IsTrue(stream.CanWrite, $"{providerName} should leave the caller's stream open");
writer.Flush();
string written = Encoding.UTF8.GetString(stream.ToArray());
Assert.Contains("first", written, $"{providerName} should write the first object");
Assert.Contains("second", written, $"{providerName} should write the second object");
}

[TestMethod]
[DynamicData(nameof(JsonSerializationProviders))]
public void Serialization_Json_Deserialize_ShapeMismatch_Returns_Default(ISerializationProvider serializer, string providerName)
{
TestObject? result = serializer.Deserialize<TestObject>("[1,2]"u8);

Assert.IsNull(result, $"{providerName} should return default for JSON whose shape doesn't match the type");
}

[TestMethod]
[DynamicData(nameof(SerializationProviders))]
public void Serialization_Ignores_Members_The_Target_Type_Lacks(ISerializationProvider serializer, string providerName)
Expand Down
Loading