Skip to content

Conversation

@Jeffpython
Copy link
Owner

No description provided.

Copy link

@vppuzakov vppuzakov left a comment

Choose a reason for hiding this comment

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

👍 хорошая работа, вмерживай. Далее по комментам продолжай.

Choose a reason for hiding this comment

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

❗ этот файл крайне полезный - не удаляй его, он позволяет нам понимать, какие файлы подлежат версионированию и отправке в гитхаб, а какие исключены

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'

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

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']

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():

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):

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'), [

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'), [

Choose a reason for hiding this comment

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

💡 этого и ниже тестов постигла та же участь, что и тест выше - параметры лишние - кейсы - разные - а значит разные должны быть тесты - не экономь ты их.

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
...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants