1

If I have a function that keeps changing number of arguments (adding, removing, refactoring etc.), how can I call this function in a test with arbitrary arguments? I just want to test that when a dependency returns True, the function itself raises a certain exception. Right now I have something like

dependency.return_value = True
self.assertRaises(Expcetion, function_being_tested, None, None, None, None, None)
petabyte
  • 1,487
  • 4
  • 15
  • 31

1 Answers1

1

While I'm not really sure that your unit tests are well designed if you need this kind of functionality, working with the information presented in this answer: Programmatically determining amount of parameters a function requires - Python we can see how we can get what you want.

import inspect

def call_wrapper(func):
    num_args = len(inspect.getargspec(func)[0])
    return func(*([None]*num_args))

And then your unit test becomes:

self.assertRaises(Expcetion, call_wrapper, function_being_tested)
Community
  • 1
  • 1
aruisdante
  • 8,875
  • 2
  • 30
  • 37
  • Honestly, that seems like overkill but you're probably right that I should refactor – petabyte Mar 02 '15 at 19:49
  • 1
    I mean you can certainly one-line it with `self.assertRaises(Exception, function_being_tested, *([None]*len(inpsect.getargspec(func)[0])))` but breaking it out lets you reuse it if you do the pattern frequently and makes what you're doing a little clearer to anyone else looking at the code. – aruisdante Mar 02 '15 at 19:51