Django 测试打印或日志失败
Django test print or log failure
我有一个 django_rest_framework 测试(问题与常规 django 测试相同),如下所示:
from rest_framework.test import APITestCase
class APITests(APITestCase):
# tests for unauthorized access
def test_unauthorized(self):
...
for api in apipoints:
response = self.client.options(api)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
我有一个 url 失败了,终端显示如下:
FAIL: test_unauthorized (app.misuper.tests.APITests)
---------------------------------------------------------------------- Traceback (most recent call last): File
"/home/alejandro/...",
line 64, in test_unauthorized
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) AssertionError: 200 != 403
好的,我怎么知道哪个 url 没有通过测试?我正在遍历所有需要登录的 url,即许多 url,我如何打印未通过测试的那个?
为了简单的快速修复,您可以在断言方法的第三个参数中传递apipoint
:
>>> from unittest import TestCase
>>> TestCase('__init__').assertEqual(1, 2, msg='teh thing is b0rked')
AssertionError: teh thing is b0rked
本着单元测试的精神,这些确实应该是每种不同的测试方法,而不是只有一种带有循环的测试方法。查看 nose_parameterized 以获取有关使它更干的帮助。您将像这样装饰测试方法:
from nose_parameterized import parameterized
@parameterized.expand(apipoints)
def test_unauthorized(self, apipoint):
response = self.client.options(apipoint)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
装饰器将为每个端点生成不同的测试方法,以便它们可以 pass/fail 相互独立。
虽然这个包的名字里有nose
,it's also compatible with other runners比如unittest
和py.test
.
我有一个 django_rest_framework 测试(问题与常规 django 测试相同),如下所示:
from rest_framework.test import APITestCase
class APITests(APITestCase):
# tests for unauthorized access
def test_unauthorized(self):
...
for api in apipoints:
response = self.client.options(api)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
我有一个 url 失败了,终端显示如下:
FAIL: test_unauthorized (app.misuper.tests.APITests) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/alejandro/...",
line 64, in test_unauthorized
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) AssertionError: 200 != 403
好的,我怎么知道哪个 url 没有通过测试?我正在遍历所有需要登录的 url,即许多 url,我如何打印未通过测试的那个?
为了简单的快速修复,您可以在断言方法的第三个参数中传递apipoint
:
>>> from unittest import TestCase
>>> TestCase('__init__').assertEqual(1, 2, msg='teh thing is b0rked')
AssertionError: teh thing is b0rked
本着单元测试的精神,这些确实应该是每种不同的测试方法,而不是只有一种带有循环的测试方法。查看 nose_parameterized 以获取有关使它更干的帮助。您将像这样装饰测试方法:
from nose_parameterized import parameterized
@parameterized.expand(apipoints)
def test_unauthorized(self, apipoint):
response = self.client.options(apipoint)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
装饰器将为每个端点生成不同的测试方法,以便它们可以 pass/fail 相互独立。
虽然这个包的名字里有nose
,it's also compatible with other runners比如unittest
和py.test
.