def skip_if_usuable(environment_cls): def skip_or_not(): if not environment_cls.is_usable(): raise SkipTest("Environment '{}' is not usable here" "".format(repr(environment_cls))) return with_setup(skip_or_not)
def check_app_state(test): def checker(when): def check_app_state(): import editxt assert not hasattr(editxt, "app"), editxt.app return check_app_state return with_setup(checker("before"), checker("after"))(test)
def check_app_state(test): def checker(when): def check_app_state(): from editxt.application import DocumentController dc = DocumentController.sharedDocumentController() assert not dc.documents(), "app state was dirty %s %s: %r" \ % (when, test.__name__, dc.documents()) return check_app_state return with_setup(checker("before"), checker("after"))(test)
return func return decorator def clean_warning_registry(): """Safe way to reset warnings """ warnings.resetwarnings() reg = "__warningregistry__" for mod_name, mod in list(sys.modules.items()): if 'six.moves' in mod_name: continue if hasattr(mod, reg): getattr(mod, reg).clear() def check_skip_network(): if int(os.environ.get('SKLEARN_SKIP_NETWORK_TESTS', 0)): raise SkipTest("Text tutorial requires large dataset download") def check_skip_travis(): """Skip test if being run on Travis.""" if os.environ.get('TRAVIS') == "true": raise SkipTest("This test needs to be skipped on Travis") with_network = with_setup(check_skip_network) with_travis = with_setup(check_skip_travis)
def teardown(teardown_): return with_setup(teardown=teardown_)
def log_in(*auth): delete_all_dashboards(*auth) add_empty_dashboard(*auth) log_in_clean(*auth) splinter_tests.visit("/#/add_widget") # Wait a moment for everything to settle do_sleep() with screenshot_on_exception("log_in_not_add_widget"): assert_that(browser.url, ends_with('/#/add_widget')) log_in_before = with_setup( lambda: log_in("e2e_user", "e2e_password", "e2e_fqdn")) log_in_test_before = with_setup( lambda: log_in("test_user", "e2e_password", "login.etherios.com")) def is_error_message_present(key, message): xpath = ("//div[contains(@class, 'alert alert-danger')]/ul/li" "/strong[contains(., '{}')]/..").format(key) match = browser.find_by_xpath(xpath) # Check that we found a matching error message with screenshot_on_exception("find_error_%s" % key): assert not match.is_empty(), "No error message for %s" % key assert_that(match.first.text, contains_string(message))
global mc_pid LOGGER.info("Killing memcached instance running on port %d", settings['correlator']['memcached_port']) try: # Tue le serveur memcached lancé en arrière-plan. os.kill(mc_pid, signal.SIGTERM) os.wait() # Avoid zombies. Bad zombies. except OSError, e: # We mostly ignore errors, maybe we should # do something more useful here. print e finally: mc_pid = None return MemcachedConnection.reset() with_mc = nose.with_setup(setup_mc, teardown_mc) #Create an empty database before we start our tests for this module def setup_db(): """Crée toutes les tables du modèle dans la BDD.""" from vigilo.models.tables.grouppath import GroupPath from vigilo.models.tables.usersupitem import UserSupItem tables = metadata.tables.copy() del tables[GroupPath.__tablename__] del tables[UserSupItem.__tablename__] metadata.create_all(tables=tables.itervalues()) metadata.create_all(tables=[GroupPath.__table__, UserSupItem.__table__]) #Teardown that database def teardown_db(): """Supprime toutes les tables du modèle de la BDD."""
import os from nose import SkipTest, with_setup def check_skip_travis(): """Skip test if being run on Travis.""" if os.environ.get('TRAVIS') == "true": raise SkipTest("This test needs to be skipped on Travis") with_travis = with_setup(check_skip_travis)
def with_dummy_transmitter_setup(f): return with_setup(DummyTestController.start_dummy_streaming_process, DummyTestController.stop_dummy_streaming_process)(f)
def teardown(): splinter_tests.kill_browser() def do_logout(): splinter_tests.visit("/logout") splinter_tests.visit("/#/login") browser = splinter_tests.browser # Wait up to 15 seconds for the page to load assert browser.is_element_present_by_css("h1.title", wait_time=15) logout_before = with_setup(do_logout) @logout_before def test_at_login_page(): """After logout, the user should end up at the login page.""" browser = splinter_tests.browser # Check that we should be at the login page. assert_that(browser.url, ends_with("#/login")) # Check that "Log in" appears on screen assert browser.is_text_present("Log in") # Check the title indicates we're at the login page. assert_that(browser.title, is_("Login | XBee ZigBee Cloud Kit"))
import os import simplejson from nose import with_setup from redis import Redis redis = Redis(host=os.getenv('REDIS_HOST', 'localhost'), port=int(os.getenv('REDIS_PORT', 6379)), db=int(os.getenv('REDIS_DB', 0))) def assert_queue_entry(json, item, **envelope_keys): assert isinstance(json, basestring) entry = simplejson.loads(json) assert isinstance(entry, dict) assert 'ts' in entry assert 'first_ts' in entry assert 'attempts' in entry assert 'v' in entry assert 'item' in entry assert entry['item'] == item for key, value in envelope_keys.iteritems(): assert entry[key] == value, '{} != {}'.format(entry[key], value) def assert_error_queue_empty(queue): assert not queue.error_queue.errors() class TestRetryError(Exception): pass clear = with_setup(redis.flushdb)
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 dec(f): return with_setup(setup, teardown)(f)
def log_in(*auth): delete_all_dashboards(*auth) add_empty_dashboard(*auth) log_in_clean(*auth) splinter_tests.visit("/#/add_widget") # Wait a moment for everything to settle do_sleep() with screenshot_on_exception("log_in_not_add_widget"): assert_that(browser.url, ends_with('/#/add_widget')) log_in_before = with_setup(lambda: log_in("e2e_user", "e2e_password", "e2e_fqdn")) log_in_test_before = with_setup(lambda: log_in("test_user", "e2e_password", "login.etherios.com")) def is_error_message_present(key, message): xpath = ("//div[contains(@class, 'alert alert-danger')]/ul/li" "/strong[contains(., '{}')]/..").format(key) match = browser.find_by_xpath(xpath) # Check that we found a matching error message with screenshot_on_exception("find_error_%s" % key): assert not match.is_empty(), "No error message for %s" % key assert_that(match.first.text, contains_string(message))
os.mkdir(LOCAL_NXDRIVE_CONF_FOLDER) ctl = Controller(LOCAL_NXDRIVE_CONF_FOLDER) def teardown_integration_env(): if ctl is not None: ctl.get_session().close() if remote_client is not None and remote_client.exists(TEST_WORKSPACE): remote_client.delete(TEST_WORKSPACE, use_trash=False) if os.path.exists(LOCAL_TEST_FOLDER): shutil.rmtree(LOCAL_TEST_FOLDER) with_integration_env = with_setup(setup_integration_env, teardown_integration_env) def make_server_tree(): # create some folders on the server folder_1 = remote_client.make_folder(TEST_WORKSPACE, "Folder 1") folder_1_1 = remote_client.make_folder(folder_1, "Folder 1.1") folder_1_2 = remote_client.make_folder(folder_1, "Folder 1.2") folder_2 = remote_client.make_folder(TEST_WORKSPACE, "Folder 2") # create some files on the server remote_client.make_file(folder_2, "Duplicated File.txt", content="Some content.") remote_client.make_file(folder_2, "Duplicated File.txt", content="Other content.") remote_client.make_file(folder_1, "File 1.txt", content="aaa") remote_client.make_file(folder_1_1, "File 2.txt", content="bbb")
SOME_TEXT_DIGEST = hashlib.md5(SOME_TEXT_CONTENT).hexdigest() def setup_temp_folder(): global lcclient, LOCAL_TEST_FOLDER, TEST_WORKSPACE LOCAL_TEST_FOLDER = tempfile.mkdtemp('-nuxeo-drive-tests') lcclient = LocalClient(LOCAL_TEST_FOLDER) TEST_WORKSPACE = lcclient.make_folder('/', 'Some Workspace') def teardown_temp_folder(): if os.path.exists(LOCAL_TEST_FOLDER): shutil.rmtree(LOCAL_TEST_FOLDER) with_temp_folder = with_setup(setup_temp_folder, teardown_temp_folder) @with_temp_folder def test_make_documents(): doc_1 = lcclient.make_file(TEST_WORKSPACE, 'Document 1.txt') assert_true(lcclient.exists(doc_1)) assert_equal(lcclient.get_content(doc_1), "") doc_1_info = lcclient.get_info(doc_1) assert_equal(doc_1_info.name, 'Document 1.txt') assert_equal(doc_1_info.path, doc_1) assert_equal(doc_1_info.get_digest(), EMPTY_DIGEST) assert_equal(doc_1_info.folderish, False) doc_2 = lcclient.make_file(TEST_WORKSPACE, 'Document 2.txt', content=SOME_TEXT_CONTENT)
browser.fill("username", "test_user") browser.fill("password", "e2e_password") browser.find_by_css('.btn.login-button').click() do_sleep() assert not browser.is_text_present("Username or password was incorrect.") assert_that(browser.url, ends_with("#/setup")) def clear_dashboards(user="******", password="******", fqdn="e2e_fqdn"): delete_all_dashboards(user, password, fqdn) log_back_in_before = with_setup(re_login) log_in_nodevices_before = with_setup(re_login_no_devices) clear_dashboards_before = with_setup(lambda: clear_dashboards) clear_dashboards_nodevices_before = with_setup( lambda: clear_dashboards("e2e_user_nodevices", fqdn="login.etherios.com")) clear_dashboards_test_before = with_setup( lambda: clear_dashboards("test_user", fqdn="login.etherios.com")) #clear_dashboards = with_setup(clear_dashboards) def get_user_device_option_labels(username='******'): user = get_e2e_user(username) if not user: raise ValueError("Failed to find user")
return func return decorator def clean_warning_registry(): """Safe way to reset warnings """ warnings.resetwarnings() reg = "__warningregistry__" for mod in sys.modules.copy().values(): if hasattr(mod, reg): getattr(mod, reg).clear() def check_skip_network(): if int(os.environ.get('SKLEARN_SKIP_NETWORK_TESTS', 0)): raise SkipTest("Text tutorial requires large dataset download") with_network = with_setup(check_skip_network) def check_skip_travis(): """Skip test if being run on Travis.""" if os.environ.get('TRAVIS') == "true": raise SkipTest("This test needs to be skipped on Travis") with_network = with_setup(check_skip_network)
do_sleep(multiplier=0.5) # Navigate to the dashboard page splinter_tests.visit("#/dashboard") def expand_username_menu(): # Expand the menu by clicking on the username in the top right. link_css = ".navbar a.dropdown-toggle" username_link = browser.find_by_css(link_css) assert not username_link.is_empty() username_link.click() clean_slate_before = with_setup(clean_slate) make_dashboard_before = with_setup(make_dashboard) def check_dashboard_is_empty(): '''Check there are no widgets on this page.''' widgets = browser.find_by_css(".gridster > .widget") assert widgets.is_empty() def check_we_are_at_dashboard_page(): '''Are we currently on the dashboard page?''' assert_that(browser.url, ends_with("/#/dashboard")) def click_add_widget():
build_workspace = os.environ.get('WORKSPACE') tmpdir = None if build_workspace is not None: tmpdir = os.path.join(build_workspace, "tmp") if not os.path.isdir(tmpdir): os.makedirs(tmpdir) LOCAL_TEST_FOLDER = tempfile.mkdtemp(u'-nuxeo-drive-tests', dir=tmpdir) lcclient = LocalClient(LOCAL_TEST_FOLDER) TEST_WORKSPACE = lcclient.make_folder(u'/', u'Some Workspace') def teardown_temp_folder(): clean_dir(LOCAL_TEST_FOLDER) with_temp_folder = with_setup(setup_temp_folder, teardown_temp_folder) @with_temp_folder def test_make_documents(): doc_1 = lcclient.make_file(TEST_WORKSPACE, u'Document 1.txt') assert_true(lcclient.exists(doc_1)) assert_equal(lcclient.get_content(doc_1), b"") doc_1_info = lcclient.get_info(doc_1) assert_equal(doc_1_info.name, u'Document 1.txt') assert_equal(doc_1_info.path, doc_1) assert_equal(doc_1_info.get_digest(), EMPTY_DIGEST) assert_equal(doc_1_info.folderish, False) doc_2 = lcclient.make_file(TEST_WORKSPACE, u'Document 2.txt',
setup_environment() global DATA_FUNCS DATA_FUNCS['home_dir_func'] = nibd.get_nipy_user_dir DATA_FUNCS['sys_dir_func'] = nibd.get_nipy_system_dir DATA_FUNCS['path_func'] = nibd.get_data_path def teardown_data_env(): teardown_environment() nibd.get_nipy_user_dir = DATA_FUNCS['home_dir_func'] nibd.get_nipy_system_dir = DATA_FUNCS['sys_dir_func'] nibd.get_data_path = DATA_FUNCS['path_func'] # decorator to use setup, teardown environment with_environment = with_setup(setup_data_env, teardown_data_env) def test_datasource(): # Tests for DataSource pth = pjoin('some', 'path') ds = Datasource(pth) yield assert_equal, ds.get_filename('unlikeley'), pjoin(pth, 'unlikeley') yield (assert_equal, ds.get_filename('un','like','ley'), pjoin(pth, 'un','like','ley')) def test_versioned(): with TemporaryDirectory() as tmpdir: yield (assert_raises, DataError,
See http://trac.turbogears.org/turbogears/ticket/1217 for details. """ turbogears.startup.stopTurboGears() cherrypy.root = Root() def test_method(): "the index method should return a string called now" import types result = testutil.call(cherrypy.root.index) assert type(result["now"]) == types.StringType test_method = with_setup(teardown=teardown_func)(test_method) def test_indextitle(): "The indexpage should have the right title" testutil.createRequest("/") assert "<TITLE>Welcome to TurboGears</TITLE>" in cherrypy.response.body[0] test_indextitle = with_setup(teardown=teardown_func)(test_indextitle) def test_logintitle(): "login page should have the right title" testutil.createRequest("/login") assert "<TITLE>Login</TITLE>" in cherrypy.response.body[0]
def register(fn): all_queue_tests.append(with_setup(clear_redis)(fn)) return fn
from turbogears import testutil from videostore.controllers import Root import cherrypy def teardown_func(): """Tests for apps using identity need to stop CP/TG after each test to stop the VisitManager thread. See http://trac.turbogears.org/turbogears/ticket/1217 for details. """ turbogears.startup.stopTurboGears() cherrypy.root = Root() def test_method(): "the index method should return a string called now" result = testutil.call(cherrypy.root.index) assert type(result["now"]) == type('') test_method = with_setup(teardown=teardown_func)(test_method) def test_indextitle(): "The indexpage should have the right title" testutil.createRequest("/") assert "<TITLE>Welcome to TurboGears</TITLE>" in cherrypy.response.body[0] test_indextitle = with_setup(teardown=teardown_func)(test_indextitle) def test_logintitle(): "login page should have the right title" testutil.createRequest("/login") assert "<TITLE>Login</TITLE>" in cherrypy.response.body[0] test_logintitle = with_setup(teardown=teardown_func)(test_logintitle)
"environment.") nxclient = NuxeoClient(NUXEO_URL, USER, PASSWORD, base_folder='/') parent_path = os.path.dirname(TEST_WORKSPACE_PATH) workspace_name = os.path.basename(TEST_WORKSPACE_PATH) TEST_WORKSPACE = nxclient.create( parent_path, 'Workspace', name=workspace_name, properties={'dc:title': 'Nuxeo Drive Tests'})[u'uid'] def teardown_integration_server(): if nxclient is not None and nxclient.exists(TEST_WORKSPACE): nxclient.delete(TEST_WORKSPACE, use_trash=False) with_integration_server = with_setup( setup_integration_server, teardown_integration_server) def check_addon(): if not nxclient.is_addon_installed(): raise SkipTest('Nuxeo Drive server addon is not installed') with_addon = with_setup(check_addon) @with_integration_server def test_authentication_failure(): assert_raises( Unauthorized, NuxeoClient, nxclient.server_url, 'someone else', 'bad password')
""" (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff os.chdir(old_wd) reload(path) for key in list(env): if key not in oldenv: del env[key] env.update(oldenv) if hasattr(sys, 'frozen'): del sys.frozen # Build decorator that uses the setup_environment/setup_environment with_environment = with_setup(setup_environment, teardown_environment) @contextmanager def patch_get_home_dir(dirpath): orig_get_home_dir = path.get_home_dir path.get_home_dir = lambda: dirpath try: yield finally: path.get_home_dir = orig_get_home_dir @skip_if_not_win32 @with_environment def test_get_home_dir_1():
browser.fill("password", "e2e_password") browser.find_by_css('.btn.login-button').click() do_sleep() assert not browser.is_text_present("Username or password was incorrect.") assert_that(browser.url, ends_with("#/setup")) def clear_dashboards(user="******", password="******", fqdn="e2e_fqdn"): delete_all_dashboards(user, password, fqdn) log_back_in_before = with_setup(re_login) log_in_nodevices_before = with_setup(re_login_no_devices) clear_dashboards_before = with_setup(lambda: clear_dashboards) clear_dashboards_nodevices_before = with_setup( lambda: clear_dashboards("e2e_user_nodevices", fqdn="login.etherios.com")) clear_dashboards_test_before = with_setup( lambda: clear_dashboards("test_user", fqdn="login.etherios.com")) #clear_dashboards = with_setup(clear_dashboards) def get_user_device_option_labels(username='******'): user = get_e2e_user(username) if not user: raise ValueError("Failed to find user")
@wraps(func) def func(*args, **kwargs): raise SkipTest(message) return func return decorator def clean_warning_registry(): """Safe way to reset warnings """ warnings.resetwarnings() reg = "__warningregistry__" for mod_name, mod in list(sys.modules.items()): if 'six.moves' in mod_name: continue if hasattr(mod, reg): getattr(mod, reg).clear() def check_skip_network(): if int(os.environ.get('SKLEARN_SKIP_NETWORK_TESTS', 0)): raise SkipTest("Text tutorial requires large dataset download") def check_skip_travis(): """Skip test if being run on Travis.""" if os.environ.get('TRAVIS') == "true": raise SkipTest("This test needs to be skipped on Travis") with_network = with_setup(check_skip_network) with_travis = with_setup(check_skip_travis)
'(see issue #636)'): """Test decorator that skips test if OS is Mac OS X and its major version is one of ``versions``. """ mac_version, _, _ = platform.mac_ver() skip = '.'.join(mac_version.split('.')[:2]) in versions def decorator(func): if skip: @wraps(func) def func(*args, **kwargs): raise SkipTest(message) return func return decorator def clean_warning_registry(): """Safe way to reset warnings """ warnings.resetwarnings() reg = "__warningregistry__" for mod in sys.modules.copy().values(): if hasattr(mod, reg): getattr(mod, reg).clear() def check_skip_network(): if int(os.environ.get('SKLEARN_SKIP_NETWORK_TESTS', 0)): raise SkipTest("Text tutorial requires large dataset download") with_network = with_setup(check_skip_network)
def teardown_environment(): """Restore things that were remembered by the setup_environment function """ (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff os.chdir(old_wd) reload(path) for key in list(env): if key not in oldenv: del env[key] env.update(oldenv) if hasattr(sys, 'frozen'): del sys.frozen # Build decorator that uses the setup_environment/setup_environment with_environment = with_setup(setup_environment, teardown_environment) @skip_if_not_win32 @with_environment def test_get_home_dir_1(): """Testcase for py2exe logic, un-compressed lib """ unfrozen = path.get_home_dir() sys.frozen = True #fake filename for IPython.__init__ IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py")) home_dir = path.get_home_dir() nt.assert_equal(home_dir, unfrozen)