Django 测试 : increase testsRun counter

标签 django django-testing

在一些 Django 测试中,我有循环来测试很多东西。
在最终结果中它显示为:
Ran 1 test in 3.456s
我想为每个循环增加该计数器,我该怎么做?
它正在使用 subTest() ,但这不会更新计数器(我认为这是一个参数 testsRun )

我的测试看起来像这样

class MyTestCase(TestCase):

   def test_auth_pages(self):
      pages = ['homepage', 'dashboard', 'profile']

      for page in pages:
         with self.subTest():
            # ....testsRun  += 1 
            self.c.login(username='test', password='test')
            response = self.c.get(reverse_lazy(page))
            self.assertEqual(200, response.status_code, msg=page)
            self.c.logout()
            response = self.c.get(reverse_lazy(page))
            self.assertEqual(302, response.status_code, msg=page) 

最佳答案

如果您不介意更改测试框架,请考虑 pytestpytest-django包裹。您可以使用 @pytest.mark.parametrize 轻松地对测试进行参数化。 :

import pytest

@pytest.mark.parametrize("page_name", ['homepage', 'dashboard', 'profile'])
def test_some_page(page_name, client):
    client.login(username='test', password='test')
    response = client.get(reverse_lazy(page))
    assert response.status_code == 200
    client.logout()
    response = client.get(reverse_lazy(page))
    assert response.status_code == 302

如果没有,您可以创建一个测试函数工厂,该工厂将接受页面名称并返回该页面的测试函数:

class MyTestCase(TestCase):

   def _create_page_test(page_name):
       def test_function(self):
           self.c.login(username='test', password='test')
           response = self.c.get(reverse_lazy(page_name))
           self.assertEqual(200, response.status_code, msg=page_name)
           self.c.logout()
           response = self.c.get(reverse_lazy(page_name))
           self.assertEqual(302, response.status_code, msg=page_name)
        return test_function

    test_homepage = _create_page_test("homepage")
    test_dashboard = _create_page_test("dashboard")
    test_profile = _create_page_test("profile")

此类更改的额外好处是每个页面都有一个独立的测试,彼此独立。这使得调试更容易。

关于Django 测试 : increase testsRun counter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56429695/

相关文章:

django - 序列化错误 : Incorrect type. 预期的 pk 值,已收到帖子

django - django_webtest 中的用户身份验证

django 测试客户端获取 404,但浏览器工作

python - 索引、for 循环和让事情看起来更干净

python - Django:在数据迁移中创建 super 用户

Django 日志记录在 View 中不起作用

django - 帮助 process_template_response django 中间件

python - Django:优化违反 DRY 的测试

django - setUp 函数在 django TestCase 中被多次调用

django - Django 测试运行程序和测试客户端登录与身份验证后端的问题