Created
October 10, 2019 14:01
-
-
Save boechat107/6f8f2511c7e8135824f0a55efff9c2d4 to your computer and use it in GitHub Desktop.
Counting the number of times a function is called in a test (pytest)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
class MutableCounter: | |
""" | |
Used by "count_calls". | |
""" | |
n = 0 | |
def inc(self): | |
self.n += 1 | |
def get(self): | |
return self.n | |
def count_calls(monkeypatch, module, fn) -> MutableCounter: | |
""" | |
Returns a mutable object containing the number of times the given function | |
"fn", from the module "module", was called. | |
Intended to be used inside pytest functions. | |
""" | |
cnt = MutableCounter() | |
def mock_fn(*args, **kwargs): | |
nonlocal cnt | |
cnt.inc() | |
return fn(*args, **kwargs) | |
mock_fn.__name__ = fn.__name__ | |
monkeypatch.setattr(module, fn.__name__, mock_fn) | |
return cnt | |
def test_calls_to_fn(monkeypatch): | |
def fn_to_be_tested(): | |
return random.randint(0, 10) | |
calls_cnt = count_calls(monkeypatch, random, random.randint) | |
assert calls_cnt.get() == 0 | |
x = fn_to_be_tested() | |
assert 0 <= x <= 10 | |
assert calls_cnt.get() == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment