Skip to content

Instantly share code, notes, and snippets.

@Pigueiras
Last active May 22, 2018 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pigueiras/0687f2500136b63d739b2cb272bf3ce0 to your computer and use it in GitHub Desktop.
Save Pigueiras/0687f2500136b63d739b2cb272bf3ce0 to your computer and use it in GitHub Desktop.
How to mock imports in python?
/tmp/wow
15:12 $ cat a.py
import requests
def my_fn():
return requests.get("not")
/tmp/wow
15:13 $ cat test.py
import pytest
import mock
import a
def test_my_fn():
with mock.patch("a.requests") as MockReq:
MockReq.get.return_value = "whatever"
assert a.my_fn() == "whatever"
/tmp/wow
15:13 $ py.test test.py
==================================================================== test session starts ====================================================================
platform linux2 -- Python 2.7.14, pytest-2.9.2, py-1.4.33, pluggy-0.3.1
metadata: {'Python': '2.7.14', 'Platform': 'Linux-4.14.11-200.fc26.x86_64-x86_64-with-fedora-26-Twenty_Six', 'Packages': {'py': '1.4.33', 'pytest': '2.9.2', 'pluggy': '0.3.1'}, 'Plugins': {'cov': '2.4.0', 'xdist': '1.15.0', 'html': '1.14.2', 'timeout': '1.2.0', 'metadata': '1.5.0', 'flake8': '0.8.1'}}
rootdir: /tmp/wow, inifile:
plugins: xdist-1.15.0, timeout-1.2.0, metadata-1.5.0, html-1.14.2, flake8-0.8.1, cov-2.4.0
collected 1 items
test.py .
================================================================= 1 passed in 0.08 seconds ==================================================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment