python responses - Not all requests have been executed

3.6k Views Asked by At

I'm trying test case to mock a api call and using python responses to mock the api call.

Below is my mock,

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)        

When I execute this mock, I get this error -

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

When I remove the mock and directly call the api, it works fine.

Any inputs on why my mock fails?

Error message -

======================================================================
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

There are 1 best solutions below

1
On BEST ANSWER

You are mocking the request, but the request was not called on this test. You are calling courses = self.app.courses.get_all (page = 1, page_size = 2), that I suspect that this method courses.get_all is calling the requests lib.

According to docs, after adding a response for mock, it is expected to call the request. And you're not calling request just after, you're calling get_all, and this method is calling, requests.

So, you must move this test, and adapt it, get_all method, or mock the request from class where it is used, that looking at you code, I suppose to be inCourse.get_all.