Skip to content

Commit

Permalink
Merge pull request #28 from hackathone-prosept-team2/feat/tests
Browse files Browse the repository at this point in the history
Feat/tests
  • Loading branch information
ratarov authored Dec 6, 2023
2 parents 6b4cb53 + 23a9551 commit 5fb4872
Show file tree
Hide file tree
Showing 14 changed files with 469 additions and 27 deletions.
24 changes: 0 additions & 24 deletions apps/prices/migrations/0002_load_prices.py

This file was deleted.

4 changes: 2 additions & 2 deletions apps/prices/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ def recommend_products(key_datasets: dict[int, str]) -> None:


@atomic
def create_prices() -> None:
def create_prices(price_data: list[dict] | None = None) -> None:
"""Сервис по созданию Цен дилеров с подбором продуктов к ним."""
data = get_prices_data()
data = price_data if price_data is not None else get_prices_data()
id_counter = get_first_free_dealer_key_id()
prices_datasets = []
keys_to_match = {}
Expand Down
130 changes: 129 additions & 1 deletion 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
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ black = "^23.11.0"
ruff = "^0.1.6"
isort = "^5.12.0"
pre-commit = "^3.5.0"
pytest-django = "^4.7.0"
coverage = "^7.3.2"

[build-system]
requires = ["poetry-core"]
Expand Down
3 changes: 3 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[pytest]
DJANGO_SETTINGS_MODULE = config.settings
python_files = tests.py test_*.py *_tests.py
Empty file added tests/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pytest_plugins = [
"tests.fixtures",
]
56 changes: 56 additions & 0 deletions tests/fixtures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import pytest

from rest_framework.test import APIClient
from rest_framework.authtoken.models import Token

from apps.prices.models import DealerPrice
from apps.prices.services import create_prices

from .utils import TEST_PRICE_DATA


@pytest.fixture
def user(django_user_model):
"""Тестовый пользователь оператор."""
return django_user_model.objects.create_user(
email="[email protected]", password="Password-123"
)


@pytest.fixture
def user_token(user):
"""Токен для оператора."""
token = Token.objects.create(user=user)
return token.key


@pytest.fixture
def user_client(user_token):
"""Аутентифицированный клиент-оператор."""
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=f"Token {user_token}")
return client


@pytest.fixture
def price():
"""Цена для ключа с указанным продуктом."""
return DealerPrice.objects.create(
key_id=1,
price=233,
name="Средство универсальное Prosept Universal Spray, 500мл",
date="2023-07-14",
product_url=(
"https://akson.ru//p/sredstvo_universalnoe"
"_prosept_universal_spray_500ml/"
),
)


@pytest.fixture
def price2():
"""Цена для ключа без подобранного продукта."""
create_prices(price_data=TEST_PRICE_DATA)
key = TEST_PRICE_DATA[0]["product_key"]
dealer_id = TEST_PRICE_DATA[0]["dealer_id"]
return DealerPrice.objects.get(key__key=key, key__dealer_id=dealer_id)
49 changes: 49 additions & 0 deletions tests/test_00_users.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from http import HTTPStatus

import pytest
from rest_framework.test import APIClient

from .utils import USER_VALID_DATA, USER_INVALID_DATA


@pytest.mark.django_db()
class Test00User:
create_url = "/api/v1/auth/users/"
me_url = "/api/v1/auth/users/me/"

@pytest.mark.parametrize("data,messege", USER_VALID_DATA)
def test_01_create_user_success(
self, client: APIClient, data: dict[str, str], messege: str
) -> None:
"""Удачное создание пользователя."""
response = client.post(self.create_url, data=data)
assert response.status_code == HTTPStatus.CREATED, (
f"Попытка создания пользователя с валидными данными ({messege})"
f"не удалась - статус {response.status_code}"
)

@pytest.mark.parametrize("data,messege", USER_INVALID_DATA)
def test_02_create_user_fail(
self, client: APIClient, data: dict[str, str], messege: str
) -> None:
"""Неудачное создание пользователя."""
response = client.post(self.create_url, data=data)
assert response.status_code == HTTPStatus.BAD_REQUEST, (
f"Попытка создания пользователя с невалидными данными ({messege})"
f"вернула статус {response.status_code}"
)

def test_03_me_endpoint(
self, client: APIClient, user_client: APIClient
) -> None:
"""Доступ к ендпоинту аутентифицированного пользователя."""
mapping = (
("гость", client, HTTPStatus.UNAUTHORIZED),
("зарег.юзер", user_client, HTTPStatus.OK),
)
for scenario, conn, status in mapping:
response = conn.get(self.me_url)
assert response.status_code == status, (
f"Попытка доступа {scenario} к данным по ручке /me"
f"вернула статус {response.status_code}"
)
27 changes: 27 additions & 0 deletions tests/test_01_dealers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from http import HTTPStatus

import pytest
from rest_framework.test import APIClient


@pytest.mark.django_db()
class Test01Dealer:
list_url = "/api/v1/dealers/"
get_url = "/api/v1/dealers/1/"
report_url = "/api/v1/dealers/report/"

def test_01_access_to_urls(
self, client: APIClient, user_client: APIClient
) -> None:
"""Доступ к эндпоинтам дилеров для гостя и пользователя."""
mapping = (
("гость", client, HTTPStatus.UNAUTHORIZED),
("зарег.юзер", user_client, HTTPStatus.OK),
)
for scenario, conn, status in mapping:
for url in [self.list_url, self.get_url, self.report_url]:
response = conn.get(url)
assert response.status_code == status, (
f"Попытка доступа {scenario} к {url}"
f"вернула статус {response.status_code}"
)
26 changes: 26 additions & 0 deletions tests/test_02_products.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from http import HTTPStatus

import pytest
from rest_framework.test import APIClient


@pytest.mark.django_db()
class Test02Product:
list_url = "/api/v1/products/"
get_url = "/api/v1/products/1/"

def test_01_access_to_urls(
self, client: APIClient, user_client: APIClient
) -> None:
"""Доступ к эндпоинтам продуктов для гостя и пользователя."""
mapping = (
("гость", client, HTTPStatus.UNAUTHORIZED),
("зарег.юзер", user_client, HTTPStatus.OK),
)
for scenario, conn, status in mapping:
for url in [self.list_url, self.get_url]:
response = conn.get(url)
assert response.status_code == status, (
f"Попытка доступа {scenario} к {url}"
f"вернула статус {response.status_code}"
)
Loading

0 comments on commit 5fb4872

Please sign in to comment.