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 all commits
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
35 changes: 18 additions & 17 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ 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/*.py: S101, WPS201, WPS202, WPS218, WPS226, WPS436, WPS442
# Tests have some more freedom:
tests/*.py: S101, WPS201, WPS202, WPS218, WPS226, WPS436, WPS442, WPS305, WPS306, WPS118, PT011, WPS300


[isort]
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.
85 changes: 85 additions & 0 deletions tests/test_apps/test_pictures/services/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import json
import re
from typing import Any, Iterator, cast

import httpretty
import pytest
from mimesis import Field, Locale, Schema
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):
"""Representation of single object from pictures service api."""

id: int
url: str


@pytest.fixture()
def seed() -> int:
"""Seed for generation random data."""
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': mf('numeric.increment'),
'url': str(mf('url')),
},
)
return cast(list[PicturesAPIResponse], list(schema.create()))


@pytest.fixture()
def api_url(settings: Settings) -> re.Pattern[str]:
"""Regex of picture API url."""
return re.compile(f'{settings.PLACEHOLDER_API_URL}.*')


@pytest.fixture()
def _pictures_api_mock(
api_url: re.Pattern[str],
pictures_expected_api_response: list[PicturesAPIResponse],
) -> Iterator[None]:
"""Mock external `PLACEHOLDER_API_URL/*` calls."""
with httpretty.httprettized():
_mock_pictures_api(pictures_expected_api_response, api_url)
yield
assert httpretty.has_request()


@pytest.fixture()
def _pictures_api_mock_corrupted(
api_url: re.Pattern[str],
) -> Iterator[None]:
"""Mock external `PLACEHOLDER_API_URL/*` calls, returns invalid data."""
with httpretty.httprettized():
invalid_data: list[dict[str, Any]] = [{}]
_mock_pictures_api(invalid_data, api_url)
yield


def _mock_pictures_api(
mocked_response: list[Any],
api_url: re.Pattern[str],
) -> None:
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)
54 changes: 54 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,54 @@
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

from .conftest import PicturesAPIResponse


class TestPicturesFetchServiceMockedAPI:
"""Test with mocked API."""

@pytest.mark.usefixtures('_pictures_api_mock')
def test_service_fetches_expected_pictures(
self,
pictures_expected_api_response: list[PicturesAPIResponse],
pictures_service: pictures_fetch.PicturesFetch,
) -> None:
"""Check that API call returns pictures in expected form."""
pictures_from_service: list[PictureResponse] = pictures_service()
type_adapter = TypeAdapter(list[PictureResponse])
deserialized_pictures_from_net: list[PictureResponse] = (
type_adapter.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,
) -> None:
"""Check that service raises ValueError when fetched data is invalid."""
with pytest.raises(ValueError):
pictures_service()


@pytest.mark.webtest()
class TestPicturesFetchServiceRealAPI:
"""Test with real API."""

@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,
) -> None:
"""Tests `limit` query param."""
pictures = pictures_service(limit)
assert len(pictures) == limit