Best JavaScript code snippet using ava
test_basic.py
Source:test_basic.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4test_standardpaths5----------------------------------6Tests for `standardpaths` module.7"""8import os9import pathlib10import platform11import sys12import unittest13from nose.plugins.skip import SkipTest14from nose.tools import nottest, eq_, assert_is_instance15from PyQt5.QtCore import qVersion, QCoreApplication, QStandardPaths16from standardpaths import (17 Location, configure, get_writable_path, get_standard_paths,18)19qt_version = tuple(int(c) for c in qVersion().split('.'))20def test_get_writable_path_string():21 eq_(get_writable_path('desktop'), get_writable_path(Location.desktop))22def nottest_unless(criteria):23 def _nottest_unless(f):24 if criteria:25 return f26 return nottest(f)27 return _nottest_unless28def nottest_if(criteria):29 def _nottest_if(f):30 if not criteria:31 return f32 return nottest(f)33 return _nottest_if34class EnumValuesMixin(object):35 @classmethod36 def setup_class(cls):37 cls.enum_values = set([v for v in Location])38 cls.app = QCoreApplication(sys.argv)39 cls.app.setApplicationName('Yksom')40 cls.app.setOrganizationName('uranusjr')41 configure(application_name='Yksom', organization_name='uranusjr')42 @classmethod43 def teardown_class(cls):44 # Make sure all locations are tested.45 eq_(cls.enum_values, set())46 def setUp(self):47 value_name = self._testMethodName.split('__')[-1]48 if value_name != 'data': # "data" is covered by "app_local_data"49 self.enum_values.remove(Location[value_name])50class GetWritablePathTests(EnumValuesMixin, unittest.TestCase):51 def _test_against_qt(self, location, qt_location):52 path = get_writable_path(location)53 assert_is_instance(path, pathlib.Path)54 eq_(path.as_posix(), QStandardPaths.writableLocation(qt_location))55 def test__desktop(self):56 self._test_against_qt(Location.desktop, QStandardPaths.DesktopLocation)57 def test__documents(self):58 self._test_against_qt(59 Location.documents, QStandardPaths.DocumentsLocation,60 )61 def test__fonts(self):62 self._test_against_qt(Location.fonts, QStandardPaths.FontsLocation)63 def test__applications(self):64 self._test_against_qt(65 Location.applications, QStandardPaths.ApplicationsLocation,66 )67 def test__music(self):68 self._test_against_qt(Location.music, QStandardPaths.MusicLocation)69 def test__movies(self):70 self._test_against_qt(Location.movies, QStandardPaths.MoviesLocation)71 def test__pictures(self):72 self._test_against_qt(73 Location.pictures, QStandardPaths.PicturesLocation,74 )75 def test__temp(self):76 self._test_against_qt(Location.temp, QStandardPaths.TempLocation)77 def test__home(self):78 self._test_against_qt(Location.home, QStandardPaths.HomeLocation)79 def test__data(self):80 self._test_against_qt(Location.data, QStandardPaths.DataLocation)81 def test__cache(self):82 self._test_against_qt(Location.cache, QStandardPaths.CacheLocation)83 def test__generic_data(self):84 self._test_against_qt(85 Location.generic_data, QStandardPaths.GenericDataLocation,86 )87 def test__runtime(self):88 self._test_against_qt(Location.runtime, QStandardPaths.RuntimeLocation)89 def test__config(self):90 self._test_against_qt(Location.config, QStandardPaths.ConfigLocation)91 def test__download(self):92 self._test_against_qt(93 Location.download, QStandardPaths.DownloadLocation,94 )95 def test__generic_cache(self):96 self._test_against_qt(97 Location.generic_cache, QStandardPaths.GenericCacheLocation,98 )99 def test__generic_config(self):100 self._test_against_qt(101 Location.generic_config, QStandardPaths.GenericConfigLocation,102 )103 def test__app_data(self):104 if qt_version < (5, 4, 1):105 raise SkipTest106 self._test_against_qt(107 Location.app_data, QStandardPaths.AppDataLocation,108 )109 def test__app_local_data(self):110 if qt_version < (5, 4, 1):111 raise SkipTest112 self._test_against_qt(113 Location.app_local_data, QStandardPaths.AppLocalDataLocation,114 )115 @nottest_unless(platform.system() == 'Darwin')116 def test_osx__log(self):117 eq_(get_writable_path(Location.log),118 pathlib.Path(os.path.expanduser('~/Library/Logs/uranusjr/Yksom')))119 @nottest_unless(platform.system() == 'Windows')120 def test_windows__log(self):121 eq_(get_writable_path(Location.log),122 get_writable_path(Location.app_local_data) / 'log')123 @nottest_if(platform.system() in ('Darwin', 'Windows',))124 def test_unix__log(self):125 eq_(get_writable_path(Location.log),126 get_writable_path(Location.cache) / 'log')127class GetStandardPathsTests(EnumValuesMixin, unittest.TestCase):128 def _test_against_qt(self, location, qt_location):129 paths = get_standard_paths(location)130 path_strs = []131 for path in paths:132 assert_is_instance(path, pathlib.Path)133 path_strs.append(path.as_posix())134 eq_(path_strs, QStandardPaths.standardLocations(qt_location))135 def test__desktop(self):136 self._test_against_qt(Location.desktop, QStandardPaths.DesktopLocation)137 def test__documents(self):138 self._test_against_qt(139 Location.documents, QStandardPaths.DocumentsLocation,140 )141 def test__fonts(self):142 self._test_against_qt(Location.fonts, QStandardPaths.FontsLocation)143 def test__applications(self):144 self._test_against_qt(145 Location.applications, QStandardPaths.ApplicationsLocation,146 )147 def test__music(self):148 self._test_against_qt(Location.music, QStandardPaths.MusicLocation)149 def test__movies(self):150 self._test_against_qt(Location.movies, QStandardPaths.MoviesLocation)151 def test__pictures(self):152 self._test_against_qt(153 Location.pictures, QStandardPaths.PicturesLocation,154 )155 def test__temp(self):156 self._test_against_qt(Location.temp, QStandardPaths.TempLocation)157 def test__home(self):158 self._test_against_qt(Location.home, QStandardPaths.HomeLocation)159 def test__data(self):160 paths = get_standard_paths(Location.data)161 path_strs = []162 for path in paths:163 assert_is_instance(path, pathlib.Path)164 path_strs.append(path.as_posix())165 qt_path_strs = QStandardPaths.standardLocations(166 QStandardPaths.DataLocation,167 )168 if platform.system() == 'Darwin':169 # Exclude bundle path on OS X. See comments in170 # `get_standard_paths` implementation for more information.171 if qt_path_strs[-1].rstrip('/').endswith('Python.app'):172 qt_path_strs = qt_path_strs[:-1]173 elif platform.system() == 'Windows':174 # Exclude paths relative to executable. See comments in175 # `get_standard_paths` implementation for more information.176 python_loc = (pathlib.Path(sys.executable) / '..').resolve()177 qt_path_strs = [178 ps for ps in qt_path_strs179 if ps not in (180 python_loc.as_posix(), (python_loc / 'data').as_posix(),181 )182 ]183 eq_(path_strs, qt_path_strs)184 def test__cache(self):185 self._test_against_qt(Location.cache, QStandardPaths.CacheLocation)186 def test__generic_data(self):187 self._test_against_qt(188 Location.generic_data, QStandardPaths.GenericDataLocation,189 )190 def test__runtime(self):191 self._test_against_qt(Location.runtime, QStandardPaths.RuntimeLocation)192 def test__config(self):193 paths = get_standard_paths(Location.config)194 path_strs = []195 for path in paths:196 assert_is_instance(path, pathlib.Path)197 path_strs.append(path.as_posix())198 qt_path_strs = QStandardPaths.standardLocations(199 QStandardPaths.ConfigLocation,200 )201 if platform.system() == 'Windows':202 # Exclude paths relative to executable. See comments in203 # `get_standard_paths` implementation for more information.204 python_loc = (pathlib.Path(sys.executable) / '..').resolve()205 qt_path_strs = [206 ps for ps in qt_path_strs207 if ps not in (208 python_loc.as_posix(), (python_loc / 'data').as_posix(),209 )210 ]211 eq_(path_strs, qt_path_strs)212 def test__download(self):213 self._test_against_qt(214 Location.download, QStandardPaths.DownloadLocation,215 )216 def test__generic_cache(self):217 self._test_against_qt(218 Location.generic_cache, QStandardPaths.GenericCacheLocation,219 )220 def test__generic_config(self):221 paths = get_standard_paths(Location.generic_config)222 path_strs = []223 for path in paths:224 assert_is_instance(path, pathlib.Path)225 path_strs.append(path.as_posix())226 qt_path_strs = QStandardPaths.standardLocations(227 QStandardPaths.GenericConfigLocation,228 )229 if platform.system() == 'Windows':230 # Exclude paths relative to executable. See comments in231 # `get_standard_paths` implementation for more information.232 python_loc = (pathlib.Path(sys.executable) / '..').resolve()233 qt_path_strs = [234 ps for ps in qt_path_strs235 if ps not in (236 python_loc.as_posix(), (python_loc / 'data').as_posix(),237 )238 ]239 eq_(path_strs, qt_path_strs)240 def test__app_data(self):241 if qt_version < (5, 4, 1):242 raise SkipTest243 paths = get_standard_paths(Location.app_data)244 path_strs = []245 for path in paths:246 assert_is_instance(path, pathlib.Path)247 path_strs.append(path.as_posix())248 qt_path_strs = QStandardPaths.standardLocations(249 QStandardPaths.AppDataLocation,250 )251 if platform.system() == 'Darwin':252 # Exclude bundle path on OS X. See comments in253 # `get_standard_paths` implementation for more information.254 if qt_path_strs[-1].rstrip('/').endswith('Python.app'):255 qt_path_strs = qt_path_strs[:-1]256 elif platform.system() == 'Windows':257 # Exclude paths relative to executable. See comments in258 # `get_standard_paths` implementation for more information.259 python_loc = (pathlib.Path(sys.executable) / '..').resolve()260 qt_path_strs = [261 ps for ps in qt_path_strs262 if ps not in (263 python_loc.as_posix(), (python_loc / 'data').as_posix(),264 )265 ]266 eq_(path_strs, qt_path_strs)267 def test__app_local_data(self):268 if qt_version < (5, 4, 1):269 raise SkipTest270 paths = get_standard_paths(Location.app_local_data)271 path_strs = []272 for path in paths:273 assert_is_instance(path, pathlib.Path)274 path_strs.append(path.as_posix())275 qt_path_strs = QStandardPaths.standardLocations(276 QStandardPaths.AppLocalDataLocation,277 )278 if platform.system() == 'Darwin':279 # Exclude bundle path on OS X. See comments in280 # `get_standard_paths` implementation for more information.281 if qt_path_strs[-1].rstrip('/').endswith('Python.app'):282 qt_path_strs = qt_path_strs[:-1]283 elif platform.system() == 'Windows':284 # Exclude paths relative to executable. See comments in285 # `get_standard_paths` implementation for more information.286 python_loc = (pathlib.Path(sys.executable) / '..').resolve()287 qt_path_strs = [288 ps for ps in qt_path_strs289 if ps not in (290 python_loc.as_posix(), (python_loc / 'data').as_posix(),291 )292 ]293 eq_(path_strs, qt_path_strs)294 @nottest_unless(platform.system() == 'Darwin')295 def test_osx__log(self):296 exp = pathlib.Path(os.path.expanduser('~/Library/Logs/uranusjr/Yksom'))297 eq_(get_standard_paths(Location.log), [exp])298 @nottest_unless(platform.system() == 'Windows')299 def test_windows__log(self):300 eq_(get_standard_paths(Location.log),301 [get_writable_path(Location.app_local_data) / 'log'])302 @nottest_if(platform.system() in ('Darwin', 'Windows',))303 def test_unix__log(self):304 eq_(get_standard_paths(Location.log),...
CordTestServer.py
Source:CordTestServer.py
1# Copyright 2017-present Open Networking Foundation2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14#15# Copyright 2016-present Ciena Corporation16#17# Licensed under the Apache License, Version 2.0 (the "License");18# you may not use this file except in compliance with the License.19# You may obtain a copy of the License at20#21# http://www.apache.org/licenses/LICENSE-2.022#23# Unless required by applicable law or agreed to in writing, software24# distributed under the License is distributed on an "AS IS" BASIS,25# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.26# See the License for the specific language governing permissions and27# limitations under the License.28#29from CordContainer import Container, Onos, OnosStopWrapper, OnosCord, OnosCordStopWrapper, Quagga, QuaggaStopWrapper, Radius, reinitContainerClients30from nose.tools import nottest31from SimpleXMLRPCServer import SimpleXMLRPCServer32from resource import getrlimit, RLIMIT_NOFILE33import daemon34import xmlrpclib35import os36import signal37import json38import time39import threading40##Server to handle container restart/stop requests from test container.41##Used now to restart ONOS from vrouter test container42CORD_TEST_HOST = '172.17.0.1'43CORD_TEST_PORT = 2500044class CordTestServer(object):45 onos_cord = None46 def __restart_onos(self, node = None, config = None, timeout = 10):47 if self.onos_cord:48 onos_config = '{}/network-cfg.json'.format(self.onos_cord.onos_config_dir)49 else:50 onos_config = '{}/network-cfg.json'.format(Onos.host_config_dir)51 if config is None:52 try:53 os.unlink(onos_config)54 except:55 pass56 print('Restarting ONOS')57 if self.onos_cord:58 self.onos_cord.start(restart = True, network_cfg = config)59 else:60 Onos.restart_node(node = node, network_cfg = config, timeout = timeout)61 return 'DONE'62 def restart_onos(self, kwargs):63 return self.__restart_onos(**kwargs)64 def __shutdown_onos(self, node = None):65 if node is None:66 node = Onos.NAME67 OnosStopWrapper(node)68 return 'DONE'69 def shutdown_onos(self, kwargs):70 return self.__shutdown_onos(**kwargs)71 def __restart_cluster(self, config = None, timeout = 10, setup = False):72 Onos.restart_cluster(network_cfg = config, timeout = timeout, setup = setup)73 return 'DONE'74 def restart_cluster(self, kwargs):75 return self.__restart_cluster(**kwargs)76 def __add_cluster_onos(self, count = 1, config = None):77 Onos.add_cluster(count = count, network_cfg = config)78 return 'DONE'79 def add_cluster_onos(self, kwargs):80 return self.__add_cluster_onos(**kwargs)81 def __restart_quagga(self, config = None, boot_delay = 30 ):82 config_file = Quagga.quagga_config_file83 if config is not None:84 quagga_config = '{}/testrib_gen.conf'.format(Quagga.host_quagga_config)85 config_file = '{}/testrib_gen.conf'.format(Quagga.guest_quagga_config)86 with open(quagga_config, 'w+') as fd:87 fd.write(str(config))88 print('Restarting QUAGGA with config file %s, delay %d' %(config_file, boot_delay))89 Quagga(prefix = Container.IMAGE_PREFIX, restart = True, config_file = config_file, boot_delay = boot_delay)90 return 'DONE'91 def restart_quagga(self, kwargs):92 return self.__restart_quagga(**kwargs)93 def stop_quagga(self):94 quaggaStop = QuaggaStopWrapper()95 time.sleep(5)96 try:97 quagga_config_gen = '{}/testrib_gen.conf'.format(Quagga.host_quagga_config)98 os.unlink(quagga_config_gen)99 except: pass100 return 'DONE'101 def __run_shell_quagga(self, cmd = None):102 ret = 0103 if cmd is not None:104 exec_cmd = 'docker exec {} {}'.format(Quagga.NAME, cmd)105 ret = os.system(exec_cmd)106 return ret107 def __run_shell(self, cmd = None):108 ret = 0109 if cmd is not None:110 ret = os.system(cmd)111 return ret112 def run_shell_quagga(self, kwargs):113 return self.__run_shell_quagga(**kwargs)114 def run_shell(self, kwargs):115 return self.__run_shell(**kwargs)116 def restart_radius(self):117 print('Restarting RADIUS Server')118 Radius(prefix = Container.IMAGE_PREFIX, restart = True)119 return 'DONE'120 def shutdown(self):121 print('Shutting down cord test server')122 os.kill(0, signal.SIGKILL)123 return 'DONE'124def find_files_by_path(*paths):125 wanted = []126 for p in paths:127 try:128 fd = os.open(p, os.O_RDONLY)129 wanted.append(os.fstat(fd)[1:3])130 finally:131 os.close(fd)132 def fd_wanted(fd):133 try:134 return os.fstat(fd)[1:3] in wanted135 except OSError:136 return False137 max_fd = getrlimit(RLIMIT_NOFILE)[1]138 return [ fd for fd in xrange(max_fd) if fd_wanted(fd) ]139@nottest140def cord_test_server_start(daemonize = True,141 cord_test_host = CORD_TEST_HOST,142 cord_test_port = CORD_TEST_PORT,143 onos_cord = None,144 foreground=False):145 server = SimpleXMLRPCServer( (cord_test_host, cord_test_port) )146 server.register_instance(CordTestServer())147 CordTestServer.onos_cord = onos_cord148 if daemonize is True:149 ##before daemonizing, preserve urandom needed by paramiko150 preserve_list = find_files_by_path('/dev/urandom')151 preserve_list.append(server)152 d = daemon.DaemonContext(files_preserve = preserve_list,153 detach_process = True)154 with d:155 reinitContainerClients()156 server.serve_forever()157 else:158 if foreground:159 try:160 server.serve_forever()161 except KeyboardInterrupt:162 return server163 else:164 task = threading.Thread(target = server.serve_forever)165 ##terminate when main thread exits166 task.daemon = True167 task.start()168 return server169@nottest170def cord_test_server_stop(server):171 server.shutdown()172 server.server_close()173@nottest174def get_cord_test_loc():175 host = os.getenv('CORD_TEST_HOST', CORD_TEST_HOST)176 port = int(os.getenv('CORD_TEST_PORT', CORD_TEST_PORT))177 return host, port178def rpc_server_instance():179 '''Stateless'''180 host, port = get_cord_test_loc()181 rpc_server = 'http://{}:{}'.format(host, port)182 return xmlrpclib.Server(rpc_server, allow_none = True)183@nottest184def __cord_test_onos_restart(**kwargs):185 return rpc_server_instance().restart_onos(kwargs)186@nottest187def cord_test_onos_restart(node = None, config = None, timeout = 10):188 '''Send ONOS restart to server'''189 for i in range(3):190 try:191 data = __cord_test_onos_restart(node = node, config = config, timeout = timeout)192 if data == 'DONE':193 return True194 except:195 time.sleep(2)196 return False197@nottest198def __cord_test_onos_shutdown(**kwargs):199 return rpc_server_instance().shutdown_onos(kwargs)200@nottest201def cord_test_onos_shutdown(node = None):202 data = __cord_test_onos_shutdown(node = node)203 if data == 'DONE':204 return True205 return False206@nottest207def __cord_test_restart_cluster(**kwargs):208 return rpc_server_instance().restart_cluster(kwargs)209@nottest210def cord_test_restart_cluster(config = None, timeout = 10, setup = False):211 for i in range(3):212 try:213 data = __cord_test_restart_cluster(config = config, timeout = timeout, setup = setup)214 if data == 'DONE':215 return True216 except:217 time.sleep(2)218 return False219@nottest220def __cord_test_onos_add_cluster(**kwargs):221 return rpc_server_instance().add_cluster_onos(kwargs)222@nottest223def cord_test_onos_add_cluster(count = 1, config = None):224 data = __cord_test_onos_add_cluster(count = count, config = config)225 if data == 'DONE':226 return True227 return False228@nottest229def __cord_test_quagga_restart(**kwargs):230 return rpc_server_instance().restart_quagga(kwargs)231@nottest232def cord_test_quagga_restart(config = None, boot_delay = 30):233 '''Send QUAGGA restart to server'''234 data = __cord_test_quagga_restart(config = config, boot_delay = boot_delay)235 if data == 'DONE':236 return True237 return False238@nottest239def __cord_test_quagga_shell(**kwargs):240 return rpc_server_instance().run_shell_quagga(kwargs)241@nottest242def cord_test_quagga_shell(cmd = None):243 '''Send QUAGGA shell cmd to server'''244 return __cord_test_quagga_shell(cmd = cmd)245@nottest246def __cord_test_shell(**kwargs):247 return rpc_server_instance().run_shell(kwargs)248@nottest249def cord_test_shell(cmd = None):250 '''Send shell cmd to run remotely'''251 return __cord_test_shell(cmd = cmd)252@nottest253def cord_test_quagga_stop():254 data = rpc_server_instance().stop_quagga()255 if data == 'DONE':256 return True257 return False258@nottest259def cord_test_radius_restart():260 '''Send Radius server restart to server'''261 data = rpc_server_instance().restart_radius()262 if data == 'DONE':263 return True264 return False265@nottest266def cord_test_server_shutdown(host, port):267 '''Shutdown the cord test server'''268 rpc_server = 'http://{}:{}'.format(host, port)269 try:270 xmlrpclib.Server(rpc_server, allow_none = True).shutdown()271 except: pass...
test_standard_stats.py
Source:test_standard_stats.py
1"""2Currently just running and making sure there's no uncaught exceptions.3TODO: check that the correct output is generated too4In future we should put this in a web-accessible place5Usage: pytest test_standard_stats.py6"""7import tempfile8import pytest9import toml10from pathlib import Path11from lama.tests import (wt_registration_dir, mut_registration_dir, target_dir,12 stats_output_dir)13from lama.stats.standard_stats import lama_stats_new14root_config = dict(15 stats_types=[16 'organ_volumes',17 'intensity',18 'jacobians'19 ],20 normalise_organ_vol_to_mask=True,21 use_log_jacobians = True,22 reg_folder='similarity',23 jac_folder='similarity',24 mask='mask_tight.nrrd',25 label_info='label_info.csv',26 label_map='labels.nrrd',27 blur_fwhm=100,28 voxel_size=14.0,29 invert_stats=True,30 normalise='mask',31 use_staging=True,32 memmap=True33)34@pytest.fixture()35def get_config() -> Path:36 """37 Fixture to get stats config and to write it to temporary file38 Returns39 -------40 location of stats config temporary file41 """42 def make_config(config_updates={}):43 # Create a nested function to allow the fixture to take arguments44 c = root_config.copy()45 c.update(config_updates)46 with tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.toml') as fh:47 fh.write(toml.dumps(c))48 return c, fh.name49 return make_config50def test_all(get_config):51 """52 Run the stats module. The data required for this to work must be initially made53 by running the test: tests/test_data_generation.py54 """55 config, config_file = get_config()56 lama_stats_new.run(config_file, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir)57@pytest.mark.skip58def test_no_mask(get_config):59 config, config_file = get_config({'mask': None})60 # Should get value errors if mask not specified61 # with pytest.raises(ValueError):62 # lama_stats_new.run(config_file, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir)63# # @nottest64# # def test_no_use():65# # """66# # For the organ volume test, if the meta data dataframe has a column of 'no_analysis', do not include the label in the67# # analysis68# # """69# # pass70#71# @nottest72# def test_mutant_id_subset():73# """74# Thest whether specifying mutant id subset works75# """76#77# config = stats_config_dir / 'new_stats_config_test_mutant_id_subset.toml'78# lama_stats_new.run(config, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir)79#80# @nottest81# def test_specifiy_line():82# """83# Run the stats module. The data requirted for this to work must be initially made84# by running the test: tests/test_lama.py:test_lama_job_runner()85# """86# line = 'mutant_1' # Only run this line87#88# # Remove any previous output89# if stats_output_dir.is_dir():90# shutil.rmtree(stats_output_dir)91#92# config = stats_config_dir / 'new_stats_config.toml'93# lama_stats_new.run(config, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir, lines_to_process=[line])94#95# output_lines = [x.name for x in stats_output_dir.iterdir() if x.is_dir()]96# assert_equal([line], output_lines)97#98#99# @nottest100# def test_erroneuos_configs():101# error_config_dir = stats_config_dir / 'erroneous_configs'102#103# for config in error_config_dir.iterdir():104# lama_stats_new.run(config, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir)105#106# # @nottest107# # def test_organ_vols():108# # config = join(CONFIG_DIR, 'organ_vols.yaml')109# # run_lama_stats.run(config)110# #111# # @nottest112# # def test_glcm():113# # config = join(CONFIG_DIR, 'test_glcm.yaml')114# # run_lama_stats.run(config)115# #116# # @nottest117# # def test_from_arbitrary_directory():118# # config = join(CONFIG_DIR, 'all_specimens.yaml')119# # os.chdir(os.path.expanduser('~'))120# # run_lama_stats.run(config)121# #122# # @nottest123# # def test_missing_config():124# # config = join(CONFIG_DIR, 'all_specimens.flaml')125# # assert_raises(Exception, run_lama_stats.run, config)126# #127# # @nottest128# # def test_misc():129# # config = join(CONFIG_DIR, 'misc_test.yaml')130# # run_lama_stats.run(config)131# #132# #133# # @nottest134# # def test_incorrect_staging_file():135# # pass136#...
test_lama_stats.py
Source:test_lama_stats.py
1"""2Currently just running and making sure there's no uncaught exceptions.3TODO: check that the correct output is generated too4To run these tests, the test data needs to be fechted from bit/dev/lama_stats_test_data5In future we should put this in a web-accessible place6Usage: pytest -v -m "not notest"7"""8import shutil9import tempfile10from nose.tools import nottest, assert_equal11import toml12# import paths from the __init__13from . import (stats_config_dir, wt_registration_dir, mut_registration_dir, target_dir,14 stats_output_dir)15from lama.stats.standard_stats import lama_stats_new16root_config = dict(17 stats_types=[18 'organ_volumes'19 # 'intensity',20 # 'jacobians'21 ],22 reg_folder='similarity',23 jac_folder='similarity',24 mask='mask_tight.nrrd',25 label_info='label_info.csv',26 label_map='labels.nrrd',27 blur_fwhm=100,28 voxel_size=14.0,29 invert_stats=True,30 normalise='mask',31 use_staging=False,32)33# @nottest34def test_all():35 """36 Run the stats module. The data requirted for this to work must be initially made37 by running the test: tests/test_lama.py:test_lama_job_runner()38 """39 with tempfile.NamedTemporaryFile(mode='w+', delete=False) as fh:40 # print(fh.name)41 fh.write(toml.dumps(root_config))42 lama_stats_new.run(fh.name, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir)43# @nottest44# def test_no_use():45# """46# For the organ volume test, if the meta data dataframe has a column of 'no_analysis', do not include the label in the47# analysis48# """49# pass50@nottest51def test_mutant_id_subset():52 """53 Thest whether specifying mutant id subset works54 """55 config = stats_config_dir / 'new_stats_config_test_mutant_id_subset.toml'56 lama_stats_new.run(config, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir)57@nottest58def test_specifiy_line():59 """60 Run the stats module. The data requirted for this to work must be initially made61 by running the test: tests/test_lama.py:test_lama_job_runner()62 """63 line = 'mutant_1' # Only run this line64 # Remove any previous output65 if stats_output_dir.is_dir():66 shutil.rmtree(stats_output_dir)67 config = stats_config_dir / 'new_stats_config.toml'68 lama_stats_new.run(config, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir, lines_to_process=[line])69 output_lines = [x.name for x in stats_output_dir.iterdir() if x.is_dir()]70 assert_equal([line], output_lines)71@nottest72def test_erroneuos_configs():73 error_config_dir = stats_config_dir / 'erroneous_configs'74 for config in error_config_dir.iterdir():75 lama_stats_new.run(config, wt_registration_dir, mut_registration_dir, stats_output_dir, target_dir)76# @nottest77# def test_organ_vols():78# config = join(CONFIG_DIR, 'organ_vols.yaml')79# run_lama_stats.run(config)80#81# @nottest82# def test_glcm():83# config = join(CONFIG_DIR, 'test_glcm.yaml')84# run_lama_stats.run(config)85#86# @nottest87# def test_from_arbitrary_directory():88# config = join(CONFIG_DIR, 'all_specimens.yaml')89# os.chdir(os.path.expanduser('~'))90# run_lama_stats.run(config)91#92# @nottest93# def test_missing_config():94# config = join(CONFIG_DIR, 'all_specimens.flaml')95# assert_raises(Exception, run_lama_stats.run, config)96#97# @nottest98# def test_misc():99# config = join(CONFIG_DIR, 'misc_test.yaml')100# run_lama_stats.run(config)101#102#103# @nottest104# def test_incorrect_staging_file():105# pass106if __name__ == '__main__':...
test_helper_functions.py
Source:test_helper_functions.py
1import os2import logging3import psycopg24import psycopg2.extras as psycop_extras5from nose.tools import nottest6from application.services import config_service7from application.services import logging_service8from application.services import debug_service9from application.services import conversion_service10from application.services import database_service11from application.models.classes import dycast_parameters12debug_service.enable_debugger()13current_dir = os.path.basename(os.path.dirname(os.path.realpath(__file__)))14@nottest15def init_test_environment():16 config_path = os.path.join(current_dir, '..', 'dycast.config')17 config_service.init_config(config_path)18 logging_service.init_logging()19@nottest20def get_dycast_parameters():21 dycast = dycast_parameters.DycastParameters()22 dycast.srid_of_cases = '3857'23 dycast.files_to_import = get_test_cases_import_files_latlong()24 dycast.spatial_domain = 60025 dycast.temporal_domain = 2826 dycast.close_in_space = 10027 dycast.close_in_time = 428 dycast.case_threshold = 1029 dycast.startdate = conversion_service.get_date_object_from_string('2016-03-30')30 dycast.enddate = conversion_service.get_date_object_from_string('2016-03-31')31 dycast.extent_min_x = 183040032 dycast.extent_min_y = 212060033 dycast.extent_max_x = 183070034 dycast.extent_max_y = 212030035 dycast.srid_of_extent = 385736 return dycast 37@nottest38def get_test_data_directory():39 return os.path.join(current_dir, 'test_data')40@nottest41def get_test_data_import_directory():42 return os.path.join(get_test_data_directory(), 'import')43@nottest44def get_test_data_export_directory():45 return os.path.join(get_test_data_directory(), 'export')46@nottest47def get_test_cases_import_files_latlong():48 file_1 = os.path.join(get_test_data_import_directory(), 'input_cases_latlong1.tsv')49 file_2 = os.path.join(get_test_data_import_directory(), 'input_cases_latlong2.tsv')50 return [file_1, file_2]51@nottest52def get_test_cases_import_file_geometry():53 return os.path.join(get_test_data_import_directory(), 'input_cases_geometry.tsv')54@nottest55def get_count_from_table(table_name):56 cur, conn = database_service.init_db()57 querystring = "SELECT count(*) from " + table_name58 try:59 cur.execute(querystring)60 except Exception:61 conn.rollback()62 logging.exception("Can't select count from table, exiting...")63 raise64 new_row = cur.fetchone()65 return new_row[0]66@nottest67def insert_test_risk():68 cur, conn = database_service.init_db()69 querystring = "INSERT INTO risk VALUES %s"70 data_tuple = [('2016-03-30', 1830400, 2120400, 10, 1, 6, 7, 0.3946), ('2016-03-31', 1830400, 2120400, 10, 1, 6, 7, 0.3946)]71 try:72 psycop_extras.execute_values(cur, querystring, data_tuple)73 except psycopg2.IntegrityError:74 conn.rollback()75 logging.warning("Couldn't insert duplicate key in tuple: %s...", data_tuple) 76 except Exception:77 conn.rollback()78 logging.exception("Couldn't insert tuple")79 raise...
tests.py
Source:tests.py
1from master import *2from nose.tools import nottest3#######################################################################################4@nottest5def walk(folder):6 data = []7 for root, dirs, files in os.walk(folder):8 del dirs[:] # walk down only one level9 path = root.split('/')10 for file in files:11 if file[-3:] == ".py":12 data.append(folder.replace("backdoors/", "") + "/" + str(file).replace(".py", ""))13 return data14@nottest15def get_backdoors_list():16 bds = []17 bds += walk("backdoors/access")18 bds += walk("backdoors/escalation")19 bds += walk("backdoors/windows")20 bds += walk("backdoors/shell")21 bds += walk("backdoors/auxiliary")22 return bds23@nottest24def get_backdoors():25 objs = []26 args = get_backdoors_list();27 for s in args:28 bd = s.split()[0]29 loc, bd = bd.rsplit("/", 1)30 if "backdoors/" + loc not in sys.path: 31 sys.path.insert(0, "backdoors/" + loc)32 mod = importlib.import_module(bd)33 clsmembers = inspect.getmembers(sys.modules[bd], inspect.isclass)34 objs.append([m for m in clsmembers if m[1].__module__ == bd][0][1])35 objs = [o for o in objs if o.__name__ != "Option"]36 return objs37@nottest38def get_modules():39 bd = BackdoorMe()40 return bd.enabled_modules.keys()41@nottest42def check_add_module_test(bd, m):43 core = BackdoorMe()44 bd = bd(core)45 if bd.allow_modules:46 bd.do_add(m)47 bd.do_show("options")48 pass49@nottest50def check_crash_test(bd):51 core = BackdoorMe()52 bd(core).do_show("options")53 pass54@nottest55def check_help_text(bd):56 core = BackdoorMe()57 if bd(core).help_text == "":58 assert False59#######################################################################################60def backdoor_crash_test():61 bds = get_backdoors()62 for bd in bds:63 yield check_crash_test, bd64def add_module_test():65 bds = get_backdoors()66 for bd in bds:67 for m in get_modules():68 yield check_add_module_test, bd, m69def help_text_test():70 bds = get_backdoors()71 for bd in bds:72 yield check_help_text, bd 73def add_target_test():74 bd = BackdoorMe()75 bd.addtarget("10.1.0.2", "student", "target123")76 ...
test_dev_skip_test.py
Source:test_dev_skip_test.py
1from dev_skip_test import istest, nottest, dev_skip_test2d = {}3@istest4def test_passes():5 d['istest'] = True6 assert True7@nottest8def test_fails():9 d['nottest'] = True10 assert False11def test_dev_skip_test():12 assert dev_skip_test is istest or dev_skip_test is nottest13 assert d.get('istest', False) is True...
notTest.py
Source:notTest.py
1def notTest(num):2 if num != 0 and num != 3:3 print("yes")4 else:5 print("no")6if __name__ == '__main__':7 notTest(1)8 notTest(2)9 notTest(0)...
Using AI Code Generation
1var available = require('./available');2available.notTest();3var test = function() {4 console.log('test');5};6var notTest = function() {7 console.log('notTest');8};9module.exports.test = test;10module.exports.notTest = notTest;11var available = require('./available');12available.notTest();13I'm not sure if this is the right place to post this, but I'm having trouble importing a module. I have a file called "test.js" which imports a module called "test-module" and tries to call a function from it. The test-module is in the same directory as test.js. The code for the module is: var test = function() { console.log("test"); } module.exports = test; The code for test.js is: var test = require("./test-module"); test(); When I run test.js, I get the following error: module.js:338 throw err; ^ Error: Cannot find module './test-module' at Function.Module._resolveFilename (module.js:336:15) at Function.Module._load (module.js:278:25) at Module.require (module.js:365:17) at require (module.js:384:17) at Object. (/Users
Using AI Code Generation
1availableModule.notTest();2module.exports = {3 test: function() {4 console.log('test');5 },6 notTest: function() {7 console.log('not test');8 }9}
Using AI Code Generation
1var available = require('./available');2available.notTest();3module.exports = {4 notTest: function() {5 console.log('not a test');6 }7}
Using AI Code Generation
1var available = require('available');2var result = available.notTest();3console.log(result);4exports.notTest = function() {5 return 'notTest';6};7var available = require('available');8var result = available.test();9console.log(result);10exports.test = function() {11 return 'test';12};13var available = require('available');14var result = available.notTest();15console.log(result);16exports.notTest = function() {17 return 'notTest';18};19var available = require(require.resolve('available'));20var result = available.test();21console.log(result);22exports.test = function() {23 return 'test';24};
Using AI Code Generation
1var availableTest = require('./availableTest');2availableTest.notTest(availableTest.test);3module.exports = {4 test: function(){5 console.log('test');6 },7 notTest: function(callback){8 callback();9 }10}
Using AI Code Generation
1var available = require('./available');2available.notTest();3console.log(available.test);4module.exports = {5 notTest: function() {6 console.log('Not Hello World!');7 }8}
Using AI Code Generation
1var availableObjects = require('./availableObjects.js');2var test = function(){3 availableObjects.notTest();4}5module.exports.test = test;6var notTest = function(){7 console.log('I am not a test');8}9module.exports.notTest = notTest;
Using AI Code Generation
1var available = require('./available.js');2console.log(available.notTest('hello'));3exports.notTest = function (str) {4 return str + 'world';5};6module.exports = {7 notTest: function (str) {8 return str + 'world';9 }10};11var available = {12 notTest: function (str) {13 return str + 'world';14 }15};16module.exports = available;17var available = function () {18 return {19 notTest: function (str) {20 return str + 'world';21 }22 }23};24module.exports = available();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!