Django Testing Tutorial with Pytest #1 - Setup (2018)
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
😀 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.
🛠️ 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.
📚 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
💡Automated Testing
💡Django
💡Model
💡Property Decorator
💡View
💡Template
💡Migrations
💡Login Required
💡Test Coverage
💡Mocking
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
hello everybody I hope you are having a
great day in this tutorial series you
will learn all of the major concepts
that go into testing your jenga
application by the end of series you
will have a good understanding of how
the testing lifecycle inside of your
projects can work and should work and
you'll be able to write your own tests
for your applications and therefore
ensure their integrity and what we mean
by automated testing is the writing of
some simple code snippets that is used
to test some other code snippets of your
production code and this just gives you
the confidence that your code is working
correctly and whenever you need to make
changes you can just run all of your
tests and make sure that everything
works fine without worrying that you
just broke something and your end-users
are going to have a horrible time
refusing your application so that's
going to give you some more confidence
and in this part we want to set up the
required things for our testing in the
future so we are going to create a new
project in your application and then set
up some other things so let's get
started as you can see I'm in the
command line and i can create a new app
using Django admin start project and
that I'm going to name this project
testing and now we can change the
directory into testing and now we can
start our actual app and this is going
to be cold friendship I'll start app and
then I'm going to sign in the name of
products and now that we have that we
can open our folder inside of atom using
atom and then a dot so instead of the
motor stop by file we can now create a
new model and call it product which
suffers from model so model of course
and then I'm going to assign the field
of name and set it equal to a model
store char field with the max length of
let's say 100 then every product is
going to have one description and we can
set a equal to model store text field
then a price which is going to be a
models the decimal fields
the symbol field and I'm setting the
next digits equal to five and then the
decimal places will be two then we want
to associate a quantity with it which
tells us how many of the specific
product we still have in a you know fake
stock I guess and set it equal to
modeled store integer field and then we
want to set it published on equal to
models the date field and on this model
we want to be able to use one function
which is called def is in stock and
whenever we call this function we want
to return a boolean which tells us if we
still have some product inside of a
stock so all we have to do is return
self-taught quantity is greater than
zero and if it's greater than zero it
means that the self-taught quality
variable is equal to one or above and if
that's the case of course we still have
this specific product in stock and if
it's not the case we're going to get
false so that should work how expected
and then we can mark it as a property
the property decorator and next up we
want to go into the testing folder in
the uracil pi file we can add a new path
and this is quite simply just going to
lead to any integer which we are going
to named pk and whenever we hit this
route we want to redirect or we want to
call the use the product detail function
and that I'm going to assign the name
earth detail to this path and next we
want to import the views from the
product app so from products import
views and now that we have imported them
we of course have created them yet so
just go back to the view supplier
anger the new function called product
detail which takes a new request and an
ID or do we name it probably I guess we
can't name it okay and now we want to
get the product by their private key but
of course we still have to import the
model itself first so from the models
import product and at this stage we can
set the product equal to get object or
for for product and then we want to
select by the ID of private key or you
could use PK but works that will also
work here let's do this
and then we have to import the get
object or for for function which is
going to take care of returning a for
for error if this specific product which
we want to access doesn't exist in the
database
and then we can return a render with the
request to product detail dot HTML and
pass on a product with this dictionary
and last we want to go into the project
entity products and create a new folder
called templates and then here we can
create the product and it's called
detailed or HTML and just simply spit
out an h1 which says product dot name
that would be enough for us to identify
it and now of course you have to go into
the settings to PI and include your
application
and that should be about it actually
let's go back and now you can make all
of the migrations using managed up I
make migrations and manage the pipe
migrate and that will just run through
and spit out a whole bunch of gibberish
which we don't understand and now we can
run our server using manage the pipe run
server and go back to your localhost
8080 can see we have nothing at this in
XP and if we go 2-1 we get a 404 because
there is no product with the idea of one
yet and we want to create one so go back
and enter the mansion pie shell actually
that should work fine enough for this
one
and now from products the product or
from products models import product and
from daytime import daytime because we
need a temp to fill out one product as
you can see we have two state field
which we also need to specify and now we
can create a new product using product
so objects don't create and I'm going to
give it the name of book the description
of an awesome book about Django and what
do we have
yeah the price will be $19.99 so quite
standard and then the quantity let's say
we have still 100 books inside of our
stock and then we can specify the
published on as daytime don't know close
it off
and then just hit dot safe so it gets
saved to the database and you will see
it runs through and now we can test it
out by using product the objects don't
get by the private key and specify to
one because of course it will count all
the objects we create up from one two
you know n however many we have annual
CD product object so that works fine and
you can just head out o go out of the
shell using quit and if we go back and
run a server can just reload it and you
see we to get booked which was the name
of a product and this is kind of tedious
doing the setup
manually but it will serve for the next
parts where we are actually going to
test all of this functionality and last
but not least I want to go to this view
and make it a login required view just
so we can test that only logged in users
can access certain views so make sure
that it's marked by a log and written
quiet and then we need to import this
decorator so from Django top contrib
total top decorators import login
required and if we go back you'll see
that we get redirected to accounts login
because it wants us to look in but of
course we have no account yet so that
will be fine but it will work if we all
have been so don't worry about that
anyways it should be about it for this
project itself but first of all we want
to now install some packages which we
are going to use so first of all I want
to pip install PI test you also there
already have it but for you it should
run through and then pip install
fighters dead stringer and last I want
to install PI test dash curve which can
be used to test the coverage of our
project and I want you installed mixer
as well and there will be used to mock
database a bit more conveniently and
that should be avoided so now that we
have our set up work set up we can go
into the next pattern and actually start
writing our first test I hope you
enjoyed it make sure to share this
series with anybody you think would
enjoy it as well leave a comment and a
like down below and I hope to see you
inside of the next one Cheers
関連動画をさらに表示
Django Testing Tutorial with Pytest #2 - Unit Testing (2018)
Curso Sistema de Ventas en ASP.NET Core 6 y SQL Server - Parte 06
How to test React apps with Vitest and Vite
How To Create And Publish Your First NPM Package
2024 Unity VR Tutorial (OpenXR and XR Interaction Toolkit) - PART 1 - Project Setup
How to Setup the XR Interaction Toolkit - 2023 Unity VR Basics
5.0 / 5 (0 votes)