From 5f5510fba829e12d57adb949667ce8e3c5ff09d9 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Mon, 16 Jan 2017 07:58:53 -0500 Subject: A one_of decorator for checking function arguments. --- coverage/misc.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'coverage/misc.py') diff --git a/coverage/misc.py b/coverage/misc.py index 240a2587..e78a1537 100644 --- a/coverage/misc.py +++ b/coverage/misc.py @@ -58,6 +58,17 @@ if env.TESTING: new_contract('bytes', lambda v: isinstance(v, bytes)) if env.PY3: new_contract('unicode', lambda v: isinstance(v, unicode_class)) + + def one_of(argnames): + """Ensure that only one of the argnames is non-None.""" + def _decorator(func): + argnameset = set(name.strip() for name in argnames.split(",")) + def _wrapped(*args, **kwargs): + vals = set(kwargs.get(name) for name in argnameset) + assert sum(val is not None for val in vals) == 1 + return func(*args, **kwargs) + return _wrapped + return _decorator else: # pragma: not covered # We aren't using real PyContracts, so just define a no-op decorator as a # stunt double. @@ -69,6 +80,12 @@ else: # pragma: not covered """Dummy no-op implementation of `new_contract`.""" pass + def one_of(argnames_unused): + """Dummy no-op implementation of `one_of`.""" + def _decorator(func): + return func + return _decorator + def nice_pair(pair): """Make a nice string representation of a pair of numbers. -- cgit v1.2.1