Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit tests: Convert NUnit Classic Assert to Constraint Model #364

Merged
merged 2 commits into from
Jan 7, 2024
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
4 changes: 2 additions & 2 deletions src/SmartFormat.Tests/Core/EscapedLiteralTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,6 @@ public void UnEscape_With_StartIndex_not_zero()
var full = "abc(de";
var startIndex = 3;
var resultBuffer = new Span<char>(new char[full.Length]);
Assert.That("(de", Is.EqualTo(EscapedLiteral.UnEscapeCharLiterals('\\', full.AsSpan(startIndex, full.Length - startIndex), true, resultBuffer).ToString()));
Assert.That(EscapedLiteral.UnEscapeCharLiterals('\\', full.AsSpan(startIndex, full.Length - startIndex), true, resultBuffer).ToString(), Is.EqualTo("(de"));
}
}
}
40 changes: 23 additions & 17 deletions src/SmartFormat.Tests/Core/FormatterExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,12 @@ public void Formatters_Can_Be_Initialized()
var negatedAutoDetection = formatter.CanAutoDetect;
formatter.Name = guid;
formatter.GetType().GetProperty("Names")?.SetValue(formatter, new[] {guid}); // "Names" property is obsolete

Assert.That(formatter.GetType().GetProperty("Names")?.GetValue(formatter), Is.EqualTo(new[]{guid})); // "Names" property is obsolete
Assert.That(formatter.Name, Is.EqualTo(guid));

Assert.Multiple(() =>
{
Assert.That(formatter.GetType().GetProperty("Names")?.GetValue(formatter), Is.EqualTo(new[] { guid })); // "Names" property is obsolete
Assert.That(formatter.Name, Is.EqualTo(guid));
});

if (formatter is not TemplateFormatter)
{
formatter.CanAutoDetect = negatedAutoDetection;
Expand Down Expand Up @@ -76,25 +78,26 @@ public void Add_Known_FormatterExtensions_In_Recommended_Order()
var orderedFormatters = allFormatters.OrderBy(f => WellKnownExtensionTypes.Formatters[f.GetType().FullName!])
.ToList().AsReadOnly();

CollectionAssert.AreEqual(orderedFormatters, sf.GetFormatterExtensions());
Assert.That(sf.GetFormatterExtensions(), Is.EqualTo(orderedFormatters).AsCollection);
}

#region: Default Extensions :

[Test]
#pragma warning disable CA1861 // Not called repeatedly, but called with different arguments
[TestCase("{0:cond:zero|one|two}", 0, "zero")]
[TestCase("{0:cond:zero|one|two}", 1, "one")]
[TestCase("{0:cond:zero|one|two}", 2, "two")]
[TestCase("{0:list:+{}|, |, and }", new []{ 1, 2, 3 }, "+1, +2, and +3")]
[TestCase("{0:list:+{}|, |, and }", new []{ 1, 2, 3 }, "+1, +2, and +3")]
[TestCase("{0:list:+{}|, |, and }", new[] { 1, 2, 3 }, "+1, +2, and +3")]
[TestCase("{0:list:+{}|, |, and }", new[] { 2, 3, 4 }, "+2, +3, and +4")]
[TestCase("{0:d()}", 5, "5")]
[TestCase("{0:d:N2}", 5, "5.00")]
public void Invoke_extensions_by_name(string format, object arg0, string expectedResult)
{
var smart = Smart.CreateDefaultSmartFormat();
var actualResult = smart.Format(new CultureInfo("en-US"), format, arg0); // must be culture with decimal point
Assert.AreEqual(expectedResult, actualResult);
Assert.That(actualResult, Is.EqualTo(expectedResult));
}
#pragma warning restore CA1861

#endregion

Expand All @@ -104,10 +107,13 @@ public void Invoke_extensions_by_name(string format, object arg0, string expecte
public void Conditional_Formatter_With_Parenthesis(bool value, string expected)
{
var smart = Smart.CreateDefaultSmartFormat();
// explicit conditional formatter
Assert.AreEqual(expected, smart.Format("{value:cond:yes (probably)|no (possibly)}", new { value }));
// implicit
Assert.AreEqual(expected, smart.Format("{value:yes (probably)|no (possibly)}", new { value }));
Assert.Multiple(() =>
{
// explicit conditional formatter
Assert.That(smart.Format("{value:cond:yes (probably)|no (possibly)}", new { value }), Is.EqualTo(expected));
// implicit
Assert.That(smart.Format("{value:yes (probably)|no (possibly)}", new { value }), Is.EqualTo(expected));
});
}

#region: Custom Extensions :
Expand All @@ -119,7 +125,7 @@ public void Without_NamedFormatter_extensions_are_invoked_in_order(string format
{
var smart = GetFormatterWithTestExtensions();
var actualResult = smart.Format(format, arg0);
Assert.AreEqual(expectedResult, actualResult);
Assert.That(actualResult, Is.EqualTo(expectedResult));
}

[Test]
Expand All @@ -145,7 +151,7 @@ public void NamedFormatter_invokes_a_specific_formatter(string format, object ar
{
var smart = GetFormatterWithTestExtensions();
var actualResult = smart.Format(new CultureInfo("en-US"), format, arg0); // must be culture with decimal point
Assert.AreEqual(expectedResult, actualResult);
Assert.That(actualResult, Is.EqualTo(expectedResult));
}

[Test]
Expand All @@ -158,7 +164,7 @@ public void Implicit_formatters_require_an_isDefaultFormatter_flag(string format
formatter.GetFormatterExtension<TestExtension1>()!.CanAutoDetect = false;
formatter.GetFormatterExtension<TestExtension2>()!.CanAutoDetect = true;
var actual = formatter.Format(format, arg0);
Assert.AreEqual(expectedOutput, actual);
Assert.That(actual, Is.EqualTo(expectedOutput));
}

private static SmartFormatter GetFormatterWithTestExtensions()
Expand Down Expand Up @@ -203,4 +209,4 @@ public bool TryEvaluateFormat(IFormattingInfo formattingInfo)

#endregion

}
}
82 changes: 53 additions & 29 deletions src/SmartFormat.Tests/Core/FormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,14 @@ public void Formatter_NotifyFormattingError()
var formatter = Smart.CreateDefaultSmartFormat(new SmartSettings {Formatter = new FormatterSettings {ErrorAction = FormatErrorAction.Ignore}});
formatter.OnFormattingFailure += (o, args) => badPlaceholder.Add(args);
var res = formatter.Format("{NoName} {Name} {OtherMissing}", obj);
Assert.That(badPlaceholder.Count, Is.EqualTo(2));
Assert.That(badPlaceholder[0].Placeholder == "{NoName}");
Assert.That(badPlaceholder[1].Placeholder == "{OtherMissing}");
Assert.That(badPlaceholder[0].ErrorIndex, Is.EqualTo(7));
Assert.That(badPlaceholder[0].IgnoreError, Is.EqualTo(true));
Assert.That(badPlaceholder, Has.Count.EqualTo(2));
Assert.Multiple(() =>
{
Assert.That(badPlaceholder[0].Placeholder, Is.EqualTo("{NoName}"));
Assert.That(badPlaceholder[1].Placeholder, Is.EqualTo("{OtherMissing}"));
Assert.That(badPlaceholder[0].ErrorIndex, Is.EqualTo(7));
Assert.That(badPlaceholder[0].IgnoreError, Is.EqualTo(true));
});
}

[TestCase("\\{Test}", "\\Hello", false)]
Expand All @@ -156,7 +159,7 @@ public void LeadingBackslashMustNotEscapeBraces(string format, string expected,
{StringFormatCompatibility = true, Parser = new ParserSettings {ConvertCharacterStringLiterals = convertCharacterStringLiterals}});

var actual = smart.Format(format, new { Test = "Hello" });
Assert.AreEqual(expected, actual);
Assert.That(actual, Is.EqualTo(expected));
}

[Test]
Expand All @@ -165,7 +168,7 @@ public void NullAndBoxedNullBehaveTheSame()
// see issue https://github.com/scottrippey/SmartFormat.NET/issues/101
var smart = Smart.CreateDefaultSmartFormat();
object? boxedNull = null;
Assert.AreEqual(smart.Format("{0}", default(object)!), smart.Format("{0}", boxedNull!));
Assert.That(smart.Format("{0}", boxedNull!), Is.EqualTo(smart.Format("{0}", default(object)!)));
}

[Test]
Expand All @@ -182,10 +185,13 @@ public void SmartFormatter_FormatDetails()
});
var formatParsed = formatter.Parser.ParseFormat(format);
var formatDetails = new FormatDetails().Initialize(formatter, formatParsed, args, null, output);

Assert.AreEqual(args, formatDetails.OriginalArgs);
Assert.AreEqual(format, formatDetails.OriginalFormat.RawText);
Assert.AreEqual(formatter.Settings, formatDetails.Settings);

Assert.Multiple(() =>
{
Assert.That(formatDetails.OriginalArgs, Is.EqualTo(args));
Assert.That(formatDetails.OriginalFormat.RawText, Is.EqualTo(format));
Assert.That(formatDetails.Settings, Is.EqualTo(formatter.Settings));
});
}

[Test]
Expand All @@ -195,7 +201,7 @@ public void Missing_FormatExtensions_Should_Throw()
// make sure we test against missing format extensions
formatter.AddExtensions(new DefaultSource());

Assert.That(formatter.FormatterExtensions.Count, Is.EqualTo(0));
Assert.That(formatter.FormatterExtensions, Is.Empty);
Assert.Throws<InvalidOperationException>(() => formatter.Format("", Array.Empty<object>()));
}

Expand All @@ -206,7 +212,7 @@ public void Missing_SourceExtensions_Should_Throw()
// make sure we test against missing source extensions
formatter.AddExtensions(new DefaultFormatter());

Assert.That(formatter.SourceExtensions.Count, Is.EqualTo(0));
Assert.That(formatter.SourceExtensions, Is.Empty);
Assert.Throws<InvalidOperationException>(() => formatter.Format("", Array.Empty<object>()));
}

Expand All @@ -224,17 +230,19 @@ public void Adding_FormatExtension_With_Existing_Name_Should_Throw()
public void Remove_None_Existing_Source()
{
var formatter = new SmartFormatter();

Assert.That(formatter.SourceExtensions.Count, Is.EqualTo(0));
Assert.That(formatter.RemoveSourceExtension<StringSource>(), Is.EqualTo(false));
Assert.Multiple(() =>
{
Assert.That(formatter.SourceExtensions, Is.Empty);
Assert.That(formatter.RemoveSourceExtension<StringSource>(), Is.EqualTo(false));
});
}

[Test]
public void Remove_Existing_Source()
{
var formatter = new SmartFormatter();

Assert.That(formatter.SourceExtensions.Count, Is.EqualTo(0));
Assert.That(formatter.SourceExtensions, Is.Empty);
formatter.AddExtensions(new StringSource());
Assert.That(formatter.RemoveSourceExtension<StringSource>(), Is.EqualTo(true));
}
Expand All @@ -243,17 +251,19 @@ public void Remove_Existing_Source()
public void Remove_None_Existing_Formatter()
{
var formatter = new SmartFormatter();

Assert.That(formatter.FormatterExtensions.Count, Is.EqualTo(0));
Assert.That(formatter.RemoveFormatterExtension<DefaultFormatter>(), Is.EqualTo(false));
Assert.Multiple(() =>
{
Assert.That(formatter.FormatterExtensions, Is.Empty);
Assert.That(formatter.RemoveFormatterExtension<DefaultFormatter>(), Is.EqualTo(false));
});
}

[Test]
public void Remove_Existing_Formatter()
{
var formatter = new SmartFormatter();

Assert.That(formatter.FormatterExtensions.Count, Is.EqualTo(0));
Assert.That(formatter.FormatterExtensions, Is.Empty);
formatter.AddExtensions(new DefaultFormatter());
Assert.That(formatter.RemoveFormatterExtension<DefaultFormatter>(), Is.EqualTo(true));
}
Expand All @@ -262,16 +272,24 @@ public void Remove_Existing_Formatter()
public void Formatter_GetSourceExtension()
{
var formatter = GetSimpleFormatter();
Assert.That(formatter.GetSourceExtensions().Count, Is.EqualTo(formatter.SourceExtensions.Count));
Assert.That(formatter.GetSourceExtension<DefaultSource>(), Is.InstanceOf(typeof(DefaultSource))); ;
Assert.Multiple(() =>
{
Assert.That(formatter.GetSourceExtensions(), Has.Count.EqualTo(formatter.SourceExtensions.Count));
Assert.That(formatter.GetSourceExtension<DefaultSource>(), Is.InstanceOf(typeof(DefaultSource)));
});
;
}

[Test]
public void Formatter_GetFormatterExtension()
{
var formatter = GetSimpleFormatter();
Assert.That(formatter.GetFormatterExtensions().Count, Is.EqualTo(formatter.FormatterExtensions.Count));
Assert.That(formatter.GetFormatterExtension<DefaultFormatter>(), Is.InstanceOf(typeof(DefaultFormatter))); ;
Assert.Multiple(() =>
{
Assert.That(formatter.GetFormatterExtensions(), Has.Count.EqualTo(formatter.FormatterExtensions.Count));
Assert.That(formatter.GetFormatterExtension<DefaultFormatter>(), Is.InstanceOf(typeof(DefaultFormatter)));
});
;
}

[Test]
Expand Down Expand Up @@ -312,10 +330,16 @@ public void Parallel_Smart_Format()
results.TryAdd(i, Smart.Format("{0}", i));
Interlocked.Increment(ref resultCounter);
}), Throws.Nothing);
Assert.That(threadIds.Count, Is.AtLeast(2)); // otherwise the test is not significant
Assert.That(Smart.CreateDefaultSmartFormat().GetFormatterExtension<ChooseFormatter>(), Is.Not.Null);
Assert.That(threadIds.Count, Is.EqualTo(formatterInstancesCounter));
Assert.That(results.Count, Is.EqualTo(resultCounter));
Assert.Multiple(() =>
{
Assert.That(threadIds, Has.Count.AtLeast(2)); // otherwise the test is not significant
Assert.That(Smart.CreateDefaultSmartFormat().GetFormatterExtension<ChooseFormatter>(), Is.Not.Null);
});
Assert.Multiple(() =>
{
Assert.That(threadIds, Has.Count.EqualTo(formatterInstancesCounter));
Assert.That(results, Has.Count.EqualTo(resultCounter));
});

// Restore to saved value
ThreadSafeMode.SwitchTo(savedMode);
Expand Down
12 changes: 6 additions & 6 deletions src/SmartFormat.Tests/Core/LiteralTextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ public void FormatCharacterLiteralsAsString()
var formatter = Smart.CreateDefaultSmartFormat(new SmartSettings {Parser = new ParserSettings {ConvertCharacterStringLiterals = false}});

var result = formatter.Format(formatWithFileBehavior);
Assert.AreEqual(string.Format(formatWithFileBehavior), result);
Assert.That(result, Is.EqualTo(string.Format(formatWithFileBehavior)));

result = formatter.Format(formatWithCodeBehavior);
Assert.AreEqual(string.Format(formatWithCodeBehavior), result);
Assert.That(result, Is.EqualTo(string.Format(formatWithCodeBehavior)));
}

[Test]
Expand All @@ -37,7 +37,7 @@ public void AllSupportedCharacterLiteralsAsUnicode()
var formatter = Smart.CreateDefaultSmartFormat(new SmartSettings {Parser = new ParserSettings {ConvertCharacterStringLiterals = true}});

var result = formatter.Format(formatWithFileBehavior);
Assert.AreEqual(formatWithCodeBehavior, result);
Assert.That(result, Is.EqualTo(formatWithCodeBehavior));
}

[TestCase(@"Some text \u2022 with the value {0}", "Some text \u2022 with the value 123")]
Expand All @@ -46,7 +46,7 @@ public void AllSupportedCharacterLiteralsAsUnicode()
public void UnicodeEscapeSequenceIsParsed(string format, string expectedOutput)
{
var formatter = Smart.CreateDefaultSmartFormat(new SmartSettings {Parser = new ParserSettings {ConvertCharacterStringLiterals = true}});
Assert.AreEqual(expectedOutput, formatter.Format(format, 123));
Assert.That(formatter.Format(format, 123), Is.EqualTo(expectedOutput));
}

[TestCase(@"Some text {0} \uABCP", @"\uABCP")]
Expand All @@ -69,8 +69,8 @@ public void ConvertCharacterLiteralsToUnicodeWithListFormatter()
var items = new[] { "one", "two", "three" };
// Note the @ before the format string will switch off conversion of \n by the compiler
var result = smart.Format(@"{0:list:{}|\n|\nand }", new object[] { items });
Assert.AreEqual("one\ntwo\nand three", result);

Assert.That(result, Is.EqualTo("one\ntwo\nand three"));
}

[Test, Description("Illegal escape sequence should always throw")]
Expand Down
17 changes: 10 additions & 7 deletions src/SmartFormat.Tests/Core/NestingTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public void Nesting_can_access_root_via_number(string format, string expectedOut
{
var smart = Smart.CreateDefaultSmartFormat();
var actual = smart.Format(format, _data);
Assert.AreEqual(expectedOutput, actual);
Assert.That(actual, Is.EqualTo(expectedOutput));
}

[Test]
Expand All @@ -43,11 +43,14 @@ public void Nesting_CurrentScope_propertyName_outrules_OuterScope_propertyName()
Child = new {IdenticalName = "Name from Child", ChildValue = "Child value"}
};

// Access to outer scope, if no current scope variable is found
Assert.AreEqual(string.Format($"{nestedObject.ParentValue} - {nestedObject.Child.ChildValue}"), smart.Format("{Child:{ParentValue} - {Child.ChildValue}|}", nestedObject));
Assert.Multiple(() =>
{
// Access to outer scope, if no current scope variable is found
Assert.That(smart.Format("{Child:{ParentValue} - {Child.ChildValue}|}", nestedObject), Is.EqualTo(string.Format($"{nestedObject.ParentValue} - {nestedObject.Child.ChildValue}")));

// Access to current scope, although outer scope variable with same name exists
Assert.AreNotEqual(string.Format($"{nestedObject.IdenticalName} - {nestedObject.Child.IdenticalName}"), smart.Format("{Child:{IdenticalName} - {Child.IdenticalName}|}", nestedObject));
// Access to current scope, although outer scope variable with same name exists
Assert.That(smart.Format("{Child:{IdenticalName} - {Child.IdenticalName}|}", nestedObject), Is.Not.EqualTo(string.Format($"{nestedObject.IdenticalName} - {nestedObject.Child.IdenticalName}")));
});
}

[Test]
Expand All @@ -60,6 +63,6 @@ public void Nesting_can_access_outer_scopes_no_blanks(string format, string expe
// Removing the spaces from Nesting_can_access_outer_scopes requires alternative escaping of { and }!
var sf = Smart.CreateDefaultSmartFormat();
var actual = sf.Format(format, _data);
Assert.AreEqual(expectedOutput, actual);
Assert.That(actual, Is.EqualTo(expectedOutput));
}
}
}
6 changes: 3 additions & 3 deletions src/SmartFormat.Tests/Core/Output/StringOutputTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ public void Output_Of_Span()
{
var so = new StringOutput();
so.Write("text".AsSpan(), null!);
Assert.AreEqual("text", so.ToString());
Assert.That(so.ToString(), Is.EqualTo("text"));
}

[Test]
public void Output_Of_String()
{
var so = new StringOutput(16);
so.Write("text", null!);
Assert.AreEqual("text", so.ToString());
Assert.That(so.ToString(), Is.EqualTo("text"));
}

[Test]
Expand All @@ -30,6 +30,6 @@ public void Output_Of_ValueStringBuilder()
using var sb = SmartFormat.Utilities.ZStringBuilderExtensions.CreateZStringBuilder();
sb.Append("text");
so.Write(sb, null!);
Assert.AreEqual("text", so.ToString());
Assert.That(so.ToString(), Is.EqualTo("text"));
}
}
Loading