Skip to content

Голубев Владимир#54

Open
tazik23 wants to merge 27 commits intokontur-courses:masterfrom
tazik23:homework/tests-refactoring
Open

Голубев Владимир#54
tazik23 wants to merge 27 commits intokontur-courses:masterfrom
tazik23:homework/tests-refactoring

Conversation

@tazik23
Copy link

@tazik23 tazik23 commented Oct 28, 2025

@lev_shisterov

using NUnit.Framework;
using NUnit.Framework.Legacy;

namespace HomeExercise.Tasks.NumberValidator;

Choose a reason for hiding this comment

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

Не знаю, говорили ли вам, было бы круто вынести тесты в отдельный проект, чтобы код тестов не попадал вместе с библиотекой на продуктовую площадку.

Choose a reason for hiding this comment

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

В код самого валидатора (NumberValidator) тоже можно заглянуть, может найдется что не так.

ClassicAssert.AreEqual(expectedTsar.Parent.Parent, actualTsar.Parent.Parent);
actualTsar.Should().BeEquivalentTo(expectedTsar, o => o
.Excluding(p => p.Id)
.Excluding(p => p.Parent.Id));

Choose a reason for hiding this comment

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

Как быть, если там окажется целая династия, 5-10-20 царей?
Предлагаю прям попробовать.
Еще можно подумать: какие еще вариации на эту тему могут попасться?

Copy link
Author

Choose a reason for hiding this comment

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

Да, проверил, тесты не падали, когда условный дед различался
И еще проблема, когда циклические ссылки есть и предков больше 10, т.к. по умолчанию глубина рекурсии в FLuentAssertions 10
Поправил

[TestCase("++12.34", TestName = "MultipleSigns")]
[TestCase("12.", TestName = "FractionPartIsMissing")]
[TestCase(".34", TestName = "IntegerPartIsMissing")]
public void IsValidNumber_WithInvalidStringFormat_ShouldReturnFalse(string value)

Choose a reason for hiding this comment

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

Можно добавить смесь букв и цифр.

{
var act = () => new NumberValidator(precision, scale);

act.Should().Throw<ArgumentException>();

Choose a reason for hiding this comment

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

Здесь можно было бы проверить что вылетает именно то исключение, которые мы ожидаем, а не какое-то другое.

[Description("Проверка текущего царя")]
[Category("ToRefactor")]
public void CheckCurrentTsar()
public void CheckTsarEquality_WithValidTsar_ShouldNotThrow()

Choose a reason for hiding this comment

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

Раз не получается в отдельное решение, давай тесты хотя бы в отдельный класс вынесем.

}

private bool AreEqual(Person? actual, Person? expected)
private static Person CreateTsarWithWrongAncestor(int generations, int wrongAncestorLevel)

Choose a reason for hiding this comment

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

Посмотри, может для этого метода есть более подходящее место.

Copy link
Author

Choose a reason for hiding this comment

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

вынес в TsarRegistry

actualTsar.Should().BeEquivalentTo(expectedTsar, o => o
.ExcludingMembersNamed(nameof(Person.Id))
.IgnoringCyclicReferences()
.AllowingInfiniteRecursion());

Choose a reason for hiding this comment

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

Круто что ты догадался про цикличность!
Как быть если у меня для объектов Person указано свойство типа class City { int Id; string Name; } и я бы хотел чтобы сравнение не прошло, если идентификатор города не совпадает?

Copy link
Author

Choose a reason for hiding this comment

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

ага, поправил, теперь проверяю что type именно Person, добавил тест на проверку с City

* 2.) Явно указываем, какие поля мы исключаем из проверки
* 3.) При добавлении новых полей в Person нужно провести минимальный рефакторинг(исключить из проверки
* или вообще ничего не трогать)
* 4.) Падаем с адекватной информацией об ошибке, в отличие от просто непонятного False

Choose a reason for hiding this comment

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

Напишем тут что-нибудь про рекурсию?

if (scale < 0 || scale >= precision)
throw new ArgumentException("precision must be a non-negative number less or equal than precision");
throw new ArgumentException("scale must be a non-negative number less than precision");
numberRegex = new Regex(@"^([+-]?)(\d+)([.,](\d+))?$", RegexOptions.IgnoreCase);

Choose a reason for hiding this comment

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

Посмотри про RegexOptions.Compiled и, возможно, можно инстанс переиспользовать для всех NumberValidator?

Copy link
Author

Choose a reason for hiding this comment

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

сделал static полем

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants