-
Notifications
You must be signed in to change notification settings - Fork 0
Feat: add pytest for TestBooksCollector #8
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
zhulevk-gif
wants to merge
2
commits into
main
Choose a base branch
from
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
2 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 |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| __pycache__/ | ||
| *.py[cod] | ||
| .pytest_cache/ | ||
| venv/ | ||
| .venv/ |
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,12 @@ | ||
| # qa_python | ||
| ## Описание тестов | ||
|
|
||
| - `test_add_new_book_add_one_book` — проверка успешного добавления одной книги. | ||
| - `test_add_new_book_invalid_name_length_not_added` — проверка, что книги с некорректной длиной названия (0 или 41+ символов) не добавляются. | ||
| - `test_set_book_genre_existing_genre` — проверка установки жанра из списка разрешённых. | ||
| - `test_set_book_genre_not_in_list_not_set` — проверка, что жанр не устанавливается, если его нет в списке `genre`. | ||
| - `test_get_books_with_specific_genre_is_correct` — проверка фильтрации книг по выбранному жанру. | ||
| - `test_get_books_genre_returns_dict` — проверка корректного возврата всего словаря книг. | ||
| - `test_get_books_for_children_excludes_age_rating_genres` — проверка, что книги с жанрами из `genre_age_rating` не попадают в детский список. | ||
| - `test_add_book_in_favorites_added_successfully` — проверка успешного добавления книги в список избранного. | ||
| - `test_add_book_in_favorites_book_not_in_collector_not_added` — проверка запрета на добавление в избранное книг, отсутствующих в коллекции. | ||
| - `test_delete_book_from_favorites_removed_successfully` — проверка удаления книги из списка избранного. |
Binary file not shown.
Binary file not shown.
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,67 @@ | ||
| 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_add_new_book_add_one_book(self): | ||
| collector = BooksCollector() | ||
|
|
||
| # добавляем две книги | ||
| collector.add_new_book('Гордость и предубеждение и зомби') | ||
| collector.add_new_book('Что делать, если ваш кот хочет вас убить') | ||
|
|
||
| # проверяем, что добавилось именно две | ||
| # словарь books_rating, который нам возвращает метод get_books_rating, имеет длину 2 | ||
| assert len(collector.get_books_rating()) == 2 | ||
|
|
||
| # напиши свои тесты ниже | ||
| # чтобы тесты были независимыми в каждом из них создавай отдельный экземпляр класса BooksCollector() | ||
| collector.add_new_book('Гордость и предубеждение') | ||
| assert 'Гордость и предубеждение' in collector.get_books_genre() | ||
|
|
||
| @pytest.mark.parametrize('name', ['', 'Название книги, которое длиннее сорока одного символа']) | ||
| def test_add_new_book_invalid_name_length_not_added(self, name): | ||
| collector = BooksCollector() | ||
| collector.add_new_book(name) | ||
| assert name not in collector.get_books_genre() | ||
|
|
||
| def test_set_book_genre_existing_genre(self): | ||
| collector = BooksCollector() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Отлично: в каждом тесте создается собственный экземпляр BooksCollector, но можно лучше - перенести создание экземпляра в фикстуры в отдельный файл conftest, а не повторять это предусловие в каждом тесте |
||
| collector.add_new_book('Дюна') | ||
| collector.set_book_genre('Дюна', 'Фантастика') | ||
| assert collector.get_book_genre('Дюна') == 'Фантастика' | ||
|
|
||
| def test_set_book_genre_not_in_list_not_set(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Дюна') | ||
| collector.set_book_genre('Дюна', 'Киберпанк') | ||
| assert collector.get_book_genre('Дюна') == '' | ||
|
|
||
| def test_get_books_with_specific_genre_is_correct(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Дракула') | ||
| collector.set_book_genre('Дракула', 'Ужасы') | ||
| assert 'Дракула' in collector.get_books_with_specific_genre('Ужасы') | ||
|
|
||
| def test_get_books_genre_returns_dict(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Оно') | ||
| assert isinstance(collector.get_books_genre(), dict) | ||
| assert 'Оно' in collector.get_books_genre() | ||
|
|
||
| def test_get_books_for_children_excludes_age_rating_genres(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 and 'Сияние' not in children_books | ||
|
|
||
| def test_add_book_in_favorites_added_successfully(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Ведьмак') | ||
| collector.add_book_in_favorites('Ведьмак') | ||
| assert 'Ведьмак' in collector.get_list_of_favorites_books() | ||
|
|
||
| def test_add_book_in_favorites_book_not_in_collector_not_added(self): | ||
| collector = BooksCollector() | ||
| collector.add_book_in_favorites('Неизвестная книга') | ||
| assert len(collector.get_list_of_favorites_books()) == 0 | ||
|
|
||
| def test_delete_book_from_favorites_removed_successfully(self): | ||
| collector = BooksCollector() | ||
| collector.add_new_book('Гарри Поттер') | ||
| collector.add_book_in_favorites('Гарри Поттер') | ||
| collector.delete_book_from_favorites('Гарри Поттер') | ||
| assert 'Гарри Поттер' not in 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.
Отлично: удачное применение параметризации, протестированы разные граничные значения для длины имени