Testing Strategy
Relevant source files
The following files were used as context for generating this wiki page:The Becathlon project employs a comprehensive testing strategy focused on ensuring code reliability and maintainability, with a stated goal of achieving 90% code coverage. The strategy relies on Django's built-in testing framework, leveraging django.test.TestCase for creating isolated test environments. Tests are organized by application, with dedicated tests.py files for models and views within each app, such as main, cart, order, and profiles.
The testing scope covers unit tests for model logic, view functionality, and API endpoints. This includes testing for correct data creation, validation, business logic, and handling of both valid and invalid user interactions. The use of the coverage tool is integral to the development workflow, providing detailed reports to track and maintain high test coverage across the application suite.
Sources: README.md, apps/cart/tests.py, apps/order/tests.py, apps/main/tests.py, apps/profiles/tests.py
Test Execution and Coverage
The project uses the coverage library to run tests and generate coverage reports. The README.md file provides clear instructions for executing tests.
Running Tests
The following commands are used to run tests and generate reports.
| Command | Description |
|---|---|
coverage run --source='apps' manage.py test | Runs all tests for all applications within the apps directory. |
coverage run --source='apps/<app_name>' manage.py test apps.<app_name> | Runs tests for a specific application. |
coverage report -m | Generates a detailed coverage report in the console. |
Sources: README.md
Coverage Goal
The project has a high standard for testing, with a stated total coverage goal of 90%. This ensures that most of the codebase is verified, reducing the likelihood of regressions and bugs.
Sources: README.md
Test Structure and Patterns
Tests across the project follow a consistent structure, primarily using Django's TestCase and Client for creating isolated database tests and simulating HTTP requests.
Base Test Classes
To reduce code duplication, a base test class pattern is used, as seen in the order app. The BaseOrderTestCase sets up common data needed for multiple test classes.
This diagram shows BaseOrderTestCase inheriting from Django's TestCase to provide shared setup logic.
Sources: apps/order/tests/test_base.py:12-25
Setup and Fixtures
Each test class typically uses a setUp method to create necessary model instances like User, Product, Cart, and Order before each test runs. This ensures a clean state for every test case.
# Example from apps/cart/tests.py
class CartModelTestCase(TestCase):
"""Test cases for Cart model"""
def setUp(self):
"""Set up test data"""
self.user = User.objects.create_user(
username='testuser',
email='test@example.com',
password='testpass123'
)
# ... more setup
Sources: apps/cart/tests.py:11-29, apps/order/tests.py:16-41, apps/main/tests.py:126-144
Application-Specific Testing
Each application module has its own suite of tests covering its models and views.
Main App Testing
Tests for the main app focus on core models like Product and ProductType, as well as the primary views and API endpoints.
Key Tested Components:
- Models:
ProductType: Uniqueness, ordering.Product: Creation, default values (stock, rating), relationships, and ordering.Customer: Creation, relationship withUser, and cascade deletion.
- Views & APIs:
home: Page loads successfully.product_detail: Correctly displays product data and handles 404s./api/products/: Returns a valid JSON response with products and pagination.add_product_ajax: Correctly handles permissions (seller-only), validates data, and creates products.delete_product_ajax: Enforces ownership and account type permissions before deletion.
Sources: apps/main/tests.py
Cart App Testing
The cart app tests cover cart management for both authenticated users and guests.
Key Tested Components:
- Models:
Cart: Creation for users and guests, unique constraints, and methods likeget_total_items(),get_subtotal(), andmerge_carts().CartItem: Creation, subtotal calculation, and unique constraints within a cart.
- Utilities:
get_or_create_cart: Correctly retrieves or creates a cart for both guests and logged-in users.transfer_guest_cart_to_user: Merges a guest's session cart with a user's cart upon login.validate_cart_item_stock: Checks product availability.
- Views & APIs:
add_to_cart: Handles both standard and AJAX requests, increments quantity for existing items, and validates stock.update_cart_item: Updates quantity and removes the item if quantity is zero.remove_from_cart: Deletes an item from the cart.api_cart_summary: Provides a correct JSON summary of the cart.
The following diagram illustrates the logic for transferring a guest cart to a user upon login.
Sources: apps/cart/tests.py:180-230
Order App Testing
The order app has the most extensive test suite, covering the entire checkout flow, order management, and product rating system.
Test Classes:
ShippingAddressModelTestCaseOrderModelTestCaseOrderItemModelTestCasePaymentModelTestCaseProductRatingModelTestCaseOrderViewsTestCase
Key Tested Components:
- Models:
ShippingAddress: Creation with and without optional fields.Order: Creation, status transitions, delivery tracking logic (start_delivery_tracking,get_current_delivery_status), and creation from a cart (create_from_cart).OrderItem: Subtotal calculation and unique product constraint per order.Payment: Creation and status transitions.ProductRating: Creation, unique constraints, and logic for updating the product's aggregate rating.
- Views & APIs:
checkout: Authentication checks, empty cart redirection, and form rendering.process_checkout: Full end-to-end test of a successful checkout, including address and payment validation, order creation, and stock decrementation.order_detail: Ensures a user can only view their own orders.check_delivery_status: API endpoint to get real-time delivery progress.submit_rating: AJAX endpoint for submitting a product rating, with validation to ensure the order is delivered and the product was part of the order.
The sequence diagram below shows a successful checkout process as tested in test_process_checkout_valid_data.
Sources: apps/order/tests.py:628-656
Profiles App Testing
The profiles app tests ensure user profiles are managed correctly, including account type switching.
Key Tested Components:
- Models:
Profile: Automatic creation uponUsercreation (via signals), default values, and methods likeget_full_name().
- Forms:
ProfileForm: Validation for fields likephone.
- Views & APIs:
profile_detail&profile_edit: Authentication, rendering, and successful form submission for both standard and AJAX requests.toggle_newsletter_ajax: Toggles thenewsletter_opt_inflag.switch_account_type_ajax: Switches a user's account type between 'BUYER' and 'SELLER'. It also tests the side effect of deleting a user's products when they switch from 'SELLER' to 'BUYER'.
*Sources: apps/profiles/tests.py
*
Catalog App Testing
The test file for the catalog app is present but currently empty. This indicates a gap in the test coverage for this module.
Sources: apps/catalog/tests.py