ApriOri
ApriOri

Reputation: 2688

mocker won't mock requests session

I'm tyring to mock the behavior of code that uses the library requests and uses requests. Session However I can't make mocker to mock the Session.get() method:

from mocker import Mocker, ANY
mocker = Mocker()
obj = mocker.proxy("requests.Session") #replace didn't work either
obj.get("anyurl")
mocker.result("mocksessionget")
mocker.replay()
import requests
s = requests.Session()
x = s.get("anyurl")

session.get is not mocked and this code throws:

requests.exceptions.MissingSchema: Invalid URL u'anyurl'

Upvotes: 2

Views: 947

Answers (1)

ApriOri
ApriOri

Reputation: 2688

It seems like it's impossible to mock requests.Session directly.

To the benefit of others here is how I managed to solve this:

requests_mock = mocker.replace("requests")
session_mock = mocker.mock()
requests_mock.Session()
mocker.result(session_mock)

You may have to add few calls to mocker to make it happy with it's ref counting.

Upvotes: 1

Related Questions