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

Вильданов Савелий #241

Open
wants to merge 39 commits into
base: master
Choose a base branch
from

Conversation

Saveliy21
Copy link

@Saveliy21 Saveliy21 changed the title Home work Вильданов Савелий Nov 13, 2024
public Rectangle PutNextRectangle(Size rectangleSize)
{
Rectangle rectangle;
if (rectangleSize.Width < 0 || rectangleSize.Height < 0)

Choose a reason for hiding this comment

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

А есть ли смысл работать с нулевой шириной или высотой?

angle = 0;
}

public Point getNextPointOnSpiral()

Choose a reason for hiding this comment

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

Публичный метод с маленькой буквы

Comment on lines 8 to 9
private List<Rectangle> rectangles;
private Spiral spiral;

Choose a reason for hiding this comment

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

Эти поля тоже можно readonly сделать

[Test]
public void PutNextRectangle_ShouldAddNewRectangle()
{
CircularCloudLayouter circularCloudLayouter = new CircularCloudLayouter(new Point());

Choose a reason for hiding this comment

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

Создание этого класса происходит во всех тестах этого класса - можно вынести в SetUp, как обязательное действие перед прогоном теста. Плюсом будет то, что код самих тестов станет читать попроще

Comment on lines 37 to 39
CircularCloudLayouter circularCloudLayouter = new CircularCloudLayouter(new Point());
circularCloudLayouter.PutNextRectangle(new Size(2, 2));
circularCloudLayouter.GetRectangles().Should().Contain(new Rectangle(-1, -1, 2, 2));

Choose a reason for hiding this comment

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

По выполняемым в тесте действиям этот тест идентичен предыдущему, а значит и проверку из этого теста можно включить в предыдущий

}

[Test]
public void PutNextRectangle_ShouldHaveCorrectSize()

Choose a reason for hiding this comment

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

Из названия теста не совсем понятно, Size чего будет проверяться в тесте - размещенного прямоугольника или коллекции с размещенными прямоугольниками

public class CircularCloudLayotherTest
{
[TestCase(-2, 3, TestName = "Negative width")]
[TestCase(-2, 3, TestName = "Negative height")]

Choose a reason for hiding this comment

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

В Negative height тесте высота положительная)

Comment on lines 9 to 10
[Test]
public void getNextPointOnSpiral_ShouldReturnNextPointOnSpiral()

Choose a reason for hiding this comment

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

Давай тест на несколько размещаемых точек ещё напишем


namespace TagsCloudVisualization.TagsCloudVisualizationTests;

public class CircularCloudLayotherTest

Choose a reason for hiding this comment

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

Было бы круто ещё написать тест на вставку ооооочень большого количества прямоугольников, проверим, что он отработает за некоторое вменяемое время

Проверок внутри не нужно будет, у Nunit есть атрибут, который завершит тест, если тот не уложится в заданное время

Choose a reason for hiding this comment

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

Хорошей практикой считается разделять тесты и основной код на отдельные проекты, так ты не нагружаешь процесс сборки основного кода лишними зависимостями. На больших проектах с тысячами тестов это может значительно сказаться на производительности.

Давай и тут выделим под тесты отдельный проект

Comment on lines 24 to 27
Bitmap bmp = new Bitmap(1000, 1000);
Graphics newGraphics = Graphics.FromImage(bmp);
var backgroundBrush = new SolidBrush(Color.White);
var rectanglePen = new Pen(Color.Black);

Choose a reason for hiding this comment

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

Все ли ресурсы тут освобождены после того, как они стали не нужными?


namespace TagsCloudVisualization;

public static class CloudGenerator

Choose a reason for hiding this comment

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

Этот класс взвалил на себя две ответственности - он и прямоугольники генерирует, и в файл сохраняет, а это все же разные ответственности. Давай сохранение в файл вынесем в отдельный модуль. А метод GenerateRectangles просто запишем в Program.cs как обычный вызывающий код


namespace TagsCloudVisualization.TagsCloudVisualizationTests;

public class CloudGeneratorTest

Choose a reason for hiding this comment

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

Этот класс тестировать не обязательно (именно ту часть, которая просто вызывает лейаутер и его построение), так как это не основной код твоей программы. Он просто вызывает основные модули и методы в определенном порядке. А после вынесения в Program.cs и тестировать будет нечего))

А вот тест на сохранение в файл тест можно будет оставить

Comment on lines 24 to 26
CircularCloudLayouter circularCloudLayouter =
new CircularCloudLayouter(new Point(CloudLayouterConst.CloudCentreX, CloudLayouterConst.CloudCentreY));
circularCloudLayouter.PutNextRectangle(new Size(2, 2));

Choose a reason for hiding this comment

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

Это лишняя работа в тесте. Когда тестируем сохраняльщик в файл, то нам не важно, откуда взялись прямоугольники, нам важно просто их нарисовать. Поэтому можешь тут просто руками создать список, лейаутер вызывать не нужно

</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" />

Choose a reason for hiding this comment

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

альфа пакеты на свой страх и риск))

Comment on lines 9 to 12
Bitmap bmp = new Bitmap(1000, 1000);
Graphics newGraphics = Graphics.FromImage(bmp);
var backgroundBrush = new SolidBrush(Color.White);
var rectanglePen = new Pen(Color.Black);

Choose a reason for hiding this comment

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

Все ещё не освободил ресурсы тут

        using var bmp = new Bitmap(1000, 1000);
        using var newGraphics = Graphics.FromImage(bmp);
        using var backgroundBrush = new SolidBrush(Color.White);
        using var rectanglePen = new Pen(Color.Black);

Классы, которые реализуют IDisposable можно с помощью синтакисческого сахара диспоузить через using, когда они завершат выполнение в своем скоупе

{
public static Bitmap DrawRectangles(List<Rectangle> rectangles)
{
Bitmap bmp = new Bitmap(1000, 1000);

Choose a reason for hiding this comment

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

Если прямоугольников будет много, они могут просто не влезть в этот размер, почему именно 1000 на 1000?

newGraphics.DrawRectangle(rectanglePen, rectangle);
}

newGraphics.Dispose();

Choose a reason for hiding this comment

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

Это можно убрать, юзинга будет достаточно

@@ -9,6 +9,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.2" />

Choose a reason for hiding this comment

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

А зачем пакет для ассертов в проекте, где он не будет использоваться?

@@ -5,10 +5,11 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>TagsCloudVisualisationTests</RootNamespace>

Choose a reason for hiding this comment

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

Можно не добавлять, по умолчанию RootNamespace равен названию проекта


namespace TagsCloudVisualization.TagsCloudVisualizationTests;

public class CloudDrawerTest

Choose a reason for hiding this comment

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

Это название уже не актуально, по факту внутри тестируется не CloudDrawer


namespace TagsCloudVisualization;

public class SaveImages

Choose a reason for hiding this comment

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

Классы называем существительными, сейчас у тебя получился глагол "Сохрани изображения", а надо "Сохранятель изображений"))

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