Python nose 模块,tools() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用nose.tools()。
def test_nose_setup(testdir):
p = testdir.makepyfile("""
l = []
from nose.tools import with_setup
@with_setup(lambda: l.append(1),lambda: l.append(2))
def test_hello():
assert l == [1]
def test_world():
assert l == [1,2]
test_hello.setup = lambda: l.append(1)
test_hello.teardown = lambda: l.append(2)
""")
result = testdir.runpytest(p, '-p', 'nose')
result.assert_outcomes(passed=2)
def test_nose_setup_func_failure(testdir):
p = testdir.makepyfile("""
from nose.tools import with_setup
l = []
my_setup = lambda x: 1
my_teardown = lambda x: 2
@with_setup(my_setup,my_teardown)
def test_hello():
print (l)
assert l == [1]
def test_world():
print (l)
assert l == [1,2]
""")
result = testdir.runpytest(p, 'nose')
result.stdout.fnmatch_lines([
"*TypeError: <lambda>()*"
])
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,specifies that the decorated callable is a test.
If False,specifies that the decorated callable is not a test.
Default is True.
Notes
-----
This decorator can't use the nose namespace,because it can be
called from a non-test module. See also ``istest`` and ``nottest`` in
``nose.tools``.
Examples
--------
`setastest` can be used in the following way::
from numpy.testing.decorators import setastest
@setastest(False)
def func_with_test_in_name(arg1,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def apply_wrapper(wrapper, func):
"""Apply a wrapper to a function for decoration.
This mixes Michele Simionato's decorator tool with nose's make_decorator,
to apply a wrapper in a decorator so that all nose attributes,as well as
function signature and other properties,survive the decoration cleanly.
This will ensure that wrapped functions can still be well introspected via
IPython,for example.
"""
warnings.warn("The function `apply_wrapper` is deprecated since IPython 4.0",
DeprecationWarning, stacklevel=2)
import nose.tools
return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
def kNownfailureif(fail_condition, msg=None):
"""
Make function raise KNownFailureTest exception if given condition is true.
Parameters
----------
fail_condition : bool
Flag to determine whether to mark the decorated test as a kNown
failure (if True) or not (if False).
msg : str,optional
Message to give on raising a KNownFailureTest exception.
Default is None.
Returns
-------
decorator : function
Decorator,which,when applied to a function,causes KNownFailureTest to
be raised when `fail_condition` is True and the test fails.
Notes
-----
The decorator itself is decorated with the ``nose.tools.make_decorator``
function in order to transmit function name,and varIoUs other Metadata.
"""
if msg is None:
msg = 'Test skipped due to kNown failure'
def kNownfail_decorator(f):
# Local import to avoid a hard nose dependency and only incur the
# import time overhead at actual test-time.
import nose
def kNownfailer(*args, **kwargs):
if fail_condition:
raise KNownFailureTest(msg)
else:
return f(*args, **kwargs)
return nose.tools.make_decorator(f)(kNownfailer)
return kNownfail_decorator
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def status_code_validation(context, expected_http_status_code):
nose.tools.assert_equal(context.r.status_code, int(expected_http_status_code))
def status_code_validation(context, invalid_http_status_code):
nose.tools.assert_not_equal(context.r.status_code, int(invalid_http_status_code))
def status_code_array_validation(context, expected_http_status_codes):
expected_codes_list = [int(x) for x in expected_http_status_codes.split(',')]
nose.tools.assert_in(context.r.status_code, expected_codes_list)
def status_message_validation(context, expected_http_status_message):
nose.tools.assert_equal(context.r.reason, str(expected_http_status_message))
def parameter_validation(context, parameter_name, expected_parameter_value):
data = context.r.json()
if expected_parameter_value.startswith("context"):
expected_parameter_value = getattr(context, expected_parameter_value[8:])
nose.tools.assert_equal(data[parameter_name], expected_parameter_value)
else:
converted_value = json.loads(expected_parameter_value)
nose.tools.assert_equal(data[parameter_name], converted_value)
def parameter_validation(context, header_name, expected_header_value):
nose.tools.assert_equal(context.r.headers[header_name], str(expected_header_value))
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def test_random_string():
ts = random_string()
print(ts)
assert_equal(len(ts), 6)
nose.tools.assert_not_equal(ts, random_string())
def test_analyze_sg():
template_path = here(
'resources/sample_kumo_viz/ELBStickinessSample.template')
with open(template_path, 'r') as tfile:
template = json.loads(tfile.read())
kNown_sg, open_sg = _analyze_sg(template['Resources'])
nose.tools.assert_in('InstanceSecurityGroup', kNown_sg)
nose.tools.assert_in('InstanceSecurityGroup', open_sg)
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def apply_wrapper(wrapper,nose.tools.make_decorator(func)(wrapper))
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def test_nose_setup_func(testdir):
p = testdir.makepyfile("""
from nose.tools import with_setup
l = []
def my_setup():
a = 1
l.append(a)
def my_teardown():
b = 2
l.append(b)
@with_setup(my_setup, 'nose')
result.assert_outcomes(passed=2)
def test_module_level_setup(testdir):
testdir.makepyfile("""
from nose.tools import with_setup
items = {}
def setup():
items[1]=1
def teardown():
del items[1]
def setup2():
items[2] = 2
def teardown2():
del items[2]
def test_setup_module_setup():
assert items[1] == 1
@with_setup(setup2,teardown2)
def test_local_setup():
assert items[2] == 2
assert 1 not in items
""")
result = testdir.runpytest('-p', 'nose')
result.stdout.fnmatch_lines([
"*2 passed*",
])
def test_istest_function_decorator(testdir):
p = testdir.makepyfile("""
import nose.tools
@nose.tools.istest
def not_test_prefix():
pass
""")
result = testdir.runpytest(p)
result.assert_outcomes(passed=1)
def test_istest_class_decorator(testdir):
p = testdir.makepyfile("""
import nose.tools
@nose.tools.istest
class NottestPrefix:
def test_method(self):
pass
""")
result = testdir.runpytest(p)
result.assert_outcomes(passed=1)
def test_doom_not_defined(self):
from nose.tools import assert_raises
def invoke_doom():
DoomWrapper
assert_raises(NameError,invoke_doom)
def apply_wrapper(wrapper,func):
"""Apply a wrapper to a function for decoration.
This mixes Michele Simionato's decorator tool with nose's make_decorator,for example.
"""
warnings.warn("The function `apply_wrapper` is deprecated and might be removed in IPython 5.0", DeprecationWarning)
import nose.tools
return decorator(wrapper,nose.tools.make_decorator(func)(wrapper))
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def test_broken_add():
g=rdflib.Graph()
nose.tools.assert_raises(AssertionError, lambda : g.add((1,2,3)))
nose.tools.assert_raises(AssertionError, lambda : g.addN([(1,3,g)]))
def apply_wrapper(wrapper,nose.tools.make_decorator(func)(wrapper))
def setastest(tf=True):
"""
Signals to nose that this function is or is not a test.
Parameters
----------
tf : bool
If True,arg2):
pass
"""
def set_test(t):
t.__test__ = tf
return t
return set_test
def kNownfailureif(fail_condition, msg=None):
"""
Make function raise KNownFailureException exception if given condition is true.
If the condition is a callable,it is used at runtime to dynamically
make the decision. This is useful for tests that may require costly
imports,to delay the cost until the test suite is actually executed.
Parameters
----------
fail_condition : bool or callable
Flag to determine whether to mark the decorated test as a kNown
failure (if True) or not (if False).
msg : str,optional
Message to give on raising a KNownFailureException exception.
Default is None.
Returns
-------
decorator : function
Decorator,causes
KNownFailureException to be raised when `fail_condition` is True,
and the function to be called normally otherwise.
Notes
-----
The decorator itself is decorated with the ``nose.tools.make_decorator``
function in order to transmit function name,and varIoUs other Metadata.
"""
if msg is None:
msg = 'Test skipped due to kNown failure'
# Allow for both boolean or callable kNown failure conditions.
if isinstance(fail_condition, collections.Callable):
fail_val = lambda: fail_condition()
else:
fail_val = lambda: fail_condition
def kNownfail_decorator(f):
# Local import to avoid a hard nose dependency and only incur the
# import time overhead at actual test-time.
import nose
from .noseclasses import KNownFailureException
def kNownfailer(*args, **kwargs):
if fail_val():
raise KNownFailureException(msg)
else:
return f(*args, **kwargs)
return nose.tools.make_decorator(f)(kNownfailer)
return kNownfail_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's,to avoid
printing them during the test suite run,while checking that the test
actually raises a DeprecationWarning.
Parameters
----------
conditional : bool or callable,optional
Flag to determine whether to mark test as deprecated or not. If the
condition is a callable,it is used at runtime to dynamically make the
decision. Default is True.
Returns
-------
decorator : function
The `deprecated` decorator itself.
Notes
-----
.. versionadded:: 1.4.0
"""
def deprecate_decorator(f):
# Local import to avoid a hard nose dependency and only incur the
# import time overhead at actual test-time.
import nose
def _deprecated_imp(*args, **kwargs):
# Poor man's replacement for the with statement
with warnings.catch_warnings(record=True) as l:
warnings.simplefilter('always')
f(*args, **kwargs)
if not len(l) > 0:
raise AssertionError("No warning raised when calling %s"
% f.__name__)
if not l[0].category is DeprecationWarning:
raise AssertionError("First warning for %s is not a "
"DeprecationWarning( is %s)" % (f.__name__, l[0]))
if isinstance(conditional, collections.Callable):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, collections.Callable):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def kNownfailureif(fail_condition, msg=None):
"""
Make function raise KNownFailureTest exception if given condition is true.
If the condition is a callable,causes SkipTest
to be raised when `skip_condition` is True,and the function
to be called normally otherwise.
Notes
-----
The decorator itself is decorated with the ``nose.tools.make_decorator``
function in order to transmit function name, collections.Callable):
fail_val = lambda: fail_condition()
else:
fail_val = lambda: fail_condition
def kNownfail_decorator(f):
# Local import to avoid a hard nose dependency and only incur the
# import time overhead at actual test-time.
import nose
from .noseclasses import KNownFailureTest
def kNownfailer(*args, **kwargs):
if fail_val():
raise KNownFailureTest(msg)
else:
return f(*args, **kwargs)
return nose.tools.make_decorator(f)(kNownfailer)
return kNownfail_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, collections.Callable):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, collections.Callable):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def kNownfailureif(fail_condition,and varIoUs other Metadata.
"""
if msg is None:
msg = 'Test skipped due to kNown failure'
# Allow for both boolean or callable kNown failure conditions.
if callable(fail_condition):
fail_val = lambda : fail_condition()
else:
fail_val = lambda : fail_condition
def kNownfail_decorator(f):
# Local import to avoid a hard nose dependency and only incur the
# import time overhead at actual test-time.
import nose
def kNownfailer(*args, **kwargs)
return nose.tools.make_decorator(f)(kNownfailer)
return kNownfail_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, **kwargs):
# Poor man's replacement for the with statement
ctx = WarningManager(record=True)
l = ctx.__enter__()
warnings.simplefilter('always')
try:
f(*args, **kwargs)
if not len(l) > 0:
raise AssertionError("No warning raised when calling %s"
% f.__name__)
if not l[0].category is DeprecationWarning:
raise AssertionError("First warning for %s is not a " \
"DeprecationWarning( is %s)" % (f.__name__, l[0]))
finally:
ctx.__exit__()
if callable(conditional):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, collections.Callable):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, **kwargs):
# Poor man's replacement for the with statement
with assert_warns(DeprecationWarning):
f(*args, **kwargs)
if isinstance(conditional, collections.Callable):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, l[0]))
finally:
ctx.__exit__()
if callable(conditional):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
def deprecated(conditional=True):
"""
Filter deprecation warnings while running the test suite.
This decorator can be used to filter DeprecationWarning's, collections.Callable):
cond = conditional()
else:
cond = conditional
if cond:
return nose.tools.make_decorator(f)(_deprecated_imp)
else:
return f
return deprecate_decorator
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。