【问题标题】:Is there a better way to write these tests?有没有更好的方法来编写这些测试?
【发布时间】:2019-08-26 04:16:08
【问题描述】:

所以基本上,测试有效,当我进入控制台时它说 OK

python3 manage.py test apps/diary

但问题是,当我查看其他来源时,尤其是 W.S. Vincent(https://wsvincent.com/) 的测试方式,比较干净;它不必担心创建对象的会话是否经过身份验证,或者我认为。

因此,在我的代码中,这些都只是本应编写良好的测试的某种临时改动,只是因为我想不出另一种方法。我已经在https://realpython.com/testing-in-django-part-1-best-practices-and-examples/ 中阅读过这篇测试中的“最佳实践”文章,但它仍然没有帮助。

这是我的代码的 sn-p,一个 Test 类: 类 DetailViewTest(TestCase):

def setUp(self):
    self.user = get_user_model().objects.create_user(
        username='testuser', email='test@email.com',
        password='secretpw', first_name='John',
        last_name='Doe'
    )
    self.client.force_login(self.user)
    self.client.post(reverse('diary:add'), {
        'title': 'Test Title',
        'author': self.user,
        'content': 'Loren ipsum'
    })
    self.client.logout()
    self.user2 = get_user_model().objects.create_user(
        username='testuser2', email='test2@email.com',
        password='secretpw', first_name='John',
        last_name='Doe'
    )
    self.client.force_login(self.user2)
    self.client.post(reverse('diary:add'), {
        'title': 'Test Title',
        'author': self.user,
        'content': 'Loren ipsum'
    })
    self.client.logout()

def test_view_url_exists_at_proper_location(self):
    self.client.force_login(self.user)
    response = self.client.get('/post/1/')
    self.assertEqual(response.status_code, 200)

def test_view_uses_correct_template(self):
    self.client.force_login(self.user)
    response = self.client.get('/post/1/')
    self.assertEqual(response.status_code, 200)
    self.assertTemplateUsed(response, 'diary/post_detail.html')

def test_cannot_view_others_post(self):
    self.client.force_login(self.user2)
    response = self.client.get('/post/1/')
    self.assertEqual(response.status_code, 404)

(这里还是完整的代码:https://pastebin.com/6ufabmJP

另外,我一直想知道是否可以将 Test 类继承给其他人,或者我是否总是必须在创建 db 对象之前登录,以及我是否总是必须创建用户才能登录。

我们将非常感谢您的帮助和提示。谢谢~

【问题讨论】:

    标签: python testing django-testing django-2.1


    【解决方案1】:

    这确实是一个广泛的问题。一世 强烈推荐这篇关于如何在 Django-Projects 中编写好的测试的帖子:

    https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing

    它为您提供了测试视图的绝佳示例,就像您在 sn-p 中尝试一样。

    【讨论】:

    • 谢谢!当我搜索一些测试指南时,并没有偶然发现这一点。无论如何,你能评论一下我写的测试吗?是好的、坏的、低效的还是其他什么?
    猜你喜欢
    • 2013-08-18
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多