Skip to content
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
106 changes: 106 additions & 0 deletions Create create tests 3
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import unittest
from parameterized import parameterized


class TestBooksCollector(unittest.TestCase):

# Тест на добавление новой книги
def test_add_new_book(self):
collector = BooksCollector()
collector.add_new_book("1984")
assert "1984" in collector.books_genre
assert collector.books_genre["1984"] == ''

# Тест на добавление книги, превышающей максимальную длину
def test_add_new_book_too_long_name(self):
collector = BooksCollector()
max_length = 40
long_title = "A" * (max_length + 1)
collector.add_new_book(long_title)
assert long_title not in collector.books_genre, f"Книга с длинным названием '{long_title}' была добавлена, хотя должна была быть отклонена."

# Тест на установку жанра для книги
def test_set_book_genre(self):
collector = BooksCollector()
collector.add_new_book("Fahrenheit 451")
collector.set_book_genre("Fahrenheit 451", "Фантастика")
assert collector.get_book_genre("Fahrenheit 451") == "Фантастика"

# Тест на получение жанра книги
def test_get_book_genre(self):
collector = BooksCollector()
collector.add_new_book("The Shining")
collector.set_book_genre("The Shining", "Ужасы")
assert collector.get_book_genre("The Shining") == collector.books_genre["The Shining"]

# Тест на получение книг с определенным жанром
def test_get_books_with_specific_genre(self):
collector = BooksCollector()
collector.add_new_book("It")
collector.set_book_genre("It", "Ужасы")
collector.add_new_book("Harry Potter")
collector.set_book_genre("Harry Potter", "Фантастика")
books = collector.get_books_with_specific_genre("Ужасы")
assert "It" in books
assert "Harry Potter" not in books

# Тест на получение детских книг
def test_get_books_for_children(self):
collector = BooksCollector()
collector.add_new_book("Маша и Медведь")
collector.set_book_genre("Маша и Медведь", "Мультфильмы")
collector.add_new_book("Ужас Вихря")
collector.set_book_genre("Ужас Вихря", "Ужасы")
children_books = collector.get_books_for_children()
assert "Маша и Медведь" in children_books
assert "Ужас Вихря" not in children_books

# Тест на добавление книги в избранное
def test_add_book_in_favorites(self):
collector = BooksCollector()
collector.add_new_book("Lord of the Flies")
collector.add_book_in_favorites("Lord of the Flies")
assert "Lord of the Flies" in collector.get_list_of_favorites_books()

# Тест на удаление книги из избранного
def test_delete_book_from_favorites(self):
collector = BooksCollector()
collector.add_new_book("Pride and Prejudice")
collector.add_book_in_favorites("Pride and Prejudice")
collector.delete_book_from_favorites("Pride and Prejudice")
assert "Pride and Prejudice" not in collector.get_list_of_favorites_books()

# Тест на невозможность повторной записи книги в избранное
def test_add_book_in_favorites_twice(self):
collector = BooksCollector()
collector.add_new_book("The Great Gatsby")
collector.add_book_in_favorites("The Great Gatsby")
collector.add_book_in_favorites("The Great Gatsby")
assert len(collector.get_list_of_favorites_books()) == 1

# Параметризованный тест на добавление книг
@parameterized.expand([
("The Catcher in the Rye",),
("To Kill a Mockingbird",),
("Brave New World",)
])
def test_add_books_with_parameterization(self, book_name):
collector = BooksCollector()
collector.add_new_book(book_name)
assert book_name in collector.books_genre

# Дополнительный тест для метода get_books_genre
def test_get_books_genre(self):
collector = BooksCollector()
collector.add_new_book("War and Peace")
collector.set_book_genre("War and Peace", "Classic")
result = collector.get_books_genre()
expected = {"War and Peace": "Classic"}
assert result == expected

# Дополнительный тест для метода get_list_of_favorites_books
def test_get_list_of_favorites_books_positive(self):
collector = BooksCollector()
collector.add_new_book("Great Expectations")
collector.add_book_in_favorites("Great Expectations")
assert collector.get_list_of_favorites_books() == ["Great Expectations"]
111 changes: 111 additions & 0 deletions create tests 2
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import unittest
from parameterized import parameterized


class TestBooksCollector(unittest.TestCase):

def setUp(self):

Choose a reason for hiding this comment

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

Нужно исправить: тут ничего не происходит, метод можно удалить

pass # Объект будет создаваться внутри тестов

# Тест на добавление новой книги
def test_add_new_book(self):
collector = BooksCollector()
collector.add_new_book("1984")
assert "1984" in collector.books_genre
assert collector.books_genre["1984"] == ''

# Тест на добавление книги, превышающей максимальную длину
def test_add_new_book_too_long_name(self):
collector = BooksCollector()
max_length = 40
long_title = "A" * (max_length + 1)
collector.add_new_book(long_title)
assert long_title not in collector.books_genre, f"Книга с длинным названием '{long_title}' была добавлена, хотя должна была быть отклонена."

# Тест на установку жанра для книги
def test_set_book_genre(self):
collector = BooksCollector()
collector.add_new_book("Fahrenheit 451")
collector.set_book_genre("Fahrenheit 451", "Фантастика")
assert collector.get_book_genre("Fahrenheit 451") == "Фантастика"

# Тест на получение жанра книги
def test_get_book_genre(self):
collector = BooksCollector()
collector.add_new_book("The Shining")
collector.set_book_genre("The Shining", "Ужасы")
assert collector.get_book_genre("The Shining") == "Ужасы"

Choose a reason for hiding this comment

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

Нужно исправить: тест не отличается от проверки set метода. Чтобы методы не проверяли друг друга, сравни полученное с состоянием словаря


# Тест на получение книг с определенным жанром
def test_get_books_with_specific_genre(self):
collector = BooksCollector()
collector.add_new_book("It")
collector.set_book_genre("It", "Ужасы")
collector.add_new_book("Harry Potter")
collector.set_book_genre("Harry Potter", "Фантастика")
books = collector.get_books_with_specific_genre("Ужасы")
assert "It" in books
assert "Harry Potter" not in books

# Тест на получение детских книг
def test_get_books_for_children(self):
collector = BooksCollector()
collector.add_new_book("Маша и Медведь")
collector.set_book_genre("Маша и Медведь", "Мультфильмы")
collector.add_new_book("Ужас Вихря")
collector.set_book_genre("Ужас Вихря", "Ужасы")
children_books = collector.get_books_for_children()
assert "Маша и Медведь" in children_books
assert "Ужас Вихря" not in children_books

# Тест на добавление книги в избранное
def test_add_book_in_favorites(self):
collector = BooksCollector()
collector.add_new_book("Lord of the Flies")
collector.add_book_in_favorites("Lord of the Flies")
assert "Lord of the Flies" in collector.get_list_of_favorites_books()

# Тест на удаление книги из избранного
def test_delete_book_from_favorites(self):
collector = BooksCollector()
collector.add_new_book("Pride and Prejudice")
collector.add_book_in_favorites("Pride and Prejudice")
collector.delete_book_from_favorites("Pride and Prejudice")
assert "Pride and Prejudice" not in collector.get_list_of_favorites_books()

# Тест на невозможность повторной записи книги в избранное
def test_add_book_in_favorites_twice(self):
collector = BooksCollector()
collector.add_new_book("The Great Gatsby")
collector.add_book_in_favorites("The Great Gatsby")
collector.add_book_in_favorites("The Great Gatsby")
assert len(collector.get_list_of_favorites_books()) == 1

# Параметризованный тест на добавление книг
@parameterized.expand([
("The Catcher in the Rye",),
("To Kill a Mockingbird",),
("Brave New World",)
])
def test_add_books_with_parameterization(self, book_name):
collector = BooksCollector()
collector.add_new_book(book_name)
assert book_name in collector.books_genre

# Дополнительный тест для метода get_books_genre
def test_get_books_genre(self):
collector = BooksCollector()
collector.add_new_book("War and Peace")
collector.set_book_genre("War and Peace", "Classic")
result = collector.get_books_genre()
expected = {"War and Peace": "Classic"}
assert result == expected

# Дополнительный тест для метода get_list_of_favorites_books

Choose a reason for hiding this comment

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

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

def test_get_list_of_favorites_books_empty(self):
collector = BooksCollector()
assert collector.get_list_of_favorites_books() == []


if __name__ == '__main__':

Choose a reason for hiding this comment

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

Можно убрать

unittest.main()
83 changes: 83 additions & 0 deletions tests
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import unittest

class TestBooksCollector(unittest.TestCase):

Choose a reason for hiding this comment

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

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


def setUp(self):

Choose a reason for hiding this comment

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

Нужно исправить: объект класса BooksCollector() нужно создавать для каждого теста. Чтобы не дублировать код, можно вынести это в фикстуру

self.collector = BooksCollector()

# Тест на добавление новых книг
def test_add_new_book(self):
self.collector.add_new_book("1984")

Choose a reason for hiding this comment

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

Нужно исправить: ты указываешь объект, self для вызова не требуется. Так же он не требуется для вызова ассертов - это не методы объекта

self.assertIn("1984", self.collector.books_genre)
self.assertEqual(self.collector.books_genre["1984"], '')

# Тест на добавление книги, превышающей максимальную длину
def test_add_new_book_too_long_name(self):
self.collector.add_new_book("A" * 41)
self.assertNotIn("A" * 41, self.collector.books_genre)

Choose a reason for hiding this comment

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

Можно улучшить: этот тест не исключает, что название обрезается


# Тест на установку жанра для книги
def test_set_book_genre(self):
self.collector.add_new_book("Fahrenheit 451")
self.collector.set_book_genre("Fahrenheit 451", "Фантастика")
self.assertEqual(self.collector.get_book_genre("Fahrenheit 451"), "Фантастика")

# Тест на получение жанра книги
def test_get_book_genre(self):
self.collector.add_new_book("The Shining")
self.collector.set_book_genre("The Shining", "Ужасы")
self.assertEqual(self.collector.get_book_genre("The Shining"), "Ужасы")

Choose a reason for hiding this comment

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

Нужно исправить: тест не отличается от предыдущего. Подумай, как иначе ты можешь убедится, что get_book_genre возвращает именно то значение, которое есть в словаре


# Тест на получение книг с определённым жанром
def test_get_books_with_specific_genre(self):
self.collector.add_new_book("It")
self.collector.set_book_genre("It", "Ужасы")
self.collector.add_new_book("Harry Potter")
self.collector.set_book_genre("Harry Potter", "Фантастика")
books = self.collector.get_books_with_specific_genre("Ужасы")
self.assertIn("It", books)
self.assertNotIn("Harry Potter", books)

# Тест на получение книг для детей
def test_get_books_for_children(self):
self.collector.add_new_book("Маша и медведь")
self.collector.set_book_genre("Маша и медведь", "Мультфильмы")
self.collector.add_new_book("Ужас вихря")
self.collector.set_book_genre("Ужас вихря", "Ужасы")
children_books = self.collector.get_books_for_children()
self.assertIn("Маша и медведь", children_books)
self.assertNotIn("Ужас вихря", children_books)

# Тест на добавление книги в избранное
def test_add_book_in_favorites(self):
self.collector.add_new_book("Lord of the Flies")
self.collector.add_book_in_favorites("Lord of the Flies")
self.assertIn("Lord of the Flies", self.collector.get_list_of_favorites_books())

# Тест на удаление книги из избранного
def test_delete_book_from_favorites(self):
self.collector.add_new_book("Pride and Prejudice")
self.collector.add_book_in_favorites("Pride and Prejudice")
self.collector.delete_book_from_favorites("Pride and Prejudice")
self.assertNotIn("Pride and Prejudice", self.collector.get_list_of_favorites_books())

# Тест на отсутствие повторного добавления в избранное
def test_add_book_in_favorites_twice(self):
self.collector.add_new_book("The Great Gatsby")
self.collector.add_book_in_favorites("The Great Gatsby")
self.collector.add_book_in_favorites("The Great Gatsby") # Повторное добавление
self.assertEqual(len(self.collector.get_list_of_favorites_books()), 1)

# Параметризованный тест на добавление книг
from parameterized import parameterized
@parameterized.expand([
("The Catcher in the Rye",),
("To Kill a Mockingbird",),
("Brave New World",)
])
def test_add_books_with_parameterization(self, book_name):
self.collector.add_new_book(book_name)
self.assertIn(book_name, self.collector.books_genre)

if __name__ == '__main__':
unittest.main()