Skip to content

Instantly share code, notes, and snippets.

@boechat107
Created October 10, 2019 14:01
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 boechat107/6f8f2511c7e8135824f0a55efff9c2d4 to your computer and use it in GitHub Desktop.
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)
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