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(): """Runs the testsuite as command line application. """ try: unittest.main() except Exception as e: print('Error: %s' % e)
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 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 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_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 main(): import sys sys.path.insert(0, "C:/Program Files/Southpaw/Tactic1.9/src/client") try: unittest.main() except SystemExit: pass
def main(suite=None): if not suite: unittest.main() else: unittest.TestSuite(suite) runner = unittest.TextTestRunner() runner.run(suite)
def q1(): ''' How can I handle errors, like the Zero Division Error, while testing? ''' if __name__ == "__main__": unittest.main()
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_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(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 )
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 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(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 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(): 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 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 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 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 run_unittest(tester): """run unittest""" import unittest unittest.main( None, None, [unittest.__file__, tester.test_suite], testLoader = unittest.TestLoader() )
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(): 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 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 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 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(): unittest.main() def test_gauges(self): pkt = 'foo:50|g' self.svc._process(pkt, None) self.assertEquals(self.stats.gauges, {'foo': '50'})
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 main(**kwargs): """A simple test runner. This test runner is essentially equivalent to `unittest.main` from the standard library, but adds support for tornado-style option parsing and log formatting. The easiest way to run a test is via the command line:: python -m tornado.testing tornado.test.stack_context_test See the standard library unittest module for ways in which tests can be specified. Projects with many tests may wish to define a test script like ``tornado/test/runtests.py``. This script should define a method ``all()`` which returns a test suite and then call `tornado.testing.main()`. Note that even when a test script is used, the ``all()`` test suite may be overridden by naming a single test on the command line:: # Runs all tests python -m tornado.test.runtests # Runs one test python -m tornado.test.runtests tornado.test.stack_context_test Additional keyword arguments passed through to ``unittest.main()``. For example, use ``tornado.testing.main(verbosity=2)`` to show many test details as they are run. See http://docs.python.org/library/unittest.html#unittest.main for full argument list. """ from tornado.options import define, options, parse_command_line define('exception_on_interrupt', type=bool, default=True, help=("If true (default), ctrl-c raises a KeyboardInterrupt " "exception. This prints a stack trace but cannot interrupt " "certain operations. If false, the process is more reliably " "killed, but does not print a stack trace.")) # support the same options as unittest's command-line interface define('verbose', type=bool) define('quiet', type=bool) define('failfast', type=bool) define('catch', type=bool) define('buffer', type=bool) argv = [sys.argv[0]] + parse_command_line(sys.argv) if not options.exception_on_interrupt: signal.signal(signal.SIGINT, signal.SIG_DFL) if options.verbose is not None: kwargs['verbosity'] = 2 if options.quiet is not None: kwargs['verbosity'] = 0 if options.failfast is not None: kwargs['failfast'] = True if options.catch is not None: kwargs['catchbreak'] = True if options.buffer is not None: kwargs['buffer'] = True if __name__ == '__main__' and len(argv) == 1: print("No tests specified", file=sys.stderr) sys.exit(1) try: # In order to be able to run tests by their fully-qualified name # on the command line without importing all tests here, # module must be set to None. Python 3.2's unittest.main ignores # defaultTest if no module is given (it tries to do its own # test discovery, which is incompatible with auto2to3), so don't # set module if we're not asking for a specific test. if len(argv) > 1: unittest.main(module=None, argv=argv, **kwargs) else: unittest.main(defaultTest="all", argv=argv, **kwargs) except SystemExit as e: if e.code == 0: gen_log.info('PASS') else: gen_log.error('FAIL') raise
# create posts now = datetime.utcnow() p1 = Post(body='Post from John', author=u1, timestamp=now + timedelta(seconds=1)) p2 = Post(body='Post from Susan', author=u2, timestamp=now + timedelta(seconds=4)) p3 = Post(body='Post from Mary', author=u3, timestamp=now + timedelta(seconds=3)) p4 = Post(body='Post from Dave', author=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([p1, p2, p3, p4]) db.session.commit() # setup followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows dave u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows dave db.session.commit() # check followed posts of each user f1 = u1.followed_posts().all() f2 = u2.followed_posts().all() f3 = u3.followed_posts().all() f4 = u4.followed_posts().all() self.assertEqual(f1, [p2, p4, p1]) self.assertEqual(f2, [p2, p3]) self.assertEqual(f3, [p3, p4]) self.assertEqual(f4, [p4]) if __name__ == '__main__': unittest.main(verbosity=2)
0, 1, 1, 1, 0, 1, 0, 5, # Action color 2, # Target color 1, # Action layer 0, # Target layer ]]) g = Genotype(data=data, dna=dna) g.update() # Did the shift look in the top-left direction?? expected_layer = np.ones((3, 3, 3)) expected_layer[0][0] = (0, 0, 0) expected_layer[0][1] = (0, 0, 0) expected_layer[1][0] = (0, 0, 0) expected_layer[1][1] = (0, 0, 0) expected_layer *= (90, 90, 120) assert (g.data[1] == expected_layer).all() if __name__ == '__main__': unittest.main()
from Sprint3_Main import Gedcom import unittest class TestGedcom(unittest.TestCase): @classmethod def setUpClass(cls): """ Set up objects with filenames """ cls.x = Gedcom("US26_US27_testing.ged", "y") cls.errorlog = cls.x.analyze_gedcom_file() def test_Corresponding_entries(self): """ To test if the individual and family records is consistent with each other """ self.assertNotEqual(self.errorlog["US26_Corresponding_entries"], 0) def test_Include_individual_ages(self): """ To Test US27_Include_individual_ages while listing """ print("------------- Testing of Include person's current age when listing individuals done -------------") g = Gedcom("../gedcomData.ged", "y") g.analyze_gedcom_file() self.assertEqual(g.individualdata["I1"]['AGE'], 26) self.assertEqual(g.individualdata["I2"]['AGE'], 61) self.assertEqual(g.individualdata["I17"]['AGE'], 78) self.assertNotEqual(g.individualdata["I15"]['AGE'], 16) if __name__ == '__main__': # note: there is no main(). Only test cases here unittest.main(exit=False, verbosity=2)
signer = pkcs1_15.new(key) hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1", "SHA224", "SHA256", "SHA384", "SHA512", "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512") for name in hash_names: hashed = load_hash_by_name(name).new(b("Test")) signer.sign(hashed) from Crypto.Hash import BLAKE2b, BLAKE2s for hash_size in (20, 32, 48, 64): hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test")) signer.sign(hashed_b) for hash_size in (16, 20, 28, 32): hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test")) signer.sign(hashed_s) def get_tests(config={}): tests = [] tests += list_test_cases(FIPS_PKCS1_Verify_Tests) tests += list_test_cases(FIPS_PKCS1_Sign_Tests) tests += list_test_cases(PKCS1_15_NoParams) tests += list_test_cases(PKCS1_Legacy_Module_Tests) tests += list_test_cases(PKCS1_All_Hashes_Tests) return tests if __name__ == '__main__': suite = lambda: unittest.TestSuite(get_tests()) unittest.main(defaultTest='suite')
def main(): unittest.main(module=__name__, defaultTest='test_suite', argv=sys.argv[:1])
a[80:120] = 1 a[200] = 1 # rising fronts self.assertTrue(all(rises(a) == np.array([80, 200]))) # falling fronts self.assertTrue(all(falls(a) == np.array([120, 201]))) # both ind, val = fronts(a) self.assertTrue(all(ind == np.array([80, 120, 200, 201]))) self.assertTrue(all(val == np.array([1, -1, 1, -1]))) # test a 2D case with 2 long pulses and a dirac a = np.zeros((2, 500)) a[0, 80:120] = 1 a[0, 200] = 1 a[1, 280:320] = 1 a[1, 400] = 1 # rising fronts self.assertTrue(np.all(rises(a) == np.array([[0, 0, 1, 1], [80, 200, 280, 400]]))) # falling fronts self.assertTrue(np.all(falls(a) == np.array([[0, 0, 1, 1], [120, 201, 320, 401]]))) # both ind, val = fronts(a) self.assertTrue(all(ind[0] == np.array([0, 0, 0, 0, 1, 1, 1, 1]))) self.assertTrue(all(ind[1] == np.array([80, 120, 200, 201, 280, 320, 400, 401]))) self.assertTrue(all(val == np.array([1, -1, 1, -1, 1, -1, 1, -1]))) if __name__ == "__main__": unittest.main(exit=False)
self.assertEqual(data['Item']['status']['S'], 'INFO') def test_update(self): self.dyn.put(self.key, self.sample_data) self.dyn.update(self.key, 'WARNING') data = self.dyn.get(self.key) self.assertEqual(data['Item']['status']['S'], 'WARNING') def test_filters(self): TOTAL_ITEMS = 50 with self.table.batch_writer() as batch: for i in range(TOTAL_ITEMS): batch.put_item( Item={ TIMESTAMP: '2020-01-01-01-{}'.format(str(i)), STATUS: 'ERROR', 'message': f'#{i} log message' }) response = self.dyn.filter_by_timestamp_status(self.key, 'ERROR') self.assertEqual(len(response['Items']), 1) response = self.dyn.filter_by_status('ERROR') self.assertEqual(len(response['Items']), TOTAL_ITEMS) if __name__ == '__main__': unittest.main(warnings='ignore')
def test_main_no_ping(self): output = scrap_output(main, ["127.0.0.1", "10", "-V", "-T", "0.001"]) self.assertIn("--ignore-ping-check", output) self.assertIn("skipping", output) def test_main_no_ping_ipv6(self): output = scrap_output(main, ["::1", "10", "-V", "-T", "0.001"]) self.assertIn("--ignore-ping-check", output) self.assertIn("skipping", output) def test_active_scanner(self): local_ip = get_local_ip() print ("ip: {}".format(local_ip)) config = load_test_servers() test_server_ip = config["COMMON"]["DEFAULT_IP"] dtls_servers = ["goldy"] for dtls_server in dtls_servers: port = config["DTLS_TEST_SERVERS"][dtls_server + "_port"] print ("test_server_ip: {} port: {}".format(test_server_ip, port)) output = scrap_output(main, [test_server_ip, port, "-P", "DTLS"]) self.assertIn("Finished active security scanning", output) self.assertIn("Starting scan: supported_protocol_versions", output) self.assertIn("Supported protocol versions", output) if __name__ == "__main__": TEST_RUNNER = TimerTestRunner() unittest.main(testRunner=TEST_RUNNER)