I want to write a python decorator to decorate a test function of a unittest.TestCase, to decide the target host this function should run against. See this example:
class MyTestCase(unittest.TestCase):
@target_host(["host1.com", "host2.com"])
def test_my_command(self):
#do something here against the target host
In the decorated function, I want to be able to execute this test against all hosts, how do I do that? The declaration of target_host is supposed to return a new function, but is it possible to return multiple function that the test runner can execute?
Thanks!
You can return exactly one object (so technically, you could return a collections of functions). If you want to avoid astonishing everyone and if you want to call the result, you better return a single function though. But that function may very well call several other function in a loop… do you see where this leads to?
You need a factory for decorators that return a closure calling the function they’re applied to once per set of arguments that factory got. In code (including
functools.wrapsto keep name and docstring, may be useful or not, I tend to include it by default):Supporting keyword arguments requires more code and perhaps some ugliness, but is possible. If it’s always going to be a single argument, the code can be simplified (
def call_with_each(*args),for arg in args: f(arg), etc.).