1

everyone! I can't figure out how the sessions work in Django.
I have a shop, an anonymous user's shopping cart is bound to session_key.
The session key is taken from the request object.

def _check_session(self, request) -> int | str:
        session_key = getattr(request.session, ‘session_key’, None)
        if session_key:
            return session_key
        else:
            request.session.create()
            return request.session.session_key

I'm writing tests, one test adds items to the basket, I take the anonymous user client and make a post request to add, everything is ok.
Then in the second test, I take the same anonymous client, make a get request to get the contents of the basket.
But in this request the request object has no session_key.
Why in the second test, the request object does not contain a session_key? The client is the same.
These two tests are written within one TestCase.

1 Answer 1

0

Session data is stored in the Database. The database is cleared between tests. So you need to combine your two tests into one test, so what was written by the first is available to be read by the second.

You might find subtests useful. This isn't the intended use case, but subTests behave much like individual tests, except that the database is not cleared between subtests. See unittest.subTest documentation.

This ought to work (off the top of my head)

class Tests( TestCase):

    def Test1( self):

        # run a sequence of subTests with the database contents accumulating
        # until the end of this test

        for subtest in ('method1', 'method2', ...):
            with self.subTest( subtest):
                getattr( self, subtest) ()

    def method1( self):  # NB name NOT starting with test!
        ...

Not the answer you're looking for? Browse other questions tagged or ask your own question.