django 单元测试

The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program.

作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。

介绍 (Introduction)

It is nearly impossible to build websites that work perfectly the first time without errors. For that reason, you need to test your web application to find these errors and work on them proactively. In order to improve the efficiency of tests, it is common to break down testing into units that test specific functionalities of the web application. This practice is called unit testing. It makes it easier to detect errors because the tests focus on small parts (units) of your project independently from other parts.

建立几乎没有错误的首次完美运行的网站几乎是不可能的。 因此,您需要测试您的Web应用程序以查找这些错误并主动进行处理。 为了提高测试效率,通常将测试分解为测试Web应用程序特定功能的单元。 这种做法称为单元测试 。 由于测试着重于项目的小部分(单元),而与其他部分无关,因此它更易于检测错误。

Testing a website can be a complex task to undertake because it is made up of several layers of logic like handling HTTP requests, form validation, and rendering templates. However Django provides a set of tools that makes testing your web application seamless. In Django, the preferred way to write tests is to use the Python unittest module, although it is possible to use other testing frameworks.

测试网站可能是一项复杂的任务,因为它由几层逻辑组成,例如处理HTTP请求,表单验证和呈现模板。 但是Django提供了一组工具,可以无缝测试Web应用程序。 在Django中,编写测试的首选方法是使用Python unittest模块,尽管可以使用其他测试框架。

In this tutorial, you will set up a test suite in your Django project and write unit tests for the models and views in your application. You will run these tests, analyze their results, and learn how to find the causes of failing tests.

在本教程中,您将在Django项目中设置测试套件,并为应用程序中的模型和视图编写单元测试。 您将运行这些测试,分析它们的结果,并学习如何找到失败的测试原因。

先决条件 (Prerequisites)

Before beginning this tutorial, you’ll need the following:

在开始本教程之前,您需要满足以下条件:

  • Django installed on your server with a programming environment set up. To do this, you can follow one of our How To Install the Django Web Framework and Set Up a Programming Environment tutorials.

    在您的服务器上安装了Django,并设置了编程环境。 为此,您可以按照我们的“ 如何安装Django Web框架和设置编程环境”教程之一进行操作。

  • A Django project created with models and views. In this tutorial, we have followed the project from our Django Development tutorial series.

    使用模型和视图创建的Django项目。 在本教程中,我们遵循了Django开发教程系列中的项目。

第1步-将测试套件添加到Django应用程序 (Step 1 — Adding a Test Suite to Your Django Application)

A test suite in Django is a collection of all the test cases in all the apps in your project. To make it possible for the Django testing utility to discover the test cases you have, you write the test cases in scripts whose names begin with test. In this step, you’ll create the directory structure and files for your test suite, and create an empty test case in it.

Django中的测试套件是项目中所有应用程序中所有测试用例的集合。 为了使Django测试实用程序能够发现您拥有的测试用例,请在名称以test开头的脚本中编写test 。 在此步骤中,您将为测试套件创建目录结构和文件,并在其中创建一个空的测试用例。

If you followed the Django Development tutorial series, you’ll have a Django app called blogsite.

如果您遵循Django开发教程系列,那么您将拥有一个名为blogsite的Django应用。

Let’s create a folder to hold all our testing scripts. First, activate the virtual environment:

让我们创建一个文件夹来保存我们所有的测试脚本。 首先,激活虚拟环境:

  • cd ~/my_blog_app

    cd〜 / my_blog_app

  • . env/bin/activate

    。 env / bin /激活

Then navigate to the blogsite app directory, the folder that contains the models.py and views.py files, and then create a new folder called tests:

然后导航到blogsite应用程序目录,即包含models.pyviews.py文件的文件夹,然后创建一个名为tests的新文件夹:

  • cd ~/my_blog_app/blog/blogsite cd〜/ my_blog_app / blog / blogsite
  • mkdir tests mkdir测试

Next, you’ll turn this folder into a Python package, so add an __init__.py file:

接下来,将这个文件夹转换为Python包,因此添加__init__.py文件:

  • cd ~/my_blog_app/blog/blogsite/tests cd〜/ my_blog_app / blog / blogsite / tests
  • touch __init__.py 触摸__init__.py

You’ll now add a file for testing your models and another for testing your views:

现在,您将添加一个用于测试模型的文件和另一个用于测试视图的文件:

  • touch test_models.py 触摸test_models.py
  • touch test_views.py 触摸test_views.py

Finally, you will create an empty test case in test_models.py. You will need to import the Django TestCase class and make it a super class of your own test case class. Later on, you will add methods to this test case to test the logic in your models. Open the file test_models.py:

最后,您将在test_models.py创建一个空的测试用例。 您将需要导入Django TestCase类,并使它成为您自己的测试用例类的超类。 稍后,您将向该测试用例添加方法以测试模型中的逻辑。 打开文件test_models.py

  • nano test_models.py 纳米test_models.py

Now add the following code to the file:

现在将以下代码添加到文件中:

~/my_blog_app/blog/blogsite/tests/test_models.py
〜/ my_blog_app / blog / blogsite / tests / test_models.py
from django.test import TestCaseclass ModelsTestCase(TestCase):pass

You’ve now successfully added a test suite to the blogsite app. Next, you will fill out the details of the empty model test case you created here.

现在,您已成功将测试套件添加到blogsite应用程序。 接下来,您将填写在此处创建的空模型测试用例的详细信息。

第2步-测试您的Python代码 (Step 2 — Testing Your Python Code)

In this step, you will test the logic of the code written in the models.py file. In particular, you will be testing the save method of the Post model to ensure it creates the correct slug of a post’s title when called.

在此步骤中,您将测试在models.py文件中编写的代码的逻辑。 特别是,您将测试Post模型的save方法,以确保它在调用时创建正确的帖子标题。

Let’s begin by looking at the code you already have in your models.py file for the save method of the Post model:

让我们从查看models.py文件中已经存在的Post模型的save方法代码开始:

  • cd ~/my_blog_app/blog/blogsite cd〜/ my_blog_app / blog / blogsite
  • nano models.py 纳米模型

You’ll see the following:

您会看到以下内容:

~/my_blog_app/blog/blogsite/models.py
〜/ my_blog_app / blog / blogsite / models.py
class Post(models.Model):...def save(self, *args, **kwargs):if not self.slug:self.slug = slugify(self.title)super(Post, self).save(*args, **kwargs)...

We can see that it checks whether the post about to be saved has a slug value, and if not, calls slugify to create a slug value for it. This is the type of logic you might want to test to ensure that slugs are actually created when saving a post.

我们可以看到它检查了即将保存的帖子是否有一个slug值,如果没有,则调用slugify为它创建一个slug值。 这是您可能需要测试的逻辑类型,以确保在保存帖子时实际创建了条。

Close the file.

关闭文件。

To test this, go back to test_models.py:

要对此进行测试,请返回到test_models.py

  • nano test_models.py 纳米test_models.py

Then update it to the following, adding in the highlighted portions:

然后将其更新为以下内容,并添加突出显示的部分:

~/my_blog_app/blog/blogsite/tests/test_models.py
〜/ my_blog_app / blog / blogsite / tests / test_models.py
from django.test import TestCase
from django.template.defaultfilters import slugify
from blogsite.models import Postclass ModelsTestCase(TestCase):def test_post_has_slug(self):"""Posts are given slugs correctly when saving"""post = Post.objects.create(title="My first post")post.author = "John Doe"post.save()self.assertEqual(post.slug, slugify(post.title))

This new method test_post_has_slug creates a new post with the title "My first post" and then gives the post an author and saves the post. After this, using the assertEqual method from the Python unittest module, it checks whether the slug for the post is correct. The assertEqual method checks whether the two arguments passed to it are equal as determined by the "==" operator and raises an error if they are not.

此新方法test_post_has_slug创建一个标题为"My first post"的新帖子,然后为该帖子提供作者并保存该帖子。 之后,使用Python unittest模块中的assertEqual方法,检查帖子的子弹是否正确。 assertEqual方法检查传递给它的两个参数是否等于"=="运算符所确定的参数,如果不相等,则会引发错误。

Save and exit test_models.py.

保存并退出test_models.py

This is an example of what can be tested. The more logic you add to your project, the more there is to test. If you add more logic to the save method or create new methods for the Post model, you would want to add more tests here. You can add them to the test_post_has_slug method or create new test methods, but their names must begin with test.

这是可以测试的示例。 添加到项目中的逻辑越多,要测试的内容就越多。 如果向save方法添加更多逻辑或为Post模型创建新方法,则需要在此处添加更多测试。 您可以将它们添加到test_post_has_slug方法中或创建新的测试方法,但是它们的名称必须以test开头。

You have successfully created a test case for the Post model where you asserted that slugs are correctly created after saving. In the next step, you will write a test case to test views.

您已经成功为Post模型创建了一个测试用例,您在其中断言在保存之后可以正确创建块。 在下一步中,您将编写一个测试用例以测试视图。

第3步-使用Django的测试客户端 (Step 3 — Using Django’s Test Client)

In this step, you will write a test case that tests a view using the Django test client. The test client is a Python class that acts as a dummy web browser, allowing you to test your views and interact with your Django application the same way a user would. You can access the test client by referring to self.client in your test methods. For example, let us create a test case in test_views.py. First, open the test_views.py file:

在此步骤中,您将编写一个使用Django测试客户端测试视图的测试用例。 测试客户端是一个Python类,充当虚拟Web浏览器,使您可以测试视图并以与用户相同的方式与Django应用程序进行交互。 您可以通过在测试方法中引用self.client来访问测试客户端。 例如,让我们在test_views.py创建一个测试用例。 首先,打开test_views.py文件:

  • nano test_views.py 纳米test_views.py

Then add the following:

然后添加以下内容:

~/my_blog_app/blog/blogsite/tests/test_views.py
〜/ my_blog_app / blog / blogsite / tests / test_views.py
from django.test import TestCaseclass ViewsTestCase(TestCase):def test_index_loads_properly(self):"""The index page loads properly"""response = self.client.get('your_server_ip:8000')self.assertEqual(response.status_code, 200)

The ViewsTestCase contains a test_index_loads_properly method that uses the Django test client to visit the index page of the website (http://your_server_ip:8000, where your_server_ip is the IP address of the server you are using). Then the test method checks whether the response has a status code of 200, which means the page responded without any errors. As a result you can be sure that when the user visits, it will respond without errors too.

ViewsTestCase包含一个test_index_loads_properly方法,该方法使用Django测试客户端访问网站的索引页( http:// your_server_ip :8000 ,其中your_server_ip是您使用的服务器的IP地址)。 然后,测试方法检查响应是否具有状态码200 ,这意味着页面已响应而没有任何错误。 结果,您可以确定,当用户访问时,它也将正确响应。

Apart from the status code, you can read about other properties of the test client response you can test in the Django Documentation Testing Responses page.

除了状态代码外,您还可以在Django Documentation Testing Responses页面上阅读有关测试客户端响应的其他属性。

In this step, you created a test case for testing that the view rendering the index page works without errors. There are now two test cases in your test suite. In the next step you will run them to see their results.

在此步骤中,您创建了一个测试用例,用于测试呈现索引页面的视图是否正常运行。 现在,您的测试套件中有两个测试用例。 在下一步中,您将运行它们以查看其结果。

第4步-运行测试 (Step 4 — Running Your Tests)

Now that you have finished building a suite of tests for the project, it is time to execute these tests and see their results. To run the tests, navigate to the blog folder (containing the application’s manage.py file):

既然您已经完成了针对项目的一组测试,那么现在该执行这些测试并查看其结果了。 要运行测试,请导航到blog文件夹(包含应用程序的manage.py文件):

  • cd ~/my_blog_app/blog cd〜/ my_blog_app / blog

Then run them with:

然后使用以下命令运行它们:

  • python manage.py test python manage.py测试

You’ll see output similar to the following in your terminal:

您将在终端中看到类似于以下内容的输出:

Output
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
..
----------------------------------------------------------------------
Ran 2 tests in 0.007sOK
Destroying test database for alias 'default'...

In this output, there are two dots .., each of which represents a passed test case. Now you’ll modify test_views.py to trigger a failing test. First open the file with:

在此输出中,有两个点.. ,每个点代表一个通过的测试用例。 现在,您将修改test_views.py以触​​发失败的测试。 首先使用以下命令打开文件:

  • nano test_views.py 纳米test_views.py

Then change the highlighted code to:

然后将突出显示的代码更改为:

~/my_blog_app/blog/blogsite/tests/test_views.py
〜/ my_blog_app / blog / blogsite / tests / test_views.py
from django.test import TestCaseclass ViewsTestCase(TestCase):def test_index_loads_properly(self):"""The index page loads properly"""response = self.client.get('your_server_ip:8000')self.assertEqual(response.status_code, 404)

Here you have changed the status code from 200 to 404. Now run the test again from your directory with manage.py:

在这里,您已将状态码从200更改为404 。 现在,使用manage.py从您的目录再次运行测试:

  • python manage.py test python manage.py测试

You’ll see the following output:

您将看到以下输出:

Output
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.F
======================================================================
FAIL: test_index_loads_properly (blogsite.tests.test_views.ViewsTestCase)
The index page loads properly
----------------------------------------------------------------------
Traceback (most recent call last):File "~/my_blog_app/blog/blogsite/tests/test_views.py", line 8, in test_index_loads_properlyself.assertEqual(response.status_code, 404)
AssertionError: 200 != 404----------------------------------------------------------------------
Ran 2 tests in 0.007sFAILED (failures=1)
Destroying test database for alias 'default'...

You see that there is a descriptive failure message that tells you the script, test case, and method that failed. It also tells you the cause of the failure, the status code not being equal to 404 in this case, with the message AssertionError: 200 != 404. The AssertionError here is raised at the highlighted line of code in the test_views.py file:

您会看到一条描述性的失败消息,告诉您失败的脚本,测试用例和方法。 它还告诉你失败的原因,状态代码不等于404在这种情况下,与消息AssertionError: 200 != 404test_views.py文件中突出显示的代码行处引发AssertionError

~/my_blog_app/blog/blogsite/tests/test_views.py
〜/ my_blog_app / blog / blogsite / tests / test_views.py
from django.test import TestCaseclass ViewsTestCase(TestCase):def test_index_loads_properly(self):"""The index page loads properly"""response = self.client.get('your_server_ip:8000')self.assertEqual(response.status_code, 404)

It tells you that the assertion is false, that is, the response status code (200) is not what was expected (404). Preceding the failure message, you can see that the two dots .. have now changed to .F, which tells you that the first test case passed while the second didn’t.

它告诉您断言是错误的,也就是说,响应状态代码( 200 )不是预期的结果( 404 )。 在失败消息之前,您可以看到两个点..现在已更改为.F ,这告诉您第一个测试用例通过了,而第二个没有通过。

结论 (Conclusion)

In this tutorial, you created a test suite in your Django project, added test cases to test model and view logic, learned how to run tests, and analyzed the test output. As a next step, you can create new test scripts for Python code not in models.py and views.py.

在本教程中,您在Django项目中创建了一个测试套件,为测试模型和视图逻辑添加了测试用例,学习了如何运行测试以及分析了测试输出。 下一步,您可以不在models.pyviews.py为Python代码创建新的测试脚本。

Following are some articles that may prove helpful when building and testing websites with Django:

以下是一些在使用Django构建和测试网站时可能会有所帮助的文章:

  • The Django Unit Tests documentation

    Django单元测试文档

  • The Scaling Django tutorial series

    扩展Django教程系列

You can also check out our Django topic page for further tutorials and projects.

您还可以查看我们的Django主题页面,以获取更多教程和项目。

翻译自: https://www.digitalocean.com/community/tutorials/how-to-add-unit-testing-to-your-django-project

django 单元测试

django 单元测试_如何将单元测试添加到Django项目相关推荐

  1. python的django介绍_【Python基础知识】Django框架简介

    很多初学Python的小伙伴不知道该从何开始学起,其实零基础学习的话可以先学习一些Python基础知识,等基础打牢之后再去接触更加深入的技术,接下来小编就为大家简单介绍一下有关于 Django框架内容 ...

  2. python搭建django环境_在BAE上搭建python,django环境小记

    BAE 是百度推出的一个云平台,类似于谷歌GAE,新浪SAE, 但谷歌经常被 "和谐",而SAE的使用我也未能申请成功,这里PS 一下新浪. 好在百度 今年3.9日正式开放了BAE ...

  3. django安装_技术大牛详解:Django框架之环境安装

    黑马程序员视频库 播妞微信号:boniu236 传智播客旗下互联网资讯.学习资源免费分享平台 虚拟环境安装:开发中问题:如何在同一台主机中,要开发多个不同的项目,而且需要用到同一个包的不同版本?尝试分 ...

  4. @sql 单元测试_如何在SQL单元测试中使用假表?

    @sql 单元测试 In this article on SQL unit testing, we will talk about how to isolate SQL unit tests from ...

  5. @sql 单元测试_简单单词中使用tSQLt进行的常规SQL单元测试

    @sql 单元测试 This article is about basics of conventional SQL unit testing concepts and its implementat ...

  6. 大数据可视化陈为智慧树_智慧树知到_大数据可视化_答案章节单元测试答案

    智慧树知到_大数据可视化_答案章节单元测试答案 更多相关问题 (1)33+(-23)2-48-12×6:(2)当a=2时,计算21-a-a1+a的值. 计算(1-11-a)(1a2-1)的结果正确的是 ...

  7. php带参数单元测试_一文搞定单元测试核心概念

    基础概念 单元测试(unittesting),是指对软件中的最小可测试单元进行检查和验证,这里的最小可测试单元通常是指函数或者类.单元测试是即所谓的白盒测试,一般由开发人员负责测试,因为开发人员知道被 ...

  8. 前端如何实现网络速度测试功能_前端组件单元测试

    啥?单元测试?我哪有时间写单元测试? 从软件质量说起 日常生活中,商品质量永远是我们进行选择时需要着重考虑的因素,计算机软件也不例外.优秀的软件应当如我们预期的一样工作,能够正确地处理所有功能性需求. ...

  9. python 读取配置文件的单元测试_单元测试

    [TOC] mydict.py代码如下: ~~~ class Dict(dict): def __init__(self, **kw): super().__init__(**kw) def __ge ...

最新文章

  1. JS ES6 实用笔记
  2. Java从入门到精通——数据库篇之JAVA中的对Oracle数据库操作
  3. Poj2480欧拉函数
  4. Spring Boot集成Debezium监控数据库变化
  5. mysql sql wait 写法_有关SQL语句写法注意的那些事情(原创整理)
  6. (转)TDI FILTER 网络过滤驱动完全解析
  7. 这边本来有1个人,现在没了:你有没有想过有一天自己也会被取代
  8. java明文发送_使用java MD5加密网络明文
  9. windowbuilder安装
  10. 使用 ale.js 制作一个小而美的表格编辑器(4)
  11. visualvm远程监控jvm_别再说你不会 JVM 性能监控和调优了,看完这篇再发言
  12. Codeforces Round #245 (Div. 2): C. Xor-tree(BFS)
  13. Linux网络编程 --- HTTP协议
  14. VMware安装Centos8(Centos8与Centos7的区别)
  15. 二值图像连通区域标记
  16. python+selenium打开浏览器-设置浏览器路径和驱动器路径
  17. 开放式运动耳机排行榜,排行榜最高的五款骨传导耳机
  18. mapping文件的编写
  19. 装饰模式之半透明装饰模式
  20. UnknownHostException: xxx异常

热门文章

  1. 和数软件:区块市场回归价值理性,才能保护投资者利益
  2. Adobe Acrobat Pro DC设置文档多级列表
  3. 计算A/B Test需要的样本量
  4. 买了日光的free pass
  5. 世界最大花朵时隔20个月再度开花
  6. iPhone/iOS开启个人热点的相关位置调整小结
  7. 校宝在线的延迟满足:做教育产业互联网平台
  8. Linux服务器常见运维性能测试(1)综合跑分unixbench、superbench
  9. 计算机毕业设计之java+ssm智慧仓库进销存系统
  10. WEB漏洞扫描器 – 北极熊扫描器