Skip to content

Commit

Permalink
Merge pull request #11 from Horlawhumy-dev/add-product-tests
Browse files Browse the repository at this point in the history
Add 100% e2e tests coverage for product endpoints
  • Loading branch information
Horlawhumy-dev authored Jul 4, 2024
2 parents 3456817 + 2981746 commit 1ee6fa9
Show file tree
Hide file tree
Showing 2 changed files with 105 additions and 9 deletions.
21 changes: 12 additions & 9 deletions inventory/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,15 +221,18 @@ class SalesReportView(APIView):
def get(self, request, period='day'):
now = datetime.now()

match period:
case 'day':
start_date = now - timedelta(days=1)
case 'week':
start_date = now - timedelta(weeks=1)
case 'month':
start_date = now - timedelta(days=30)
case _:
return Response({'error': 'Invalid period specified.'}, status=status.HTTP_400_BAD_REQUEST)
start_project = None

#match case would have been better but its only supported by python3.8+

if period == 'day':
start_date = now - timedelta(days=1)
elif period == 'week':
start_date = now - timedelta(weeks=1)
elif period == 'month':
start_date = now - timedelta(days=30)
else:
return Response({'error': 'Invalid period specified.'}, status=status.HTTP_400_BAD_REQUEST)

sales_data = OrderItem.objects.filter(
order__created_at__gte=start_date
Expand Down
93 changes: 93 additions & 0 deletions test/test_product.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from users.models import User
from django.contrib.auth import authenticate
from inventory.models import Product


@pytest.fixture
def api_client():
return APIClient()

@pytest.fixture
def admin_user(db):
user = User.objects.create_user(email='[email protected]', username='admin', password='admin123', is_staff=True)
user.set_password('admin123')
user.metadata = {'is_admin': True}
user.save()
print(f"Admin user created: {user.email}")
return user

@pytest.fixture
def regular_user(db):
user = User.objects.create_user(email='[email protected]', username='user', password='user123')
user.set_password('user123')
user.metadata = {'is_admin': False}
user.save()
print(f"Regular user created: {user.email}")
return user

@pytest.fixture
def product_data():
return {
'name': 'Test Product',
'description': 'Test Description',
'quantity': 10,
'price': 100.0
}

@pytest.fixture
def get_token(api_client):
def _get_token(user, password):
response = api_client.post('/api/users/login/', {'email': user.email, 'password': password}, format='json')
print(f"Login response data: {response.data}")
assert response.status_code == status.HTTP_200_OK, f"Login failed: {response.data}"
return response.data['access']
return _get_token

@pytest.mark.django_db
def test_regular_user_cannot_create_product(api_client, regular_user, product_data, get_token):
token = get_token(regular_user, 'user123')
api_client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
response = api_client.post('/api/inventory/products/add/', product_data, format='json')
print(f"Response for regular user: {response.data}")
assert response.status_code == status.HTTP_403_FORBIDDEN

@pytest.mark.django_db
def test_admin_can_create_product(api_client, admin_user, product_data, get_token):
token = get_token(admin_user, 'admin123')
api_client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
response = api_client.post('/api/inventory/products/add/', product_data, format='json')
print(f"Response for admin user: {response.data}")
assert response.status_code == status.HTTP_201_CREATED
assert response.data['name'] == product_data['name']
assert response.data['description'] == product_data['description']
assert response.data['quantity'] == product_data['quantity']
assert response.data['price'] == product_data['price']
# Check that is_admin is True in user metadata
assert admin_user.metadata['is_admin'] is True

@pytest.fixture
def check_password():
def _check_password(email, password):
user = authenticate(email=email, password=password)
return user is not None
return _check_password

def test_password_check(admin_user, check_password):
assert check_password('[email protected]', 'admin123') is True
assert check_password('[email protected]', 'wrongpassword') is False


@pytest.mark.django_db
def test_create_product_with_valid_data(api_client, admin_user, product_data, get_token):
token = get_token(admin_user, 'admin123')
api_client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
response = api_client.post('/api/inventory/products/add/', product_data, format='json')
assert response.status_code == status.HTTP_201_CREATED
assert Product.objects.filter(name=product_data['name']).exists()

def test_unauthenticated_user_cannot_create_product(api_client, product_data):
response = api_client.post('/api/inventory/products/add/', product_data, format='json')
assert response.status_code == status.HTTP_401_UNAUTHORIZED

0 comments on commit 1ee6fa9

Please sign in to comment.