django向自己发送请求

时间:2016-01-15 15:54:14

标签: python django

有两次尝试从"工作" django服务器。工作版本是硬编码的,在单元测试时不起作用

# working
# a = requests.post('http://localhost:8000/ImportKeys/',
#                   data=json.dumps({'user_id': key_obj.email,
#'key': self.restore_pubkey(key_obj.fingerprint)}))

# not working

a = requests.post('http://' + request.get_host() + reverse('import_keys'),data=json.dumps({'user_id': key_obj.email,'key': self.restore_pubkey(key_obj.fingerprint)}))

在那个版本上,我想开始工作,我已经得到了这个(结束栈跟踪):

  

文件" /home/PycharmProjects/lib/python3.4/site-packages/requests/sessions.py",第576行,发送       r = adapter.send(request,** kwargs)     文件" /home/PycharmProjects/lib/python3.4/site-packages/requests/adapters.py" ;,第437行,发送       引发ConnectionError(e,request = request)   requests.exceptions.ConnectionError:HTTPConnectionPool(host =' testserver',port = 80):使用url超出了最大重试次数:/ ImportKeys /(由NewConnectionError引起(':无法建立新连接: [Errno -2]名称或服务未知',))

是的,我发现它正在尝试连接到80端口,这很糟糕。

2 个答案:

答案 0 :(得分:1)

要在TestCase课程中测试您的观看次数,请使用专为此目的而设计的django.test.Client。如果您从django.test.TestCase继承了测试用例,那么它已经通过self.client属性提供了。

class YourTestCase(TestCase):
    def test_import_keys_posting(self):
        data = {
            'user_id': key_obj.email,
            'key': self.restore_pubkey(key_obj.fingerprint)
        }
        response = self.client.post(reverse('import_keys'), data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {'result': 'ok'})

如果您使用Django Rest Framework,请考虑使用其精彩的APIClient,这样可以进一步简化API测试。

答案 1 :(得分:0)

If you need to send requests to the server during tests (in that case this will probably not be from the test code itself but from some mock or from JS code):

Extend LiveServerTestCase instead TestCase. This will launch an actual server during tests.

If you are using request.build_absolute_uri() in your regular code which is being tested, you need to change the test code to update the HTTP request headers accordingly like this:

checkout_url = '{}{}'.format(self.live_server_url, reverse('checkout', kwargs={'pk': article.id}))
parsed_url = parse.urlparse(self.live_server_url)

# add the info on host and port to the http header to make subsequent
# request.build_absolute_uri() calls work
response = self.client.get(checkout_url, SERVER_NAME=parsed_url.hostname, SERVER_PORT=parsed_url.port)