Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test Recursive Python Function

I have a recursive function that I'm looking to test, however I'm having difficulty limiting the recursive call during testing. For example, below is a simple example of a recursive function that calls a bool_function(n) to check if it should break the recursive loop.

def factorial(n):
  if bool_function(n):
      return 1
  else:
      return n * factorial(n-1)

What would be the best way to test or mock bool_function(n) so that it is true for the first iteration and false for any call after?

like image 230
sokeefe Avatar asked Feb 09 '26 19:02

sokeefe


1 Answers

You could always implement a class to encapsulate the state and give you more flexibility, here's a sketch:

>>> class MockBoolCheck:
...     def __init__(self, fail_after=0):
...         self.count = 0
...         self.fail_after = fail_after
...     def __call__(self, n):
...         called = self.count
...         self.count += 1
...         return called <= self.fail_after
...
>>> bool_function = MockBoolCheck()
>>> bool_function(42)
True
>>> bool_function(42)
False
>>> bool_function(42)
False
>>> bool_function(42)
False
>>> bool_function(42)
False
like image 140
juanpa.arrivillaga Avatar answered Feb 12 '26 11:02

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!