{"id":306,"date":"2026-11-16T12:00:00","date_gmt":"2026-11-16T12:00:00","guid":{"rendered":"https:\/\/rezachegini.com\/?p=306"},"modified":"2026-11-16T19:20:30","modified_gmt":"2026-11-16T19:20:30","slug":"building-a-job-board-api-part-19-who-can-do-what-and-what-the-api-really-does","status":"publish","type":"post","link":"https:\/\/rezachegini.com\/?p=306","title":{"rendered":"Building a Job Board API, Part 19: Who Can Do What, and What the API Really Does"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">I&#8217;m sharing one of my projects here from the beginning, step by step. It&#8217;s a Job Board API built with Django, Django REST Framework, PostgreSQL and Docker Compose, with S3 and SQS (through LocalStack), Redis, and a background worker.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I&#8217;m a junior engineer looking for my first role in DevOps, SRE or Cloud. That&#8217;s why I build projects like this and write about them in public. It shows how I think, and writing it down helps me really understand it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Part 18 I set up the tests and wrote the first unit tests. This part answers two questions:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Who can do what? Permission tests: unit tests for each permission class, and a matrix that tries every protected action as every kind of user.<\/li><li>What does each endpoint really do? API tests for signup, login, jobs, filters and applications.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">On the way, one fixture made the whole suite 29 times faster.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Part 1: testing the permission classes directly<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">I have four permission classes from Part 5: <code>IsVerifiedCompany<\/code>, <code>IsCandidate<\/code>, <code>IsJobOwner<\/code> and <code>IsApplicantOwner<\/code>. They only read <code>request.user<\/code>, so I don&#8217;t need a full HTTP request to test them:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from types import SimpleNamespace\n\n\ndef req(user):\n    return SimpleNamespace(user=user)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>SimpleNamespace(user=...)<\/code> is a tiny object with one attribute. That&#8217;s all the classes need.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_is_verified_company(make_company, make_candidate):\n    permission = IsVerifiedCompany()\n\n    assert not permission.has_permission(req(AnonymousUser()), None)\n    assert not permission.has_permission(req(make_candidate().user), None)\n    assert permission.message == \"Only company accounts can do this.\"\n    assert permission.has_permission(req(make_company(\"acme\").user), None)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>AnonymousUser<\/code> is what Django puts on <code>request.user<\/code> when nobody is logged in. Its <code>is_authenticated<\/code> is <code>False<\/code>, and it has no <code>is_company<\/code> or <code>is_candidate<\/code> attribute.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The anonymous case works only because the class checks <code>not user.is_authenticated<\/code> first. Python&#8217;s <code>or<\/code> stops there, so the missing <code>is_company<\/code> is never read. If someone reordered those checks, this test would crash with <code>AttributeError<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>None<\/code> for the view, because the class doesn&#8217;t use it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">A message that explains why<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>IsVerifiedCompany<\/code> changes its own message to explain why access was denied. The tests check both cases, an unverified company and an &#8220;orphan&#8221; (a company-role user with no <code>Company<\/code> row), and they both get &#8220;Your company account is not verified.&#8221;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The orphan works because of <code>getattr(user, \"company\", None)<\/code>. Django&#8217;s &#8220;related object does not exist&#8221; error is a subclass of <code>AttributeError<\/code>, which <code>getattr<\/code> with a default catches.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The last line is the important one:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>assert IsVerifiedCompany.message == \"Only company accounts can do this.\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The message is changed on the instance, not the class. DRF creates a new permission object for every request. If the class default changed, one denied request could change the message for the next user.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The other three classes<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>IsCandidate<\/code>: anonymous, a company and a candidate role without a profile are all denied. The role alone isn&#8217;t enough, because applying needs a <code>candidate_profile<\/code>. <code>IsJobOwner<\/code>: tested with both a <code>Job<\/code> and an <code>Application<\/code>. It uses <code>obj.job<\/code> for applications, which is how one class protects both job updates and status changes. Another company, a candidate and anonymous are denied. <code>IsApplicantOwner<\/code>: two kinds of owner may read an application: the applicant and the job&#8217;s company. Another candidate and another company may not.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>has_object_permission(request, view, obj)<\/code> is the object-level check. Remember this one: it matters in the next section.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Part 2: the matrix through the real endpoints<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Unit tests prove each class is correct. But a class can be correct and still wired wrong, for example attached to the wrong action in <code>get_permissions()<\/code>. So the second set of tests goes through the real endpoints.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">One small world with every kind of user<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@pytest.fixture\ndef world(make_company, make_candidate, make_job, make_application):\n    acme = make_company(\"acme\", verified=True)\n    globex = make_company(\"globex\", verified=True)\n    initech = make_company(\"initech\", verified=False)\n    sam = make_candidate(\"sam\", skills=[\"aws\"])\n    riya = make_candidate(\"riya\")\n    job = make_job(acme, required_skills=[\"aws\"])\n    application = make_application(job, sam, resume=\"resume\/job-test\/cv.pdf\")\n    users = {\n        \"anon\": None,\n        \"acme\": acme.user,\n        \"globex\": globex.user,\n        \"initech\": initech.user,\n        \"sam\": sam.user,\n        \"riya\": riya.user,\n    }\n    return SimpleNamespace(job=job, application=application, users=users)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Six actors:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>acme, the job&#8217;s owner;<\/li><li>globex, another verified company;<\/li><li>initech, an unverified company;<\/li><li>sam, the applicant;<\/li><li>riya, another candidate;<\/li><li>anon, nobody.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The names match my manual <code>curl<\/code> checks from earlier phases. And <code>resume=<\/code> is only a file name: no upload happens. Creating a presigned URL is a local signing calculation, so the resume endpoint works without S3.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@pytest.fixture\ndef client_for(world):\n    def _client(who):\n        client = APIClient()\n        if world.users[who] is not None:\n            client.force_authenticate(user=world.users[who])\n        return client\n\n    return _client<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>APIClient<\/code> is DRF&#8217;s test client. It understands <code>format=\"json\"<\/code> and <code>\"multipart\"<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>force_authenticate(user=...)<\/code> skips JWT completely and logs the request in as that user. The matrix is about who the user is, not about tokens. The real token flow has its own tests later in this article.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For <code>anon<\/code>, there&#8217;s no authentication at all.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The matrix tests<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Each test tries one action as several users, with <code>parametrize<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@pytest.mark.parametrize(\n    (\"who\", \"expected\"),\n    [(\"anon\", 401), (\"sam\", 403), (\"initech\", 403), (\"acme\", 201), (\"globex\", 201)],\n)\ndef test_only_verified_companies_post_jobs(client_for, who, expected):\n    response = client_for(who).post(\"\/api\/jobs\/\", NEW_JOB, format=\"json\")\n\n    assert response.status_code == expected<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A candidate is the wrong role, and initech isn&#8217;t verified.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Two verified companies succeed with <code>201 Created<\/code>, so the rule really is &#8220;verified companies&#8221;, not &#8220;only acme&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A second test checks the <code>403<\/code> body: initech gets &#8220;Your company account is not verified.&#8221; and sam gets &#8220;Only company accounts can do this.&#8221;. The response tells the user what to do.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">401 or 403?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>401<\/code> means &#8220;who are you?&#8221;: no credentials, or bad ones.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>403<\/code> means &#8220;I know who you are, and you can&#8217;t do this&#8221;.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Anonymous users get <code>401<\/code>, not <code>403<\/code>. DRF returns <code>401<\/code> when the request isn&#8217;t authenticated and the authenticator can send a <code>WWW-Authenticate<\/code> header. The JWT authenticator does (<code>Bearer realm=\"api\"<\/code>).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Denied means nothing changed<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is the most important idea in the matrix:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@pytest.mark.parametrize(\n    (\"who\", \"expected\"),\n    [(\"anon\", 401), (\"sam\", 403), (\"globex\", 403), (\"acme\", 200)],\n)\ndef test_only_the_owner_updates_a_job(client_for, world, who, expected):\n    response = client_for(who).patch(\n        f\"\/api\/jobs\/{world.job.id}\/\", {\"title\": \"Changed\"}, format=\"json\"\n    )\n    world.job.refresh_from_db()\n\n    assert response.status_code == expected\n    assert (world.job.title == \"Changed\") == (expected == 200)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>refresh_from_db()<\/code> reloads the row from the database. The last line says: the title changed if and only if the request was allowed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Why check the data and not only the status code? Because a view could save first and check permissions later. It would return <code>403<\/code> and still have changed the data. A status check alone would pass. This line catches it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The same idea protects status changes. The applicant can&#8217;t change their own status, which is a real risk: a candidate moving themselves to &#8220;offered&#8221;. After the request, the test reloads the application and checks the status is still <code>submitted<\/code> unless the job&#8217;s owner did it.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The other rows<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Reading jobs needs any login, and nothing more. Even an unverified company may browse.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The applicants list contains other people&#8217;s names and match scores. Only the job&#8217;s owner gets <code>200<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Applying: sam gets <code>400<\/code> on purpose. An empty body passes the permission check and fails validation. The <code>400<\/code> proves he got through the permission. A real successful apply needs an S3 upload, which is in the next article.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reading an application and the resume link (a working download link to someone&#8217;s CV, the most sensitive endpoint): only the applicant and the job&#8217;s owner.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Non-owners get <code>403<\/code>, not <code>404<\/code>. The object is found first, then the permission check denies it. That reveals the ID exists. It&#8217;s an accepted trade-off from Part 5, because IDs aren&#8217;t secret here.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the whole matrix in one picture:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"744\" height=\"360\" src=\"http:\/\/rezachegini.com\/wp-content\/uploads\/2026\/11\/job-board-api-part-19-diagram.png\" alt=\"Every protected action, tried as every kind of user\" class=\"wp-image-305\" srcset=\"https:\/\/rezachegini.com\/wp-content\/uploads\/2026\/11\/job-board-api-part-19-diagram.png 744w, https:\/\/rezachegini.com\/wp-content\/uploads\/2026\/11\/job-board-api-part-19-diagram-300x145.png 300w\" sizes=\"auto, (max-width: 744px) 100vw, 744px\" \/><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Two fixtures that apply to every test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The matrix needed two fixtures marked <code>autouse=True<\/code>. An <code>autouse<\/code> fixture applies to every test, without being named as an argument.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">A fresh in-memory cache for each test<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@pytest.fixture(autouse=True)\ndef local_cache(settings):\n    settings.CACHES = {\n        \"default\": {\"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\"}\n    }\n    from django.core.cache import cache\n\n    cache.clear()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>settings<\/code> is pytest-django&#8217;s fixture for changing settings in one test. The old value comes back automatically afterwards.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Why replace Redis? Two reasons:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Isolation.<\/strong> Inside a test, nothing is ever committed. So my cache invalidation from Part 9, which runs on commit, never runs. A cached job list from one test would be served to the next.<\/li><li><strong>No dependency.<\/strong> The suite doesn&#8217;t need Redis running. I proved it: with Redis stopped, 80 passed.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Assigning <code>CACHES<\/code> fires Django&#8217;s <code>setting_changed<\/code> signal, which resets the cache connections, so cache really points at the new backend.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>cache.clear()<\/code>: the in-memory cache lives as long as the process, so clearing it gives each test an empty cache.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The 29x speedup<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">After I added the matrix, the suite suddenly took 27.13 seconds. It had been about 2.7 seconds. That&#8217;s 10 times slower.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I didn&#8217;t guess. I measured with <code>--durations=3<\/code>, which shows the slowest test phases. All of them were the setup phase of matrix tests, at 0.62 to 0.63 seconds each.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The cause: the <code>world<\/code> fixture creates 5 users per test. <code>create_user<\/code> hashes each password with PBKDF2, and Django makes PBKDF2 slow on purpose, with hundreds of thousands of iterations, so stolen password hashes are hard to crack. About 160 slow hashes added up to 27 seconds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The fix:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@pytest.fixture(autouse=True)\ndef fast_password_hashing(settings):\n    settings.PASSWORD_HASHERS = [\"django.contrib.auth.hashers.MD5PasswordHasher\"]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">MD5 is fast, and completely unsafe for real passwords. That&#8217;s fine here, because test users live for one test.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The result: the same 80 tests in 0.92 seconds, about 29 times faster. I switched the fixture off and on with <code>sed<\/code> to measure both.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Production is unchanged. <code>grep PASSWORD_HASHERS<\/code> finds it only in <code>conftest.py<\/code>. Production keeps PBKDF2.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Why does speed matter this much? A 27-second suite is one that people stop running. A 1-second suite runs after every change.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Part 3: what each endpoint really does<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The matrix proved who gets in. The API tests prove what happens when they do. I added one more factory fixture, <code>api_as(user)<\/code>, which returns an <code>APIClient<\/code> logged in as any user, or anonymous with <code>api_as()<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Registration<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>STRONG = \"s3cure-pass-2026\"\nCOMPANY = {\"username\": \"newco\", \"email\": \"Hello@NewCo.test\", \"password\": STRONG, \"company_name\": \"NewCo\"}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>STRONG<\/code> passes all four of Django&#8217;s password validators. The email has capitals on purpose, to test lower-casing.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_company_registration_creates_user_and_unverified_company(db):\n    response = post(\"\/api\/auth\/register\/company\/\", COMPANY)\n    body = response.json()\n\n    assert response.status_code == 201\n    assert body[\"role\"] == \"company\"\n    assert body[\"email\"] == \"hello@newco.test\"\n    assert \"password\" not in body\n    company = Company.objects.get(user__username=\"newco\")\n    assert company.name == \"NewCo\"\n    assert company.is_verified is False<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The response is checked against the database, not just itself.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>\"password\" not in body<\/code>: the field is <code>write_only<\/code>, so signup can&#8217;t echo the password back.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>is_verified is False<\/code>: new companies can&#8217;t post jobs until they&#8217;re verified. Self-registration can&#8217;t skip that step.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The other registration tests:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The client can&#8217;t choose its role or staff flag. Sending <code>\"role\": \"company\", \"is_staff\": True<\/code> to the candidate endpoint still creates a normal candidate. This attack is called mass assignment. The serializer has no <code>role<\/code> or <code>is_staff<\/code> field, so DRF ignores unknown keys, and the role comes from which endpoint was called.<\/li><li>The password is hashed: the stored value isn&#8217;t the plain password, and the plain password still verifies with <code>check_password<\/code>.<\/li><li>Duplicates are rejected case-insensitively: <code>SAM<\/code> and <code>SAM@Example.test<\/code> both clash with an existing sam. The error key shows which check fired.<\/li><li>Weak passwords are rejected, one example per validator (<code>12345678<\/code>, <code>password<\/code>, <code>short<\/code>), and no user is created.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Registration is atomic<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_company_registration_is_atomic(db, monkeypatch):\n    def boom(**kwargs):\n        raise RuntimeError(\"database hiccup\")\n\n    monkeypatch.setattr(Company.objects, \"create\", boom)\n\n    with pytest.raises(RuntimeError):\n        post(\"\/api\/auth\/register\/company\/\", COMPANY)\n\n    assert not User.objects.filter(username=\"newco\").exists()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>monkeypatch.setattr(obj, name, value)<\/code> replaces something for this test only, then puts it back. Here, creating the company fails after the user was already created.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What it proves: <code>@transaction.atomic<\/code> rolls back the user too. Without it, there would be a company-role user with no company, and every company endpoint would treat them as &#8220;not verified&#8221; forever.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>pytest.raises<\/code> around an API call works because Django&#8217;s test client re-raises an unhandled exception from a view, instead of returning a <code>500<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One more registration test sends <code>Authorization: Bearer garbage<\/code>. It still gets <code>201<\/code>, because the signup views set <code>authentication_classes = []<\/code>. Otherwise, a browser with an expired token from an old session could never sign up again.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The real JWT flow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The matrix used <code>force_authenticate<\/code>. These tests use real tokens:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def bearer(token):\n    client = APIClient()\n    client.credentials(HTTP_AUTHORIZATION=f\"Bearer {token}\")\n    return client<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Login returns exactly <code>access<\/code> and <code>refresh<\/code>, nothing extra.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The access token opens protected endpoints. The full chain: credentials, then token, then endpoint.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A wrong password is <code>401<\/code>, and a garbage token is <code>401<\/code>, not a <code>500<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Refresh gives a working access token, checked by using it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A refresh token is not an access token:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_refresh_token_is_not_an_access_token(make_candidate):\n    make_candidate(\"sam\")\n    refresh = login(\"sam\").json()[\"refresh\"]\n\n    assert bearer(refresh).get(\"\/api\/jobs\/\").status_code == 401<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A refresh token lives for 1 day, and an access token for 15 minutes. If a refresh token worked as an access token, the short lifetime would mean nothing. SimpleJWT stores a <code>token_type<\/code> inside each token and rejects the wrong kind.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Jobs: creating and updating<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_create_normalises_skills_and_takes_company_from_the_user(api_as, acme, make_company):\n    make_company(\"globex\")\n    response = api_as(acme.user).post(\n        \"\/api\/jobs\/\",\n        {**NEW_JOB, \"required_skills\": [\" Python \", \"AWS\", \"aws\"], \"company\": \"Globex\"},\n        format=\"json\",\n    )\n    body = response.json()\n\n    assert response.status_code == 201\n    assert body[\"required_skills\"] == [\"python\", \"aws\"]\n    assert body[\"company\"] == \"Acme\"\n    assert Job.objects.get(id=body[\"id\"]).company == acme<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Skill normalising, step by step: DRF trims <code>\" Python \"<\/code> first, then my validator lower-cases, then <code>dict.fromkeys<\/code> removes the duplicate and keeps the first-seen order. So the result is exactly <code>[\"python\", \"aws\"]<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>\"company\": \"Globex\"<\/code> is ignored. <code>company<\/code> is read-only, and the view sets it from the logged-in user. A company can&#8217;t post jobs as someone else.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Updates go through the same validator. If only create normalised, a later edit could bring back <code>\"Go\"<\/code> and break the filters, which search in lower case.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">I had marked one expectation as uncertain before running it, and it turned out correct. A blank skill <code>\" \"<\/code> is rejected with <code>400<\/code>, not silently dropped. DRF trims <code>\" \"<\/code> to <code>\"\"<\/code> and rejects it as blank before my validator even runs. So the blank-skill filter inside my validator never sees blanks from the API. It still protects the model if something else writes skills.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Other job tests: missing fields are all reported at once (<code>{\"title\", \"description\", \"location\"} &lt;= set(...)<\/code>, where <code>&lt;=<\/code> on sets means &#8220;is a subset&#8221;), an invalid <code>job_type<\/code> is a <code>400<\/code>, and closed jobs are hidden from the list but not from the detail page, so old links and the owner&#8217;s applicant pages keep working.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Filters, search and ordering<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>board<\/code> fixture creates four jobs, built so that every filter separates them: different companies, types, locations and skills. A fourth, closed job matches <code>aws<\/code> and <code>acme<\/code>, so every test also proves it stays hidden.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@pytest.mark.parametrize(\n    (\"params\", \"expected\"),\n    [\n        ({}, [\"Data Analyst\", \"Junior DevOps Engineer\", \"SRE Intern\"]),\n        ({\"job_type\": \"contract\"}, [\"Data Analyst\"]),\n        ({\"location\": \"vancouver\"}, [\"Junior DevOps Engineer\"]),\n        ({\"skills\": \"python\"}, [\"Data Analyst\", \"SRE Intern\"]),\n        ({\"skills\": \" AWS , Go \"}, [\"Junior DevOps Engineer\"]),\n        ({\"skills\": \"python,terraform\"}, [\"Data Analyst\", \"Junior DevOps Engineer\", \"SRE Intern\"]),\n        ({\"search\": \"acme\"}, [\"Junior DevOps Engineer\", \"SRE Intern\"]),\n        ({\"search\": \"analyst\"}, [\"Data Analyst\"]),\n        ({\"job_type\": \"contract\", \"skills\": \"python\"}, [\"Data Analyst\"]),\n    ],\n)\ndef test_filters_and_search(api_as, board, params, expected):\n    response = api_as(board.user).get(\"\/api\/jobs\/\", params)\n\n    assert response.status_code == 200\n    assert sorted(titles(response)) == expected<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">One row per rule:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>location<\/code> is a case-insensitive substring;<\/li><li><code>skills<\/code> is normalised the same way as stored skills;<\/li><li>several skills match any of them (PostgreSQL&#8217;s array overlap), not all;<\/li><li><code>search<\/code> covers the title, the description and the company name;<\/li><li>several filters combine with AND.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><code>sorted(...)<\/code> is used because these tests are about which jobs, not their order. An invalid filter value like <code>job_type=forever<\/code> returns <code>400<\/code> with an explanation, instead of silently returning nothing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ordering test does not sort, because the order is the thing being tested. The default is newest first. And <code>ordering=password<\/code> is ignored: only fields in <code>ordering_fields<\/code> are allowed. Sorting by an arbitrary field would let clients sort by data they can&#8217;t see, and with enough requests, work out hidden values.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The pagination test creates 21 jobs, the smallest number that needs a second page (<code>PAGE_SIZE<\/code> is 20). Page 1 has 20 results and a <code>next<\/code> link, and page 2 has 1 result and <code>next<\/code> is <code>None<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Applications: every rejection before any upload<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The application tests check that each bad request is rejected before anything is uploaded to S3: no resume (<code>400<\/code>), a wrong file type (<code>400<\/code>), a closed job (&#8220;This job is no longer accepting applications.&#8221;), an unknown job (<code>400<\/code>, not <code>404<\/code>), and a second application to the same job (&#8220;You have already applied for this job.&#8221;, with still only 1 application in the database).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The reading tests check the response shape. <code>match_score<\/code> is 50 (1 of 2 required skills), <code>has_resume<\/code> is <code>True<\/code>, and <code>\"resume\" not in body<\/code>: the storage path never leaves the server. The only way to get the file is the permission-checked, short-lived link, and its test checks it uses the public endpoint <code>localhost:4566<\/code>, not the internal <code>localstack:4566<\/code>. That was the bug I fixed in Part 7.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Status changes: publish once, only on a real change<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_status_change_publishes_once_and_only_on_change(api_as, setup, make_application, monkeypatch):\n    acme, sam, job = setup\n    application = make_application(job, sam)\n    calls = []\n    monkeypatch.setattr(\"jobs.views.publish_status_changed\", lambda app, old: calls.append((app.id, old)))\n    client = api_as(acme.user)\n    url = f\"\/api\/applications\/{application.id}\/status\/\"\n\n    first = client.patch(url, {\"status\": \"reviewing\"}, format=\"json\")\n    second = client.patch(url, {\"status\": \"reviewing\"}, format=\"json\")\n\n    assert first.status_code == second.status_code == 200\n    assert first.json()[\"status\"] == \"reviewing\"\n    assert \"match_score\" in first.json()\n    assert calls == [(application.id, \"submitted\")]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Patch the name where it&#8217;s used. <code>views.py<\/code> does <code>from .events import publish_status_changed<\/code>, which copies the reference into <code>jobs.views<\/code>. Patching <code>jobs.events.publish_status_changed<\/code> would leave the view calling the original. The same rule caught me in Phase 3, with the worker.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>lambda<\/code> records calls instead of sending anything. This test is about when the view publishes, not how. The &#8220;how&#8221; is in the next article.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Two identical <code>PATCH<\/code>es: the first publishes once, with the old status. The second changes nothing, so it publishes nothing. That&#8217;s the same rule as the &#8220;no email after a 200&#8221; surprise in Part 14.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">An empty body and an unknown status like <code>hired<\/code> both return <code>400<\/code> with DRF&#8217;s exact messages. The empty body used to return <code>200<\/code> and do nothing, which was a bug back in Phase 2. This test makes sure it stays fixed.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Problems I hit<\/h3>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>14 errors from my own fixture<\/strong><br>The first run of the job tests gave 14 setup errors:<br><code>TypeError: QuerySet.create() got multiple values for keyword argument 'location'<\/code><br>The cause was my <code>make_job<\/code> fixture from Part 18. At first it passed <code>location=\"Vancouver\"<\/code> hard-coded, and <code>**fields<\/code>. The <code>board<\/code> fixture was the first to pass its own <code>location=<\/code>, so location arrived twice.<br>The fix: <code>location=\"Vancouver\"<\/code> became a parameter with a default. A parameter with a default can be overridden. A hard-coded argument next to <code>**fields<\/code> can&#8217;t.<\/li><li><strong>A typo that worked<\/strong><br>While reading the serializer, I found <code>def validate_email(delf, value)<\/code>. It worked, because Python doesn&#8217;t care what the first parameter is called. I fixed it to <code>self<\/code> anyway.<\/li><li><strong>Output that scrolled away<\/strong><br>The first output was too long to read. I re-ran with <code>-q<\/code> and <code>2&gt;&amp;1 | tail -n 40<\/code>.<\/li><\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Breaking the code on purpose<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">As in Part 18, I broke the code to prove the tests can catch it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The permissions: I removed the owner check from the views:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>return [IsAuthenticated(), IsJobOwner()]    # the real code\nreturn [IsAuthenticated()]                  # the deliberate bug<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The result: 7 failed, 35 passed. The 7 were exactly every non-owner case of the three actions <code>IsJobOwner<\/code> protects: job update, the applicants list and status change. They all got <code>200<\/code> and changed data. The failure output even showed <code>job=&lt;Job: Changed (Acme)&gt;<\/code>: non-owners had really renamed Acme&#8217;s job. That&#8217;s the &#8220;denied means nothing changed&#8221; check doing its job. The anonymous cases still got <code>401<\/code>, because <code>IsAuthenticated<\/code> was still there.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This also showed something important about <code>has_object_permission<\/code>: it only runs when the view calls <code>get_object()<\/code>. So <code>IsJobOwner<\/code> protects nothing on a list or create action.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The skills: I removed <code>.lower()<\/code> from the skills validator. Exactly 2 tests failed: the two normalisation tests, with <code>['Python', 'AWS', 'aws']<\/code> and <code>['Go', 'GO']<\/code> kept as typed. Everything else passed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After each check, <code>git checkout<\/code> restored the code, and all tests passed again.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The numbers: 42 permission tests (<code>permissions.py<\/code> at 100%) and 51 API tests (<code>serializers.py<\/code> at 99%). The total coverage went to 78%.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why I chose this way<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Unit tests and an endpoint matrix.<\/strong> A class can be right but wired wrong in <code>get_permissions<\/code>. Only both together catch both kinds of mistakes.<\/li><li><strong>One world per test.<\/strong> Each test is independent. Shared module-level data would let tests affect each other.<\/li><li><strong><code>force_authenticate<\/code> in the matrix.<\/strong> It separates who you are from how you logged in. The real tokens have their own tests.<\/li><li><strong>MD5 in tests only.<\/strong> 29 times faster, production unaffected.<\/li><li><strong>Record calls instead of mocking SQS in the view test.<\/strong> It tests the view&#8217;s decision, not the transport.<\/li><li><strong>Exact user-facing messages.<\/strong> They&#8217;re part of the API&#8217;s contract, not just the status codes.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">What I learned<\/h3>\n\n\n\n<ul class=\"wp-block-list\"><li>Test the classes and the wiring. Unit tests alone miss a class attached to the wrong action.<\/li><li><code>has_object_permission<\/code> only runs through <code>get_object()<\/code>.<\/li><li><code>401<\/code> means &#8220;who are you?&#8221;, <code>403<\/code> means &#8220;you can&#8217;t&#8221;.<\/li><li>A denied write must change nothing. Check the data, not only the status.<\/li><li>Measure before optimising. <code>--durations<\/code> pointed straight at password hashing.<\/li><li>Mass assignment is blocked by not declaring fields, and a test proves it.<\/li><li>A refresh token must not work as an access token.<\/li><li>Patch a name where it&#8217;s used, not where it&#8217;s defined.<\/li><li>A mutation that fails exactly the expected tests is the best proof your tests are aimed right.<\/li><\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">What comes next<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">So far, no test has talked to S3 or SQS. The next article is about faking AWS with a library called <code>moto<\/code>, testing the worker&#8217;s main loop with a fake queue, and testing what happens when Redis fails. Some of those tests document known gaps instead of hiding them.<\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>I&#8217;m sharing one of my projects here from the beginning, step by step. It&#8217;s a Job Board API built with Django, Django&hellip;<\/p>\n","protected":false},"author":2,"featured_media":304,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_rezaops_part":"19","_rezaops_linkedin_url":"https:\/\/www.linkedin.com\/pulse\/building-job-board-api-part-19-who-can-do-what-really-reza-chegini-sv0tc\/","footnotes":""},"categories":[10,116],"tags":[214,8,111,191,118,82,212,25,112,213],"series":[117],"class_list":["post-306","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-devops","category-django","tag-coverage","tag-devops","tag-django","tag-drf","tag-job-board","tag-permissions","tag-pytest","tag-python","tag-rest-api","tag-testing","series-job-board-api"],"jetpack_featured_media_url":"https:\/\/rezachegini.com\/wp-content\/uploads\/2026\/11\/job-board-api-part-19-cover.png","_links":{"self":[{"href":"https:\/\/rezachegini.com\/index.php?rest_route=\/wp\/v2\/posts\/306","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/rezachegini.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/rezachegini.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/rezachegini.com\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/rezachegini.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=306"}],"version-history":[{"count":1,"href":"https:\/\/rezachegini.com\/index.php?rest_route=\/wp\/v2\/posts\/306\/revisions"}],"predecessor-version":[{"id":307,"href":"https:\/\/rezachegini.com\/index.php?rest_route=\/wp\/v2\/posts\/306\/revisions\/307"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/rezachegini.com\/index.php?rest_route=\/wp\/v2\/media\/304"}],"wp:attachment":[{"href":"https:\/\/rezachegini.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=306"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/rezachegini.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=306"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/rezachegini.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=306"},{"taxonomy":"series","embeddable":true,"href":"https:\/\/rezachegini.com\/index.php?rest_route=%2Fwp%2Fv2%2Fseries&post=306"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}