Skip to content
This repository was archived by the owner on Mar 19, 2024. It is now read-only.
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 44 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pyproject.toml
Copy link

Choose a reason for hiding this comment

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

httpretty и mimesis по логике лучше вынести в dev зависимости, ибо в текущем виде toml файла они будут устанавливаться и на проде

Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ requests = "^2.28"
attrs = "^23.1"
pydantic = "^2.3"
punq = "^0.6"
httpretty = "^1.1.4"
mimesis = "^11.1.0"

[tool.poetry.group.dev.dependencies]
django-debug-toolbar = "^4.2"
Expand Down
33 changes: 17 additions & 16 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ ignore = D100, D104, D106, D401, X100, W504, RST303, RST304, DAR103, DAR203
# You can completely or partially disable our custom checks,
# to do so you have to ignore `WPS` letters for all python files:
per-file-ignores =
# Allow upper-case constants in classes, because it is settings:
# Allow upper-case constants in classes, because it is settings:
server/common/django/types.py: WPS115
# Allow `__init__.py` with logic for configuration:
# Allow `__init__.py` with logic for configuration:
server/settings/*.py: WPS226, WPS407, WPS412, WPS432
# Allow to have magic numbers and wrong module names inside migrations:
# Allow to have magic numbers and wrong module names inside migrations:
server/*/migrations/*.py: WPS102, WPS114, WPS432
# Tests have some more freedom:
# Tests have some more freedom:
tests/*.py: S101, WPS201, WPS202, WPS218, WPS226, WPS436, WPS442


Expand Down Expand Up @@ -77,12 +77,12 @@ addopts =
--strict-config
--doctest-modules
--fail-on-template-vars
# Output:
# Output:
--tb=short
# Parallelism:
# -n auto
# --boxed
# Coverage:
# Parallelism:
# -n auto
# --boxed
# Coverage:
--cov=server
--cov=tests
--cov-branch
Expand All @@ -92,26 +92,27 @@ addopts =
--cov-fail-under=0

filterwarnings =
# TODO: get rid of these warnings in our code:
# TODO: get rid of these warnings in our code:
ignore::django.utils.deprecation.RemovedInDjango50Warning
ignore::django.utils.deprecation.RemovedInDjango51Warning
# Some dependencies have deprecation warnings, we don't want to see them,
# but, we want to list them here:
# Some dependencies have deprecation warnings, we don't want to see them,
# but, we want to list them here:
ignore::DeprecationWarning:password_reset.*:
ignore::DeprecationWarning:pytest_freezegun:


markers =
webtest: test make external api call
[coverage:run]
# Coverage configuration:
# https://coverage.readthedocs.io/en/latest/config.html
plugins =
# Docs: https://github.com/nedbat/django_coverage_plugin
# Docs: https://github.com/nedbat/django_coverage_plugin
django_coverage_plugin
# Docs: https://pypi.org/project/covdefaults
# Docs: https://pypi.org/project/covdefaults
covdefaults

omit =
# Is not reported, because is imported during setup:
# Is not reported, because is imported during setup:
server/settings/components/logging.py


Expand Down
Empty file added tests/test_apps/__init__.py
Empty file.
Empty file.
Empty file.
75 changes: 75 additions & 0 deletions tests/test_apps/test_pictures/services/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import json
import re
from re import Pattern
from typing import Iterator, Any

import httpretty
import pytest
from mimesis import Field, Schema, Locale
from typing_extensions import TypedDict

from server.apps.pictures.container import container
from server.apps.pictures.logic.usecases import pictures_fetch
from server.common.django.types import Settings


class PicturesAPIResponse(TypedDict):
id: int
url: str


@pytest.fixture
def seed() -> int:
return Field()('integer_number')


@pytest.fixture
def pictures_expected_api_response(seed: int) -> list[PicturesAPIResponse]:
"""Create fake external api response for pictures."""

mf = Field(locale=Locale.EN, seed=seed)
schema = Schema(
schema=lambda:
{
'id': str(mf('numeric.increment')),
'url': str(mf('url')),
},
)
return list(schema.create())


@pytest.fixture
def pictures_api_mock(
settings: Settings,
pictures_expected_api_response: list[PicturesAPIResponse],
) -> Iterator[list[PicturesAPIResponse]]:
"""Mock external `PLACEHOLDER_API_URL/*` calls."""
with httpretty.httprettized():
_mock_pictures_api(pictures_expected_api_response, re.compile(rf'{settings.PLACEHOLDER_API_URL}.*'))
yield
assert httpretty.has_request()


@pytest.fixture
def pictures_api_mock_corrupted(
settings: Settings,
) -> Iterator[list[PicturesAPIResponse]]:
"""Mock external `PLACEHOLDER_API_URL/*` calls, call returns invalid data"""
with httpretty.httprettized():
invalid_data = [{}]
_mock_pictures_api(invalid_data, re.compile(rf'{settings.PLACEHOLDER_API_URL}.*'))
yield


def _mock_pictures_api(mocked_response: list[Any], api_url: Pattern[str]):
httpretty.register_uri(
method=httpretty.GET,
body=json.dumps(mocked_response),
uri=api_url,
)


@pytest.fixture
def pictures_service() -> pictures_fetch.PicturesFetch:
"""Get pictures service."""
return container.instantiate(pictures_fetch.PicturesFetch)
41 changes: 41 additions & 0 deletions tests/test_apps/test_pictures/services/test_pictures_fetch.py
Copy link

Choose a reason for hiding this comment

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

Немного духоты) Небольшая опечатка в названии функции test_limit_query_params_limits_response_size - либо если param в единственном числе, то он без s, либо если он во множественном, тогда глагол limits после него без s

Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import httpretty
import pytest
from pydantic import TypeAdapter

from server.apps.pictures.intrastructure.services.placeholder import PictureResponse
from server.apps.pictures.logic.usecases import pictures_fetch


class TestPicturesFetchServiceMockedAPI:

@pytest.mark.usefixtures('pictures_api_mock')
def test_service_fetches_expected_pictures(
self,
pictures_expected_api_response: list,
pictures_service: pictures_fetch.PicturesFetch
):
"""Check that `pictures service` returns pictures from external source in expected form."""
pictures_from_service: list[PictureResponse] = pictures_service()
deserialized_pictures_from_net: list[PictureResponse] = (
TypeAdapter(list[PictureResponse]).validate_python(pictures_expected_api_response)
)

assert pictures_from_service == deserialized_pictures_from_net
assert '_limit' in httpretty.last_request().querystring

@pytest.mark.usefixtures('pictures_api_mock_corrupted')
def test_service_raises_value_error_on_invalid_data(
self,
pictures_service: pictures_fetch.PicturesFetch
):
"""Check that `pictures service` raises ValueError when fetched data is invalid."""
with pytest.raises(ValueError):
pictures_service()


@pytest.mark.webtest
class TestPicturesFetchServiceRealAPI:
@pytest.mark.parametrize('limit', [1, 3, 5, 10, 15])
def test_limit_query_params_limits_response_size(self, limit: int, pictures_service: pictures_fetch.PicturesFetch):
pictures = pictures_service(limit)
assert len(pictures) == limit