繁体   English   中英

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

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

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

测试在两个函数中设置,test_get 和 test_post。 测试运行程序从 Tests 类开始,其中的问题在 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM