-
Notifications
You must be signed in to change notification settings - Fork 29
Sprint_4 – Adding tests for the BooksCollector class #23
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
Open
duke300-QA
wants to merge
4
commits into
yandex-praktikum:main
Choose a base branch
from
duke300-QA:develop
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1 +1,15 @@ | ||
| # qa_python | ||
| # qa_python | ||
| Тесты для BooksCollector | ||
|
|
||
| test_initial_state - проверка первоначального состояния | ||
| test_add_new_book_correct_add_book_successful_add - проверка добавления книги в словарь без жанра | ||
| test_add_new_book_incorrect_add_book_unsuccessful_add - проверка добавления книги в словарь | ||
| test_set_book_genre_correct_genre_success - проверка на успешную установку жанра из списка | ||
| test_set_book_genre_incorrect_genre_unsuccess - проверку жанр не входящий в список не устанавливается | ||
| test_get_book_genre - получение книг по жанрам | ||
| test_get_books_with_specific_genre - проверка выведения списка книг с определенным жанром | ||
| test_get_books_genre - проверка получения списка книг | ||
| test_get_books_for_children - проверка возврата детских книг | ||
| test_add_book_in_favorites - проверка добавления книги в избранное | ||
| test_delete_book_from_favorites - проверка удаления книги из избранного | ||
| test_get_list_of_favorites_books - проверка получения списка избранных книг |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import pytest | ||
| from main import BooksCollector | ||
|
|
||
|
|
||
| class TestBooksCollector: | ||
|
|
||
| # фикстура для пустого коллектора | ||
| @pytest.fixture | ||
| def collector(self): | ||
| return BooksCollector() | ||
|
|
||
| # фикстура с несколькими книгами и жанрами | ||
| @pytest.fixture | ||
| def collector_with_books(self): | ||
| collector = BooksCollector() | ||
| # добавляем книги разных жанров | ||
| collector.add_new_book('Гарри Поттер') # фантастика | ||
| collector.add_new_book('Дюна') # фантастика | ||
| collector.add_new_book('Оно') # ужасы | ||
| collector.add_new_book('Дракула') # ужасы | ||
| collector.add_new_book('Малыш и Карлсон') # детская / мультфильм | ||
| collector.add_new_book('Незнайка на Луне') # детская / мультфильм | ||
| collector.add_new_book('Ну, погоди!') # мультфильм | ||
|
|
||
| # устанавливаем жанры | ||
| collector.set_book_genre('Гарри Поттер', 'Фантастика') | ||
| collector.set_book_genre('Дюна', 'Фантастика') | ||
| collector.set_book_genre('Оно', 'Ужасы') | ||
| collector.set_book_genre('Дракула', 'Ужасы') | ||
| collector.set_book_genre('Малыш и Карлсон', 'Мультфильмы') | ||
| collector.set_book_genre('Незнайка на Луне', 'Мультфильмы') | ||
| collector.set_book_genre('Ну, погоди!', 'Мультфильмы') | ||
| return collector | ||
|
|
||
| # проверка добавления одной книги | ||
| def test_add_new_book_add_one_book(self, collector): | ||
| collector.add_new_book('Том Сойер') | ||
| # проверяем, что книга добавилась | ||
| assert 'Том Сойер' in collector.get_books_genre() | ||
| # проверяем, что жанр пустой | ||
| assert collector.get_book_genre('Том Сойер') == '' | ||
|
|
||
| # проверка разных вариантов добавления книги | ||
| @pytest.mark.parametrize( | ||
| "name, expected_count", | ||
| [ | ||
| ('Том Сойер', 1), | ||
| ('', 0), | ||
| ('А'*41, 0) # название слишком длинное | ||
| ], | ||
| ids=["valid_name", "empty_name", "too_long_name"] | ||
| ) | ||
| def test_add_new_book_various_cases(self, collector, name, expected_count): | ||
| collector.add_new_book(name) | ||
| assert len(collector.get_books_genre()) == expected_count | ||
|
|
||
| # проверка установки жанра книги корректного | ||
| def test_set_book_genre_correct(self, collector): | ||
| collector.add_new_book('Том Сойер') | ||
| collector.set_book_genre('Том Сойер', 'Фантастика') | ||
| assert collector.get_book_genre('Том Сойер') == 'Фантастика' | ||
|
|
||
| # проверка установки жанра книги некорректного | ||
| def test_set_book_genre_wrong_genre(self, collector): | ||
| collector.add_new_book('Том Сойер') | ||
| collector.set_book_genre('Том Сойер', 'НеверныйЖанр') | ||
| assert collector.get_book_genre('Том Сойер') == '' | ||
|
|
||
| # проверка получения жанра книги | ||
| def test_get_book_genre_returns_right_genre(self, collector_with_books): | ||
| assert collector_with_books.get_book_genre('Гарри Поттер') == 'Фантастика' | ||
| assert collector_with_books.get_book_genre('Оно') == 'Ужасы' | ||
|
|
||
| # проверка получения списка книг по жанру | ||
| def test_get_books_with_specific_genre(self, collector_with_books): | ||
| books = collector_with_books.get_books_with_specific_genre('Фантастика') | ||
| assert 'Гарри Поттер' in books | ||
| assert 'Дюна' in books | ||
| assert len(books) == 2 | ||
|
|
||
| # проверка получения словаря всех книг | ||
| def test_get_books_genre_returns_dict(self, collector_with_books): | ||
| books_dict = collector_with_books.get_books_genre() | ||
| assert 'Гарри Поттер' in books_dict | ||
| assert isinstance(books_dict, dict) | ||
|
|
||
| # проверка получения книг для детей | ||
| def test_get_books_for_children_excludes_rated(self, collector_with_books): | ||
| books_for_children = collector_with_books.get_books_for_children() | ||
| # книги без возрастного рейтинга должны быть | ||
| assert 'Малыш и Карлсон' in books_for_children | ||
| assert 'Незнайка на Луне' in books_for_children | ||
| assert 'Ну, погоди!' in books_for_children | ||
| # книги с возрастным рейтингом не должны быть | ||
| assert 'Оно' not in books_for_children | ||
| assert 'Дракула' not in books_for_children | ||
|
|
||
| # проверка добавления книги в избранное | ||
| def test_add_book_in_favorites_adds_book(self, collector): | ||
| collector.add_new_book('Том Сойер') | ||
| collector.add_book_in_favorites('Том Сойер') | ||
| assert collector.get_list_of_favorites_books() == ['Том Сойер'] | ||
|
|
||
| # проверка, что дубликаты не добавляются в избранное | ||
| def test_add_book_in_favorites_no_duplicates(self, collector): | ||
| collector.add_new_book('Том Сойер') | ||
| collector.add_book_in_favorites('Том Сойер') | ||
| collector.add_book_in_favorites('Том Сойер') | ||
| assert collector.get_list_of_favorites_books() == ['Том Сойер'] | ||
|
|
||
| # проверка удаления книги из избранного | ||
| def test_delete_book_from_favorites(self, collector): | ||
| # создаём книгу | ||
| collector.add_new_book('Том Сойер') | ||
|
|
||
| # добавляем в избранное | ||
| collector.add_book_in_favorites('Том Сойер') | ||
| # проверяем, что книга в избранном | ||
| assert collector.get_list_of_favorites_books() == ['Том Сойер'] | ||
|
|
||
| # удаляем из избранного | ||
| collector.delete_book_from_favorites('Том Сойер') | ||
| # проверяем, что её больше нет | ||
| assert collector.get_list_of_favorites_books() == [] | ||
|
|
||
| # проверка получения списка всех избранных книг | ||
| def test_get_list_of_favorites_books_returns_correct_list(self, collector): | ||
| collector.add_new_book('Том Сойер') | ||
| collector.add_new_book('Дюна') | ||
| collector.add_book_in_favorites('Том Сойер') | ||
| collector.add_book_in_favorites('Дюна') | ||
| favorites = collector.get_list_of_favorites_books() | ||
| assert favorites == ['Том Сойер', 'Дюна'] | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,24 +1,89 @@ | ||
| import pytest | ||
| from main import BooksCollector | ||
|
|
||
| # класс TestBooksCollector объединяет набор тестов, которыми мы покрываем наше приложение BooksCollector | ||
| # обязательно указывать префикс Test | ||
|
|
||
| class TestBooksCollector: | ||
|
|
||
| # пример теста: | ||
| # обязательно указывать префикс test_ | ||
| # дальше идет название метода, который тестируем add_new_book_ | ||
| # затем, что тестируем add_two_books - добавление двух книг | ||
| def test_add_new_book_add_two_books(self): | ||
| # создаем экземпляр (объект) класса BooksCollector | ||
| def test_initial_state(self): | ||
| collector = BooksCollector() | ||
| assert collector.get_books_genre() == {} and collector.get_list_of_favorites_books() == [] | ||
|
|
||
| def test_add_new_book_correct_add_book_successful_add(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| assert collector.get_book_genre('Азбука') == '' | ||
|
|
||
| @pytest.mark.parametrize("name, expected_count", [ | ||
| ('Азбука', 1), | ||
| ('', 0), | ||
| ('Азбука' * 10, 0) | ||
| ]) | ||
| def test_add_new_book_incorrect_add_book_unsuccessful_add(self, name, expected_count): | ||
| collector = BooksCollector() | ||
| collector.add_new_book(name) | ||
| assert len(collector.get_books_genre()) == expected_count | ||
|
|
||
| def test_set_book_genre_correct_genre_success(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| collector.set_book_genre('Азбука', 'Ужасы') | ||
| assert collector.books_genre['Азбука'] == 'Ужасы' | ||
|
|
||
| def test_set_book_genre_incorrect_genre_unsuccess(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| collector.set_book_genre('Азбука', 'FFFFFF') | ||
| assert collector.books_genre['Азбука'] == '' | ||
|
|
||
| def test_get_book_genre(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| collector.set_book_genre('Азбука', 'Ужасы') | ||
| assert collector.get_book_genre('Азбука') == 'Ужасы' | ||
|
|
||
| # добавляем две книги | ||
| collector.add_new_book('Гордость и предубеждение и зомби') | ||
| collector.add_new_book('Что делать, если ваш кот хочет вас убить') | ||
| def test_get_books_with_specific_genre(self): | ||
| collector = BooksCollector() | ||
| books = ['Азбука', 'Алгебра', 'Маленький принц'] | ||
| for book in books: | ||
| collector.add_new_book(book) | ||
| collector.set_book_genre(book, 'Ужасы') | ||
|
|
||
| collector.add_new_book('Ну погоди') | ||
| collector.set_book_genre('Ну погоди', 'Мультфильмы') | ||
|
|
||
| assert collector.get_books_with_specific_genre('Ужасы') == books | ||
|
|
||
| def test_get_books_genre(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| assert collector.get_books_genre() == {'Азбука': ''} | ||
|
|
||
| def test_get_books_for_children(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Детская') | ||
| collector.add_new_book('Взрослая') | ||
| collector.set_book_genre('Детская', 'Фантастика') | ||
| collector.set_book_genre('Взрослая', 'Ужасы') | ||
|
|
||
| # проверяем, что добавилось именно две | ||
| # словарь books_rating, который нам возвращает метод get_books_rating, имеет длину 2 | ||
| assert len(collector.get_books_rating()) == 2 | ||
| assert collector.get_books_for_children() == ['Детская'] | ||
|
|
||
| # напиши свои тесты ниже | ||
| # чтобы тесты были независимыми в каждом из них создавай отдельный экземпляр класса BooksCollector() | ||
| def test_add_book_in_favorites(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| collector.add_book_in_favorites('Азбука') | ||
| assert collector.get_list_of_favorites_books() == ['Азбука'] | ||
|
|
||
| def test_delete_book_from_favorites(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| collector.add_book_in_favorites('Азбука') | ||
| collector.delete_book_from_favorites('Азбука') | ||
| assert collector.get_list_of_favorites_books() == [] | ||
|
|
||
| def test_get_list_of_favorites_books(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Азбука') | ||
| collector.add_new_book('Алгебра') | ||
| collector.add_book_in_favorites('Азбука') | ||
| collector.add_book_in_favorites('Алгебра') | ||
| assert collector.get_list_of_favorites_books() == ['Азбука', 'Алгебра'] |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нужно исправить: фикстуры живут в модуле conftest