This repository was archived by the owner on Mar 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
тесты сервиса с картинками #60
Open
nopilei
wants to merge
3
commits into
tough-dev-school:master
Choose a base branch
from
nopilei:master
base: master
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
3 commits
Select commit
Hold shift + click to select a range
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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
Empty file.
Empty file.
Empty file.
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 |
|---|---|---|
| @@ -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
54
tests/test_apps/test_pictures/services/test_pictures_fetch.py
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Немного духоты) Небольшая опечатка в названии функции test_limit_query_params_limits_response_size - либо если param в единственном числе, то он без s, либо если он во множественном, тогда глагол limits после него без s |
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 |
|---|---|---|
| @@ -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 |
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.
httpretty и mimesis по логике лучше вынести в dev зависимости, ибо в текущем виде toml файла они будут устанавливаться и на проде