0

I tried to mock a specific URL as shown in this example: How can I mock requests and the response? to test my own function:

class URLStatus():
  @staticmethod
  def check(url, redirects):
    try:
      session = requests.Session()
      session.max_redirects = redirects
      urlcheck = session.get(url)
      return urlcheck.status_code

The issue is that it never takes the mocked url, but instead only takes real ones.

import requests

from unittest import TestCase, mock
from unittest.mock import patch

from lib.checks.url_status import URLStatus


def mocked_requests_get(*args, **kwargs):
  class MockResponse:
    def __init__(self, json_data, status_code):
      self.json_data = json_data
      self.status_code = status_code

    def json(self):
      return self.json_data

  if args[0] == 'http://someurl.com/test.json':
    return MockResponse({"key1": "value1"}, 200)
  elif args[0] == 'http://someotherurl.com/anothertest.json':
    return MockResponse({"key2": "value2"}, 200)

  return MockResponse(None, 404)

class URLStatusTestCase(TestCase):

  @mock.patch('lib.checks.url_status.requests.get', side_effect=mocked_requests_get)
  def test_check(self, mock_get):

    url_status = URLStatus()
    test_data = url_status.check('http://someurl.com/test.json', 5)
    self.assertEqual(test_data, 200)


if __name__ == '__main__':
  unittest.main()

This one, for example, fails because it sees 'http://someurl.com/test.json' as a 404, not a 200. I have no idea why this is happening.

How do I make it take the mocked URL?

Photon
  • 5
  • 2

1 Answers1

0

You are mocking the wrong function. requests.get is a convenience function that creates its own, one-use Session, then uses its get method to provide the result. Your check method is using its own Session object; you need to at least mock that object's get method.

Given that you aren't reusing this session elsewhere, it would probably be simplest to change its implementation to take advantage of requests.get:

class URLStatus():
    @staticmethod
    def check(url, redirects):
        return requests.get(url, max_redirects=redirects).status_code
chepner
  • 497,756
  • 71
  • 530
  • 681