unittest assertionError in python AssertionError: <Response [200]> != 200



我正在使用unittest编写python测试并请求模块,但得到了
AssertionError: <Response [200]> != 200

测试设置在两个函数中,test_get 和 test_post。 测试运行程序从测试类开始,其中问题在 test2 中。我也试图断言这一点:<Response [200]>也是。但是得到这个错误:

<Response [200]> != <Response [200]>
Expected :<Response [200]>
Actual   :<Response [200]>

为此,我正在使用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()

现在您正在比较r它为您提供整数<Response [200]>,因此断言错误。相反,您可能想要断言 r.status_code ,这会将状态代码作为带有 200 的整数。

def test2(self):
    self.assertEqual(post_httpbin(post_url).status_code, 200)

您正在将响应对象与数字进行比较。他们不平等。

您打算将响应对象的状态代码与数字进行比较。试试这个:

def test2(self):
    self.assertEqual(post_httpbin(post_url).status_code, 200)

相关内容

最新更新