0

I am mocking a get request in my unittest code using requests-mock, but when I run the code during testing, it still tries to hit the actual URL instead of returning the mocked data.

This is my code:

    try:
        response = requests.get(api_url, auth=requests.auth.HTTPBasicAuth(username, password))
        response.raise_for_status()
    except requests.ConnectionError as e:
        raise dke.CLIError(f"Could not connect to Artifactory server to get NPM auth information: {str(e)}")

This is my test code

class MyTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        m = requests_mock.Mocker()
        m.get('https://artifactory.apps.openshift-sandbox.example.com/artifactory/api/npm/auth',
              text=("_auth = base64string==\n"
                    "always-auth = true\n"
                    "email = shareduser@fake.com"))

The api_url in my code matches the URL I pass to m.get(). However, when I run the test, I do not get the value of "text" but instead I get a 401 Client Error: Unauthorized and a response from the server indicating "Bad credentials" which tells me it actually tried to contact the server instead of returning the text I had requested in the Mock.

I'm lost. As far as I can tell, I'm using this exactly as the docs indicate. Any ideas?

2 Answers2

0

So, it seems you can't use the request_mocker that way. It has to be a decorator or context manager.

0

I mean the context manager/decorator is just a pattern around normal code. I haven't tested it but i think you just have to call m.start()/m.stop().

It's generally used as a context manager or decorator because if you instantiate it once like that then your request history is going to include all requests across all unit tests which is very hard to make assertions about.

jamielennox
  • 368
  • 1
  • 2
  • 9