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

Шевырин Никита #14

Open
wants to merge 6 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 .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
bin/
obj/
.vs/
shpora-testing.sln
2 changes: 2 additions & 0 deletions Testing/Basic/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.idea/
Folder.DotSettings.user
27 changes: 16 additions & 11 deletions Testing/Basic/Homework/1. ObjectComparison/ObjectComparison.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using NUnit.Framework;
using FluentAssertions;
using NUnit.Framework;
using NUnit.Framework.Legacy;

namespace HomeExercise.Tasks.ObjectComparison;
Expand All @@ -14,16 +15,19 @@ public void CheckCurrentTsar()
var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,
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
.AllowingInfiniteRecursion()

This comment was marked as resolved.

.Excluding(x => x.Path.EndsWith("Id")));

This comment was marked as resolved.

Copy link
Author

Choose a reason for hiding this comment

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

Я написал так потому, что если написать .Excluding(x=> x.Id), то тест падает с сообщением Expected field actualTsar.Parent.Id to be 2, but found 0. То есть он сравнивает поля Id у объектов Person, находящихся в поле Parent. Но как я понял мы хотим этого избежать

/*
* Это решение лучше так как оно более расширяемо:
* Нет необходимости прописывать сравнения для каждого
* свойства класса Person. С помощью второго параметра
* метода BeEquivalentTo() мы исключаем из сравнения
* ненужные свойства (Id) не только для actualTsar,
* но и для его Parent (в том числе и для последующих
* Parent в этой рекурсивной структуре)
*/
}

[Test]
Expand All @@ -35,6 +39,7 @@ public void CheckCurrentTsar_WithCustomEquality()
new Person("Vasili III of Russia", 28, 170, 60, null));

// Какие недостатки у такого подхода?
// нужно прописывать отдельное сравнение для каждого нового свойства

This comment was marked as resolved.

ClassicAssert.True(AreEqual(actualTsar, expectedTsar));
}

Expand Down
224 changes: 204 additions & 20 deletions Testing/Basic/Homework/2. NumberValidator/NumberValidatorTests.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,215 @@

using System.Collections;
using FluentAssertions;
using FluentAssertions.Execution;
using NUnit.Framework;
using NUnit.Framework.Legacy;

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"));
[Description("Проверяем, что конструктор NumberValidator не кидает исключения если входные параметры" +
"заданы верно: precision > 0 и 0 <= scale < precision")]
[TestCase(1, 0, true)]

Choose a reason for hiding this comment

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

Давай добавим Description или название теста, а то просто по входным данным может быть непонятно, что мы тестируем

[TestCase(1, 0, false)]
[TestCase(12, 5, true)]
[TestCase(12, 5, false)]
public void NumberValidator_DoesNotThrowOnCreation_WithCorrectArguments(
int precision,
int scale,
bool onlyPositive)
{
new Action(() => new NumberValidator(precision, scale, onlyPositive))
.Should()
.NotThrow();
}

[Test]
[Description("Проверяем, что конструктор NumberValidator кидает ArgumentException, " +
"если аргумент scale имеет значение больше или равное precision")]
[TestCase(1, 2, false)]
[TestCase(1, 2, true)]
[TestCase(7, 9, true)]
[TestCase(7, 9, false)]
[TestCase(7, 7, true)]
[TestCase(7, 7, false)]
public void NumberValidator_ThrowsOnCreation_WithScale_BeingMoreOrEqualTo_Precision(
int precision,
int scale,
bool onlyPositive)
{
new Action(() => new NumberValidator(precision, scale, onlyPositive))
.Should()
.Throw<ArgumentException>()
.WithMessage("precision must be a non-negative number less or equal than precision");
}

[Test]
[Description("Проверяем, что конструктор NumberValidator кидает ArgumentException, " +
"если аргумент precision имеет значение меньше или равное нулю")]
[TestCase(-1, 2, false)]
[TestCase(-1, 2, true)]
[TestCase(0, 0, false)]
[TestCase(0, 0, true)]
public void NumberValidator_ThrowsOnCreation_WithPrecision_BeingLessOrEqualTo_Zero(
int precision,
int scale,
bool onlyPositive)
{
new Action(() => new NumberValidator(precision, scale, onlyPositive))
.Should()
.Throw<ArgumentException>()
.WithMessage("precision must be a positive number");
}

[Test]

This comment was marked as resolved.

[Description("Проверяем, что конструктор NumberValidator кидает ArgumentException, " +
"если аргумент scale имеет значение меньше нуля")]
[TestCase(1, -2, true)]
[TestCase(1, -2, false)]
[TestCase(7, -1, true)]
[TestCase(7, -1, false)]
public void NumberValidator_ThrowsOnCreation_WithScale_BeingLessThan_Zero(
int precision,
int scale,
bool onlyPositive)
{
new Action(() => new NumberValidator(precision, scale, onlyPositive))
.Should()
.Throw<ArgumentException>()
.WithMessage("precision must be a non-negative number less or equal than precision");
}

[Test]
[Description("Проверяем, что метод IsValidNumber возвращает: " +
"1) true для корректных чисел если они положительны (параметр onlyPositive == true)" +
"2) false для некорректных и любых отрицательных чисел (параметр onlyPositive == true)" +
"3) true для корректных чисел с любым знаком (параметр onlyPositive == false)" +
"4) false для некорректных чисел с любым знаком (параметр onlyPositive == false)")]
[TestCaseSource(nameof(OnlyPositiveValidNumberCases))]
[TestCaseSource(nameof(OnlyPositiveInvalidNumberCases))]
[TestCaseSource(nameof(GeneralValidNumberCases))]
[TestCaseSource(nameof(GeneralInvalidNumberCases))]
public void IsValidNumber_Returns_ExpectedResult(
int precision,
int scale,
bool onlyPositive,
string number,
bool expectedResult)
{
new NumberValidator(precision, scale, onlyPositive)
.IsValidNumber(number)
.Should()
.Be(expectedResult);
}

public static object[] OnlyPositiveValidNumberCases()
{
var onlyPositiveCasesWithScaleOfZero = new[]
{
"1", "+0", "01", "00"
}.Select(number => new object[]
{
2, 0, true, number, true
});

var onlyPositiveCases = new[]
{
"0.0", "0,0", "0", "1.23", "+0.00", "01.10", "+0,00", "1,0"

This comment was marked as resolved.

}.Select(number => new object[]
{
4, 2, true, number, true
});

return onlyPositiveCasesWithScaleOfZero
.Concat(onlyPositiveCases)
.ToArray<object>();
}

public static object[] OnlyPositiveInvalidNumberCases()
{
var numbers = new[]
{
"000.0", "-0.00", "+0,00", "+1.23", "-1,23", "a.sd",
"0.000", "0.", ",00", "", null, " ", " ", "-", "+",
" 1.5", "0,2 ", "0 . 11"
};

var onlyPositiveCasesWithScaleOfZero =
new[]
{
"-1", "+000", "0.0", "3.14", "-0.1"
}
.Concat(numbers)
.Select(number => new object[]
{
3, 0, true, number, false
});

var onlyPositiveCases =
numbers.Select(number => new object[]
{
3, 2, true, number, false
});

return onlyPositiveCasesWithScaleOfZero
.Concat(onlyPositiveCases)
.ToArray<object>();
}

public static object[] GeneralValidNumberCases()
{
var onlyPositiveCasesWithScaleOfZero = new[]
{
"1", "+0", "01", "00", "-0", "+2", "-2"
}.Select(number => new object[]
{
2, 0, false, number, true
});

var onlyPositiveCases = new[]
{
"0.0", "0", "-0", "-1.23", "+0.00", "01.10", "-1,10", "+10.0"
}.Select(number => new object[]
{
4, 2, false, number, true
});

return onlyPositiveCasesWithScaleOfZero
.Concat(onlyPositiveCases)
.ToArray<object>();
}

public static object[] GeneralInvalidNumberCases()
{
var numbers = new[]
{
"000.0", "-0.00", "+0,00", "+1.23", "-1,23", "a.sd",
"0.000", "0.", ",00", "", null, " ", " ", "-,0",
"+0,", " 1.5", "0,2 ", "0 . 11"
};

var onlyPositiveCasesWithScaleOfZero =
new[]
{
"-1.0", "+000", "0.0", "3.14", "-0.1", "1111"
}
.Concat(numbers)
.Select(number => new object[]
{
3, 0, false, number, false
});

var onlyPositiveCases =
numbers.Select(number => new object[]
{
3, 2, false, number, false
});

return onlyPositiveCasesWithScaleOfZero
.Concat(onlyPositiveCases)
.ToArray<object>();
}
}