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

Alexander Andronov #203

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
1 change: 1 addition & 0 deletions ObjectPrinting.Tests/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using NUnit.Framework;
25 changes: 25 additions & 0 deletions ObjectPrinting.Tests/ObjectPrinting.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.4.2" />
<PackageReference Include="NUnit.Analyzers" Version="3.6.1" />
<PackageReference Include="coverlet.collector" Version="3.2.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\ObjectPrinting\ObjectPrinting.csproj" />
</ItemGroup>

</Project>
14 changes: 14 additions & 0 deletions ObjectPrinting.Tests/Tests/Node.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObjectPrinting.Tests.Tests
{
public class Node
{
public int Value { get; set; }
public Node Next { get; set; }
}
}
210 changes: 210 additions & 0 deletions ObjectPrinting.Tests/Tests/ObjectPrinterAcceptanceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
using FluentAssertions;
using FluentAssertions.Primitives;
using NUnit.Framework;
using System.Globalization;
using System.Reflection;

namespace ObjectPrinting.Tests.Tests
{
[TestFixture]
public class ObjectPrinterAcceptanceTests
{
private Person person;
private PrintingConfig<Person> personPrinter;

[SetUp]
public void SetUp()
{
person = new Person()
{
Id = Guid.NewGuid(),
Name = "John Doe",
Height = 175.5
};
personPrinter = ObjectPrinter.For<Person>();
}

[Test]
public void PrintListOfInts_ReturnCorrectString()
{
var list = new List<int>() { 1, 2, 3 };
var printer = ObjectPrinter.For<List<int>>();

var actual = printer.PrintToString(list);

Assert.AreEqual("[1,2,3]", actual);
}

[Test]
public void PrintArrayOfInts_ReturnCorrectString()
{
var list = new int[] { 1, 2, 3 };
var printer = ObjectPrinter.For<int[]>();

var actual = printer.PrintToString(list);

Assert.AreEqual("[1,2,3]", actual);
}

[Test]
public void PrintListDictOfStrings_ReturnCorrectString()
{
var dict = new Dictionary<int, string>
{
{ 1, "a" },
{ 2, "b" }
};
var printer = ObjectPrinter.For<Dictionary<int, string>>();

var actual = printer.PrintToString(dict);

Assert.AreEqual("{1 : a,2 : b}", actual);
}

[Test]
public void ExcludeProperty_Success()
{
personPrinter.Excluding(o => o.Height);

var actual = personPrinter.PrintToString(person);

StringAssert.DoesNotContain("Height", actual);
}

[Test]
public void ExcludeType_Success()
{
personPrinter.Excluding<Guid>();

var actual = personPrinter.PrintToString(person);

StringAssert.DoesNotContain("Id", actual);
}

[Test]
public void PrintForTypes_Success()
{
personPrinter.Print<string>().Using(o => "ABCDEF");

var actual = personPrinter.PrintToString(person);

StringAssert.Contains("ABCDEF", actual);
}

[Test]
public void PrintForProperties_Success()
{
personPrinter.Print(o => o.Name).Using(o => "ABCDEF");

var actual = personPrinter.PrintToString(person);

StringAssert.Contains("ABCDEF", actual);
}

[Test]
public void TruncateString_Success()
{
personPrinter.Print<string>().TruncateLength(6);

var actual = personPrinter.PrintToString(person);

StringAssert.DoesNotContain("John Do", actual);
StringAssert.Contains("John D", actual);
}

[Test]
public void SetMaxStringLengthViaConfigure_Success()
{
personPrinter.Configure(opt => opt.MaxStringLength = 6);

var actual = personPrinter.PrintToString(person);

StringAssert.DoesNotContain("John Do", actual);
StringAssert.Contains("John D", actual);
}

[TestCase("ru-RU")]
[TestCase("en-US")]
[TestCase("fr-FR")]
public void SetCulture_ShouldApplyCulture(string code)
{
var culture = new CultureInfo(code);
personPrinter.Print<double>()
.SetCulture(culture);
var should = person.Height.ToString(culture);


var actual = personPrinter.PrintToString(person);


StringAssert.Contains(should, actual);
}

[TestCase("ru-RU")]
[TestCase("en-US")]
[TestCase("fr-FR")]
public void SetCultureViaConfigure_ShouldApplyCulture(string code)
{
var culture = new CultureInfo(code);
personPrinter.Configure(opt => opt.CultureInfo = culture);
var should = person.Height.ToString(culture);


var actual = personPrinter.PrintToString(person);


StringAssert.Contains(should, actual);
}

[Test]
public void CyclicReference_DoesnThrowStackOverflow()
{
var node1 = new Node() { Value = 1 };
var node2 = new Node() { Value = 2 };
node1.Next = node2;
node2.Next = node1;
var printer = ObjectPrinter.For<Node>();

Console.WriteLine(printer.PrintToString(node1));
Assert.DoesNotThrow(() => printer.PrintToString(node1));
}

[Test]
public void Demo()
{
var person = new Person { Name = "Alex", Age = 19, Height = 172.1,
Father = new Parent() { Name = "Bob Robinson", Age = 54, Height = 182.2},
Mother = new Parent() { Name = "Sara Robinson", Age = 50, Height = 185.4}
};

var printer = ObjectPrinter.For<Person>();
//1. Исключить из сериализации свойства определенного типа
//2. Указать альтернативный способ сериализации для определенного типа
//3. Для числовых типов указать культуру
//4. Настроить сериализацию конкретного свойства
//5. Настроить обрезание строковых свойств (метод должен быть виден только для строковых свойств)
//6. Исключить из сериализации конкретного свойства

printer.Excluding(o => o.Id)
.Print(o => o.Height)
.Using(h => $"{h} сантиметров")
.Print(o => o.Name)
.TruncateLength(10)
.Configure(opts =>
{
opts.MaxStringLength = 100;
opts.CultureInfo = CultureInfo.InvariantCulture;
});



string s1 = printer.PrintToString(person);

Console.WriteLine(s1);

s1.Should().Be(s1);
//7. Синтаксический сахар в виде метода расширения, сериализующего по-умолчанию
//8. ...с конфигурированием
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
using System;

namespace ObjectPrinting.Solved.Tests
namespace ObjectPrinting.Tests.Tests
{
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public double Height { get; set; }
public int Age { get; set; }
public Parent Father { get; set; }
public Parent Mother { get; set; }
}

public class Parent : Person
{

}
}
22 changes: 22 additions & 0 deletions ObjectPrinting/Configuration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Globalization;

namespace ObjectPrinting
{
public class Configuration
{
public List<Predicate> ToExclude;
public List<(Predicate predicate, Func<object, string> serializer)> Serializers;
public Options Options;

public Configuration
(List<Predicate> toExclude = null,
List<(Predicate predicate, Func<object, string> serializer)> serializers =null)
{
ToExclude = toExclude ?? new List<Predicate>();
Serializers = serializers ?? new List<(Predicate predicate, Func<object, string> serializer)>();
Options = new Options();
}
}
}
5 changes: 5 additions & 0 deletions ObjectPrinting/ObjectPrinter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,10 @@ public static PrintingConfig<T> For<T>()
{
return new PrintingConfig<T>();
}

public static string Print<T>(T obj)
{
return new PrintingConfig<T>().PrintToString(obj);
}
}
}
5 changes: 0 additions & 5 deletions ObjectPrinting/ObjectPrinting.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,4 @@
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
</ItemGroup>

</Project>
14 changes: 14 additions & 0 deletions ObjectPrinting/Options.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace ObjectPrinting
{
public class Options

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Рекомендую всегда и все свои классы делать sealed (можно даже в шаблоне к классу это добавить). В некоторых ситуациях это микроскопически улучшает производительность, но что более важно - напоминает более тщательно продумывать иерархию наследования
  • Поля в подобных классах обычно делают пропами. Это поможет закрыть следующую рекомендацию - параметры желательно ограничить для редактирования. В идеале они должны быть init-only. Это даст хоть какую-то гарантию где-то в неожиданном месте не произойдет мутация и не внесет суету в поведение. Можно заморочиться и ввести еще и интерфейс, с аналогичными полями но только getterами, тогда у тебя будет абсолютная иммутабельность и полиморфность

{
public int MaxStringLength = -1;
public CultureInfo CultureInfo = CultureInfo.InvariantCulture;
public int MaxRecursionDepth = 10;
}
}
41 changes: 0 additions & 41 deletions ObjectPrinting/PrintingConfig.cs

This file was deleted.

Loading