python响应-并非所有请求都已执行

时间:2018-12-10 19:23:56

标签: python mocking python-responses

我正在尝试测试用例来模拟api调用,并使用python响应来模拟api调用。

下面是我的模拟,

with responses.RequestsMock() as rsps:
    url_re = re.compile(r'.*udemy.com/api-2.0/courses.*')           
    url_re = re.compile(r'https://www.udemy.com/api-2.0/courses')
    rsps.add(
        responses.GET, url_re,
        body=mocked_good_json, 
        status=200,
        content_type='application/json',
        match_querystring=True
    )
    courses = self.app.courses.get_all(page=1, page_size=2)         
    for course in courses:              
        self.assertTrue(isinstance(course, Course))
        self.assertTrue(hasattr(course, 'id'))
        self.assertTrue(hasattr(course, 'title'))           
        self.assertIsNotNone(course.id)        

执行此模拟时,出现此错误-

AssertionError: Not all requests have been executed [(u'GET', 'https://www.udemy.com/api-2.0/courses/')]

当我删除模拟程序并直接调用api时,它可以正常工作。

关于我的模拟失败的任何信息吗?

错误消息-

======================================================================
FAIL: test_get_all_courses (tests.test_courses.TestApiCourses)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/rem/git/udemy/tests/test_courses.py", line 136, in test_get_all_courses
    courses = self.app.courses.get_all(page=1, page_size=2)
  File "/Users/rem/.virtualenvs/udemyapp/lib/python2.7/site-packages/responses.py", line 536, in __exit__
    self.stop(allow_assert=success)
  File "/Users/rem/.virtualenvs/udemyapp/lib/python2.7/site-packages/responses.py", line 620, in stop
    [(match.method, match.url) for match in not_called]
AssertionError: Not all requests have been executed [(u'GET', 'https://www.udemy.com/api-2.0/courses/')]

1 个答案:

答案 0 :(得分:0)

您在嘲笑该请求,但是此测试未调用该请求。您正在调用courses = self.app.courses.get_all (page = 1, page_size = 2),我怀疑此方法courses.get_all正在调用请求库。

根据docs,在添加了模拟响应之后,预计将调用该请求。而且您不是紧接着才调用请求,而是调用get_all,而此方法正在调用请求。

因此,您必须移动此测试,并采用get_all方法对其进行调整,或者模拟使用该类的类中的请求,即看来您正在查看的代码Course.get_all中。

相关问题