Skip to content

Commit

Permalink
Написал тесты для приложений
Browse files Browse the repository at this point in the history
  • Loading branch information
Abramov0Alexandr committed Sep 29, 2023
1 parent f819bf5 commit 2c2297f
Show file tree
Hide file tree
Showing 9 changed files with 306 additions and 3 deletions.
File renamed without changes.
60 changes: 60 additions & 0 deletions custom_user/tests/test_common_user_creation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase


class CommonUserCreate(APITestCase):

def test_success_creation(self):
"""Тесткейс успешного создания нового пользователя"""

users_data: dict = {
"first_name": "Alex",
"last_name": "Abramov",
"email": "common@user.ru",
"phone": "800000000",
"password": "123654",
"password_confirmation": "123654"
}

response = self.client.post(reverse('custom_user:custom_user_create'), data=users_data)

self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(),
{'message': 'Регистрация успешно завершена!',
'status': status.HTTP_201_CREATED})

def test_failed_password_confirmation(self):
"""Тесткейс при неверной передачи значения password_confirmation"""

users_data: dict = {
"first_name": "Ivan",
"last_name": "Ivanov",
"email": "common@user.ru",
"phone": "800000000",
"password": "123654",
"password_confirmation": "000000"
}

response = self.client.post(reverse('custom_user:custom_user_create'), data=users_data)

self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(),
{'non_field_errors': ['Пароль и его подтверждение не совпадают']})

def test_no_password_confirmation(self):
"""Тесткейс при отсутствии значения password_confirmation"""

users_data: dict = {
"first_name": "Ivan",
"last_name": "Ivanov",
"email": "common@user.ru",
"phone": "800000000",
"password": "123654"
}

response = self.client.post(reverse('custom_user:custom_user_create'), data=users_data)

self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(),
{'password_confirmation': ['Обязательное поле.']})
58 changes: 58 additions & 0 deletions custom_user/tests/test_seller_creation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase


class CommonUserCreateTestCase(APITestCase):

def test_success_creation(self):
"""Тесткейс успешного создания нового продавца"""

seller_data: dict = {
"is_seller": True,
"shop_name": "ASOS",
"email": "asos@shop.com",
"password": "123654",
"password_confirmation": "123654"
}

response = self.client.post(reverse('custom_user:custom_user_create'), data=seller_data)

self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(),
{'message': 'Вы зарегистрированы в качестве продавца и можете размещать товары на площадке',
'shop_title': 'ASOS',
'status': 201})

def test_failed_password_confirmation(self):
"""Тесткейс при неверной передачи значения password_confirmation"""

seller_data: dict = {
"is_seller": True,
"shop_name": "ASOS",
"email": "asos@shop.com",
"password": "123654",
"password_confirmation": "000000"
}

response = self.client.post(reverse('custom_user:custom_user_create'), data=seller_data)

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json(),
{'non_field_errors': ['Пароль и его подтверждение не совпадают']})

def test_no_password_confirmation(self):
"""Тесткейс при отсутствии значения password_confirmation"""

seller_data: dict = {
"is_seller": True,
"shop_name": "ASOS",
"email": "asos@shop.com",
"password": "123654",
}

response = self.client.post(reverse('custom_user:custom_user_create'), data=seller_data)

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json(),
{'password_confirmation': ['Обязательное поле.']})
3 changes: 0 additions & 3 deletions products/tests.py

This file was deleted.

Empty file added products/tests/__init__.py
Empty file.
40 changes: 40 additions & 0 deletions products/tests/test_change_sale_status.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from custom_user.models import CustomUser
from products.models import Product


class ProductChangeSaleStatusTestCase(APITestCase):

def setUp(self) -> None:
"""Предварительное наполнение БД для дальнейших тестов."""

self.seller = CustomUser.objects.create(
is_seller=True,
shop_name='ASOS',
email='asos@shop.com',
password='123654'
)

self.product = Product.objects.create(
seller=self.seller,
product_title='Product Title',
price='1000.00'
)

"""Имитация авторизации пользователя по JWT токену."""
self.client = APIClient()
self.client.force_authenticate(user=self.seller)

def test_change_status(self):

response = self.client.patch(f'/products/change_status/{self.product.id}/')

self.assertEqual(response.status_code, status.HTTP_200_OK)

self.assertEqual(response.json(),
{"Product info": {
"sale status": "False",
"message": "Product Title снят с продажи",
"status": 200
}})
42 changes: 42 additions & 0 deletions products/tests/test_detail_product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from custom_user.models import CustomUser
from products.models import Product


class ProductDetailTestCase(APITestCase):

def setUp(self) -> None:
"""Предварительное наполнение БД для дальнейших тестов."""

self.seller = CustomUser.objects.create(
is_seller=True,
shop_name='ASOS',
email='asos@shop.com',
password='123654'
)

self.product = Product.objects.create(
seller=self.seller,
product_title='Product Title',
price='1000.00'
)

"""Имитация авторизации пользователя по JWT токену."""
self.client = APIClient()
self.client.force_authenticate(user=self.seller)

def test_retrieve_product(self):

response = self.client.get(f'/products/detail/{self.product.id}/')

self.assertEqual(response.status_code, status.HTTP_200_OK)

self.assertEqual(response.json(),
{'id': self.product.id,
'shop_title': self.seller.shop_name,
'seller': self.seller.email,
'product_title': self.product.product_title,
'price': self.product.price,
'is_active_sale': True}
)
60 changes: 60 additions & 0 deletions products/tests/test_product_create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIClient
from custom_user.models import CustomUser


class ProductCreateTestCase(APITestCase):

def setUp(self) -> None:
"""Предварительное наполнение БД для дальнейших тестов."""

self.seller = CustomUser.objects.create(
is_seller=True,
shop_name="ASOS",
email="asos@shop.com",
password="123654"
)

self.common_user = CustomUser.objects.create(
first_name="Alex",
last_name="Abramov",
email="common@user.ru",
phone="800000000",
password="123654",
)

self.product_data = {
'product_title': 'Product Title',
'price': '1000'
}

"""Имитация авторизации пользователя по JWT токену."""
self.client = APIClient()

def test_success_product_create(self):
"""Успешное создание нового товара продавцом"""

self.client.force_authenticate(user=self.seller)
response = self.client.post(reverse('products:create-product'), data=self.product_data)

self.assertEqual(response.status_code, status.HTTP_201_CREATED)

self.assertEqual(response.json(),
{
'id': 3,
'shop_title': 'ASOS',
'seller': 'asos@shop.com',
'product_title': 'Product Title',
'price': '1300.00',
'is_active_sale': True
}
)

def test_restrict_permission(self):
"""Тестирование ограничения доступа к размещению товара обычным пользователем"""

self.client.force_authenticate(user=self.common_user)
response = self.client.post(reverse('products:create-product'), data=self.product_data)

self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
46 changes: 46 additions & 0 deletions products/tests/test_product_list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, APIClient
from custom_user.models import CustomUser
from products.models import Product


class ProductListTestCase(APITestCase):

def setUp(self) -> None:
"""Предварительное наполнение БД для дальнейших тестов."""

self.seller = CustomUser.objects.create(
is_seller=True,
shop_name='ASOS',
email='asos@shop.com',
password='123654'
)

self.product = Product.objects.create(
seller=self.seller,
product_title='Product Title',
price='1000.00'
)

"""Имитация авторизации пользователя по JWT токену."""
self.client = APIClient()
self.client.force_authenticate(user=self.seller)

def test_product_list(self):
"""Тест для проверки вывода списка продуктов"""

response = self.client.get(reverse('products:products-list'))

self.assertEqual(response.status_code, status.HTTP_200_OK)

self.assertEqual(response.json()[0],
{
'id': self.product.id,
'shop_title': self.seller.shop_name,
'seller': self.seller.email,
'product_title': self.product.product_title,
'price': '1000.00',
'is_active_sale': True
}
)

0 comments on commit 2c2297f

Please sign in to comment.