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

Бабинцев Григорий #21

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
25 changes: 25 additions & 0 deletions Testing/Basic/Basic.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35327.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basic", "Basic.csproj", "{ECC863AA-4C3E-4E5C-A2D0-459A2A1D33A3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{ECC863AA-4C3E-4E5C-A2D0-459A2A1D33A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ECC863AA-4C3E-4E5C-A2D0-459A2A1D33A3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ECC863AA-4C3E-4E5C-A2D0-459A2A1D33A3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ECC863AA-4C3E-4E5C-A2D0-459A2A1D33A3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2B8F6D26-176B-4CA4-8C5B-A15FA83E5325}
EndGlobalSection
EndGlobal
40 changes: 25 additions & 15 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 @@ -12,33 +13,42 @@ public void CheckCurrentTsar()
var actualTsar = TsarRegistry.GetCurrentTsar();

var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60, null));
new Person("Vasili III of Russia", 28, 170, 60,
new Person("Ivan III", 65, 170, 80, 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(p => p.Path.EndsWith("Id")));
}
/*
* Преимущества подхода:
* 1) Хорошая информативность: при непрохождении теста ясно показывается, какие поля не совпали.
* 2) Хорошая расширяемость: при добавлении или удалении полей в классе, нужно внести минимум изменений в тесте.
* 3) Хорошая читаемость: из-за меньшего объема кода и понятного названия методов улучшается читаемость кода.
*/

[Test]
[Test]

Choose a reason for hiding this comment

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

Совет на будущее: хорошая привычка пересматривать изменения перед коммитом или пушем, чтобы ненужные изменения не попадали в общий репозиторий. Здесь сыграли злую шутку табы и пробелы, решается просто настройкой IDE

[Description("Альтернативное решение. Какие у него недостатки?")]
public void CheckCurrentTsar_WithCustomEquality()
{
var actualTsar = TsarRegistry.GetCurrentTsar();
var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60, null));
new Person("Vasili III of Russia", 28, 170, 60,
new Person("Ivan III", 65, 170, 80, null)));

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

private bool AreEqual(Person? actual, Person? expected)
private bool AreEqual(Person? actual, Person? expected)
{
if (actual == expected) return true;
if (actual == null || expected == null) return false;
Expand Down
9 changes: 5 additions & 4 deletions Testing/Basic/Homework/1. ObjectComparison/TsarRegistry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ public class TsarRegistry
{
public static Person GetCurrentTsar()
{
return new Person(
"Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60, null));
}
return new Person("Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60,
new Person("Ivan III", 65, 170, 80, null)));

}
}
90 changes: 67 additions & 23 deletions Testing/Basic/Homework/2. NumberValidator/NumberValidatorTests.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,75 @@

using FluentAssertions;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using NUnit.Framework.Legacy;
using System.Collections;

namespace HomeExercise.Tasks.NumberValidator;



[TestFixture]
public class NumberValidatorTests
public partial 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"));
}

[TestCase(17, 1, true, "0.0", TestName = "Number with point separator")]
[TestCase(17, 1, true, "0,0", TestName = "Number with comma separator")]
[TestCase(17, 2, true, "0", TestName = "Number without fractionl part")]
[TestCase(4, 1, true, "1234", TestName = "Number length equals to precision")]
[TestCase(17, 1, true, "+1,0", TestName = "Positive number with comma")]
[TestCase(4, 1, true, "+123", TestName = "Positive number length with equals to precision")]
[TestCase(4, 1, true, "+12.3", TestName = "Positive number length with fractionl part equals to precision")]
[TestCase(5, 3, true, "+1.000", TestName = "Positive number length with fractional part equals to precision")]
[TestCase(17, 1, false, "-1,0", TestName = "Negative number with comma")]
[TestCase(4, 1, false, "-123", TestName = "Negative number length with plus equals to precision")]
[TestCase(4, 1, false, "-12.3", TestName = "Negative number length with frctionl part equals to precision")]
[TestCase(5, 3, false, "-1.000", TestName = "Negative number length with fractional part and plus equals to precision")]

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

var result = validator.IsValidNumber(value);

result.Should().BeTrue();
}


[TestCase(3, 2, true, "00.00", TestName = "Number length with fractionl part more than precision")]
[TestCase(3, 2, true, "-0.0", TestName = "Negative number length with fractionl part more than precision")]

Choose a reason for hiding this comment

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

А этот тест проверяет не то, что указано в описании. Но сам тест хороший

[TestCase(3, 2, true, "+0.00", TestName = "Positive number length with fractionl part more than precision")]
[TestCase(3, 2, true, "a.sd", TestName = "Number consists letters")]
[TestCase(17, 2, true, "0.000", TestName = "Length number's frationl part more thn scale")]
[TestCase(3, 2, true, "", TestName = "Number is empty string")]
[TestCase(3, 2, true, null, TestName = "Number is null")]
[TestCase(4, 2, false, "10*00", TestName = "Number with invalid separator")]
[TestCase(4, 1, false, "1.0.0", TestName = "Number with more than one separator")]
public void IsValidNumber_Shoud_BeFalse_WhenArgsBad(int precision, int scale, bool onlyPositive, string value)
{
var validator = new NumberValidator(precision, scale, onlyPositive);

var result = validator.IsValidNumber(value);

result.Should().BeFalse();
}


[TestCase(-1, 2, TestName = "Negative precision")]
[TestCase(1, -2, TestName = "Negative scale")]
[TestCase(1, 2, TestName = "Precision less than scale")]
[TestCase(1, 1, TestName = "Precision equals with scale")]
public void Should_Throw_ArgumentException(int precision, int scale)
{
var action = () => new NumberValidator(precision, scale);
action.Should().Throw<ArgumentException>();
}


[TestCase(1, 0, TestName = "Zero scale")]
[TestCase(2, 1, TestName = "Precision more than scale")]
public void Should_NotThrow_AnyException(int precision, int scale)
{
var action = () => new NumberValidator(precision, scale);
action.Should().NotThrow();
}
}