Skip to content

Commit

Permalink
finished tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ratarov committed Dec 6, 2023
1 parent 049f2a3 commit 23a9551
Show file tree
Hide file tree
Showing 5 changed files with 143 additions and 8 deletions.
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
32 changes: 32 additions & 0 deletions tests/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,54 @@
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)
73 changes: 67 additions & 6 deletions tests/test_03_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,87 @@
import pytest
from rest_framework.test import APIClient

from apps.prices.models import DealerPrice
from config.constants import MATCH_NUMBER, KeyStatus


@pytest.mark.django_db()
class Test03DealerKey:
list_url = "/api/v1/keys/"
get_url = "/api/v1/keys/{key_id}/"
matches_url = "/api/v1/keys/{key_id}/matches/"
prices_url = "/api/v1/keys/{key_id}/prices/"
get_url = "/api/v1/keys/{id}/"
matches_url = "/api/v1/keys/{id}/matches/"
prices_url = "/api/v1/keys/{id}/prices/"
choose_url = "/api/v1/keys/{id}/choose_match/"
decline_url = "/api/v1/keys/{id}/decline_matches/"

def test_01_access_to_urls(
self, client: APIClient, user_client: APIClient
self, client: APIClient, user_client: APIClient, price: DealerPrice
) -> None:
"""Доступ к эндпоинтам продуктов для гостя и пользователя."""
"""Доступ к get-эндпоинтам цен для гостя и пользователя."""
mapping = (
("гость", client, HTTPStatus.UNAUTHORIZED),
("зарег.юзер", user_client, HTTPStatus.OK),
)

urls = [
self.list_url,
self.get_url.format(id=price.key_id),
self.matches_url.format(id=price.key_id),
self.prices_url.format(id=price.key_id),
]

for scenario, conn, status in mapping:
for url in [self.list_url, self.get_url]:
for url in urls:
response = conn.get(url)
assert response.status_code == status, (
f"Попытка доступа {scenario} к {url}"
f"вернула статус {response.status_code}"
)

def test_02_work_with_matches(
self, user_client: APIClient, price2: DealerPrice
) -> None:
"""Работа с подобранными вариантами продуктов для ключей."""
# Получение списка подобранных продуктов
url = self.matches_url.format(id=price2.key_id)
response = user_client.get(url)
assert (
response.status_code == HTTPStatus.OK
), f"GET-запрос к {url} вернул ответ {response.status_code}"

response = response.json()
assert (
len(response) == MATCH_NUMBER
), f"Кол-во подобранных продуктов не равно {MATCH_NUMBER}"

assert response[0]["status"] == KeyStatus.CHECK

# Выбор 1 продукта - первого из списка
chosen_product_id = response[0]["product"]["id"]
response = user_client.post(
self.choose_url.format(id=price2.key_id),
data={"product_id": chosen_product_id},
)

assert response.status_code == HTTPStatus.OK
response = response.json()
assert len(response) == MATCH_NUMBER, (
"Кол-во подобранных продуктов в ответе на выбор 1 варианта "
f"не равно {MATCH_NUMBER}"
)

assert response[0]["status"] == KeyStatus.FOUND
assert response[1]["status"] == KeyStatus.DECLINED

# Отказ от всех подобранных вариантов
response = user_client.post(self.decline_url.format(id=price2.key_id))
assert response.status_code == HTTPStatus.OK

response = response.json()
assert len(response) == MATCH_NUMBER, (
"Кол-во подобранных продуктов в ответе на отказ от "
f"вариантов подбора не равно {MATCH_NUMBER}"
)

assert response[0]["status"] == KeyStatus.DECLINED
assert response[1]["status"] == KeyStatus.DECLINED
25 changes: 25 additions & 0 deletions tests/test_04_prices.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from http import HTTPStatus

import pytest
from rest_framework.test import APIClient

from apps.prices.services import create_prices

from .utils import TEST_PRICE_DATA


@pytest.mark.django_db()
class Test04DealerPrice:
url = "/api/v1/prices/"

def test_01_load_prices_fail(self, user_client: APIClient) -> None:
"""Создание цен и попытка загрузки цен из файла."""
create_prices(TEST_PRICE_DATA)
response = user_client.post(self.url)
assert response.status_code == HTTPStatus.BAD_REQUEST

def test_02_delete_prices_from_db(self, user_client: APIClient) -> None:
"""Удаление всех цен и связанных объектов из базы данных."""

response = user_client.delete(self.url)
assert response.status_code == HTTPStatus.NO_CONTENT
17 changes: 17 additions & 0 deletions tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,20 @@
"пользователь с коротким паролем",
),
)


TEST_PRICE_DATA = [
{
"product_key": "26397139",
"price": "1975.00",
"product_url": (
"https://vimos.ru/product/kraska-dla-plit-osb-"
"prosept-dla-vnutrennih-i-naruznyh-rabot-7-kg"
),
"product_name": (
"Краска для плит OSB Prosept для внутренних и наружных работ 7 кг"
),
"date": "2023-07-14",
"dealer_id": 16,
}
]

0 comments on commit 23a9551

Please sign in to comment.