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

Рушкова Ольга #25

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
51 changes: 39 additions & 12 deletions Testing/Basic/Homework/1. ObjectComparison/ObjectComparison.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
using NUnit.Framework;
using System;
using System.Reflection;
using FluentAssertions;
using FluentAssertions.Equivalency;
using Homework._1._ObjectComparison;
using NUnit.Framework;
using NUnit.Framework.Internal;
using NUnit.Framework.Legacy;

namespace HomeExercise.Tasks.ObjectComparison;

public class ObjectComparison
{

[Test]
[Description("Проверка текущего царя")]
[Category("ToRefactor")]
Expand All @@ -15,17 +23,33 @@ public void CheckCurrentTsar()
new Person("Vasili III of Russia", 28, 170, 60, null));

// Перепишите код на использование Fluent Assertions.
ClassicAssert.AreEqual(actualTsar.Name, expectedTsar.Name);
ClassicAssert.AreEqual(actualTsar.Age, expectedTsar.Age);
ClassicAssert.AreEqual(actualTsar.Height, expectedTsar.Height);
ClassicAssert.AreEqual(actualTsar.Weight, expectedTsar.Weight);

ClassicAssert.AreEqual(expectedTsar.Parent!.Name, actualTsar.Parent!.Name);
ClassicAssert.AreEqual(expectedTsar.Parent.Age, actualTsar.Parent.Age);
ClassicAssert.AreEqual(expectedTsar.Parent.Height, actualTsar.Parent.Height);
ClassicAssert.AreEqual(expectedTsar.Parent.Parent, actualTsar.Parent.Parent);
actualTsar.Should()
.BeEquivalentTo(expectedTsar, options => options.Excluding(ctx => ComparePerson(ctx)));

Choose a reason for hiding this comment

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

В этом случае опять все ломается, если мы вводим поле PetId




//.Using<Person>(ctx => ctx.Subject
// .Should().BeEquivalentTo(ctx.Expectation, opt => opt.Excluding(x => x.Id))).WhenTypeIs<Person>());s

Choose a reason for hiding this comment

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

А это что?


/*
* Достоинства подхода по сравнению с CheckCurrentTsar_WithCustomEquality
* 1. В случае падения теста в сообщении прописывается место несовпадения, ожидаемый результат и полученный результат.
* 2. При добавлении в класс нового поля тест нужно будет изменять только в случае добавления особых проверок, то есть он лучше расширяем.
* 3. Проверки полей не блокируют друг друга, при несовпадении нескольких полей будет выведено отдельное сообщение для каждого.
* 4. Тест стал более читаемым
*/
}

private bool ComparePerson(IMemberInfo ctx)
{
var parentInfo = ctx.GetType()
?.GetField("member", BindingFlags.NonPublic | BindingFlags.Instance)
?.GetValue(ctx) as Field;

Choose a reason for hiding this comment

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

ctx.DeclaringType


return parentInfo?.ParentType == typeof(Person) && ctx.Path.EndsWith("Id");

Choose a reason for hiding this comment

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

ctx.Name == "Id"

}


[Test]
[Description("Альтернативное решение. Какие у него недостатки?")]
public void CheckCurrentTsar_WithCustomEquality()
Expand All @@ -34,7 +58,10 @@ public void CheckCurrentTsar_WithCustomEquality()
var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60, null));

// Какие недостатки у такого подхода?
// Какие недостатки у такого подхода?
// 1. Не очевидно, где произошло несовпадение в случае падения теста.
// 2. При добавлении в класс нового поля придётся изменять метод AreEqual
// 3. Проверки полей блокируют друг друга. Например, при несовпадении имён другие поля проверяться уже не будут.
ClassicAssert.True(AreEqual(actualTsar, expectedTsar));
}

Expand All @@ -49,4 +76,4 @@ private bool AreEqual(Person? actual, Person? expected)
&& actual.Weight == expected.Weight
&& AreEqual(actual.Parent, expected.Parent);
}
}
}
135 changes: 114 additions & 21 deletions Testing/Basic/Homework/2. NumberValidator/NumberValidatorTests.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,124 @@

using FluentAssertions;
using FluentAssertions.Execution;
using NUnit.Framework;
using NUnit.Framework.Legacy;
using NUnit.Framework.Internal;

namespace HomeExercise.Tasks.NumberValidator;

[TestFixture]
public class NumberValidatorTests
{
[Test]
public void Test()
{
Assert.Throws<ArgumentException>(() => new NumberValidator(-1, 2, true));
Assert.DoesNotThrow(() => new NumberValidator(1, 0, true));
Assert.Throws<ArgumentException>(() => new NumberValidator(-1, 2, false));
Assert.DoesNotThrow(() => new NumberValidator(1, 0, true));

ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0"));
ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0"));
ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0"));
ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("00.00"));
ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("-0.00"));
ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0"));
ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("+0.00"));
ClassicAssert.IsTrue(new NumberValidator(4, 2, true).IsValidNumber("+1.23"));
ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("+1.23"));
ClassicAssert.IsFalse(new NumberValidator(17, 2, true).IsValidNumber("0.000"));
ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("-1.23"));
ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("a.sd"));
public void NumberValidator_NotThrow_WhenScaleIsZero()
{
Action act = () => new NumberValidator(1, 0, true);

act
.Should().NotThrow();
}

[TestCase(-1, 2, TestName = "NumberValidator_Throw_WhenPrecisionIsNegative")]
[TestCase(0, 2, TestName = " NumberValidator_Throw_WhenPrecisionIsZero")]
[TestCase(4, 4, TestName = "NumberValidator_Throw_WhenPrecisionEqualsScale")]
[TestCase(10, -2, TestName = "NumberValidator_Throw_WhenScaleIsNegative")]
[TestCase(1, 2, TestName = "NumberValidator_Throw_WhenPrecisionLessThanScale")]
public void NumberValidator_Throw(int precision, int scale)
{
Action act = () => new NumberValidator(precision, scale);

act
.Should().Throw<ArgumentException>();
}
[TestCase("a.sd")]
[TestCase("sad")]
[TestCase("897,ава")]
[TestCase("987.3948*")]
[TestCase("?.00")]
[TestCase("а.сд")]
[TestCase("VI,II")]
[TestCase("230!450.335")]
[TestCase("⚠️📲64.56❤️")]
[TestCase("我們.我們")]
[TestCase("مان.ود")]
[TestCase("^879%56(")]
public void IsValidNumber_ReturnsFalse_WhenValueContainsNonDigitSymbols(string value)
{
IsValidNumber_ReturnsFalse(value, 12, 7);
}


[TestCase("0.9845435,9080")]
[TestCase("+0,,908")]
[TestCase("-0.00.0")]
[TestCase("0,.000")]
[TestCase("+0,00.0")]
[TestCase("0.9845435,9080")]
[TestCase("+0,,908")]
[TestCase("-0.00.0")]
[TestCase("0,.000")]
[TestCase("+0,00.0")]
public void IsValidNumber_ReturnsFalse_WhenValueHaveFewSeparators(string value)
{
IsValidNumber_ReturnsFalse(value, 17, 16);
}

[TestCase("+-0.466")]
[TestCase("-+0.000")]
[TestCase("---0.000")]
[TestCase("0.000+-")]
[TestCase("++0.000")]
[TestCase("+")]
[TestCase("+.0-00")]
public void IsValidNumber_ReturnsFalse_WhenValueHaveFewSigns(string value)
{
IsValidNumber_ReturnsFalse(value, 17, 16);
}

[TestCase("^")]
[TestCase(":")]
[TestCase(";")]
[TestCase("/")]
[TestCase("!")]
[TestCase("=")]
[TestCase("-")]
[TestCase("+")]
public void IsValidNumber_ReturnsFalse_WhenSeparatorNotCommaOrDot(string separator)
{
IsValidNumber_ReturnsFalse($"0{separator}0", 3, 2, true);
}

[TestCase("0.0", 17, 2, true, TestName = "IsValidNumber_ReturnsTrue_WhenPrecisionAndScaleMoreThanValueIntAndFracParts")]
[TestCase("0,0", 3, 2, true, TestName = "IsValidNumber_ReturnsTrue_WhenSeparatorIsComma")]
[TestCase("0", 17, 2, true, TestName = " IsValidNumber_ReturnsTrue_WhenValueIsIntegerAndHasLessDigitsThanPrecision")]
[TestCase("12345", 5, 2, true, TestName = "IsValidNumber_ReturnsTrue_WhenValueIsIntegerAndDigitCountEqualsPrecision")]
[TestCase("+1.23", 4, 2, true, TestName = "IsValidNumber_ReturnsTrue_WhenLengthIntPartAndFracPartEqualToPrecision_IncludingNumberSign")]
[TestCase("-1.23", 5, 2, TestName = "IsValidNumber_ReturnsTrue_WhenValueIsNegativeAndValidatorNotOnlyPositive")]

Choose a reason for hiding this comment

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

IsValidNumber_ReturnsTrue_ можно даже убрать. У тебя будет глобально название IsValidNumber_ReturnsTrue, а дочернее название теста, например, WhenPrecisionAndScaleMoreThanValueIntAndFracParts

У меня в райдере это в виде дерева отображается.

Copy link
Author

Choose a reason for hiding this comment

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

+

public void IsValidNumber_ReturnsTrue(string value, int precision, int scale, bool onlyPositive=false)
{
var validator = new NumberValidator(precision, scale, onlyPositive);

var isValid = validator.IsValidNumber(value);

isValid
.Should().BeTrue();
}

[TestCase("+1.23", 3, 2, true, TestName = "IsValidNumber_ReturnsFalse_WhenNumberLengthMoreThanPrecision_IncludingSignForPositiveNumber")]
[TestCase("-1.23", 3, 2, true, TestName = "IsValidNumber_ReturnsFalse_WhenNumberLengthMoreThanPrecision_IncludingSignForNegativeNumber")]
[TestCase("0.000", 17, 2, true, TestName = "IsValidNumber_ReturnsFalse_WhenValueFracPartMoreThanScale")]
[TestCase("00.00", 3, 2, true, TestName = "IsValidNumber_ReturnsFalse_WhenValueSymbolsCountMoreThanPrecision")]
[TestCase("", 3, 2, true, TestName = "IsValidNumber_ReturnsFalse_WhenValueIsEmptyString")]
[TestCase("34290.", 17, 2, true, TestName = "IsValidNumber_ReturnsFalse_WhenValueHaveSeparatorWithoutFracPart")]
[TestCase(null, 3, 2, TestName = "IsValidNumber_ReturnsFalse_WhenValueIsNull")]
[TestCase("-0.00", 4, 2, true, TestName = "IsValidNumber_ReturnsFalse_WhenValueNegative_WithOnlyPositiveNumberValidator")]
[TestCase(".000", 6, 4, true, TestName = "IsValidNumber_ReturnsFalse_WhenValueStartsWithSeparator")]
public void IsValidNumber_ReturnsFalse(string value, int precision, int scale, bool onlyPositive = false)
{
var validator = new NumberValidator(precision, scale, onlyPositive);

var isValid = validator.IsValidNumber(value);

isValid
.Should().BeFalse();
}
}