-
Notifications
You must be signed in to change notification settings - Fork 0
First #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
base: master
Are you sure you want to change the base?
First #1
Conversation
vppuzakov
left a comment
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.
👍 хорошая работа, вмерживай. Далее по комментам продолжай.
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.
❗ этот файл крайне полезный - не удаляй его, он позволяет нам понимать, какие файлы подлежат версионированию и отправке в гитхаб, а какие исключены
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.
❗ как раз пример того файла, который должен был быть исключен при отправке в github. Давай его удалим следующим образом:
git rm tests/__pycache__/test_main.cpython-312-pytest-8.0.2.pyc- после чего сделаем git commit -m "remove pycache file"
- потом добавим все
__pycache__файлы в.gitignoreфайл:
__pycache__| import httpx | ||
| from sensitive_data import client_id, client_secret, username, password | ||
|
|
||
| subreddit = 'learnpython' |
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.
💡 мы не пишим скрипты - мы пишем программы, приложения, сервисы - поэтому никаких глобальных переменных
💡 давай будем спрашивать о том сабреддите, который хотим спарсить у пользователя с помощью input()
| @@ -0,0 +1,108 @@ | |||
| import datetime | |||
|
|
|||
| import httpx | |||
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.
👍 круто, что используешь httpx
| headers = {"User-Agent": "User-Agent"} | ||
| response = httpx.post("https://www.reddit.com/api/v1/access_token", | ||
| auth=(client_id, client_secret), data=post_data, headers=headers) | ||
| return response.json()['access_token'] |
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.
💡 для валидации ответов от внешних апи очень классно заходит использовать какую-либо из библиотек валидации json, сейчас популярна pydantic. Давай в следующем ПР попробуем ее прикрутить в этом месте.
| get_latest_posts(token=token, subreddit='') | ||
|
|
||
|
|
||
| def test__get_authors__returns_authors_list(): |
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.
👍 вот это уже ближе к реальности тест - хороший, единственное только название - нам же не важно тут что возвращается list - его можно не писать (за типы mypy работает), то есть return_authors было бы достаточно
| ([{'data': {'author': 'author1'}}], ['author1']), | ||
| ([{'data': {'author': 'author1'}}, {'data': {'author': 'author2'}}], ['author1', 'author2']) | ||
| ]) | ||
| def test__get_authors__returns_authors_list(data, expected_result): |
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.
❗ вижу два теста с одинаковым названием - непорядок. Кейс один получается? В чем особенность параметров? Не лучше ли иметь два разных теста с очевидным названием?
- can_return_one_author
- can_return_many_authors
И тесты станут понятнее и запутанные сложные параметры будут не нужны.
💡 то есть я это к чему, параметры зачастую плохо применять, чем хорошо. Должен быть очень веский повод в пользу параметров. Как минимум они в этом случае должны быть максимально простыми и ясными и не касаться разных кейсов.
| assert get_authors(data) == expected_result | ||
|
|
||
|
|
||
| @pytest.mark.parametrize(('items', 'expected_result'), [ |
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 count_items_in_list(items) == expected_result | ||
|
|
||
|
|
||
| @pytest.mark.parametrize(('items', 'expected_result'), [ |
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.
💡 этого и ниже тестов постигла та же участь, что и тест выше - параметры лишние - кейсы - разные - а значит разные должны быть тесты - не экономь ты их.
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.
💡 для проектов используй следующую структуру:
redditparser/__init__.py
redditparser/__main__.py
redditparser/client.py
redditparser/topfinder.py
tests
readme.md
...
No description provided.