Django Testing Tutorial with Pytest #1 - Setup (2018)

The Dumbfounds
23 Mar 201810:59

Summary

TLDRThis tutorial series introduces viewers to the fundamental concepts of testing Jenga applications. By the end, participants will grasp the testing lifecycle's role in project integrity and learn to write their own tests. The script guides through setting up a Django project, creating a 'Product' model with stock checks, and setting up views and templates. It also covers initial testing steps, including making a view login-required, and installing necessary packages for further testing, promising a comprehensive guide for ensuring application reliability.

Takeaways

  • 📝 This tutorial series aims to teach the major concepts of testing a Jenga application, focusing on the testing lifecycle and how it should be integrated into projects.
  • 🔍 Automated testing involves writing code to test other code snippets, providing confidence that the production code is functioning correctly and allowing for safe changes without breaking the application.
  • đŸ’» The setup begins with creating a new Django project named 'testing' and then an app called 'friendship' with a 'products' model.
  • đŸ› ïž A 'Product' model is defined with fields for name, description, price, quantity, and published date, including a method to check if the product is in stock.
  • 📝 A property decorator is used to define a method that returns a boolean indicating whether the product quantity is greater than zero, signifying stock availability.
  • 🔗 In the Django URL configuration, a path is added to redirect to a product detail view based on a primary key (PK).
  • 📑 A view function 'product_detail' is created to fetch and render a product based on its ID, using Django's 'get_object_or_404' function for error handling.
  • 📁 A 'templates' folder is added within the 'products' app to create an HTML template for displaying product details.
  • 🔄 Database migrations are performed using 'manage.py makemigrations' and 'manage.py migrate' to apply changes to the database schema.
  • 🚀 The server is run using 'manage.py runserver' to test the application, with manual creation of a product in the Django shell for demonstration.
  • 🔒 The 'product_detail' view is updated to require user login, demonstrating how to restrict access to certain views for authenticated users only.
  • 📩 Additional packages are installed for testing, including 'pytest', 'pytest-django', 'pytest-cov' for coverage, and 'mixer' for mocking database entries.

Q & A

  • What is the main goal of this tutorial series?

    -The main goal of this tutorial series is to teach the major concepts of testing a Jenga application, enabling viewers to understand the testing lifecycle in projects and to write their own tests to ensure the integrity of their applications.

  • What does automated testing provide to a developer?

    -Automated testing provides developers with the confidence that their code is working correctly. It allows them to make changes and run tests to ensure that nothing is broken, thus preventing end-users from having a negative experience with the application.

  • How does the tutorial start the process of setting up testing?

    -The tutorial starts by creating a new project using Django admin startproject, naming it 'testing', and then setting up an actual app called 'friendship' with a 'products' model.

  • What are the fields defined in the 'Product' model?

    -The 'Product' model defines fields for 'name' (a CharField with a max length of 100), 'description' (a TextField), 'price' (a DecimalField with five digits and two decimal places), 'quantity' (an IntegerField), and 'published_on' (a DateField).

  • What is the purpose of the 'is_in_stock' function in the 'Product' model?

    -The 'is_in_stock' function is used to check if there are any units of the product left in stock. It returns a boolean value indicating whether the quantity of the product is greater than zero.

  • How is the 'product detail' view set up in the Django URL configuration?

    -The 'product detail' view is set up by adding a new path in the URL configuration that leads to an integer named 'pk'. When this route is hit, it calls the 'product_detail' function, which is assigned the name 'product_detail'.

  • What is the purpose of the 'get_object_or_404' function imported in the 'product detail' view?

    -The 'get_object_or_404' function is used to retrieve a product object by its primary key. If the product does not exist in the database, it returns a 404 error.

  • What is the significance of creating a 'templates' folder and a 'detailed.html' file in the 'products' app?

    -The 'templates' folder and 'detailed.html' file are created to define the HTML template that will be rendered when a product detail page is accessed. It displays the product's name in an h1 tag.

  • How does the tutorial ensure that the 'product detail' view is accessible only to logged-in users?

    -The tutorial modifies the 'product detail' view by adding the '@login_required' decorator to ensure that only logged-in users can access the view.

  • What packages are installed for testing purposes in the tutorial?

    -The tutorial installs 'pytest', 'pytest-django', 'pytest-cov' for coverage testing, and 'mixer' for mocking database entries, to facilitate various aspects of testing.

Outlines

00:00

😀 Introduction to Jenga Application Testing

This paragraph introduces the tutorial series on testing a Jenga application. It emphasizes the importance of understanding the testing lifecycle and the ability to write tests for applications to ensure their integrity. Automated testing is explained as a method to gain confidence in the code's functionality. The speaker outlines the initial setup for testing, including creating a new project and setting up models in Django, a Python web framework. The tutorial begins by creating a 'testing' project and an 'app' named 'friendship' with a 'Product' model that includes fields for name, description, price, quantity, and a published date. A method to check product stock is also implemented.

05:03

đŸ› ïž Setting Up the Testing Environment

The second paragraph delves into the setup of the testing environment. It describes the process of creating a new Django app, setting up URL paths, and defining views. The tutorial covers creating a 'product detail' view that fetches a product by its primary key and handles the case where a product might not exist. It also includes creating a basic HTML template for displaying product details and configuring the Django settings to include the new app. The speaker demonstrates how to create a product instance using the Django shell and how to access it via the web server, highlighting the need for login requirements for certain views.

10:03

📚 Installing Testing Packages and Preparing for Testing

The final paragraph focuses on the installation of necessary packages for testing the Jenga application. It mentions the installation of 'pytest', 'Faker', 'pytest-django', and 'pytest-cov' for testing and coverage, as well as 'mixer' for database mocking. The speaker outlines the next steps, which involve writing the first tests for the application. The paragraph concludes with an invitation for viewers to share the tutorial series and engage with the content by leaving comments and likes, expressing anticipation for the continuation of the series.

Mindmap

Keywords

💡Testing Lifecycle

The testing lifecycle refers to the sequence of activities involved in the testing process of software development. It is a systematic approach to ensure that the application is tested thoroughly at different stages. In the video, the testing lifecycle is discussed as an integral part of the development process, emphasizing its importance in maintaining the integrity of the application and ensuring it functions as intended.

💡Automated Testing

Automated testing involves writing code to execute tests on other code segments, known as production code. It is a crucial aspect of software development that provides confidence in the correctness of the codebase. The video script mentions automated testing as a means to verify that the application works correctly and to quickly identify issues when changes are made, which is essential for maintaining code quality.

💡Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. In the context of the video, Django is used as the framework for creating the application and setting up the testing environment. The script demonstrates how to create a new Django project and app, which is a foundational step in the tutorial series.

💡Model

In Django, a model is a Python class that defines the structure of the database tables and the relationships between them. The script describes creating a 'Product' model with various fields such as 'name', 'description', 'price', etc., which are essential for the application's data representation and manipulation.

💡Property Decorator

The property decorator in Python is used to define a method that can be accessed like an attribute. In the script, the 'is_in_stock' function is marked as a property, which allows it to be called as if it were an attribute of the 'Product' model, providing a way to check the stock status of a product.

💡View

In Django, a view is a Python function that receives a web request and returns a web response. The script explains how to create a 'product detail' view that handles the logic for displaying a product's details. This is a key component in the application's functionality and is also used to demonstrate testing concepts.

💡Template

A template in Django is a text file that Django uses to generate HTML. The script mentions creating a 'detail.html' template for the 'Product' model, which is used to render the product details on the webpage. This is an essential part of the user interface and user experience.

💡Migrations

Migrations in Django are a way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. The script describes running migrations as part of setting up the project, which is necessary to update the database schema according to the defined models.

💡Login Required

The 'login required' decorator in Django is used to restrict access to certain views to only authenticated users. In the script, this decorator is applied to the 'product detail' view to ensure that only logged-in users can access the product details, demonstrating how to implement access control in Django.

💡Test Coverage

Test coverage is a measure of how much of the codebase is covered by automated tests. The script mentions installing 'coverage', a package used to measure the test coverage of the project. This is important for ensuring that a wide range of code is tested, reducing the likelihood of undiscovered bugs.

💡Mocking

Mocking is a technique used in testing to simulate the behavior of certain parts of the system that are not being tested directly. The script refers to 'mixer', a package used for mocking database objects, which helps in creating test cases that do not rely on the actual database state, thus making tests more reliable and faster.

Highlights

Introduction to a tutorial series on testing a Jenga application.

Understanding the testing lifecycle in projects and writing tests for application integrity.

Explanation of automated testing as simple code snippets to test production code.

The importance of automated testing for ensuring code correctness and minimizing user issues.

Setting up a new project named 'testing' using Django admin.

Creating a new app called 'friendship' within the 'testing' project.

Creating a 'Product' model with fields for name, description, price, quantity, and published date.

Adding a function 'is_in_stock' to the Product model to check product availability.

Configuring a URL path for product detail view in the project's urls.py file.

Importing views from the product app and setting up the 'product detail' view function.

Using Django's get_object_or_404 function to handle non-existent product retrieval.

Creating a 'templates' folder and a 'detailed.html' template for product details.

Inclusion of the product app in the project settings to integrate it into the project.

Running migrations and starting the server to test the initial setup.

Using Django's shell to manually create a product instance for testing.

Accessing the product detail page and observing the initial setup results.

Making the product detail view login required to test access control.

Installing packages for testing, including pytest, pytest-django, pytest-cov, and mixer.

Concluding the setup phase and preparing for writing the first test in the next tutorial.

Transcripts

play00:00

hello everybody I hope you are having a

play00:02

great day in this tutorial series you

play00:04

will learn all of the major concepts

play00:06

that go into testing your jenga

play00:08

application by the end of series you

play00:10

will have a good understanding of how

play00:11

the testing lifecycle inside of your

play00:14

projects can work and should work and

play00:16

you'll be able to write your own tests

play00:19

for your applications and therefore

play00:20

ensure their integrity and what we mean

play00:22

by automated testing is the writing of

play00:24

some simple code snippets that is used

play00:27

to test some other code snippets of your

play00:29

production code and this just gives you

play00:31

the confidence that your code is working

play00:33

correctly and whenever you need to make

play00:36

changes you can just run all of your

play00:37

tests and make sure that everything

play00:39

works fine without worrying that you

play00:41

just broke something and your end-users

play00:43

are going to have a horrible time

play00:45

refusing your application so that's

play00:47

going to give you some more confidence

play00:49

and in this part we want to set up the

play00:51

required things for our testing in the

play00:54

future so we are going to create a new

play00:56

project in your application and then set

play00:58

up some other things so let's get

play01:00

started as you can see I'm in the

play01:02

command line and i can create a new app

play01:04

using Django admin start project and

play01:08

that I'm going to name this project

play01:10

testing and now we can change the

play01:15

directory into testing and now we can

play01:18

start our actual app and this is going

play01:21

to be cold friendship I'll start app and

play01:24

then I'm going to sign in the name of

play01:27

products and now that we have that we

play01:31

can open our folder inside of atom using

play01:33

atom and then a dot so instead of the

play01:37

motor stop by file we can now create a

play01:39

new model and call it product which

play01:43

suffers from model so model of course

play01:45

and then I'm going to assign the field

play01:48

of name and set it equal to a model

play01:50

store char field with the max length of

play01:54

let's say 100 then every product is

play01:58

going to have one description and we can

play02:01

set a equal to model store text field

play02:06

then a price which is going to be a

play02:09

models the decimal fields

play02:13

the symbol field and I'm setting the

play02:18

next digits equal to five and then the

play02:22

decimal places will be two then we want

play02:27

to associate a quantity with it which

play02:30

tells us how many of the specific

play02:32

product we still have in a you know fake

play02:35

stock I guess and set it equal to

play02:38

modeled store integer field and then we

play02:43

want to set it published on equal to

play02:47

models the date field and on this model

play02:53

we want to be able to use one function

play02:55

which is called def is in stock and

play02:59

whenever we call this function we want

play03:02

to return a boolean which tells us if we

play03:04

still have some product inside of a

play03:06

stock so all we have to do is return

play03:09

self-taught quantity is greater than

play03:12

zero and if it's greater than zero it

play03:15

means that the self-taught quality

play03:16

variable is equal to one or above and if

play03:19

that's the case of course we still have

play03:21

this specific product in stock and if

play03:23

it's not the case we're going to get

play03:26

false so that should work how expected

play03:28

and then we can mark it as a property

play03:31

the property decorator and next up we

play03:34

want to go into the testing folder in

play03:36

the uracil pi file we can add a new path

play03:39

and this is quite simply just going to

play03:43

lead to any integer which we are going

play03:47

to named pk and whenever we hit this

play03:53

route we want to redirect or we want to

play03:56

call the use the product detail function

play04:01

and that I'm going to assign the name

play04:03

earth detail to this path and next we

play04:08

want to import the views from the

play04:10

product app so from products import

play04:13

views and now that we have imported them

play04:18

we of course have created them yet so

play04:20

just go back to the view supplier

play04:25

anger the new function called product

play04:28

detail which takes a new request and an

play04:32

ID or do we name it probably I guess we

play04:36

can't name it okay and now we want to

play04:41

get the product by their private key but

play04:43

of course we still have to import the

play04:45

model itself first so from the models

play04:48

import product and at this stage we can

play04:54

set the product equal to get object or

play04:58

for for product and then we want to

play05:02

select by the ID of private key or you

play05:06

could use PK but works that will also

play05:09

work here let's do this

play05:10

and then we have to import the get

play05:14

object or for for function which is

play05:17

going to take care of returning a for

play05:19

for error if this specific product which

play05:22

we want to access doesn't exist in the

play05:24

database

play05:24

and then we can return a render with the

play05:30

request to product detail dot HTML and

play05:35

pass on a product with this dictionary

play05:39

and last we want to go into the project

play05:44

entity products and create a new folder

play05:48

called templates and then here we can

play05:52

create the product and it's called

play05:54

detailed or HTML and just simply spit

play05:58

out an h1 which says product dot name

play06:02

that would be enough for us to identify

play06:04

it and now of course you have to go into

play06:09

the settings to PI and include your

play06:11

application

play06:17

and that should be about it actually

play06:20

let's go back and now you can make all

play06:25

of the migrations using managed up I

play06:27

make migrations and manage the pipe

play06:32

migrate and that will just run through

play06:36

and spit out a whole bunch of gibberish

play06:38

which we don't understand and now we can

play06:42

run our server using manage the pipe run

play06:44

server and go back to your localhost

play06:48

8080 can see we have nothing at this in

play06:55

XP and if we go 2-1 we get a 404 because

play06:59

there is no product with the idea of one

play07:02

yet and we want to create one so go back

play07:06

and enter the mansion pie shell actually

play07:10

that should work fine enough for this

play07:13

one

play07:13

and now from products the product or

play07:18

from products models import product and

play07:23

from daytime import daytime because we

play07:27

need a temp to fill out one product as

play07:29

you can see we have two state field

play07:34

which we also need to specify and now we

play07:38

can create a new product using product

play07:40

so objects don't create and I'm going to

play07:45

give it the name of book the description

play07:48

of an awesome book about Django and what

play07:56

do we have

play07:56

yeah the price will be $19.99 so quite

play08:03

standard and then the quantity let's say

play08:09

we have still 100 books inside of our

play08:12

stock and then we can specify the

play08:15

published on as daytime don't know close

play08:21

it off

play08:22

and then just hit dot safe so it gets

play08:26

saved to the database and you will see

play08:29

it runs through and now we can test it

play08:32

out by using product the objects don't

play08:35

get by the private key and specify to

play08:38

one because of course it will count all

play08:40

the objects we create up from one two

play08:43

you know n however many we have annual

play08:48

CD product object so that works fine and

play08:50

you can just head out o go out of the

play08:54

shell using quit and if we go back and

play08:58

run a server can just reload it and you

play09:05

see we to get booked which was the name

play09:07

of a product and this is kind of tedious

play09:09

doing the setup

play09:10

manually but it will serve for the next

play09:12

parts where we are actually going to

play09:13

test all of this functionality and last

play09:18

but not least I want to go to this view

play09:20

and make it a login required view just

play09:24

so we can test that only logged in users

play09:27

can access certain views so make sure

play09:30

that it's marked by a log and written

play09:32

quiet and then we need to import this

play09:34

decorator so from Django top contrib

play09:38

total top decorators import login

play09:42

required and if we go back you'll see

play09:48

that we get redirected to accounts login

play09:50

because it wants us to look in but of

play09:53

course we have no account yet so that

play09:55

will be fine but it will work if we all

play09:56

have been so don't worry about that

play09:58

anyways it should be about it for this

play10:03

project itself but first of all we want

play10:06

to now install some packages which we

play10:08

are going to use so first of all I want

play10:11

to pip install PI test you also there

play10:14

already have it but for you it should

play10:15

run through and then pip install

play10:19

fighters dead stringer and last I want

play10:23

to install PI test dash curve which can

play10:26

be used to test the coverage of our

play10:28

project and I want you installed mixer

play10:32

as well and there will be used to mock

play10:36

database a bit more conveniently and

play10:38

that should be avoided so now that we

play10:41

have our set up work set up we can go

play10:45

into the next pattern and actually start

play10:47

writing our first test I hope you

play10:49

enjoyed it make sure to share this

play10:50

series with anybody you think would

play10:53

enjoy it as well leave a comment and a

play10:55

like down below and I hope to see you

play10:57

inside of the next one Cheers

Rate This
★
★
★
★
★

5.0 / 5 (0 votes)

Étiquettes Connexes
Django TestingAutomated TestingCode IntegrityTutorial SeriesTesting LifecycleWeb DevelopmentApp TestingSoftware AssuranceModel TestingLogin Required
Besoin d'un résumé en anglais ?