def test_fill_with_bad_operator(self): try: self._obj.fill({'operator': "bad"}) except: pass else: TestCase.fail(self, "Operator 'bad' doesn't exist, exception should be raised")
def fail(self, msg = None): try: TestCase.fail(self, msg) except: self.kmod.stop() self.kmod.save_logs(self.destdir) raise
def failUnlessEqual(self, first, second, msg = None): try: TestCase.failUnlessEqual(self, first, second, msg) except: self.kmod.stop() self.kmod.save_logs(self.destdir) raise
def check(self, tc, exp_log, cachedMsg): exp_level, exp_msgs = exp_log act_msgs = cachedMsg[1:] if exp_level is 'INFO': TestCase.assertEqual(tc, exp_msgs, act_msgs) if exp_level is 'ERROR': pass #
def failIfAlmostEqual(self, first, second, places = 7, msg = None): try: TestCase.failIfAlmostEqual(self, first, second, places, msg) except: self.kmod.stop() self.kmod.save_logs(self.destdir) raise
def __init__(self, *args, **kwargs): ''' initialize the test class ''' TestCase.__init__(self, *args, **kwargs) LOG.error("ConfigFile: %s " % config['__file__']) conffile = config['__file__'] if pylons.test.pylonsapp: wsgiapp = pylons.test.pylonsapp else: wsgiapp = loadapp('config: %s' % config['__file__']) self.app = TestApp(wsgiapp) conf = None if conffile.startswith('/'): conf = appconfig('config:%s' % config['__file__'], relative_to=None) else: raise Exception('dont know how to load the application relatively') #conf = appconfig('config: %s' % config['__file__'], relative_to=rel) load_environment(conf.global_conf, conf.local_conf) self.appconf = conf url._push_object(URLGenerator(config['routes.map'], environ)) self.isSelfTest = False if env.has_key("privacyidea.selfTest"): self.isSelfTest = True self.license = 'CE' return
def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): try: TestCase.failUnlessRaises(self, excClass, callableObj, *args, **kwargs) except: self.kmod.stop() self.kmod.save_logs(self.destdir) raise
def setUp(self): TestCase.setUp(self) from google.appengine.ext.testbed import Testbed self.testbed = Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub()
def setUpClass(cls): TestCase.setUpClass() virtwho.parser.VIRTWHO_CONF_DIR = '/this/does/not/exist' virtwho.parser.VIRTWHO_GENERAL_CONF_PATH = '/this/does/not/exist.conf' cls.queue = Queue() cls.sam = FakeSam(cls.queue) cls.sam.start()
def setUp(self): TestCase.setUp(self) self._expandCalled = 0 self._collapseCalled = 0 self._lastExpanded = 0 self._lastCollapsed = 0
def what_is_session(): with DocumentStore() as store: store.initialize() # region session_usage_1 with store.open_session() as session: entity = Company(name= "Company") session.store(entity) session.save_changes() company_id = entity.Id with store.open_session() as session: entity = session.load(company_id, object_type= Company) print(entity.name) # endregion # region session_usage_2 with store.open_session() as session: entity = session.load(company_id, object_type=Company) entity.name = "Another Company" session.save_changes() # endregion with store.open_session() as session: # region session_usage_3 TestCase.assertTrue(session.load(company_id, object_type=Company) is session.load(company_id, object_type=Company))
def _apply(self, put: unittest.TestCase, value, message_builder: asrt.MessageBuilder): put.assertIsInstance(value, type(self.expected), message_builder.apply('type of CrossReferenceId')) equality_checker = _CrossReferenceIdEqualsWhenClassIsEqual(self.expected, put, message_builder) equality_checker.visit(value)
def test_status_raises_exception(self): try: self.presto_cli.status(self.mock_env) except Exception as e: self.assertEqual(repr(e), 'ClientComponentHasNoStatus()') return TestCase.fail(self)
def _check_sub_class_properties(self, put: unittest.TestCase, actual: DirDependentValue, tcds: HomeAndSds, message_builder: asrt.MessageBuilder): put.assertIsInstance(actual, SingleDirDependentValue, message_builder.apply('class')) assert isinstance(actual, SingleDirDependentValue) # Type info for IDE put.assertEqual(self._resolving_dependency, actual.resolving_dependency(), message_builder.apply('resolving_dependency')) assertion_on_resolved_value = self.resolved_value(tcds) if not self._resolving_dependency or self._resolving_dependency == DirectoryStructurePartition.HOME: resolved_value_post_sds = actual.value_pre_sds(tcds.hds) assertion_on_resolved_value.apply(put, resolved_value_post_sds, message_builder.for_sub_component('value_pre_sds')) if not self._resolving_dependency or self._resolving_dependency == DirectoryStructurePartition.NON_HOME: resolved_value_post_sds = actual.value_post_sds(tcds.sds) assertion_on_resolved_value.apply(put, resolved_value_post_sds, message_builder.for_sub_component('value_pre_sds'))
def setup_db(cls_obj: TestCase, table_paths: list): cls_obj.db_client = pymongo.MongoClient() cls_obj.collection_clients = dict() for table_path in table_paths: assert len(table_path) == 2, "must be a valid table path for MongoDB!" cls_obj.collection_clients[table_path] = cls_obj.db_client[table_path[0]][table_path[1]]
def get_printed_sds_or_fail(put: unittest.TestCase, actual: SubProcessResult) -> str: printed_lines = actual.stdout.splitlines() put.assertEqual(1, len(printed_lines), 'Number of printed printed lines should be exactly 1') actual_sds_directory = printed_lines[0] return actual_sds_directory
def assert_same_html(asserter: TestCase, actual: str, expected: str): """ Tests whether two HTML strings are 'equivalent' """ bactual = HTMLBeautifier.beautify(actual) bexpected = HTMLBeautifier.beautify(expected) asserter.assertMultiLineEqual(bactual, bexpected)
def __init__(self, methodName): """ Class constructor. Starts a Changes class for use in other tests. """ TestCase.__init__(self, methodName) self.changes = Changes(filename='debexpo/tests/changes/synce-hal_0.1-1_source.changes')
def __init__(self, methodName='runTest'): # Must call super class init to properly initialize unittest class TestCase.__init__(self, methodName) # # initialize colors and reporter properly if executed from Main if Verifier.__execFromMain: # enable color (unless nocolors) and summary report if not Verifier.__nocolors: Verifier.COLORS = color.colors if Verifier.reporter is None: # make reporter static so that it remains across runs Verifier.reporter = TestReporter(self.COLORS) # # copy to this instance self.reporter = Verifier.reporter # # Protected variables are set per run to facilitate test-harness methods. self._dir = None self._testSM = None self._smApp = None self._dontSendQuit = False # used in rare cases to NOT send 'quit' self._preserveImpl = False self._subdirsToClean = [] self._keepGen = False self._useSimStateStart = False self._enableGui = False self._verbose = False self._suiteVersion = None
def test_typed_tuple_set_ints(): class TestCase(HasTraits): value = TypedTuple(trait=Int()) obj = TestCase() obj.value = (1, 2, 3) assert obj.value == (1, 2, 3)
def test_typed_tuple_bad_set(): class TestCase(HasTraits): value = TypedTuple(trait=Int()) obj = TestCase() with nt.assert_raises(TraitError): obj.value = (1, 2, 'foobar')
def _check_type(self, put: unittest.TestCase, actual, message_builder: asrt.MessageBuilder ): put.assertIsInstance(actual, self._expected_type, message_builder.apply('Actual value is expected to be a ' + str(self._expected_type)))
def test_update(self): person = db.add_person(p_first_name='Marc', p_last_name='SCHNEIDER', p_birthdate=datetime.date(1973, 4, 24)) person_u = db.update_person(p_id=person.id, p_first_name='Marco', p_last_name='SCHNEIDERO', p_birthdate=datetime.date(1981, 4, 24)) assert str(person_u.birthdate) == str(datetime.date(1981, 4, 24)) assert person_u.last_name == 'SCHNEIDERO' assert person_u.first_name == 'Marco' user_acc = db.add_user_account(a_login='******', a_password='******', a_person_id=person_u.id, a_is_admin=True) assert not db.change_password(999999999, 'IwontGiveIt', 'foo') assert db.change_password(user_acc.id, 'IwontGiveIt', 'OkIWill') assert not db.change_password(user_acc.id, 'DontKnow', 'foo') user_acc_u = db.update_user_account(a_id=user_acc.id, a_new_login='******', a_is_admin=False) assert not user_acc_u.is_admin try: db.update_user_account(a_id=user_acc.id, a_person_id=999999999) TestCase.fail(self, "An exception should have been raised : person id does not exist") except DbHelperException: pass user_acc_u = db.update_user_account_with_person(a_id=user_acc.id, a_login='******', p_first_name='Bob', p_last_name='Marley', p_birthdate=datetime.date(1991, 4, 24), a_is_admin=True, a_skin_used='skins/crocodile') assert user_acc_u.login == 'mschneider3' assert user_acc_u.person.first_name == 'Bob' assert user_acc_u.person.last_name == 'Marley' assert str(user_acc_u.person.birthdate) == str(datetime.date(1991, 4, 24)) assert user_acc_u.is_admin assert user_acc_u.skin_used == 'skins/crocodile'
def tearDown(self): TestCase.tearDown(self) os.chdir(self.oldcwd) rmtree(self.repo_parent) rmtree(self.repo_one) rmtree(self.repo_two)
def test_del(self): dt1 = db.add_device_technology('x10', 'x10', 'desc dt1') dty1 = db.add_device_type(dty_id='x10.switch', dty_name='x10 Switch', dty_description='desc1', dt_id=dt1.id) du1 = db.add_device_usage('du1_id', 'du1') du2 = db.add_device_usage('du2_id', 'du2') device1 = db.add_device(d_name='device1', d_address='A1', d_type_id=dty1.id, d_usage_id=du1.id, d_description='desc1') device2 = db.add_device(d_name='device2', d_address='A2', d_type_id=dty1.id, d_usage_id=du1.id, d_description='desc1') db.add_device_stat(make_ts(2010, 04, 9, 12, 0), 'val2', 1, device2.id) db.add_device_stat(make_ts(2010, 04, 9, 12, 1), 'val1', 2, device2.id) assert len(db.list_device_stats(device2.id)) == 2 device3 = db.add_device(d_name='device3', d_address='A3', d_type_id=dty1.id, d_usage_id=du1.id) device_del = device2 device2_id = device2.id db.del_device(device2.id) # Check cascade deletion assert len(db.list_device_stats(device2.id)) == 0 assert len(db.list_devices()) == 2 for dev in db.list_devices(): assert dev.address in ('A1', 'A3') assert device_del.id == device2.id try: db.del_device(12345678910) TestCase.fail(self, "Device does not exist, an exception should have been raised") except DbHelperException: pass
def check(put: unittest.TestCase, arrangement: Arrangement, expectation: Expectation): actor = ActorThatRecordsSteps( arrangement.test_case_generator.recorder, arrangement.actor) def action(std_files: StdOutputFiles) -> PartialExeResult: exe_conf = ExecutionConfiguration(dict(os.environ), DEFAULT_ATC_OS_PROCESS_EXECUTOR, sandbox_root_name_resolver.for_test(), exe_atc_and_skip_assertions=std_files) with home_directory_structure() as hds: conf_phase_values = ConfPhaseValues(actor, hds, timeout_in_seconds=arrangement.timeout_in_seconds) return sut.execute(arrangement.test_case_generator.test_case, exe_conf, conf_phase_values, setup.default_settings(), False, ) out_files, partial_result = capture_stdout_err(action) expectation.result.apply_with_message(put, partial_result, 'partial result') put.assertEqual(expectation.step_recordings, arrangement.test_case_generator.recorder.recorded_elements, 'steps') expectation.atc_stdout_output.apply_with_message(put, out_files.out, 'stdout') expectation.atc_stderr_output.apply_with_message(put, out_files.err, 'stderr')
def __init__(self, method='runTest'): TestCase.__init__(self, method) self.method = method self.pdb_script = None self.fnull = None self.debugger = None self.netbeans_port = 3219
def test_del(self): person1 = db.add_person(p_first_name='Marc', p_last_name='SCHNEIDER', p_birthdate=datetime.date(1973, 4, 24)) person2 = db.add_person(p_first_name='Monthy', p_last_name='PYTHON', p_birthdate=datetime.date(1981, 4, 24)) person3 = db.add_person(p_first_name='Alberto', p_last_name='MATE', p_birthdate=datetime.date(1947, 8, 6)) user1 = db.add_user_account(a_login='******', a_password='******', a_person_id=person1.id) user2 = db.add_user_account(a_login='******', a_password='******', a_person_id=person2.id) user3 = db.add_user_account(a_login='******', a_password='******', a_person_id=person3.id) user3_id = user3.id user_acc_del = db.del_user_account(user3.id) assert user_acc_del.id == user3_id assert len(db.list_persons()) == 3 l_user = db.list_user_accounts() assert len(l_user) == 2 for user in l_user: assert user.login != 'domo' person1_id = person1.id person_del = db.del_person(person1.id) assert person_del.id == person1_id assert len(db.list_persons()) == 2 assert len(db.list_user_accounts()) == 1 try: db.del_person(12345678910) TestCase.fail(self, "Person does not exist, an exception should have been raised") except DbHelperException: pass try: db.del_user_account(12345678910) TestCase.fail(self, "User account does not exist, an exception should have been raised") except DbHelperException: pass
def setUp(self): TestCase.setUp(self) self.root = "/tmp/lstestdir/" self.link_file_src = "/tmp/mylink.txt" self.date_string = self.todays_date() self.remove_folder_structure() self.create_folder_structure()
def _check_existence(self, put: unittest.TestCase, actual: DirDependentValue, message_builder: asrt.MessageBuilder): put.assertEqual(self._expected.exists_pre_sds(), actual.exists_pre_sds(), message_builder.apply('exists_pre_sds'))
def __init__(self, *args, **kwargs): """Pass in TargetingComputer values.""" super(TargetingComputerTests, self).__init__(STATS.ACCURACY, Shields.BASE_VALUE, Shields.BOOST_MOD, TargetingComputer) TestCase.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): """Pass in Engines values.""" super(EnginesTests, self).__init__(STATS.WARP, Shields.BASE_VALUE, Shields.BOOST_MOD, Engines) TestCase.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): """Pass in Shields values.""" super(ShieldsTests, self).__init__(STATS.SHIELD, Shields.BASE_VALUE, Shields.BOOST_MOD, Shields) TestCase.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): """Pass in LifeSupport values.""" super(LifeSupportTests, self).__init__(STATS.LS_CHARGE, LifeSupport.BASE_VALUE, LifeSupport.BOOST_MOD, LifeSupport) TestCase.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): """Pass in Cockpit values.""" super(CockpitTests, self).__init__(STATS.DODGE, Cockpit.BASE_VALUE, Cockpit.BOOST_MOD, Cockpit) TestCase.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): """Pass in AutoTurret values.""" super(AutoTurretTests, self).__init__(STATS.ATTACK_POWER, AutoTurret.BASE_VALUE, AutoTurret.BOOST_MOD, AutoTurret) TestCase.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs): """Pass in Maintenance values.""" super(MaintenanceTests, self).__init__(STATS.HULL_HEALTH, Shields.BASE_VALUE, Shields.BOOST_MOD, Maintenance) TestCase.__init__(self, *args, **kwargs)
def f(test_case: unittest.TestCase): solution = s() test_case.assertIsNotNone(solution.VERIFIED_ANSWER) test_case.assertEqual(solution.VERIFIED_ANSWER, solution.get_answer())
def __init__(self, *args, **kwargs): TestCase.__init__(self, *args, **kwargs) registry = Comparison.register() for k, v in registry.items(): self.addTypeEqualityFunc(k, v)
def __init__(self, *args, **kwargs): """Pass in TractorBeam values.""" super(TractorBeamTests, self).__init__(STATS.INTERCEPT, Shields.BASE_VALUE, Shields.BOOST_MOD, TractorBeam) TestCase.__init__(self, *args, **kwargs)
notes_letter = ['A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab'] def transponse_note(note, interval): if note in notes_sharps: current_notation = notes_sharps else: current_notation = notes_letter i = current_notation.index(note) l = len(current_notation) return notes_sharps[(i + interval + l) % l] def transpose(song, interval): return [transponse_note(note, interval) for note in song] test = TestCase() inp = ['A'] out = transpose(inp, 1) ans = ['A#'] test.assertEqual(out, ans, "Input: {}, 1".format(inp)) inp = ['Bb', 'C#', 'E'] out = transpose(inp, -4) ans = ['F#', 'A', 'C'] test.assertEqual(out, ans, "Input: {}, -4".format(inp)) # inp = ['C', 'C', 'C#', 'D', 'F', 'D', 'F', 'D', 'D', 'C#', 'C', 'G', 'C', 'C'] out = transpose(inp, 4) ans = ['E', 'E', 'F', 'F#', 'A', 'F#', 'A', 'F#', 'F#', 'F', 'E', 'B', 'E', 'E'] test.assertEqual(out, ans, "Input: {}, 4".format(inp))
def __len__(self): return len(self.data) def __repr__(self): return repr(self.data) # In[17]: # (1 point) from unittest import TestCase import random tc = TestCase() h = Heap() random.seed(0) for _ in range(10): h.add(random.randrange(100)) tc.assertEqual(h.data, [97, 61, 65, 49, 51, 53, 62, 5, 38, 33]) # In[18]: # (1 point) from unittest import TestCase import random
def setUp(self): TestCase.setUp(self) self.obj = Comic('comic_test', 'comic_dir') self.page = Page(None, 'page_title_1', 1)
) __all__ = [ "assert_raises", "assert_raises_regexp", "assert_array_equal", "assert_almost_equal", "assert_array_almost_equal", "assert_array_less", "assert_approx_equal", "assert_allclose", "assert_run_python_script", "SkipTest", ] _dummy = TestCase("__init__") assert_raises = _dummy.assertRaises SkipTest = unittest.case.SkipTest assert_dict_equal = _dummy.assertDictEqual assert_raises_regex = _dummy.assertRaisesRegex # assert_raises_regexp is deprecated in Python 3.4 in favor of # assert_raises_regex but lets keep the backward compat in scikit-learn with # the old name for now assert_raises_regexp = assert_raises_regex # TODO: Remove in 1.2 @deprecated( # type: ignore "`assert_warns` is deprecated in 1.0 and will be removed in 1.2." "Use `pytest.warns` instead.")
def test_case_5(): test_log("testing queries") # (10 points) test queries tc = TestCase() lst = ArrayList() tc.assertEqual(0, len(lst)) tc.assertEqual(0, lst.count(1)) with tc.assertRaises(ValueError): lst.index(1) import random data = [random.randrange(1000) for _ in range(100)] lst.data = ConstrainedList.create(data) lst.len = len(lst.data) tc.assertEqual(100, len(lst)) tc.assertEqual(min(data), lst.min()) tc.assertEqual(max(data), lst.max()) for x in data: tc.assertEqual(data.index(x), lst.index(x)) tc.assertEqual(data.count(x), lst.count(x)) with tc.assertRaises(ValueError): lst.index(1000) lst.data = ConstrainedList.create([1, 2, 1, 2, 1, 1, 1, 2, 1]) lst.len = len(lst.data) tc.assertEqual(1, lst.index(2)) tc.assertEqual(1, lst.index(2, 1)) tc.assertEqual(3, lst.index(2, 2)) tc.assertEqual(7, lst.index(2, 4)) tc.assertEqual(7, lst.index(2, 4, -1)) with tc.assertRaises(ValueError): lst.index(2, 4, -2) suc()
data = """Rome:Jan 81.2,Feb 63.2,Mar 70.3,Apr 55.7,May 53.0,Jun 36.4,Jul 17.5,Aug 27.5,Sep 60.9,Oct 117.7,Nov 111.0,Dec 97.9 London:Jan 48.0,Feb 38.9,Mar 39.9,Apr 42.2,May 47.3,Jun 52.1,Jul 59.5,Aug 57.2,Sep 55.4,Oct 62.0,Nov 59.0,Dec 52.9 Paris:Jan 182.3,Feb 120.6,Mar 158.1,Apr 204.9,May 323.1,Jun 300.5,Jul 236.8,Aug 192.9,Sep 66.3,Oct 63.3,Nov 83.2,Dec 154.7 NY:Jan 108.7,Feb 101.8,Mar 131.9,Apr 93.5,May 98.8,Jun 93.6,Jul 102.2,Aug 131.8,Sep 92.0,Oct 82.3,Nov 107.8,Dec 94.2 Vancouver:Jan 145.7,Feb 121.4,Mar 102.3,Apr 69.2,May 55.8,Jun 47.1,Jul 31.3,Aug 37.0,Sep 59.6,Oct 116.3,Nov 154.6,Dec 171.5 Sydney:Jan 103.4,Feb 111.0,Mar 131.3,Apr 129.7,May 123.0,Jun 129.2,Jul 102.8,Aug 80.3,Sep 69.3,Oct 82.6,Nov 81.4,Dec 78.2 Bangkok:Jan 10.6,Feb 28.2,Mar 30.7,Apr 71.8,May 189.4,Jun 151.7,Jul 158.2,Aug 187.0,Sep 319.9,Oct 230.8,Nov 57.3,Dec 9.4 Tokyo:Jan 49.9,Feb 71.5,Mar 106.4,Apr 129.2,May 144.0,Jun 176.0,Jul 135.6,Aug 148.5,Sep 216.4,Oct 194.1,Nov 95.6,Dec 54.4 Beijing:Jan 3.9,Feb 4.7,Mar 8.2,Apr 18.4,May 33.0,Jun 78.1,Jul 224.3,Aug 170.0,Sep 58.4,Oct 18.0,Nov 9.3,Dec 2.7 Lima:Jan 1.2,Feb 0.9,Mar 0.7,Apr 0.4,May 0.6,Jun 1.8,Jul 4.4,Aug 3.1,Sep 3.3,Oct 1.7,Nov 0.5,Dec 0.7""" data1 = """Rome:Jan 90.2,Feb 73.2,Mar 80.3,Apr 55.7,May 53.0,Jun 36.4,Jul 17.5,Aug 27.5,Sep 60.9,Oct 147.7,Nov 121.0,Dec 97.9 London:Jan 58.0,Feb 38.9,Mar 49.9,Apr 42.2,May 67.3,Jun 52.1,Jul 59.5,Aug 77.2,Sep 55.4,Oct 62.0,Nov 69.0,Dec 52.9 Paris:Jan 182.3,Feb 120.6,Mar 188.1,Apr 204.9,May 323.1,Jun 350.5,Jul 336.8,Aug 192.9,Sep 66.3,Oct 63.3,Nov 83.2,Dec 154.7 NY:Jan 128.7,Feb 121.8,Mar 151.9,Apr 93.5,May 98.8,Jun 93.6,Jul 142.2,Aug 131.8,Sep 92.0,Oct 82.3,Nov 107.8,Dec 94.2 Vancouver:Jan 155.7,Feb 121.4,Mar 132.3,Apr 69.2,May 85.8,Jun 47.1,Jul 31.3,Aug 37.0,Sep 69.6,Oct 116.3,Nov 154.6,Dec 171.5 Sydney:Jan 123.4,Feb 111.0,Mar 151.3,Apr 129.7,May 123.0,Jun 159.2,Jul 102.8,Aug 90.3,Sep 69.3,Oct 82.6,Nov 81.4,Dec 78.2 Bangkok:Jan 20.6,Feb 28.2,Mar 40.7,Apr 81.8,May 189.4,Jun 151.7,Jul 198.2,Aug 197.0,Sep 319.9,Oct 230.8,Nov 57.3,Dec 9.4 Tokyo:Jan 59.9,Feb 81.5,Mar 106.4,Apr 139.2,May 144.0,Jun 186.0,Jul 155.6,Aug 148.5,Sep 216.4,Oct 194.1,Nov 95.6,Dec 54.4 Beijing:Jan 13.9,Feb 14.7,Mar 18.2,Apr 18.4,May 43.0,Jun 88.1,Jul 224.3,Aug 170.0,Sep 58.4,Oct 38.0,Nov 19.3,Dec 2.7 Lima:Jan 11.2,Feb 10.9,Mar 10.7,Apr 10.4,May 10.6,Jun 11.8,Jul 14.4,Aug 13.1,Sep 23.3,Oct 1.7,Nov 0.5,Dec 10.7""" TestCase().assertEqual(mean("London", data), 51.199999999999996) TestCase().assertEqual(mean("Beijing", data), 52.416666666666664) TestCase().assertEqual(variance("Ln", data), 57.42833333333374) TestCase().assertEqual(variance("Beijing", data), 4808.37138888889)
def test_case_3(): test_log("testing single-element manipulation ") tc = TestCase() lst = ArrayList() data = [] for _ in range(100): to_add = random.randrange(1000) data.append(to_add) lst.append(to_add) tc.assertIsInstance(lst.data, ConstrainedList) tc.assertEqual(data, arrayListToList(lst)) for _ in range(100): to_ins = random.randrange(1000) ins_idx = random.randrange(len(data) + 1) data.insert(ins_idx, to_ins) lst.insert(ins_idx, to_ins) tc.assertEqual(data, arrayListToList(lst)) for _ in range(100): pop_idx = random.randrange(len(data)) tc.assertEqual(data.pop(pop_idx), lst.pop(pop_idx)) tc.assertEqual(data, arrayListToList(lst)) for _ in range(25): to_rem = data[random.randrange(len(data))] data.remove(to_rem) lst.remove(to_rem) tc.assertEqual(data, arrayListToList(lst)) with tc.assertRaises(ValueError): lst.remove(9999) suc()
def test_case_6(): test_log("testing bulk operations") tc = TestCase() lst = ArrayList() lst2 = ArrayList() lst3 = lst + lst2 tc.assertIsInstance(lst3, ArrayList) tc.assertEqual([], arrayListToList(lst3)) data = [random.randrange(1000) for _ in range(50)] data2 = [random.randrange(1000) for _ in range(50)] lst.data = ConstrainedList.create(data) lst.len = len(lst.data) lst2.data = ConstrainedList.create(data2) lst2.len = len(lst.data) lst3 = lst + lst2 tc.assertEqual(100, len(lst3)) tc.assertEqual(data + data2, arrayListToList(lst3)) lst.clear() tc.assertEqual([], arrayListToList(lst)) lst.data = ConstrainedList.create( [random.randrange(1000) for _ in range(50)]) lst2 = lst.copy() tc.assertIsNot(lst, lst2) tc.assertIsNot(lst.data, lst2.data) tc.assertEqual(arrayListToList(lst), arrayListToList(lst2)) lst.clear() lst.extend(range(10)) lst.extend(range(10, 0, -1)) lst.extend(data.copy()) tc.assertEqual(70, len(lst)) tc.assertEqual( list(range(10)) + list(range(10, 0, -1)) + data, arrayListToList(lst)) suc()
def test_case_1(): test_log("testing subscript-based acess ") tc = TestCase() lst = ArrayList() data = [1, 2, 3, 4] lst.data = ConstrainedList.create(data) lst.len = len(lst.data) for i in range(len(data)): tc.assertEqual(lst[i], data[i]) with tc.assertRaises(IndexError): x = lst[100] with tc.assertRaises(IndexError): lst[100] = 0 with tc.assertRaises(IndexError): del lst[100] lst[1] = data[1] = 20 del data[0] del lst[0] for i in range(len(data)): tc.assertEqual(lst[i], data[i]) data = [random.randint(1, 100) for _ in range(100)] lst.data = ConstrainedList.create(data) lst.len = len(lst.data) for i in range(len(data)): lst[i] = data[i] = random.randint(101, 200) for i in range(50): to_del = random.randrange(len(data)) del lst[to_del] del data[to_del] for i in range(len(data)): tc.assertEqual(lst[i], data[i]) for i in range(0, -len(data), -1): tc.assertEqual(lst[i], data[i]) suc()
def test_case_4(): test_log("testing predicates") tc = TestCase() lst = ArrayList() lst2 = ArrayList() lst.data = ConstrainedList.create([]) lst.len = len(lst.data) lst2.data = ConstrainedList.create([1, 2, 3]) lst2.len = len(lst2.data) tc.assertNotEqual(lst, lst2) lst.data = ConstrainedList.create([1, 2, 3]) lst.len = len(lst.data) tc.assertEqual(lst, lst2) lst.data = ConstrainedList.create([]) lst.len = len(lst.data) tc.assertFalse(1 in lst) tc.assertFalse(None in lst) lst.data = ConstrainedList.create(range(100)) lst.len = len(lst.data) tc.assertFalse(100 in lst) tc.assertTrue(50 in lst) suc()
def tearDown(self): TestCase.tearDown(self) self.rotatingFile.removeAllFiles() self.rotatingFile.scanDirectory() self.assertEqual(len(self.rotatingFile), 0)
def test_case_2(): # (4 points) test stringification test_log("test stringification ") tc = TestCase() lst = ArrayList() tc.assertIsInstance(lst.data, ConstrainedList) tc.assertEqual('[]', str(lst)) tc.assertEqual('[]', repr(lst)) lst.data = ConstrainedList.create([1]) lst.len = len(lst.data) tc.assertEqual('[1]', str(lst)) tc.assertEqual('[1]', repr(lst)) lst.data = ConstrainedList.create([10, 20, 30, 40, 50]) lst.len = len(lst.data) tc.assertEqual('[10, 20, 30, 40, 50]', str(lst)) tc.assertEqual('[10, 20, 30, 40, 50]', repr(lst)) suc()
def dfs(startings, graph, frm): if frm in startings or frm not in graph: return for to in graph[frm]: if graph[frm][to] == '': startings.add(frm) graph[frm][to] = 'T' if parent[to] == to: parent[to] = parent[frm] dfs(startings, graph, to) if to in startings: startings.remove(to) startings = set() for frm in graph: dfs(startings, graph, frm) return list(startings) if __name__ == '__main__': t = TestCase() s = Solution() t.assertCountEqual([0, 3], s.findSmallestSetOfVertices( 6, [[0, 1], [0, 2], [2, 5], [3, 4], [4, 2]])) t.assertCountEqual([0, 2, 3], s.findSmallestSetOfVertices( 5, [[0, 1], [2, 1], [3, 1], [1, 4], [2, 4]])) print('OK!')
def setUp(self): TestCase.setUp(self) self.meses = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
def assertContainsErrorIDs(test_class: unittest.TestCase, ids: List[str], verification_result: VerificationResult): for id in ids: test_class.assertTrue( any(error['id'] == id for error in verification_result.errors))
def setUp(self): TestCase.setUp(self) self.rotatingFile = RotatingFile(".\\", "test", "txt", 3)
def setUp(self): TestCase.setUp(self)
# -*- coding: utf-8 -*- import os.path as path from unittest import TestCase from server_support import server, H from amara.thirdparty import json DIR_FIXTURES = path.join(path.abspath(path.split(__file__)[0]), 'fixtures') # http://stackoverflow.com/questions/18084476/is-there-a-way-to-use-python-unit-test-assertions-outside-of-a-testcase TC = TestCase('__init__') def _get_server_response(body): url = server() + "dpla_mapper?mapper_type=pspl_oai_dc" return H.request(url, "POST", body=body) def test_pspl_oai_dc_mapping(): fixture = path.join(DIR_FIXTURES, 'pspl-oai.json') with open(fixture) as f: INPUT = f.read() TC.assertIn('id', INPUT) resp, content = _get_server_response(INPUT) TC.assertEqual(resp.status, 200) obj = json.loads(content) TC.assertIn('sourceResource', obj) TC.assertIn('originalRecord', obj) TC.assertEqual( obj['isShownAt'], "http://collections.accessingthepast.org/cgi-bin/palmsprings?a=d&d=Amistad1969" )
def __init__(self, *args, **kwargs): wsgiapp = pylons.test.pylonsapp config = wsgiapp.config self.app = TestApp(wsgiapp) url._push_object(URLGenerator(config["routes.map"], environ)) TestCase.__init__(self, *args, **kwargs)
def assertIsVerified(test_class: unittest.TestCase, verification_result: VerificationResult): test_class.assertTrue(verification_result.is_verified)