Skip to content

Commit 1a050e9

Browse files
committed
add testing
1 parent 178bcd0 commit 1a050e9

2 files changed

Lines changed: 235 additions & 0 deletions

File tree

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
原文:[Testing in Django](https://docs.djangoproject.com/en/1.9/topics/testing/)
2+
3+
---
4+
5+
对于当代的Web开发者来说,自动化测试是一个非常有用的bug专杀工具。你可以使用一个测试集合 —— 一个**测试套件** —— 来解决,或者避免许多问题:
6+
7+
* 当你编写新代码的时候,可以使用测试来验证你的代码如预期一样工作。
8+
* 当你重构或修改旧代码时,可以使用测试来确保你的修改不会意外的影响应用程序的行为。
9+
10+
测试Web应用是一项复杂的任务,因为Web应用程序是由几个逻辑层组成的 - 从HTTP级别的请求处理,到表单验证和处理,再到模板渲染。使用Django的测试执行框架和各种实用工具,你可以模拟请求,插入测试数据,检查你的应用程序的输出,以及一般性验证你的代码确实在什么它应该做的事。
11+
12+
最在,它真的很容易。
13+
14+
在Django中编写测试的首选方法是使用内置在Python标准库中的[`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest "(in Python v3.5)")模块。这在[_编写及运行测试_](https://docs.djangoproject.com/en/1.9/topics/testing/overview/)文档中详细的进行了说明。
15+
16+
你也可以使用任何其他的Python测试框架;Django为这种类型的集成提供了一个API和工具。在[_高级测试主题_](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/)的[使用不同的测试框架](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/#other-testing-frameworks)部分中对其进行了描述。
17+
18+
19+
* [编写及运行测试](https://docs.djangoproject.com/en/1.9/topics/testing/overview/)
20+
* [测试工具](https://docs.djangoproject.com/en/1.9/topics/testing/tools/)
21+
* [高级测试主题](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/)
Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
原文:[Writing and running tests](https://docs.djangoproject.com/en/1.9/topics/testing/overview/)
2+
3+
---
4+
5+
>另见
6+
>
7+
>[_测试教程_](https://docs.djangoproject.com/en/1.9/intro/tutorial05/), [_测试工具参考_](https://docs.djangoproject.com/en/1.9/topics/testing/tools/), 以及[_高级测试主题_](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/)。
8+
9+
10+
这篇文档分成两个主要部分。首先,我们解释怎么用Django编写测试。然后,我们解释如何运行它们。
11+
12+
13+
## 编写测试[](#writing-tests "Permalink to this headline")
14+
15+
Django的单元测试使用Python标准库模块:[`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest "(in Python v3.5)")。这个模块使用一种基于类的方法定义测试。
16+
17+
下面是创建[`django.test.TestCase`](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.TestCase "django.test.TestCase")子类的一个例子,`django.test.TestCase`是[`unittest.TestCase`](https://docs.python.org/3/library/unittest.html#unittest.TestCase "(in Python v3.5)")的一个子类,它运行事务中的每一个测试以提供隔离:
18+
19+
```py
20+
from django.test import TestCase
21+
from myapp.models import Animal
22+
23+
class AnimalTestCase(TestCase):
24+
def setUp(self):
25+
Animal.objects.create(name="lion", sound="roar")
26+
Animal.objects.create(name="cat", sound="meow")
27+
28+
def test_animals_can_speak(self):
29+
"""Animals that can speak are correctly identified"""
30+
lion = Animal.objects.get(name="lion")
31+
cat = Animal.objects.get(name="cat")
32+
self.assertEqual(lion.speak(), 'The lion says "roar"')
33+
self.assertEqual(cat.speak(), 'The cat says "meow"')
34+
```
35+
36+
当你[运行你的测试](#running-tests)时,该测试工具的默认行为是在任何名字以`test`开头的文件中找到所有的测试用例 (即[`unittest.TestCase`](https://docs.python.org/3/library/unittest.html#unittest.TestCase "(in Python v3.5)")的子类),根据那些测试用例,自动生成测试套件,然后运行该套件。
37+
38+
更多关于[`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest "(in Python v3.5)")的详细信息,见Python文档。
39+
40+
>这些测试存在哪里?
41+
42+
>默认的[`startapp`](https://docs.djangoproject.com/en/1.9/ref/django-admin/#django-admin-startapp)模板在新应用中创建了一个`tests.py`文件。如果你只有一些测试,这当然是可以的,但随着你的测试套件的增加,你可能会希望将其重组成一个测试包,这样的话,你就可以将你的测试分成不同的子模块,例如`test_models.py`, `test_views.py`, `test_forms.py`等等。随意挑选你喜欢的组织方案吧。
43+
44+
>另请参阅[使用Django测试运行器来测试可重用应用](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/#testing-reusable-applications)。
45+
46+
47+
>警告
48+
49+
>如果你的测试依赖于数据库访问,例如创建或查询模块,那么请确保将你的测试类作为[`django.test.TestCase`](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.TestCase "django.test.TestCase")的子类而不是[`unittest.TestCase`](https://docs.python.org/3/library/unittest.html#unittest.TestCase "(in Python v3.5)")的子类进行创建。
50+
51+
>使用[`unittest.TestCase`](https://docs.python.org/3/library/unittest.html#unittest.TestCase "(in Python v3.5)")避免了在一个事务中运行每个测试以及对数据清仓的花销,但是如果你的测试与数据库进行交互,那么他们的行为将会根据测试运行器执行他们的顺序不同而不同。这会导致当单独执行时单元测试通过,但在一个套件中运行时却失败的事情发生。
52+
53+
54+
## 运行测试[](#running-tests "Permalink to this headline")
55+
56+
一旦你写好了测试,那么就可以使用工程的`manage.py`工具中的[`test`](https://docs.djangoproject.com/en/1.9/ref/django-admin/#django-admin-test)命令来运行它们了:
57+
```sh
58+
$ ./manage.py test
59+
```
60+
测试发现基于unittest模块的[内置测试发现](https://docs.python.org/3/library/unittest.html#unittest-test-discovery "(Python v3.5)")。默认情况下,它将发现在当前工作目录下的任何名为“test*.py”的文件中的测试。
61+
62+
你可以为`./manage.py test`指令提供任意数量的“测试标签”来制定运行特殊的测试。每一个测试标签可以是一个到一个包、模块、`TestCase`子类或者测试方法的完整的Python点路径。例如:
63+
```sh
64+
# Run all the tests in the animals.tests module
65+
$ ./manage.py test animals.tests
66+
67+
# Run all the tests found within the 'animals' package
68+
$ ./manage.py test animals
69+
70+
# Run just one test case
71+
$ ./manage.py test animals.tests.AnimalTestCase
72+
73+
# Run just one test method
74+
$ ./manage.py test animals.tests.AnimalTestCase.test_animals_can_speak
75+
```
76+
你还可以提供到一个目录的一个路径来发现位于那个目录下的测试:
77+
```sh
78+
$ ./manage.py test animals/
79+
```
80+
如果你的测试文件命名与`test*.py`模式不同的话,你还可以使用`-p` (或者
81+
`--pattern`)选项来指定一个自定义的文件名模式匹配:
82+
```sh
83+
$ ./manage.py test --pattern="tests_*.py"
84+
```
85+
86+
如果在测试时按下`Ctrl-C`,那么测试运行器将会等待当前运行的测试完成,然后优雅地退出。在优雅的退出期间,测试运行器将会输出测试失败的任何详细信息,报告运行了多少测试以及遇到了多少错误及失败,并且如往常一样摧毁任何测试数据库。因此,如果你忘记传递[`--failfast`](https://docs.djangoproject.com/en/1.9/ref/django-admin/#cmdoption-test--failfast)选项了,按下`Ctrl-C`会非常有用,注意,有些测试意外失败,而你会想要获得关于失败的细节而不用等到完整的测试运行完成。
87+
88+
如果你不想等到当前的运行测试结束,那么你可以再按下`Ctrl-C`,测试运行将会立即停止,但不会优雅的停止。在中断之前运行的测试的任何细节都不会被报告出来,任何此次运行创建的测试数据库将不会被摧毁。
89+
90+
>在启用警告的情况下进行测试
91+
92+
>在启用Python警告:`python -Wall manage.py test`的情况下运行测试是个好主意。`-Wall`标识告诉Python显示废弃的告警。Django,像其他许多Python库一样,当特性消失时,使用这些告警来标识。它也可以标记你的代码中那些非严格错误,但可以受益于一个更好的实现的区域。
93+
94+
95+
### 测试数据库[](#the-test-database "Permalink to this headline")
96+
97+
需要一个数据库的测试(即模型测试)将不会使用你“真正的”(生产)数据库。而是会为此测试创建单独的空白数据库。
98+
99+
无论测试通过还是失败,当所有的测试都执行完毕后,测试数据库将会被摧毁。
100+
101+
102+
你可以通过使用[`test --keepdb`](https://docs.djangoproject.com/en/1.9/ref/django-admin/#cmdoption-test--keepdb)标识来阻止测试数据库被摧毁。 这在运行之间保留测试数据库。如果该数据库不存在,那么它将首先创建一个。任何迁移都会应用在它上面以保持它的最新状态。
103+
104+
105+
通过在[`DATABASES`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DATABASES)中的每个[`NAME`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-NAME)值之前附加`test_`来创建默认的测试数据库名。 当使用SQLite时,测试将会默认使用一个内存数据库(即,数据库完全在内存中创建,完全绕过文件系统!)。[`DATABASES`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DATABASES)中的[`TEST`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DATABASE-TEST)字典提供大量的设置来配置你的测试数据库。例如,如果你想要使用一个不同的数据库名,那么,为[`DATABASES`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DATABASES)中每个指定的数据库,在[`TEST`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DATABASE-TEST)字典中指定[`NAME`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEST_NAME)。
106+
107+
在PostgreSQL中,[`USER`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-USER)也需要对内置`postgres`数据库的读取权限。
108+
109+
除了使用一个单独的数据库,测试运行器还可以使用在你的设置文件中的所有相同的数据库设置:[`ENGINE`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DATABASE-ENGINE), [`USER`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-USER), [`HOST`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-HOST)等等。测试数据库是由[`USER`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-USER)指定的用户创建的,所以你将需要确保给定的用户账户有足够的权限在系统中创建一个新的数据库。
110+
111+
对于你的测试数据库关于字符编码细粒度的控制,使用[`CHARSET`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEST_CHARSET)测试选项。如果你使用的是MySQL,也可以使用[`COLLATION`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEST_COLLATION)选项来控制由测试数据库使用的具体的排序规则。关于细节及其他高级设置,见[_设置文档_](https://docs.djangoproject.com/en/1.9/ref/settings/)。
112+
113+
如果在Python 3.4+和SQLite 3.7.13+下使用SQLite内存数据库,那么,
114+
[共享缓存](https://www.sqlite.org/sharedcache.html)将被启用,所以你可以编写具有在线程间共享数据库的能力的测试。
115+
116+
>Django 1.8新特性
117+
>增加如上所述的使用带有共享缓存的SQLite的能力。
118+
119+
>在运行测试时,从你的生产数据库查找数据?
120+
121+
>如果当编译模块时,你的代码试图访问数据库,那么这将会在建立数据库之前发生,并带有潜在不期望的结果。例如,如果你在模块级别有一个数据库查询,并且存在一个真实的数据库,那么生产数据将会污染你的测试。 _无论如何,在你的代码中有这样的导入时间的数据库查询都不是一个好主意_ —— 重写代码,以便让它不要这样做。
122+
123+
>这也应用到[`ready()`](https://docs.djangoproject.com/en/1.9/ref/applications/#django.apps.AppConfig.ready "django.apps.AppConfig.ready")的自定义实现。
124+
125+
>另见
126+
127+
>[高级多数据库测试主题](https://docs.djangoproject.com/en/1.9/topics/testing/advanced/#topics-testing-advanced-multidb)。
128+
129+
130+
### 执行测试的顺序[](#order-in-which-tests-are-executed "Permalink to this headline")
131+
132+
为了保证所有的`TestCase`代码在一个干净的数据库中启动,Django测试运行器根据下列方式重排测试:
133+
134+
* 所有的[`TestCase`](../tools/#django.test.TestCase "django.test.TestCase")子类首先运行。
135+
* 然后,所有其他基于Django的测试 (基于[`SimpleTestCase`](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.SimpleTestCase "django.test.SimpleTestCase")的测试用例,包括[`TransactionTestCase`](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.TransactionTestCase "django.test.TransactionTestCase"))在没有特殊顺序保证或强制的情况下运行。
136+
* 然后,运行任何其他[`unittest.TestCase`](https://docs.python.org/3/library/unittest.html#unittest.TestCase "(Python v3.5)")测试(包括文档测试),它们可以改变数据库而无需将其恢复到初始状态。
137+
138+
>注意
139+
140+
>测试新的排序可能揭示了测试用例顺序意想不到的依赖关系。对于依赖一个给定的[`TransactionTestCase`](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.TransactionTestCase "django.test.TransactionTestCase")测试留在数据库中的状态的文档测试来说,情况就是这样的,它们必须被更新,以便能够独立运行。
141+
142+
>Django 1.8新特性
143+
144+
>你可以通过传递[`test --reverse`](https://docs.djangoproject.com/en/1.9/ref/django-admin/#cmdoption-test--reverse)选项来颠倒组内的执行顺序。这可以帮助你确保你的测试相互独立。
145+
146+
147+
### 回滚仿真[](#rollback-emulation "Permalink to this headline")
148+
149+
迁移加载的任何初始数据将只在`TestCase`测试中可用,而在`TransactionTestCase`测试中不可用,并且另外只在支持事务的后端上 (最重要的例外是MyISAM)。这对于那些依赖于`TransactionTestCase`的测试也是适用的,例如[`LiveServerTestCase`](https://docs.djangoproject.com/en/1.9/topics/testing/tools/#django.test.LiveServerTestCase "django.test.LiveServerTestCase")和[`StaticLiveServerTestCase`](https://docs.djangoproject.com/en/1.9/ref/contrib/staticfiles/#django.contrib.staticfiles.testing.StaticLiveServerTestCase "django.contrib.staticfiles.testing.StaticLiveServerTestCase")。
150+
151+
通过在`TestCase`或者`TransactionTestCase`中设置`serialized_rollback`选项值为`True`,Django能够为你在每个测试用例的基础上重载数据,但请注意,这将减缓测试套件将近3倍。
152+
153+
第三方应用或那些针对MyISAM的开发需要设置这个;然而,一般来说,你应该针对一个事务数据库开发自己的工程,并且为大多数的测试使用`TestCase`,因此并不需要这个设置。
154+
155+
初始序列化通常是非常快的,但如果你想要将这些应用从这个过程中排除(稍微加快测试的运行),那么你可能要添加那些应用到[`TEST_NON_SERIALIZED_APPS`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-TEST_NON_SERIALIZED_APPS)。
156+
157+
158+
要阻止序列化数据加载两次,设置`serialized_rollback=True`,当清洗测试数据库时禁用[`post_migrate`](https://docs.djangoproject.com/en/1.9/ref/signals/#django.db.models.signals.post_migrate "django.db.models.signals.post_migrate")信号。
159+
160+
161+
### 其他测试条件[](#other-test-conditions "Permalink to this headline")
162+
163+
无论在你的配置文件中,[`DEBUG`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DEBUG)设置是什么值,所有的Django测试都是在[`DEBUG`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-DEBUG)=False的条件下运行的。这是为了保证你的代码的观察输出与将在生产配置上看到的输出相匹配。
164+
165+
在每次测试之后,缓存都不会被清理,而且如果你在生产上运行测试,运行“manage.py test fooapp”会把测试中的数据插入到实时系统的缓存中,这是因为,不像数据库,不使用单独的“测试缓存”。未来,这个特性[可能会改变](https://code.djangoproject.com/ticket/11505)。
166+
167+
168+
### 了解测试输出[](#understanding-the-test-output "Permalink to this headline")
169+
170+
当运行你的测试时,你将会看到大量的测试运行器自身准备的消息。你可以在命令行使用`verbosity`选项来控制这些消息的细节级别:
171+
```
172+
Creating test database...
173+
Creating table myapp_animal
174+
Creating table myapp_mineral
175+
```
176+
这告诉你测试运行器正在创建一个测试数据库,正如上节所述。
177+
178+
一旦创建了测试数据库,Django将会运行你的测试。如果一切顺利的话,你将会看到像下面的东西:
179+
```
180+
----------------------------------------------------------------------
181+
Ran 22 tests in 0.221s
182+
183+
OK
184+
```
185+
然而,如果有测试失败,你将会看到关于失败的测试的完整细节:
186+
```
187+
======================================================================
188+
FAIL: test_was_published_recently_with_future_poll (polls.tests.PollMethodTests)
189+
----------------------------------------------------------------------
190+
Traceback (most recent call last):
191+
File "/dev/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_poll
192+
self.assertEqual(future_poll.was_published_recently(), False)
193+
AssertionError: True != False
194+
195+
----------------------------------------------------------------------
196+
Ran 1 test in 0.003s
197+
198+
FAILED (failures=1)
199+
```
200+
201+
关于这个错误输出的完整解释超出了本文的范围,但它相当直观。你可以查看Python的[`unittest`](https://docs.python.org/3/library/unittest.html#module-unittest "(in Python v3.5)")库文档以获得详细信息。
202+
203+
注意,对于任何数量的失败和错误测试,该测试运行器脚本的返回码是1。如果所有的测试都通过,那么返回码是0.如果你正在一个shell脚本中使用这个测试运行器脚本,并且需要在该级别验证测试的成功或失败,这个特性则是有用的。
204+
205+
206+
### 加速测试[](#speeding-up-the-tests "Permalink to this headline")
207+
208+
在Django的最近版本中,默认的密码散列器是相当慢的。如果在测试期间,你正验证许多用户,那么你或许想要使用自定义设置文件,并且设置[`PASSWORD_HASHERS`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-PASSWORD_HASHERS)设置项为一个更快的哈希算法:
209+
```py
210+
PASSWORD_HASHERS = [
211+
'django.contrib.auth.hashers.MD5PasswordHasher',
212+
]
213+
```
214+
如果有的话,不要忘了在[`PASSWORD_HASHERS`](https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-PASSWORD_HASHERS)中也包含任何固定使用的哈希算法。

0 commit comments

Comments
 (0)