2017-06-08 4 views
0

私がテストしている関数に対してrequests_mockを使用しようとしています。テストされた関数にrequests_mockアダプタを渡す

#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 

これは、模擬アダプタがテスト済みの機能に移行していないことを示すエラーを返します。

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

モックアダプターを機能に渡すにはどうすればよいですか?

答えて

1

requests.headの代わりにsession.headを使用する必要があるため、これは機能しません。 メイン関数のコードをいじってなくて、そうするための1つの可能性がpatchを使用することです:

from unittest.mock import patch 

[...] 

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

ありがとうございました!ドキュメントから:patch()は使いやすいです。キーは、正しい名前空間でパッチを適用することです。 –

関連する問題