Testing in Django Tutorial #11 - Testing Authentication

Net Ninja · Beginner ·🔧 Backend Engineering ·1y ago

Key Takeaways

This video tutorial covers testing authentication in Django, a Python web framework, using unit and integration testing. It demonstrates how to create test suites that cover important aspects of Django, including testing protected resources and authentication scenarios.

Full Transcript

in Jango applications many scenarios require authentication and they require that resources are protected from unauthenticated users and these are important use cases for writing tests you need to make sure that your protected resources are not exposed to people that shouldn't have access to them and that comes into permissions as well as authentication in this video we're going to look at testing authentication scenarios and we've done a bit of setup code for these so you can see in views.py at the moment we are importing the login required decorator and we have a profile view here that is protected by login required and that means that only authenticated users can access this particular page and access the profile. HTML template that's returned and we also have a simple login view here that just returns login. HTML and that's not protected by login required now I've added both of these views to the URL patterns as you can see at the bottom here and as well as that what I've done is set a login URL setting in jangle and that tells jangle where to redirect users that try and access a protected resource those users need to be redirected to a login page and the login URL here is going to tell Jango where that is and we also have two templates one is a very simple login template and the content of this doesn't really matter for this video and we also have the profile template that's protected by the login required decorator and that gives the usern name's profile page so what we want to do here is write tests that make sure that only authenticated users can view the profile page and we also want to test for the case when an un authenticated user is going to send a request to the profile page we're going to make sure they're redirected to that login URL now because we're testing views here with this authentication process what we're going to do is go to the tests directory and we're going to extend the test views.py fill that we've already seen in this series and we're going to write some new classes that are going to subass the test case for our profile page view and because we're going to log in users using these tests I'm also going to import the user model that we have in the product do models module and at the top of this file let's write a new class and we're going to call this test profile page and that's going to inherit from the test case from Jango and let's write a method in this class called test profile view accessible for authenticated users so we're going to test that authenticated users can access the profile page and in order to test that what we're going to do is we're going to create a test user so let's use the user. objects. create uncore user function and we can give this guy some generic details for username and password now before we send a request to the profile view we need to log the user in so how do you authenticate a user in a test in jangle what we can do is we can use a method on the client and remember the jangle test client that we've been working with in previous videos and this client allows you to send get and post requests to the back end but what it also does is allows you to log in a user with a set of credentials so what I'm going to do to the login method is pass these credentials that we created above so we pass these back into the login method and that's basically going to create a session in jangle for the rest of this test method we can then get a response by calling self. client. getet and we're going to reverse the protected profile route that we have in the application so we use the reverse function and the profile route is what we've added as you can see here it's got a name of profile and that's the one that's protected by login required but we have now logged in so we expect to be able to see this and not to be redirected so let's check that the user's username is in the response context and why are we doing that if we go back to the template and that's in the templates directory and it's profile. HTML you can see here the username is rendered out along with the text your profile page so we expect to see the username in the response when we are sending a request with an authenticated user so what we can do here is use a method that we've seen a couple of times before and that's assert contains we pass the response into that and we expect the username to be in that response you can see the username here it's test user so let's pass that string in here and we can then save this method now that's the happy path so to speak that's when we log the user in and we make sure that they can access the authenticated page but we also want to add a test for unauthenticated users so what I'm going to do just at the top of this above the existing method is write a new one and it's called test profile view redirects for anonymous users and again we use very verbose names for these methods now we can essentially copy the logic from the bottom of the previous method so let's let's copy that and I'm going to paste that into this method so what we're doing here is we're sending a request to the profile page but in this particular method we're not bothering creating any users or logging them in so we don't have a session here we don't have an authenticated user so we expect to see a different response here when we call the get method on the test client so we're going to need to change what comes below here so I'm going to remove this line of code and we're going to see another assert method here and I'm going to bring this onto the same line and this is added by Jango as well it's the assert redirect method and we can pass the response into that now if you just want to assert that it's redirected that's all you need to do here but you can also pass an expected URL so this is going to assert that a response is redirected to a specific URL and I'm actually going to pass an F string in here and let's explain what this F string is so we reverse the login page and that's because when we try and access a page that's behind authentication and we're not authenticated we're going to get redirected to the login page here and that's because we've set the login UR l in settings. pi so we use the reverse function on the login URL and then we're adding a query parameter of next and that's going to capture that the page we want to go to after we log in is going to be the profile page and Jango does that by adding a next URL parameter so that's the expected URL here and we can pass that to the assert redirects function now I want to test this out so let's go back to the terminal and run python manage.py test and you can see we have 13 tests and all of them are passing and again we can narrow the scope of these tests so in the products application we have the tests directory and let's look at test views.py and we can actually pass a class to this so I'm going to pass test profile page and that's only going to run the two tests in that class and you can see that they're both passing so to summarize these kind of tests here are very important if you have pages and resources that are behind authentication you need to make sure your application is not going to expose those and it's going to perform the right behavior for unauthenticated users and writing tests for these scenarios is going to make sure that if some other developer accidentally removes the login required decorator here it's not going to break the entire application if you run the tests and you discover that issue so let's bring back The Decorator and that's going to be all for this video we're going to move on in the next video and look at some more advanced testing Concepts in jangle for example we're going to look at mocking external resources so that's coming up in the next video thanks very much for watching and we'll see you there

Original Description

This Django Unit Testing tutorial series introduces unit and integration testing using the Django Web Framework in Python. You will learn how to create a test suite that covers the most important aspects of Django. 🔥🥷🏼Get access to ALL premium courses on NetNinja.dev: https://netninja.dev/ 📂🥷🏼 Access the course files on GitHub: https://github.com/bugbytes-io/django-testing-series 🧠🥷🏼 Django Crash Course: https://netninja.dev/p/django-complete-tutorial 🔗👇 Django docs: https://docs.djangoproject.com/en/5.1/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

This video tutorial teaches how to test authentication in Django using unit and integration testing. It covers creating test suites, testing protected resources, and using the Jango test client to simulate user interactions.

Key Takeaways
  1. Create a test user using the user.objects.create_user function
  2. Log in the user using the client.login method
  3. Send a request to the protected resource using the client.get method
  4. Assert that the response contains the expected content using the assertContains method
  5. Test for unauthenticated users by sending a request without logging in
  6. Assert that the response is redirected to the login page using the assertRedirect method
💡 Writing tests for authentication scenarios is crucial to ensure that protected resources are not exposed to unauthenticated users and that the application behaves correctly for both authenticated and unauthenticated users.

Related Reads

Up next
Orchestrate Copilot: Build and Test Orchestrations with AI | Deep Dive
Workday
Watch →