Tony Laidig
Tony Laidig

Reputation: 1078

Passing requests_mock adapter into tested function

I am trying to use requests_mock on a function that I am testing.

#the function
def getModificationTimeHTTP(url):
    head = requests.head(url)

    modtime = head.headers['Last-Modified'] if 'Last-Modified' in head.headers  \
        else datetime.fromtimestamp(0, pytz.UTC)
    return modtime

#in a test_ file
def test_needsUpdatesHTTP():
    session = requests.Session()
    adapter = requests_mock.Adapter()
    session.mount('mock', adapter)

    adapter.register_uri('HEAD', 'mock://test.com', headers= \
        {'Last-Modified': 'Mon, 30 Jan 1970 15:33:03 GMT'})

    update = getModificationTimeHTTP('mock://test.com')
    assert update

This returns an error which suggests the mock adapter is not making its way into the tested function.

       InvalidSchema: No connection adapters were found for 'mock://test.com'

How can I pass the mock adapter into the function?

Upvotes: 0

Views: 708

Answers (1)

julienc
julienc

Reputation: 20335

This won't work because you have to use session.head instead of requests.head. One possibility to do so without messing with the main function's code is to use patch:

from unittest.mock import patch

[...]

with patch('requests.head', session.head):
    update = getModificationTimeHTTP('mock://test.com')
assert update

Upvotes: 2

Related Questions