Chapter 17. Test Fixtures, Logging, and Server-Side Debugging
Now that we have a functional authentication system, we want to use it to identify users, and be able to show them all the lists they have created.
To do that, we’re going to have to write FTs that have a logged-in user. Rather than making each test go through the (time-consuming) Persona dialog, we want to be able to skip that part.
This is about separation of concerns. Functional tests aren’t like unit tests, in that they don’t usually have a single assertion. But, conceptually, they should be testing a single thing. There’s no need for every single FT to test the login/logout mechanisms. If we can figure out a way to “cheat” and skip that part, we’ll spend less time waiting for duplicated test paths.
Tip
Don’t overdo de-duplication in FTs. One of the benefits of an FT is that it can catch strange and unpredictable interactions between different parts of your application.
Skipping the Login Process by Pre-creating a Session
It’s quite common for a user to return to a site and still have a cookie, which means they are “pre-authenticated”, so this isn’t an unrealistic cheat at all. Here’s how you can set it up:
functional_tests/test_my_lists.py.
fromdjango.confimportsettingsfromdjango.contrib.authimportBACKEND_SESSION_KEY,SESSION_KEY,get_user_modelUser=get_user_model()fromdjango.contrib.sessions.backends.dbimportSessionStorefrom.baseimportFunctionalTestclassMyListsTest(FunctionalTest):defcreate_pre_authenticated_session ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access