【问题标题】:Change the default domain of Client() in unittest of Django在 Django 的 unittest 中更改 Client() 的默认域
【发布时间】:2011-09-11 13:52:00
【问题描述】:

我正在为 Django 视图编写单元测试。

class TestLog(unittest.TestCase):
    """Test for Contact"""
    def setUp(self):
        self.c = Client()
        try:
            self.bob = User.objects.create_user("mojo","b@example.com", "bmojo")
        except :
            print ''

    def test_get_emails(self):
        response = self.c.get('/text/')
        self.assertEqual(response.status_code, 200)


    def test_htmlemils(self):
        response = self.c.get('/emails/html/upload')
        self.assertEqual(response.status_code, 200)

c = Client() 将“http://testserver”作为我要覆盖的域,我想在该测试客户端中添加我的真实域,他们是自定义测试客户端的方式吗?

【问题讨论】:

  • 仅供参考:TestCase 自动将self.client 添加为客户端实例,因此您无需在setUp 中执行self.c = Client()。只需将您的测试方法中的self.c.get 更改为test.client.get :)

标签: python django unit-testing django-views django-unittest


【解决方案1】:

代码不仅可以帮助进行单元测试,还可以帮助 DRF 在序列化程序中使用上下文 ResponseSerializer(instance=obj, context={'request': get_request}).data

from django.test.client import RequestFactory
rf = RequestFactory()
rf.defaults['SERVER_NAME'] = 'my-site.com'
get_request = rf.get('/hello/')

【讨论】:

  • 用一些词来解释你的答案远远超出了“只是代码”的答案。
【解决方案2】:

Django 的 Client extends RequestFactory 所以你应该能够传入额外的参数作为关键字参数。

试试:

response = self.c.get('/emails/html/upload', SERVER_NAME="mydomain.com")

【讨论】:

  • 是的,我直接在客户端中添加 SERVER_NAME,例如 C = Client(SERVER_NAME="mydomain.com")
猜你喜欢
  • 2016-04-13
  • 1970-01-01
  • 2014-02-11
  • 2012-11-14
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
相关资源
最近更新 更多