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

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

我正在用单元测试和请求模块编写 python 测试,但得到
AssertionError: <Response [200]> != 200

测试设置在两个函数中,test_get 和 test_post。测试运行器从测试 class 开始,问题在 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)