【问题标题】:Django AttributeError: object has no attribute 'assertContains'Django AttributeError:对象没有属性“assertContains”
【发布时间】:2015-10-20 17:54:12
【问题描述】:

我正在尝试官方文档中的 Django 测试装置,但我的测试类找不到 assertContains。

from django.utils import unittest
from django.test import Client

class SimpleTest(unittest.TestCase):
    def setUp(self):
        self.client = Client()

    def test_details(self):
        response = self.client.post('/register',
                                    {'username': '123',
                                     'password': '123',
                                    follow=True)
        self.assertEqual(response.status_code, 200)

        self.assertContains(response, "Logout")
        self.assertNotContains(response, "Login")

【问题讨论】:

    标签: django unit-testing testing testcase


    【解决方案1】:

    assertContains 是 Django 特有的功能,而不是 Python 特有的。因此,请确保测试类是 django.test 中的 TestCase 的子类,而不是 (python) unittest 中的 TestCase。

    from django.test import TestCase
    
        class SimpleTest(TestCase):
            self.assertContains(response, "Logout")
    

    【讨论】:

      【解决方案2】:

      就是这样(第一个答案),就我而言,我正在使用 django test_plus,这就是问题所在:

      from django.test import TestCase
      
      class BlogTestCase(TestCase):
          def test_blog(self):
          response = self.get('blog_detail', self.blog.slug)
      

      将导入改为

      from test_plus.test import TestCase
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-22
        • 2018-02-11
        • 2015-03-24
        • 2018-01-14
        • 2018-07-31
        • 2021-01-12
        • 2016-12-19
        相关资源
        最近更新 更多