Ran 0 tests
Likely cause: The command ran from an unexpected directory or the app label was omitted in a different working context.
Check and correct: Open the directory containing manage.py and run python manage.py test orders --verbosity 2.
PROJECT 7 · LESSON 14 OF 16
Use staff permissions for order fulfillment and test meaningful application guarantees.
Continue from lesson 13: Build cash-on-delivery checkout and order history. Keep existing files; create or replace the complete files listed below.
Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.
The customer flow is only half of ecommerce. Staff need controlled catalog and fulfillment tools, and you need repeatable evidence that important rules still hold after changes.
Staff manage products through the existing Product admin and ship orders through a dedicated action. Order totals and snapshots remain read-only so fulfillment does not rewrite a purchase.
The test database is separate from development records. Tests create synthetic users and products. SQLite tests verify functional behavior, but they do not establish PostgreSQL row-lock guarantees; deployment verification includes the last-unit concurrency test.
A customer can register and view their own orders. A staff account can access admin only when is_staff is enabled and the relevant model permissions are granted. A superuser has broad privileges and is useful for initial setup, but routine staff should receive the smallest necessary set of permissions.
Use admin’s Users and Groups screens to create a fulfillment group with view and change order permissions, and catalog permissions only when needed. Keep add/delete order permissions absent. Test the staff account separately from the superuser; a superuser can hide missing-permission mistakes because it bypasses ordinary permission checks.
Product admin permits catalog updates. Order admin makes customer details, totals and snapshot lines read-only and disables creating or deleting orders manually. The mark-shipped action changes only placed orders when the staff user has change permission. This preserves the meaning of the checkout service as the source of order creation.
This workflow covers placed to shipped fulfillment. It does not implement returns, cancellation stock restoration, shipping-provider integration or payment settlement. Add each as an explicit state transition with its own permissions and tests instead of allowing arbitrary edits to historical totals.
Django TestCase creates an isolated test database and clears state between tests. The test client sends requests without opening a browser. force_login is useful when testing authorization after authentication; it does not test password verification. Client(enforce_csrf_checks=True) explicitly enables CSRF enforcement for that security test.
The suite checks foreign task access, own-task CRUD, invalid input, POST-only cart actions, missing CSRF, snapshot prices, duplicate checkout, rollback, private order history and tampered checkout tokens. These tests assert observable outcomes such as stock and record count rather than copying implementation statements.
Run tests from the directory containing manage.py. From production-settings checkpoints onward run collectstatic before the tests because DEBUG=False in tests activates manifest lookup. The suite runs on SQLite locally. It verifies rollback and idempotent behavior sequentially; it does not simulate PostgreSQL row locks or prove concurrent checkout correctness.
Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.
Create or grant a staff account the required model permissions.
Staff open admin and inspect immutable order details.
The fulfillment action checks permission and updates eligible placed orders.
The test runner builds an isolated database and creates two customers and products.
Requests and service calls exercise allowed, forbidden and repeated actions, then assert database outcomes.
python manage.py test orders
python manage.py check
python manage.py makemigrations --check --dry-runThe paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.
Expose fulfillment without allowing staff to create or rewrite order history.
from django.contrib import admin
from .models import Order, OrderItem
class OrderItemInline(admin.TabularInline):
model = OrderItem
extra = 0
can_delete = False
fields = ["product", "name", "price", "quantity"]
readonly_fields = fields
def has_add_permission(self, request, obj=None):
return False
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
list_display = ["id", "user", "total", "status", "created_at"]
list_filter = ["status", "created_at"]
search_fields = ["recipient", "user__username"]
readonly_fields = ["user", "token", "recipient", "address", "postal_code", "phone", "total", "status", "created_at"]
inlines = [OrderItemInline]
actions = ["mark_shipped"]
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.action(description="Mark placed orders as shipped", permissions=["change"])
def mark_shipped(self, request, queryset):
count = queryset.filter(status=Order.Status.PLACED).update(status=Order.Status.SHIPPED)
self.message_user(request, f"{count} orders marked shipped.")
Verify ownership, form behavior, CSRF, server prices, rollback and replay protection.
import uuid
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase, Client
from django.urls import reverse
from shop.models import Product
from tasks.models import Task
from .models import Order
from .services import CheckoutError, place_order
class StoreTests(TestCase):
def setUp(self):
self.a = get_user_model().objects.create_user(username="alice", password="Learn-Test-94!")
self.b = get_user_model().objects.create_user(username="bob", password="Learn-Test-95!")
self.product = Product.objects.create(name="Notebook", slug="notebook", price=Decimal("249.00"), stock=3)
self.delivery = dict(recipient="Learner", address="Test address only", postal_code="500001", phone="0000000000")
def test_foreign_task_is_inaccessible(self):
task = Task.objects.create(title="Alice task", owner=self.a)
self.client.force_login(self.b)
for action in ("edit", "delete"):
url = reverse(f"tasks:{action}", args=[task.pk])
self.assertEqual(self.client.get(url).status_code, 404)
self.assertEqual(self.client.post(url, {"title": "Changed"}).status_code, 404)
task.refresh_from_db()
self.assertEqual(task.title, "Alice task")
def test_task_crud_and_validation(self):
self.client.force_login(self.a)
self.client.post(reverse("tasks:create"), {"title": " Study "})
task = Task.objects.get(owner=self.a)
self.assertEqual(task.title, "Study")
self.client.post(reverse("tasks:edit", args=[task.pk]), {"title": "Practice", "completed": "on"})
task.refresh_from_db()
self.assertTrue(task.completed)
self.client.get(reverse("tasks:delete", args=[task.pk]))
self.assertTrue(Task.objects.filter(pk=task.pk).exists())
self.client.post(reverse("tasks:delete", args=[task.pk]))
self.assertFalse(Task.objects.exists())
self.client.post(reverse("tasks:create"), {"title": " "})
self.assertFalse(Task.objects.exists())
def test_cart_post_and_csrf(self):
url = reverse("shop:cart-add", args=[self.product.pk])
self.assertEqual(self.client.get(url).status_code, 405)
self.assertEqual(Client(enforce_csrf_checks=True).post(url).status_code, 403)
self.client.post(url)
self.assertEqual(self.client.session["cart"][str(self.product.pk)], 1)
self.client.post(reverse("shop:cart-update", args=[self.product.pk]), {"quantity": "-2"})
self.assertEqual(self.client.session["cart"][str(self.product.pk)], 1)
def test_idempotent_order_and_snapshot(self):
token = uuid.uuid4()
order = place_order(user=self.a, token=token, cart={str(self.product.pk): 2}, delivery=self.delivery)
replay = place_order(user=self.a, token=token, cart={}, delivery=self.delivery)
self.assertEqual(order.pk, replay.pk)
self.assertEqual(Order.objects.count(), 1)
self.product.refresh_from_db()
self.assertEqual(self.product.stock, 1)
self.assertEqual(order.total, Decimal("498.00"))
self.product.price = Decimal("999.00")
self.product.save()
self.assertEqual(order.items.get().price, Decimal("249.00"))
def test_multiline_failure_rolls_back_stock(self):
empty = Product.objects.create(name="Lamp", slug="lamp", price=Decimal("10.00"), stock=0)
with self.assertRaises(CheckoutError):
place_order(user=self.a, token=uuid.uuid4(), cart={str(self.product.pk): 1, str(empty.pk): 1}, delivery=self.delivery)
self.product.refresh_from_db()
self.assertEqual(self.product.stock, 3)
self.assertFalse(Order.objects.exists())
def test_checkout_view_and_private_history(self):
self.client.force_login(self.a)
self.client.post(reverse("shop:cart-add", args=[self.product.pk]))
page = self.client.get(reverse("orders:checkout"))
token = page.context["form"].initial["token"]
response = self.client.post(reverse("orders:checkout"), {**self.delivery, "token": token, "total": "0.01"})
order = Order.objects.get()
self.assertRedirects(response, reverse("orders:detail", args=[order.pk]))
self.assertEqual(order.total, Decimal("249.00"))
self.client.post(reverse("orders:checkout"), {**self.delivery, "token": token})
self.assertEqual(Order.objects.count(), 1)
self.client.force_login(self.b)
self.assertEqual(self.client.get(reverse("orders:detail", args=[order.pk])).status_code, 404)
self.assertNotContains(self.client.get(reverse("orders:list")), "Order " + str(order.pk))
self.assertEqual(self.client.get("/admin/").status_code, 302)
def test_tampered_checkout_token(self):
self.client.force_login(self.a)
response = self.client.post(reverse("orders:checkout"), {**self.delivery, "token": "tampered"})
self.assertContains(response, "Checkout expired")
self.assertFalse(Order.objects.exists())
Temporarily remove owner filtering from one task lookup and run the tests.
The foreign-task test fails. Restore the filter and rerun.
The test expresses the privacy requirement independently of the view’s current implementation, so it detects this meaningful regression.
Changing absolute stock in an old admin form can overwrite a concurrent adjustment. In a busy store, use audited inventory adjustments or optimistic version checks.
Likely cause: The command ran from an unexpected directory or the app label was omitted in a different working context.
Check and correct: Open the directory containing manage.py and run python manage.py test orders --verbosity 2.
Likely cause: Production storage is configured but collectstatic has not generated its manifest.
Check and correct: Run python manage.py collectstatic --noinput before the test suite in the final checkpoints.
Add a test that archived products cannot be ordered, then implement any missing behavior.
Attempt these questions before opening the explanations. Use the source above to justify your answer.
Failures can corrupt stock or disclose data. Rollback, replay and ownership tests cover different business guarantees than the happy path.
No. PostgreSQL concurrency must be exercised separately against PostgreSQL, ideally with independent connections and simultaneous checkout attempts.