def main(argv=sys.argv[1:]): logging.basicConfig(format='->%(asctime)s;%(levelname)s;%(message)s') top_dir = __file__[:__file__.find('/modules/core/')] build_dir = os.path.join(top_dir, '.build/modules/core/rwvx/src/core_rwvx-build') if 'MESSAGE_BROKER_DIR' not in os.environ: os.environ['MESSAGE_BROKER_DIR'] = os.path.join(build_dir, 'rwmsg/plugins/rwmsgbroker-c') if 'ROUTER_DIR' not in os.environ: os.environ['ROUTER_DIR'] = os.path.join(build_dir, 'rwdts/plugins/rwdtsrouter-c') parser = argparse.ArgumentParser() parser.add_argument('-t', '--test') parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args(argv) # Set the global logging level logging.getLogger().setLevel(logging.DEBUG if args.verbose else logging.INFO) testname = args.test logging.info(testname) # The unittest framework requires a program name, so use the name of this # file instead (we do not want to have to pass a fake program name to main # when this is called from the interpreter). unittest.main(argv=[__file__], defaultTest=testname, testRunner=xmlrunner.XMLTestRunner( output=os.environ["RIFT_MODULE_TEST"]))
def main(): import sys sys.path.insert(0, "C:/Program Files/Southpaw/Tactic1.9/src/client") try: unittest.main() except SystemExit: pass
def run_tests(self): import sys, os if sys.version_info[0] == 3: rootdir = os.path.dirname(os.path.abspath(__file__)) if rootdir in sys.path: sys.path.remove(rootdir) ei_cmd = self.get_finalized_command('egg_info') egg_name = ei_cmd.egg_name.replace('-', '_') to_remove = [] for dirname in sys.path: bn = os.path.basename(dirname) if bn.startswith(egg_name + "-"): to_remove.append(dirname) for dirname in to_remove: log.info("removing installed %r from sys.path before testing"%(dirname,)) sys.path.remove(dirname) from PyObjCTest.loader import makeTestSuite import unittest #import pprint; pprint.pprint(sys.path) unittest.main(None, None, [unittest.__file__]+self.test_args)
def test_main(): global _do_pause o = optparse.OptionParser() o.add_option("-v", "--verbose", action="store_true", help="Verbose output") o.add_option("-q", "--quiet", action="store_true", help="Minimal output") o.add_option("-l", "--list_tests", action="store_true") o.add_option("-p", "--pause", action="store_true") conf, args = o.parse_args() if conf.list_tests: list_tests(1) return if conf.pause: _do_pause = True # process unittest arguments argv = [sys.argv[0]] if conf.verbose: argv.append("-v") if conf.quiet: argv.append("-q") argv.extend(args) # run unittest unittest.main(argv=argv)
def main(): unittest.main() def test_gauges(self): pkt = 'foo:50|g' self.svc._process(pkt, None) self.assertEquals(self.stats.gauges, {'foo': '50'})
def main(): # create logger logger = logging.getLogger("decorationplan.detail3") logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler( sys.__stdout__ ) # Add this ch.setLevel(logging.DEBUG) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch ch.setFormatter(formatter) # add ch to logger logger.addHandler(ch) # 'application' code #logger.debug('debug message') #logger.info('info message') #logger.warn('warn message') #logger.error('error message') #logger.critical('critical message') unittest.main()
def run(self): os.setpgrp() unittest_args = [sys.argv[0]] if ARGS.verbose: unittest_args += ["-v"] unittest.main(argv=unittest_args)
def run_unittest(tester): """run unittest""" import unittest unittest.main( None, None, [unittest.__file__, tester.test_suite], testLoader = unittest.TestLoader() )
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "h:p:u:w:") except getopt.GetoptError as err: print str(err) usage() sys.exit(2) global host host = "127.0.0.1" global port port = 8000 global username username = None global password password = None for o, a in opts: if o == "-h": host = a elif o == "-p": port = int(a) elif o == "-u": username = a elif o == "-w": password = a else: assert False, "unhandled option" unittest.main(argv=[sys.argv[0]])
def main(): global DELETE, OUTPUT parser = OptionParser() parser.add_option("--list", action="store", dest="listTests") parser.add_option("--nodelete", action="store_true") parser.add_option("--output", action="store_true") # The following options are passed to unittest. parser.add_option("-e", "--explain", action="store_true") parser.add_option("-v", "--verbose", action="store_true") parser.add_option("-q", "--quiet", action="store_true") opts, files = parser.parse_args() if opts.nodelete: DELETE = False if opts.output: OUTPUT = True if opts.listTests: listTests(opts.listTests) else: # Eliminate script-specific command-line arguments to prevent # errors in unittest. del sys.argv[1:] for opt in ("explain", "verbose", "quiet"): if getattr(opts, opt): sys.argv.append("--" + opt) sys.argv.extend(files) unittest.main()
def test_register_and_login(self): # register a new account response = self.client.post(url_for('auth.register'), data={ 'email': '*****@*****.**', 'username': '******', 'password': '******', 'password_confirm': 'secret' }) self.assertEqual(response.status_code, 302) # login with new account response = self.client.post(url_for('auth.login'), data={'email': '*****@*****.**', 'password': '******'}, follow_redirects=True) data = response.get_data(as_text=True) self.assertRegex(data, 'Hello,\s+test!') self.assertIn('You have not confirmed your account', data) # send a confirmation token user = User.query.filter_by(email='*****@*****.**').first() token = user.generate_confirmation_token() response = self.client.get(url_for('auth.confirm', token=token), follow_redirects=True) data = response.get_data(as_text=True) self.assertIn('You have confirmed your account', data) # log out response = self.client.get(url_for('auth.logout'), follow_redirects=True) data = response.get_data(as_text=True) self.assertIn('You have been logged out', data) if __name__ == '__main__': unittest.main()
def run_tests(): if not os.path.isdir(test_repo): sys.stderr.write("Error: Test repository not found.\n" "Create test repository first using ./create_test_repo.sh script.\n") sys.exit(1) unittest.main()
def main(): if '-v' in sys.argv: unittest.TestCase.maxDiff = None logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.FATAL) unittest.main()
def main(argv=sys.argv[1:]): logging.basicConfig(format="TEST %(message)s") # The unittest framework requires a program name, so use the name of this # file instead (we do not want to have to pass a fake program name to main # when this is called from the interpreter). unittest.main(argv=[__file__] + argv, testRunner=xmlrunner.XMLTestRunner(output=os.environ["RIFT_MODULE_TEST"]))
def run(self): ''' Finds all the tests modules in tests/, and runs them. ''' from firebirdsql import tests import unittest unittest.main(tests, argv=sys.argv[:1])
def test_2Not500or404andLoginIsVisible(self): assert "500" not in driver.title # проверка на 500/404 ошибку assert "404" not in driver.title _ = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'hidden-xs'))) if __name__ == '__main__': unittest.main()
def iMain(lCmdLine): if '--test' in lCmdLine: # legacy - unused sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() unittest.main() return 0 oApp = None try: oArgParser = oParseOptions() oOptions = oArgParser.parse_args(lCmdLine) sConfigFile = oOptions.sConfigFile oConfig = oParseConfig(sConfigFile) oConfig = oMergeConfig(oConfig, oOptions) oApp = CmdLineApp(oConfig, oOptions.lArgs) if oOptions.lArgs: oApp.onecmd_plus_hooks(' '.join(oOptions.lArgs) +'\n') else: oApp._cmdloop() except KeyboardInterrupt: pass except Exception as e: print traceback.format_exc(10) # always reached if oApp: oApp.vAtexit() l = threading.enumerate() if len(l) > 1: print "WARN: Threads still running: %r" % (l,)
def main(argv=sys.argv[1:]): logging.basicConfig(format='TEST %(message)s') parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-w', '--wait', action='store_true', help="Wait after the tests are done, to inspect the system.") parser.add_argument('unittest_args', nargs='*') args = parser.parse_args(argv) if args.wait: TestRestconf.wait_forever = True # Set the global logging level logging.getLogger(__name__).setLevel(logging.DEBUG if args.verbose else logging.ERROR) try: # The unittest framework requires a program name, so use the name of this # file instead (we do not want to have to pass a fake program name to main # when this is called from the interpreter). unittest.main(argv=[__file__] + args.unittest_args, testRunner=xmlrunner.XMLTestRunner( output=os.environ["RIFT_MODULE_TEST"])) except Exception as exp: print("Exception thrown", exp) if TestRestconf.testware is not None: os.system("stty sane") TestRestconf.testware.stop_testware()
def main(): log.basicConfig( format='%(asctime)s %(name)s %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S', level=log.DEBUG) unittest.main()
def main(supported_fmts=[], supported_oses=['linux']): '''Run tests''' debug = '-d' in sys.argv verbosity = 1 if supported_fmts and (imgfmt not in supported_fmts): notrun('not suitable for this image format: %s' % imgfmt) if True not in [sys.platform.startswith(x) for x in supported_oses]: notrun('not suitable for this OS: %s' % sys.platform) # We need to filter out the time taken from the output so that qemu-iotest # can reliably diff the results against master output. import StringIO if debug: output = sys.stdout verbosity = 2 sys.argv.remove('-d') else: output = StringIO.StringIO() class MyTestRunner(unittest.TextTestRunner): def __init__(self, stream=output, descriptions=True, verbosity=verbosity): unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity) # unittest.main() will use sys.exit() so expect a SystemExit exception try: unittest.main(testRunner=MyTestRunner) finally: if not debug: sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))
def main(): if len(sys.argv) == 1: unittest.main() return waagent.LoggerInit('/var/log/waagent.log', '/dev/stdout') waagent.Log("%s started to handle." %(ExtensionShortName)) global hutil hutil = Util.HandlerUtility(waagent.Log, waagent.Error, ExtensionShortName) hutil.do_parse_context('TEST') global MyPatching MyPatching = FakePatching(hutil) if MyPatching == None: sys.exit(1) for a in sys.argv[1:]: if re.match("^([-/]*)(disable)", a): disable() elif re.match("^([-/]*)(uninstall)", a): uninstall() elif re.match("^([-/]*)(install)", a): install() elif re.match("^([-/]*)(enable)", a): enable() elif re.match("^([-/]*)(update)", a): update() elif re.match("^([-/]*)(download)", a): download() elif re.match("^([-/]*)(patch)", a): patch() elif re.match("^([-/]*)(oneoff)", a): oneoff()
def q1(): ''' How can I handle errors, like the Zero Division Error, while testing? ''' if __name__ == "__main__": unittest.main()
def main(suite=None): if not suite: unittest.main() else: unittest.TestSuite(suite) runner = unittest.TextTestRunner() runner.run(suite)
def test_add(self): self.assertEqual(2 + 3, 5) def test_sub(self): self.assertEqual(5 - 3, 2) if __name__ == '__main__': unittest.main() python python/tests/test.py # Asercje w testach self.assertEqual(2 + 3, 5) self.assertAlmostEqual(0.1 + 0.2, 0.3, delta=1e-6) self.assertNotEqual('żółw', u'Żółw') self.assertTrue([0]) self.assertFalse([]) x = [] y = x self.assertIs(x, y) self.assertIn('x', ['x']) self.assertIsInstance([], list) self.assertIsNone(None) self.assertItemsEqual((2, 3), [2, 3]) # Code coverage sudo pip install coverage coverage run python/hello.py coverage report -m coverage html
def test_generate_teams(self): data_struct = generate_data_structure( 'a2|' ' **qg** [](#qg) |' 'vs.|' ' [](#dig) **dig** |' ' [picks & bans](http://www.twitch.tv/esl_lol/v/30574431?t=1h47m41s) |' ' [game start](http://www.twitch.tv/esl_lol/v/30574431?t=1h57m05s) |' ' [picks & bans](https://www.youtube.com/watch?v=ytsjecr73nk) |' ' [game start](https://www.youtube.com/watch?v=ytsjecr73nk&t=7m45s) |' ' [highlights](https://www.youtube.com/watch?v=j67z3z9gnsc) |', 'title') self.assertTrue('qg' in data_struct['blue_team']) self.assertTrue('dig' in data_struct['red_team']) self.assertTrue('a2' in data_struct['local_id']) self.assertIsNotNone(data_struct['pick_ban']) self.assertIsNotNone(data_struct['pick_ban']['twitch']) self.assertIsNotNone(data_struct['pick_ban']['youtube']) self.assertIsNotNone(data_struct['game_start']) self.assertIsNotNone(data_struct['game_start']['youtube']) self.assertEqual(data_struct['game_start']['youtube'], ' [game start](https://www.youtube.com/watch?v=ytsjecr73nk&t=7m45s) ') self.assertIsNotNone(data_struct['highlights']) if __name__ == '__main__': unittest.main()
def ez_launch(modname, main=None, setup=None, cleanup=None, test=None, logfile=''): """ For a simple (non-tool-style) program, figure out what needs to happen and call the invoker's 'main' callback. """ if len(sys.argv) == 1 and sys.argv[0] == '': return if modname != '__main__': return sname = sys.argv[0] pname = re.sub('.py$', '', sname) if (sname.endswith('.py') and not os.path.exists(pname) and '-L' in sys.argv): print("creating symlink: %s -> %s" % (pname, sname)) os.symlink(sname, pname) elif sys._getframe(1).f_code.co_name in ['?', '<module>']: if sname.endswith('.py'): if '-d' in sys.argv: sys.argv.remove('-d') pdb.set_trace() if test is None: unittest.main() else: if setup is not None: setup() keep = testhelp.main(sys.argv, test, logfile=logfile) if not keep and cleanup is not None: cleanup() elif main is not None: main(sys.argv)
def main(): """ Starts Home Assistant. Will create demo config if no config found. """ # Do we want to run the tests? if ARG_RUN_TESTS in sys.argv: sys.argv.remove(ARG_RUN_TESTS) import unittest unittest.main(module='homeassistant.test') # Within Docker we load the config from a different path if ARG_DOCKER in sys.argv: config_path = '/config/home-assistant.conf' else: config_path = 'config/home-assistant.conf' # Ensure a config file exists to make first time usage easier if not os.path.isfile(config_path): with open(config_path, 'w') as conf: conf.write("[http]\n") conf.write("api_password=password\n\n") conf.write("[demo]\n") hass = bootstrap.from_config_file(config_path) hass.start() hass.block_till_stopped()
def resolve(): s = input() n = int(input()) - 1 print(s[int(n/5)] + s[int(n%5)]) class TestClass(unittest.TestCase): def assertIO(self, input, output): stdout, stdin = sys.stdout, sys.stdin sys.stdout, sys.stdin = StringIO(), StringIO(input) resolve() sys.stdout.seek(0) out = sys.stdout.read()[:-1] sys.stdout, sys.stdin = stdout, stdin self.assertEqual(out, output) def test_入力例1(self): input = """abcde 1""" output = """ab""" self.assertIO(input, output) def test_入力例2(self): input = """aeiou 22""" output = """ue""" self.assertIO(input, output) def test_入力例3(self): input = """vwxyz 25""" output = """zz""" self.assertIO(input, output) if __name__ == "__main__": unittest.main()
def main(): """Runs the testsuite as command line application. """ try: unittest.main() except Exception as e: print('Error: %s' % e)
def main(argv): """ Runs the test files through the xml runner :param argv: List of command line arguments """ if len(argv) != 2: raise ValueError("Usage: testrunner <path-to-test-file>") pathname = argv[1] if not os.path.exists(pathname): raise ValueError("Test file not found '{}'".format(pathname)) if not os.path.isfile(pathname): raise ValueError("Test path '{}' is not a file".format(pathname)) # Load the test and copy over any module variables so that we have # the same environment defined here test_module = imp.load_source(module_name(pathname), pathname) test_module_globals = dir(test_module) this_globals = globals() for key in test_module_globals: this_globals[key] = getattr(test_module, key) # create runner & execute unittest.main( module=test_module, # We've processed the test source so don't let unittest try to reparse it # This forces it to load the tests from the supplied module argv=(argv[0],), # these make sure that some options that are not applicable # remain hidden from the help menu. failfast=False, buffer=False, catchbreak=False )