django 单元测试_如何将单元测试添加到Django项目

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:

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

第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 TestCase

class 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 Post


class 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 TestCase


class 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.007s OK 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 TestCase


class 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_properly self.assertEqual(response.status_code, 404) AssertionError: 200 != 404 ---------------------------------------------------------------------- Ran 2 tests in 0.007s FAILED (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 TestCase


class 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构建和测试网站时可能会有所帮助的文章:

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 单元测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值