[Django]-How to properly unit test a Django middleware

4👍

The APIClient, which you use in test_browser_id_response, makes a simulated request through the whole stack and is therefore ideal in testing middleware. I would use that consistently rather than the APIFactory. You can then assert on the request attribute of the response. (Note, APITestCase already instantiates a client for you, you don’t need to create a new one.)

def test_existing_browser_id_request(self):
    mock_bid: str = 'abcd1234'
    self.client.cookies[cookie_key] = mock_bid
    response = self.client.get('/')
    req = response.request
    self.assertTrue(hasattr(req, 'bid'))
    self.assertEqual(req.bid, mock_bid)

Leave a comment