[英]unittest assertionError in python AssertionError: <Response [200]> != 200
I'm writing python tests with unittest and requests modules but getting我正在用 unittest 和 requests 模块编写 python 测试,但得到
AssertionError: <Response [200]> != 200
Tests are setup in two functions, test_get and test_post.测试在两个函数中设置,test_get 和 test_post。 Test runners starts from Tests class, where the issue is within test2.
测试运行程序从 Tests 类开始,其中的问题在 test2 中。 I've tried to assert this also:
<Response [200]>
also.我也试图断言:
<Response [200]>
也是。 But getting this Error instead:但是却收到此错误:
<Response [200]> != <Response [200]>
Expected :<Response [200]>
Actual :<Response [200]>
For this I am using httpbin and pycharm.为此,我使用了 httpbin 和 pycharm。
import requests
import unittest
# Test 1: Assert get data body
get_url = 'https://httpbin.org/get'
test_get = \
{
'args': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.21.0'},
'origin': '94.255.130.105, 94.255.130.105',
'url': 'https://httpbin.org/get'
}
def get_httpbin(get_url):
r = requests.get(get_url).json()
return r
# Test 2: Assert post is OK 200
post_url = 'https://httpbin.org/post'
test_post = \
{
'sender': 'Alice',
'receiver': 'Bob',
'message': 'We did it!'
}
def post_httpbin(post_url):
r = requests.post(post_url, test_post)
return r
# Test Runner
class Tests(unittest.TestCase):
def test1(self):
self.assertEqual(get_httpbin(get_url), test_get)
def test2(self):
self.assertEqual(post_httpbin(post_url), 200)
if __name__ == '__main__':
unittest.main()
Right now you are comparing r
which gives you <Response [200]>
with an integer, hence the asserion error.现在你正在比较
r
,它给你<Response [200]>
与一个整数,因此断言错误。 Instead you would want to assert r.status_code
, which gives you the status code as an integer with 200
.相反,您可能想要断言
r.status_code
,它为您提供状态代码作为200
的整数。
def test2(self):
self.assertEqual(post_httpbin(post_url).status_code, 200)
You're comparing a response object with a number.您正在将响应对象与数字进行比较。 They're not equal.
他们不是平等的。
What you intend is to compare the status code from the response object with a number.您打算将来自响应对象的状态代码与一个数字进行比较。 Try this:
尝试这个:
def test2(self):
self.assertEqual(post_httpbin(post_url).status_code, 200)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.