Skip to content

Instantly share code, notes, and snippets.

@edavis
Created June 24, 2012 02:13
Show Gist options
  • Save edavis/2981086 to your computer and use it in GitHub Desktop.
Save edavis/2981086 to your computer and use it in GitHub Desktop.
Mock not recording headers correctly
# transmission.py
class Transmission(object):
# ... snip ...
def _make_request(self, method, **kwargs):
body = anyjson.serialize(self._format_request_body(method, **kwargs))
response = requests.post(self.url, data=body, headers=self.headers, auth=self.auth)
if response.status_code == CSRF_ERROR_CODE:
self.headers[CSRF_HEADER] = response.headers[CSRF_HEADER]
return self._make_request(method, **kwargs)
return response
# tests.py
class TestTransmissionRequests(unittest.TestCase):
def setUp(self):
self.client = Transmission()
def test_csrf_handling(self):
headers = {transmission.CSRF_HEADER: '123'}
with mock.patch("requests.post") as mocked:
mocked.side_effect = [mock.MagicMock(name='csrf', status_code=transmission.CSRF_ERROR_CODE, headers=headers),
mock.MagicMock(name='okay')]
self.client._make_request("torrent-get", ids=1, fields=['name'])
body = anyjson.serialize(self.client._format_request_body("torrent-get", ids=1, fields=["name"]))
# The first call to request.post should have been with empty headers
mocked.assert_any_call(self.client.url, data=body, headers={}, auth=None)
# The second call should have the proper headers set
mocked.assert_any_call(self.client.url, data=body, headers=headers, auth=None)
# Instead, mocked.mock_calls =
[call('http://localhost:9091/transmission/rpc', headers={'X-Transmission-Session-Id': '123'}, data='{"tag": 0, "method": "torrent-get", "arguments": {"fields": ["name"], "ids": 1}}', auth=None),
call('http://localhost:9091/transmission/rpc', headers={'X-Transmission-Session-Id': '123'}, data='{"tag": 0, "method": "torrent-get", "arguments": {"fields": ["name"], "ids": 1}}', auth=None)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment