Skip to content

Conversation

@OKorzinina
Copy link

No description provided.

Comment out the Bun class and its methods, and add test cases for Bun.
Добавлены тесты для класса Bun, включая инициализацию, параметры и проверку типа цены.
Added tests for the Ingredient class, including initialization, type constants, and price validation.
Added comprehensive tests for the Burger class, including initialization, ingredient management, price calculation, and receipt generation.
Added tests for Database class methods including initialization, available buns, ingredients, bun prices, and ingredient names.
Добавлены фикстуры для тестирования булочек и ингредиентов.
Added an enumeration for ingredient types with descriptions.
Implemented Burger class with methods to manage buns and ingredients.
Initialize database with predefined buns and ingredients.
@pytest.fixture
def mock_sauce_ingredient():
"""Фикстура для создания мока соуса"""
ingredient = Mock(spec=Ingredient)
Copy link

Choose a reason for hiding this comment

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

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

def test_bun_initialization(self):
bun = Bun("black bun", 100.0)
assert bun.get_name() == "black bun"
assert bun.get_price() == 100.0
Copy link

Choose a reason for hiding this comment

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

Для юнит тестов стремимся проверять методы атомарно

# Test with int
bun2 = Bun("Test bun 2", 200)
# Don't check type, just check arithmetic works
total = bun.get_price() + bun2.get_price()
Copy link

Choose a reason for hiding this comment

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

нужно исправить: тест неатомарен, между ассертами не должно быть шагов, проверяем одно финальное состояние системы

Copy link
Author

@OKorzinina OKorzinina Dec 28, 2025

Choose a reason for hiding this comment

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

Спасибо за комментарий! Исправлена неатомарность теста согласно ревью.

@pytest.mark.parametrize("name,price", [
("Black bun", 100.0),
("White bun", 200.0),
("Red bun", 250.5),
Copy link

Choose a reason for hiding this comment

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

Можно лучше: для параметризации используют данные которые отличаются друг от друга, например принадлежат к разным классам эквивалентости (либо тестируют границы одного класса) и имеют одинаковый ОР. Твой список - это по сути один и тот же класс, нам не нужно проверять его много раз на самом деле. Можно было бы попробовать вводить латиницу, нелатиницу, с цифрами, с спецсимволами. Хотя у нас нет четких требований о валидации, мы все таки можем их предположить.

"""Check that price works numerically"""

ingredient = Ingredient(INGREDIENT_TYPE_SAUCE, "mayonnaise", 45.0)
assert ingredient.get_price() == 45.0
Copy link

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.

Спасибо за комментаий! Исправлена неатомарность теста согласно ревью.

@patch('praktikum.praktikum.Database') # Мокаем Database
def test_main_function_creates_burger_correctly(self, mock_database_class, mock_print):
"""
Тестирует, что функция main() правильно создает бургер:
Copy link

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.

Спасибо за комментарий, тест исправлен.

@patch('praktikum.praktikum.Database')
def test_main_handles_empty_database(self, mock_database_class, mock_print):
"""
Тестируем обработку пустой базы данных
Copy link

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