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)
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)
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)
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()
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
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)
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)
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
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)
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'])
def with_debug(*channels, **kw): """A nose decorator calls start_debug/start_debug before and after the decorated method. All positional arguments are considered channels that should be debugged. Keyword arguments are passed to start_debug() """ 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)
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)
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
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))
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))
def with_temp_folder(func): """Creates a unique temporary folder before running 'func'. The function is is assumed to take at least one parameter, the first of which is assumed to represent the temporary folder.""" global _COUNTER # pylint: disable=W0603 tmp_root = os.path.join(UNIT_TEST_ROOT, "%03i_%s" % ( _COUNTER, func.__name__, )) _COUNTER += 1 def _setup(): os.makedirs(tmp_root) def _teardown(): shutil.rmtree(tmp_root) @nose.tools.istest def _wrapper(*args, **kwargs): return func(tmp_root, *args, **kwargs) _wrapper.__name__ = func.__name__ + "__wrapped_by_with_temp_folder" return with_setup(_setup, _teardown)(_wrapper)
def attach_teardown(context, prefix='test_'): """Given a namespace and a routine prefix, attach the teardown function. """ for name, func in context.items(): if name.startswith(prefix): func = with_setup(teardown=teardown)(func) # non-destructive
def wrap(f): return with_setup( lambda: setup(f.__name__) if (setup is not None) else None, lambda: teardown(f.__name__) if (teardown is not None) else None)(f)
def setup_module(): setup_autokill(__name__, timeout=300) def teardown_module(): teardown_autokill(__name__) def check_multiprocessing(): if mp is None: raise SkipTest('Need multiprocessing to run') with_multiprocessing = with_setup(check_multiprocessing) def setup_temp_folder(): global TEMP_FOLDER TEMP_FOLDER = tempfile.mkdtemp(prefix='joblib_test_pool_') def teardown_temp_folder(): global TEMP_FOLDER if TEMP_FOLDER is not None: shutil.rmtree(TEMP_FOLDER) TEMP_FOLDER = None with_temp_folder = with_setup(setup_temp_folder, teardown_temp_folder)
teardown_autokill(__name__) def setup_temp_folder(): global TEMP_FOLDER TEMP_FOLDER = tempfile.mkdtemp(prefix='joblib_test_pool_') def teardown_temp_folder(): global TEMP_FOLDER if TEMP_FOLDER is not None: shutil.rmtree(TEMP_FOLDER) TEMP_FOLDER = None with_temp_folder = with_setup(setup_temp_folder, teardown_temp_folder) def check_array(args): """Dummy helper function to be executed in subprocesses Check that the provided array has the expected values in the provided range. """ data, position, expected = args np.testing.assert_array_equal(data[position], expected) def inplace_double(args): """Dummy helper function to be executed in subprocesses
def setup_a(): data.set({'b':"B"}) @with_setup(setup_a, teardown=teardown)
def test_impvis_mpi(): ne, ngq = 15, 4 for nproc in [4,7,12,16]: func = with_setup(lambda:None, lambda:None)(lambda:run_mpi(ne,ngq,nproc)) func.description = 'CubeMPI for impvis: Spherical Harmonics(Y35) (ne=%d, ngq=%d, nproc=%d)'%(ne,ngq,nproc) yield func
def test_compare_with_kim(): nproc = 16 func = with_setup(lambda:None, lambda:None)(lambda:run_mpi(nproc)) func.description = 'Compare with KIM: compute_and_apply_rhs() (ne=%d, ngq=%d, nproc=%d)'%(ne, ngq, nproc) yield func
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 )
def with_encoding(encoding, fallbackencoding=None): """Decorator for test function to change locale encoding temporarily""" patcher = EncodingPatcher(encoding, fallbackencoding) return tools.with_setup(patcher.patch, patcher.restore)
sockmock.reset_mock() sockpatch.start() selectpatch.start() global registry registry = SettingsRegistry() def _teardown(): sockpatch.stop() selectpatch.stop() # Decorator for generated test case functions, to ensure the socket.socket # patch is run correctly, as well as the patching of the select module. patches_socket_and_select = with_setup(_setup, _teardown) def get_listener(pubmock): """ Find and return the "command.send_serial" listener subscribed to the given pubsub.pub mock. """ return get_pubsub_listener(pubmock, "command.send_serial") # Test that when a text string is sent, that it is successfully # sent to the XBee specified. @patches_socket_and_select def do_send_serial(pubmock, attrs,
def _setup(): sockmock.reset_mock() sockpatch.start() selectpatch.start() global registry registry = SettingsRegistry() def _teardown(): sockpatch.stop() selectpatch.stop() # Decorator for generated test case functions, to ensure the socket.socket # patch is run correctly, as well as the patching of the select module. patches_socket_and_select = with_setup(_setup, _teardown) def get_listener(pubmock): """ Find and return the "command.send_serial" listener subscribed to the given pubsub.pub mock. """ return get_pubsub_listener(pubmock, "command.send_serial") # Test that when a text string is sent, that it is successfully # sent to the XBee specified. @patches_socket_and_select def do_send_serial(pubmock, attrs, encoded_data, transmit_data, expected_addr=None):
def test_avg_sequential_mpi(): ne, ngq = 3, 4 for nproc in xrange(1,33): func = with_setup(lambda:None, lambda:None)(lambda:run_mpi(ne,ngq,nproc)) func.description = 'CubeMPI for AVG: Sequential values with MPI (ne=%d, ngq=%d, nproc=%d)'%(ne,ngq,nproc) yield func
def dec(fn): return with_setup(setup_fn, teardown_fn)(fn)
from jug.tests.utils import simple_execute _jugdir = os.path.abspath(inspect.getfile(inspect.currentframe())) _jugdir = os.path.join(os.path.dirname(_jugdir), 'jugfiles') Task = jug.task.Task jug.task.Task.store = dict_store() def _setup(): jug.task.Task.store = dict_store() def _teardown(): jug.task.alltasks = [] task_reset = with_setup(_setup, _teardown) def add1(x): return x + 1 def add2(x): return x + 2 def _assert_tsorted(tasks): from itertools import chain for i,ti in enumerate(tasks): for j,tj in enumerate(tasks[i+1:]): for dep in chain(ti.args, ti.kwargs.values()): if type(dep) is list: assert tj not in dep else: assert tj is not dep
def wrap(f): return with_setup(teardown=perform_removal)(f)
# If were are still there ask the OS to kill ourself for real time.sleep(0.5) print("Timeout exceeded: killing stalled process: %d" % pid) os.kill(pid, signal.SIGKILL) _KILLER_THREADS[module_name] = t = threading.Timer(timeout, autokill) t.start() def teardown_autokill(module_name): """Cancel a previously started killer thread""" killer = _KILLER_THREADS.get(module_name) if killer is not None: killer.cancel() def check_multiprocessing(): if mp is None: raise SkipTest('Need multiprocessing to run') with_multiprocessing = with_setup(check_multiprocessing) def setup_if_has_dev_shm(): if not os.path.exists('/dev/shm'): raise SkipTest("This test requires the /dev/shm shared memory fs.") with_dev_shm = with_setup(setup_if_has_dev_shm)
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))
etype, val, tb = sys.exc_info() 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) raise exc, None, tb else: teardown_data(data) restack = (atomic_routine, setup_data) + args yield restack if is_generator(routine): wrapped_routine = iter_routine else: wrapped_routine = call_routine decorate = with_setup( setup=passthru_setup, teardown=passthru_teardown ) return decorate( wrapped_routine ) return decorate_with_data def data(self, *datasets): """returns a :class:`FixtureData` object for datasets.""" return self.Data(datasets, self.dataclass, self.loader)
from __future__ import unicode_literals, division from nose.tools import with_setup from sqlalchemy import create_engine from .. import app from .. import database as db __all__ = ['client'] client = app.app.test_client() engine = None def setup(): global engine engine = create_engine('sqlite:///:memory:') db.Session.configure(bind=engine) db.Base.metadata.create_all(bind=engine) db.User.create('root') db.Session.commit() def teardown(): db.Base.metadata.drop_all(bind=engine) db.Session.remove() with_database = with_setup(setup, teardown)
def test_avg_sequential_mpi(): ne, ngq = 3, 4 for nproc in range(1,13): func = with_setup(lambda:None, lambda:None)(lambda:run_mpi(ne,ngq,nproc)) func.description = "CubeMPI for AVG: Sequential values with MPI (ne={}, ngq={}, nproc={})".format(ne,ngq,nproc) yield func
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)
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) raise exc, None, tb else: teardown_data(data) restack = (atomic_routine, setup_data) + args yield restack if is_generator(routine): wrapped_routine = iter_routine else: wrapped_routine = call_routine decorate = with_setup(setup=passthru_setup, teardown=passthru_teardown) return decorate(wrapped_routine) return decorate_with_data def data(self, *datasets): """returns a :class:`FixtureData` object for datasets.""" return self.Data(datasets, self.dataclass, self.loader)
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))
def setup_module(): setup_autokill(__name__, timeout=30) def teardown_module(): teardown_autokill(__name__) def check_multiprocessing(): if mp is None: raise SkipTest('Need multiprocessing to run') with_multiprocessing = with_setup(check_multiprocessing) def setup_temp_folder(): global TEMP_FOLDER TEMP_FOLDER = tempfile.mkdtemp(prefix='joblib_test_pool_') def teardown_temp_folder(): global TEMP_FOLDER if TEMP_FOLDER is not None: shutil.rmtree(TEMP_FOLDER) TEMP_FOLDER = None with_temp_folder = with_setup(setup_temp_folder, teardown_temp_folder)
from nose import SkipTest from nose.tools import with_setup from nose.tools import assert_equal from nose.tools import assert_raises from nose.tools import assert_false from nose.tools import assert_true TEMP_FOLDER = None def check_multiprocessing(): if multiprocessing is None: raise SkipTest('Need multiprocessing to run') with_multiprocessing = with_setup(check_multiprocessing) def check_numpy(): if np is None: raise SkipTests('Need numpy to run') with_numpy = with_setup(check_numpy) def setup_temp_folder(): global TEMP_FOLDER TEMP_FOLDER = tempfile.mkdtemp(prefix='joblib_test_pool_')
def _cleanup(cls, name, warn_message=None): shutil.rmtree(name) if warn_message is not None: warnings.warn(warn_message, ResourceWarning) def __repr__(self): return "<{} {!r}>".format(self.__class__.__name__, self.name) def __enter__(self): return self.name def __exit__(self, exc_type, exc_value, traceback): if self.delete_on_exit: self.cleanup() def cleanup(self): if self.name is not None and not self._closed: shutil.rmtree(self.name) self._closed = True def _skip_if_no_backend(): """Test decorator to skip test if no backend is available.""" # Note that we can't use _get_backend since the user might # have set the CLUSTERLIB_BACKEND environment variable. if _which('qmod') is None and _which('scontrol') is None: raise SkipTest('A scheduler backend is required for this test.') skip_if_no_backend = with_setup(_skip_if_no_backend)