Skip to content

Commit

Permalink
Added comprehensive API test cases for Product and User
Browse files Browse the repository at this point in the history
  • Loading branch information
Nathaniel81 committed May 11, 2024
1 parent e73edf8 commit 992bd14
Show file tree
Hide file tree
Showing 2 changed files with 233 additions and 4 deletions.
82 changes: 80 additions & 2 deletions accounts/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,81 @@
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APITestCase, APIClient
from rest_framework.views import status
from accounts.models import User
from django.conf import settings
from rest_framework_simplejwt.tokens import RefreshToken

# Create your tests here.
class UserAuthenticationTestCase(APITestCase):
"""
Test Cases for the User Model
"""

def setUp(self):
self.client = APIClient()
self.user = User.objects.create_user(
email='[email protected]',
username='testuser',
password='testpass'
)

def test_token_obtain_pair(self):
"""
Test case to verify the obtainment of authentication tokens via API.
"""
response = self.client.post(
reverse('token_obtain_pair'),
{
'email': '[email protected]',
'password': 'testpass'
}
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(settings.SIMPLE_JWT['AUTH_COOKIE'] in response.cookies)
self.assertTrue(settings.SIMPLE_JWT['AUTH_COOKIE_REFRESH'] in response.cookies)

def test_token_obtain_pair_wrong_credentials(self):
"""
Test case to verify that unauthorized access is denied when using incorrect credentials to obtain tokens.
"""
response = self.client.post(
reverse('token_obtain_pair'),
{
'email': 'wronguser@email',
'password': 'wrongpass'
}
)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

def test_registration(self):
"""
Test case to verify the user registration functionality via API.
"""
response = self.client.post(
reverse('registration'),
{
'username': 'testuser1',
'email': '[email protected]',
'password': 'testpass',
'confirmPassword': 'testpass'
}
)

self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(User.objects.filter(username='testuser').exists())
self.assertTrue(settings.SIMPLE_JWT['AUTH_COOKIE'] in response.cookies)
self.assertTrue(settings.SIMPLE_JWT['AUTH_COOKIE_REFRESH'] in response.cookies)

def test_registration_existing_user(self):
"""
Test case to verify that registration fails when attempting to create an account with an existing username.
"""
User.objects.create_user(username='existinguser', password='testpass')
response = self.client.post(reverse('registration'),
{
'username': 'existinguser',
'email': '[email protected]',
'password': 'testpass',
'confirmPassword': 'testpass'
}
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
155 changes: 153 additions & 2 deletions core/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,154 @@
from django.test import TestCase
from decimal import Decimal

from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from rest_framework.test import APIClient, APITestCase
from rest_framework_simplejwt.tokens import RefreshToken
from django.conf import settings

from accounts.models import User

from .models import Category, Order, OrderItem, Product
from .serializers import ProductSerializer


# class CategoryAPITestCase(APITestCase):
# """
# Test case for Product
# """

# def setUp(self):
# self.client = APIClient()
# self.category = Category.objects.create(name='Electronics', image='electronics-img.png')
# self.assertEqual(Category.objects.count(), 1)

# def test_category_str_method(self):
# self.assertEqual(str(self.category), 'Electronics')

# def test_get_categories(self):
# response = self.client.get(reverse('categories'))
# self.assertEqual(response.status_code, status.HTTP_200_OK)

class ProductAPITestCase(TestCase):
"""
Test case for Product
"""

def setUp(self):
self.client = APIClient()
self.user = User.objects.create_user(username='testuser', password='testpass')
self.category1 = Category.objects.create(name='TestCategory1')
self.category2 = Category.objects.create(name='TestCategory2')
self.product = Product.objects.create(
user=self.user,
name='TestProduct',
brand='TestBrand',
category=self.category1,
description='TestDescription',
price=Decimal('123.45'),
countInStock=0,
)
self.product1 = Product.objects.create(
user=self.user,
name='TestProduct1',
brand='TestBrand',
category=self.category1,
description='TestDescription',
price=Decimal('123.45'),
countInStock=10,
)
self.product2 = Product.objects.create(
user=self.user,
name='TestProduct2',
brand='TestBrand',
category=self.category2,
description='TestDescription',
price=Decimal('123.45'),
countInStock=0,
)

refresh = RefreshToken.for_user(self.user)
self.access_token = str(refresh.access_token)

def test_is_new(self):
"""
Test case to verify the 'is_new' property of the Product model.
"""
# Test that a product created just now is considered new
self.assertTrue(self.product.is_new)

# Test that a product created 8 days ago is not considered new
old_product = Product.objects.create(
user=self.user,
name='OldProduct',
brand='TestBrand',
category=self.category1,
description='TestDescription',
price=Decimal('123.45'),
countInStock=10,
)
old_product.createdAt = timezone.now() - timezone.timedelta(days=8)
old_product.save()

self.assertFalse(old_product.is_new)

def test_get_products(self):
"""
Test case to verify the retrieval of all products via API.
"""

response = self.client.get(reverse('products'))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)

def test_get_products_by_category(self):
"""
Test case to verify the retrieval of products by category via API.
"""

response = self.client.get(reverse('products'), {'category': 'TestCategory1'})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)

def test_get_product_detail(self):
"""
Test case to verify the retrieval of product details via API.
"""

response = self.client.get(reverse('product-detail', kwargs={'pk': self.product1.pk}))
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['name'], 'TestProduct1')

def test_get_product_detail_not_found(self):
"""
Test case to verify that an error is returned when trying to retrieve details of a non-existent product via API.
"""

response = self.client.get(reverse('product-detail', kwargs={'pk': 9999}))
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)

def test_search_products(self):
"""
Test case to verify the search functionality for products via API.
"""
response = self.client.get(reverse('search-products-list'), {'query': 'TestProduct'})
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Only one product matches the search query and is in stock
self.assertEqual(len(response.data), 1)

def test_search_products_by_category(self):
"""
Test case to verify the search functionality for products by category via API.
"""
response = self.client.get(reverse('search-products-list'),
{
'query': 'TestProduct',
'category': 'TestCategory1'
}
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)
self.assertEqual(response.data[0]['name'], 'TestProduct1')

# Create your tests here.

0 comments on commit 992bd14

Please sign in to comment.