Start learning free

LESSON 139 OF 188 · BACKEND: TESTS AND RUNNING IT

Test the Login

Practice

A route behind a login has two jobs: keep out anyone without a valid token, and let in someone who logged in. A bug can break either job, so a good test suite checks both sides.

The token is random, a new one at every login, so a test can't type it in. It does what a real client does: it logs in, reads the token from the answer, and sends it back in the Authorization header, written as Bearer, a space, then the token. The test client's get and post take headers as a dictionary, like in this call to another route:

response = self.client.get("/orders", headers={"Authorization": "Bearer " + token})

Here, test_me_without_token already checks that GET /me answers 401 when there's no token. The check runs your tests on the shop and on two broken copies: one whose /me forgets to cut "Bearer " off the header, so it keeps everyone out, and one that lets everyone in. When you're done, Run prints:

Your tests on the shop:
  test_me_after_login ... ok
  test_me_without_token ... ok
  2 tests: OK
Your tests on a copy whose /me forgets to cut "Bearer " off the header:
  test_me_after_login ... FAIL
    AssertionError: {'error': 'Login required'} != {'id': 1, 'email': 'ana@example.com'}
  test_me_without_token ... ok
  2 tests: 1 failed, so they caught this bug
Your tests on a copy whose /me lets everyone in, even without a token:
  test_me_after_login ... ok
  test_me_without_token ... FAIL
    AssertionError: 200 != 401
  2 tests: 1 failed, so they caught this bug

Your task: below test_me_without_token, write test_me_after_login. Log Ana in with POST /login (email ana@example.com, password secret123), keep her token, call GET /me with it, and check that the answer is {"id": 1, "email": "ana@example.com"}.


Assignment
Follow the Coding Tutorial to write a test that logs in, keeps the token and calls /me with it.


Hint
The token is in response.get_json()["token"]. The header's value is the text "Bearer ", with its space, plus the token.


STEP 1 OF 5
    Ctrl + Enter to check