forked from yandex-praktikum/qa_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Unit tests (Sprint 4) #1
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
hinatakudo5
wants to merge
8
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
8 commits
Select commit
Hold shift + click to select a range
ed908f2
Изменения в tests.py
Serg-nt 94b2243
Исправление задания
Serg-nt 102d889
Добавлен README со списком тестов
Serg-nt e588da5
README.md
hinatakudo5 9fa1b2c
tests.py
hinatakudo5 b3d0ff8
README.md
hinatakudo5 d7b15f7
main.py
hinatakudo5 19a7360
Update tests.py
hinatakudo5 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,52 @@ | ||
| # qa_python | ||
| # Юнит-тестирование BooksCollector | ||
|
|
||
| Проект 4 спринта: покрытие тестами класса `BooksCollector`. | ||
|
|
||
| ## Описание реализованных тестов | ||
|
|
||
| Файл `tests.py` содержит 11 тестов. | ||
|
|
||
| ### Добавление книг | ||
|
|
||
| 1. **test_add_new_book_adds_book_without_genre** | ||
| Проверяет, что при добавлении новой книги она появляется в словаре `books_genre`, а её жанр не задан (`None`). Используется параметризация по нескольким названиям. | ||
|
|
||
| 2. **test_add_new_book_does_not_add_book_with_name_longer_than_40** | ||
| Проверяет, что книга с названием длиннее 40 символов не добавляется в `books_genre`. | ||
|
|
||
| 3. **test_add_new_book_does_not_add_duplicate_book** | ||
| Проверяет, что одну и ту же книгу нельзя добавить в словарь больше одного раза. | ||
|
|
||
| ### Работа с жанрами | ||
|
|
||
| 4. **test_set_book_genre_sets_genre_for_existing_book** | ||
| Проверяет, что для существующей книги можно установить жанр из списка доступных. | ||
|
|
||
| 5. **test_set_book_genre_does_not_set_genre_for_unknown_book** | ||
| Проверяет, что для несуществующей книги жанр не устанавливается и она не добавляется в словарь. | ||
|
|
||
| 6. **test_get_book_genre_returns_none_for_book_without_genre** | ||
| Проверяет, что `get_book_genre` возвращает `None`, если жанр не установлен. | ||
|
|
||
| 7. **test_get_books_with_specific_genre_returns_only_books_with_that_genre** | ||
| Проверяет, что метод возвращает только книги с указанным жанром. | ||
|
|
||
| 8. **test_get_books_for_children_excludes_books_with_age_rating** | ||
| Проверяет, что книги с возрастным рейтингом не попадают в список доступных детям. | ||
|
|
||
| ### Избранное | ||
|
|
||
| 9. **test_add_book_in_favorites_adds_only_existing_book_and_ignores_duplicates** | ||
| Проверяет, что книгу можно добавить в избранное только один раз. | ||
|
|
||
| 10. **test_add_book_in_favorites_does_not_add_book_which_is_not_in_books_genre** | ||
| Проверяет, что нельзя добавить в избранное книгу, которой нет в `books_genre`. | ||
|
|
||
| 11. **test_delete_book_from_favorites_removes_book** | ||
| Проверяет, что книга удаляется из избранного. | ||
|
|
||
| ## Как запустить тесты | ||
|
|
||
| ```bash | ||
| pytest -v tests.py | ||
|
|
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
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,169 @@ | ||
| 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 | ||
| collector = BooksCollector() | ||
| # ---------- Тесты для добавления книг ---------- | ||
|
|
||
| # добавляем две книги | ||
| collector.add_new_book('Гордость и предубеждение и зомби') | ||
| collector.add_new_book('Что делать, если ваш кот хочет вас убить') | ||
| @pytest.mark.parametrize('book_name', ['Книга 1', 'Очень важная книга']) | ||
| def test_add_new_book_adds_book_without_genre(book_name): | ||
| collector = BooksCollector() | ||
|
|
||
| # проверяем, что добавилось именно две | ||
| # словарь books_rating, который нам возвращает метод get_books_rating, имеет длину 2 | ||
| assert len(collector.get_books_rating()) == 2 | ||
| collector.add_new_book(book_name) | ||
|
|
||
| books = collector.get_books_genre() | ||
| assert book_name in books | ||
| # у только что добавленной книги жанр — пустая строка | ||
| assert books[book_name] == '' | ||
|
|
||
|
|
||
| def test_add_new_book_does_not_add_book_with_name_longer_than_40(): | ||
| collector = BooksCollector() | ||
| long_name = 'А' * 41 # 41 символ | ||
|
|
||
| collector.add_new_book(long_name) | ||
|
|
||
| books = collector.get_books_genre() | ||
| assert long_name not in books | ||
|
|
||
|
|
||
| def test_add_new_book_does_not_add_duplicate_book(): | ||
| collector = BooksCollector() | ||
| book_name = 'Гарри Поттер' | ||
|
|
||
| collector.add_new_book(book_name) | ||
| collector.add_new_book(book_name) | ||
|
|
||
| books = collector.get_books_genre() | ||
| # одна и та же книга должна быть только один раз | ||
| assert list(books.keys()).count(book_name) == 1 | ||
|
|
||
|
|
||
| # ---------- Тесты для установки и получения жанра ---------- | ||
|
|
||
| def test_set_book_genre_sets_genre_for_existing_book(): | ||
| collector = BooksCollector() | ||
| book_name = 'Безобидная книга' | ||
| collector.add_new_book(book_name) | ||
|
|
||
| any_genre = collector.genre[0] | ||
| collector.set_book_genre(book_name, any_genre) | ||
|
|
||
| assert collector.get_book_genre(book_name) == any_genre | ||
|
|
||
|
|
||
| def test_set_book_genre_does_not_set_genre_for_unknown_book(): | ||
| collector = BooksCollector() | ||
| unknown_book = 'Неизвестная книга' | ||
| any_genre = collector.genre[0] | ||
|
|
||
| collector.set_book_genre(unknown_book, any_genre) | ||
|
|
||
| books = collector.get_books_genre() | ||
| assert unknown_book not in books | ||
|
|
||
|
|
||
| def test_get_book_genre_returns_empty_string_for_book_without_genre(): | ||
| collector = BooksCollector() | ||
| book_name = 'Книга без жанра' | ||
| collector.add_new_book(book_name) | ||
|
|
||
| assert collector.get_book_genre(book_name) == '' | ||
|
|
||
|
|
||
| # ---------- Тесты для получения книг по жанрам ---------- | ||
|
|
||
| def test_get_books_with_specific_genre_returns_only_books_with_that_genre(): | ||
| collector = BooksCollector() | ||
| safe_genre = collector.genre[0] | ||
| other_genre = collector.genre[1] | ||
|
|
||
| collector.add_new_book('Книга 1') | ||
| collector.set_book_genre('Книга 1', safe_genre) | ||
|
|
||
| collector.add_new_book('Книга 2') | ||
| collector.set_book_genre('Книга 2', other_genre) | ||
|
|
||
| books = collector.get_books_with_specific_genre(safe_genre) | ||
|
|
||
| assert 'Книга 1' in books | ||
| assert 'Книга 2' not in books | ||
|
|
||
|
|
||
| def test_get_books_for_children_includes_safe_genre(): | ||
| collector = BooksCollector() | ||
| safe_genre = next( | ||
| genre for genre in collector.genre | ||
| if genre not in collector.genre_age_rating | ||
| ) | ||
|
|
||
| collector.add_new_book('Детская книга') | ||
| collector.set_book_genre('Детская книга', safe_genre) | ||
|
|
||
| children_books = collector.get_books_for_children() | ||
|
|
||
| assert 'Детская книга' in children_books | ||
|
|
||
|
|
||
| def test_get_books_for_children_excludes_age_rating(): | ||
| collector = BooksCollector() | ||
| age_genre = collector.genre_age_rating[0] | ||
|
|
||
| collector.add_new_book('Взрослая книга') | ||
| collector.set_book_genre('Взрослая книга', age_genre) | ||
|
|
||
| children_books = collector.get_books_for_children() | ||
|
|
||
| assert 'Взрослая книга' not in children_books | ||
|
|
||
|
|
||
| # ---------- Тесты для избранного ---------- | ||
|
|
||
| def test_add_book_in_favorites_adds_only_existing_book_and_ignores_duplicates(): | ||
| collector = BooksCollector() | ||
| book_name = 'Любимая книга' | ||
|
|
||
| collector.add_new_book(book_name) | ||
|
|
||
| collector.add_book_in_favorites(book_name) | ||
| collector.add_book_in_favorites(book_name) # в избранном она должна остаться одна | ||
|
|
||
| favorites = collector.get_list_of_favorites_books() | ||
|
|
||
| assert book_name in favorites | ||
| assert favorites.count(book_name) == 1 | ||
|
|
||
|
|
||
| def test_add_book_in_favorites_does_not_add_book_which_is_not_in_books_genre(): | ||
| collector = BooksCollector() | ||
| unknown_book = 'Неизвестная книга' | ||
|
|
||
| collector.add_book_in_favorites(unknown_book) | ||
|
|
||
| favorites = collector.get_list_of_favorites_books() | ||
| assert unknown_book not in favorites | ||
|
|
||
|
|
||
| def test_delete_book_from_favorites_removes_book(): | ||
| collector = BooksCollector() | ||
| book_name = 'Книга для удаления' | ||
|
|
||
| collector.add_new_book(book_name) | ||
| collector.add_book_in_favorites(book_name) | ||
|
|
||
| collector.delete_book_from_favorites(book_name) | ||
|
|
||
| favorites = collector.get_list_of_favorites_books() | ||
| assert book_name not in favorites | ||
|
|
||
|
|
||
| def test_get_list_of_favorites_books_returns_correct_list(): | ||
| 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() == ['Азбука', 'Алгебра'] | ||
|
|
||
| # напиши свои тесты ниже | ||
| # чтобы тесты были независимыми в каждом из них создавай отдельный экземпляр класса BooksCollector() | ||
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.
Нужно исправить здесь и далее: нарушает Эля требование «один тест — один assert».
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.
Не исправлено