本文整理汇总了Python中nose.tools.with_setup函数的典型用法代码示例。如果您正苦于以下问题:Python with_setup函数的具体用法?Python with_setup怎么用?Python with_setup使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了with_setup函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_decorator_func_sorting
def test_decorator_func_sorting(self):
from nose.tools import raises, timed, with_setup
from nose.util import func_lineno
def test1():
pass
def test2():
pass
def test3():
pass
def foo():
pass
test1_pos = func_lineno(test1)
test2_pos = func_lineno(test2)
test3_pos = func_lineno(test3)
test1 = raises(TypeError)(test1)
test2 = timed(1.0)(test2)
test3 = with_setup(foo)(test3)
self.assertEqual(func_lineno(test1), test1_pos)
self.assertEqual(func_lineno(test2), test2_pos)
self.assertEqual(func_lineno(test3), test3_pos)
示例2: user_session
def user_session(user=u"test", password=u"test"):
def start_session():
get(env.start_page_url)
do_login(user, password)
def stop_session():
delete_all_cookies()
return with_setup(start_session, stop_session)
示例3: decorator
def decorator(func):
old = {}
def setup():
for k, v in options.iteritems():
old[k] = getattr(settings, k, None)
setattr(settings, k, v)
def teardown():
for k, v in old.iteritems():
setattr(settings, k, v)
return with_setup(setup, teardown)(func)
示例4: test_params_with_setup
def test_params_with_setup(self):
from nose.tools import with_setup
def setup_func():
return ('Blue', 'Muppet!'), {'kw1': 'Hello', 'kw2': 'world'}
def t1():
pass
def t2(arg2):
# arg2 is arg1 in this case
assert_equal(arg2, 'Blue')
def t3(kw2, kw1):
assert_equal(kw1, 'Hello')
assert_equal(kw2, 'world')
def t4(arg1, arg2, kw1):
assert_equal(arg1, 'Blue')
assert_equal(arg2, 'Muppet!')
assert_equal(kw1, 'Hello')
def t5(x, y, z):
raise Exception('this should not get raised')
tests = [t1, t2, t3, t4]
for teardown_func in tests:
for tf in tests:
case = with_setup(setup_func, teardown_func, True)(tf)
case.setup()
case()
case.teardown()
case = with_setup(setup_func, teardown_func, True)(t5)
case.setup()
raises(TypeError)(case)()
case.teardown()
示例5: test_nested_decorators
def test_nested_decorators(self):
from nose.tools import raises, timed, with_setup
def test():
pass
def foo():
pass
test = with_setup(foo, foo)(test)
test = timed(1.0)(test)
test = raises(TypeError)(test)
assert test.setup == foo
assert test.teardown == foo
示例6: remove_files
def remove_files(flist, dlist):
def teardown():
from os import unlink
for f in flist:
try:
unlink(f)
except:
pass
from shutil import rmtree
for dir in dlist:
try:
rmtree(dir)
except:
pass
return with_setup(None, teardown)
示例7: cleanup
def cleanup(func):
"""Decorator to add cleanup to the testing function
@cleanup
def test_something():
" ... "
Note that `@cleanup` is useful *only* for test functions, not for test
methods or inside of TestCase subclasses.
"""
def _teardown():
plt.close('all')
warnings.resetwarnings() #reset any warning filters set in tests
return with_setup(setup=_setup, teardown=_teardown)(func)
示例8: attach_teardown
def attach_teardown(context):
"""Given a namespace dictionary, attach the teardown function.
This function is designed for nose and will raise NotImplementedError at
runtime with an additional ImportError traceback if nose is not available.
To use it put this line at the end of your test modules:
attach_teardown(globals())
"""
if with_setup is None:
raise NotImplementedError("This function is designed for nose, which "
"couldn't be imported:" + os.sep + nose_tb)
for name, func in context.items():
if name.startswith('test_'):
func = with_setup(teardown=teardown)(func) # non-destructive
示例9: test_multiple_with_setup
def test_multiple_with_setup(self):
from nose.tools import with_setup
from nose.case import FunctionTestCase
from unittest import TestResult
called = []
def test():
called.append('test')
def test2():
called.append('test2')
def test3():
called.append('test3')
def s1():
called.append('s1')
def s2():
called.append('s2')
def s3():
called.append('s3')
def t1():
called.append('t1')
def t2():
called.append('t2')
def t3():
called.append('t3')
ws1 = with_setup(s1, t1)(test)
case1 = FunctionTestCase(ws1)
case1(TestResult())
self.assertEqual(called, ['s1', 'test', 't1'])
called[:] = []
ws2 = with_setup(s2, t2)(test2)
ws2 = with_setup(s1, t1)(ws2)
case2 = FunctionTestCase(ws2)
case2(TestResult())
self.assertEqual(called, ['s1', 's2', 'test2', 't2', 't1'])
called[:] = []
ws3 = with_setup(s3, t3)(test3)
ws3 = with_setup(s2, t2)(ws3)
ws3 = with_setup(s1, t1)(ws3)
case3 = FunctionTestCase(ws3)
case3(TestResult())
self.assertEqual(called, ['s1', 's2', 's3',
'test3', 't3', 't2', 't1'])
示例10: with_debug
def with_debug(*channels, **kw):
"""
A `nose`_ decorator calls :func:`start_debug` / :func:`start_debug` before and after the
decorated method.
All positional arguments are considered channels that should be debugged.
Keyword arguments are passed to :func:`start_debug`
.. _nose: http://somethingaboutorange.com/mrl/projects/nose/
"""
from nose.tools import with_setup
def setup():
for ch in channels:
start_debug(ch, **kw)
def teardown():
for ch in channels:
stop_debug(ch)
return with_setup(setup=setup, teardown=teardown)
示例11: test_function_test_case_fixtures
def test_function_test_case_fixtures(self):
from nose.tools import with_setup
res = unittest.TestResult()
called = {}
def st():
called['st'] = True
def td():
called['td'] = True
def func_exc():
called['func'] = True
raise TypeError("An exception")
func_exc = with_setup(st, td)(func_exc)
case = nose.case.FunctionTestCase(func_exc)
case(res)
assert 'st' in called
assert 'func' in called
assert 'td' in called
示例12: __call__
def __call__(self, function):
def setup():
args = [
"Xephyr", "-keybd", "evdev",
"-name", "qtile_test",
self.display, "-ac",
"-screen", "%sx%s" % (self.width, self.height)]
if self.two_screens:
args.extend(["-screen", "%sx%s+800+0" % (
SECOND_WIDTH, SECOND_HEIGHT)])
if self.xinerama:
args.extend(["+xinerama"])
if self.randr:
args.extend(["+extension", "RANDR"])
self.sub = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
time.sleep(0.05)
self.testwindows = []
if self.start_qtile:
self.startQtile(self.config)
def teardown():
if self.start_qtile:
libqtile.hook.clear()
self.stopQtile()
os.kill(self.sub.pid, 9)
os.waitpid(self.sub.pid, 0)
@wraps(function)
def wrapped_fun():
return function(self)
return attr('xephyr')(with_setup(setup, teardown)(wrapped_fun))
示例13: SkipTest
from mahotas.io import freeimage
except OSError:
from nose import SkipTest
raise SkipTest("FreeImage not found")
def _create_tempdir():
import tempfile
global _test_dir, _testimgname
_test_dir = tempfile.mkdtemp(prefix='mh_test')
_testimgname = path.join(_test_dir, "mahotas_test.png")
def _remove_tempdir():
from shutil import rmtree
rmtree(_test_dir)
create_remove = with_setup(setup=_create_tempdir, teardown=_remove_tempdir)
@create_remove
def test_freeimage():
img = np.arange(256).reshape((16,16)).astype(np.uint8)
freeimage.imsave(_testimgname, img)
img_ = freeimage.imread(_testimgname)
assert img.shape == img_.shape
assert np.all(img == img_)
@create_remove
def test_as_grey():
colour = np.arange(16*16*3).reshape((16,16,3))
freeimage.imsave(_testimgname, colour.astype(np.uint8))
示例14: _setup
from nose.tools import with_setup
import jug.task
from jug.backends.dict_store import dict_store
def _setup():
jug.task.Task.store = dict_store()
while jug.task.alltasks:
jug.task.alltasks.pop()
def _teardown():
jug.task.Task.store = None
while jug.task.alltasks:
jug.task.alltasks.pop()
task_reset = with_setup(_setup, _teardown)
示例15: decorate_with_data
def decorate_with_data(routine):
# passthrough an already decorated routine:
# (could this be any uglier?)
if hasattr(routine, 'setup'):
def passthru_setup():
routine.setup()
if setup: setup()
else:
passthru_setup = setup
if hasattr(routine, 'teardown'):
def passthru_teardown():
routine.teardown()
if teardown: teardown()
else:
passthru_teardown = teardown
def setup_data():
data = self.data(*datasets)
data.setup()
return data
def teardown_data(data):
data.teardown()
@wraps(routine)
def call_routine(*a,**kw):
data = setup_data()
try:
routine(data, *a, **kw)
except KeyboardInterrupt:
# user wants to abort everything :
raise
except Exception as exc:
# caught exception, so try to teardown but do it safely :
try:
teardown_data(data)
except:
t_ident = ("-----[exception in teardown %s]-----" %
hex(id(teardown_data)))
sys.stderr.write("\n\n%s\n" % t_ident)
traceback.print_exc()
sys.stderr.write("%s\n\n" % t_ident)
reraise(exc.__class__, exc)
else:
teardown_data(data)
@wraps(routine)
def iter_routine():
for stack in routine():
fn = stack[0]
try:
args = stack[1:]
except IndexError:
args = tuple([])
def atomic_routine(*genargs,**kw):
setup_data = genargs[0]
data = setup_data()
try:
genargs = genargs[1:]
except IndexError:
genargs = tuple([])
genargs = (data,) + genargs
try:
fn(*genargs, **kw)
except Exception as exc:
try:
teardown_data(data)
except:
t_ident = (
"-----[exception in teardown %s]-----" %
hex(id(teardown_data)))
sys.stderr.write("\n\n%s\n" % t_ident)
traceback.print_exc()
sys.stderr.write("%s\n\n" % t_ident)
reraise(exc.__class__, exc)
else:
teardown_data(data)
restack = (atomic_routine, setup_data) + args
yield restack
if isgeneratorfunction(routine):
wrapped_routine = iter_routine
else:
wrapped_routine = call_routine
decorate = with_setup( setup=passthru_setup,
teardown=passthru_teardown )
return decorate( wrapped_routine )