【问题标题】:unittest assertionError in python AssertionError: <Response [200]> != 200python AssertionError 中的 unittest assertionError: <Response [200]> != 200
【发布时间】:2019-06-02 16:43:03
【问题描述】:

我正在使用 unittest 和 requests 模块编写 python 测试,但得到
AssertionError: &lt;Response [200]&gt; != 200

测试在两个函数中设置,test_get 和 test_post。测试运行程序从 Tests 类开始,问题在 test2 中。我也尝试过断言:&lt;Response [200]&gt; 也。但是得到了这个错误:

<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()

【问题讨论】:

    标签: python python-3.x rest python-requests python-unittest


    【解决方案1】:

    现在你正在比较r,它给你&lt;Response [200]&gt; 和一个整数,因此是断言错误。相反,您会想要断言r.status_code,它会将状态代码作为带有200 的整数提供给您。

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-09
        • 2015-12-19
        • 2020-04-16
        • 2016-03-12
        • 1970-01-01
        • 2016-02-06
        • 1970-01-01
        相关资源
        最近更新 更多