def test_queries(): say_test("test_queries") tc = TestCase() lst = LinkedList() 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)] for d in data: lst.append(d) 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 = LinkedList() for d in (1, 2, 1, 2, 1, 1, 1, 2, 1): lst.append(d) 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)
def test_corner_cases(): tc = TestCase() t = HBStree() # insert multiple times for i in range(0, 10, 2): for j in range(0, 3): t.insert(i) tc.assertEqual(t.num_versions(), len(range(0, 10, 2)) + 1) t = HBStree() for i in range(0, 5): t.insert(3 * i) for i in range(0, 5): t.delete(0) tc.assertEqual(t.num_versions(), len(range(0, 5)) + 2) with tc.assertRaises(KeyError): t[0] with tc.assertRaises(IndexError): it = t.version_iter(-1) next(it) with tc.assertRaises(IndexError): it = t.version_iter(10) next(it)
def _test_pairplot_with_gmm_inputs(caller: unittest.TestCase, **kws): X = np.random.rand(15, 3) gmm = GaussianMixture(n_components=3, **kws).fit(X) labels = ["A"] * 5 + ["B"] * 5 + ["C"] * 5 # test data with caller.assertRaises(ValueError): pairplot_with_gmm(X="test", gmm=gmm) with caller.assertRaises(ValueError): pairplot_with_gmm(X=X, gmm=gmm, labels=["A"]) with caller.assertRaises(NameError): pairplot_with_gmm(X, gmm=None)
def test_unsign_signed_blob(): blob = '123456,012345:1imRQe:bYOCLk1ZS18trP34EnE8Ph5ykFI' with freeze_time('2020-01-01') as freezer: # bad with TestCase.assertRaises(None, APIException): unsign_signed_blob('.' + blob, 1) # good impressions = unsign_signed_blob(blob, 1).split(',') assert impressions == ['123456', '012345'] # good, but now stale freezer.tick(delta=timedelta(seconds=61)) with TestCase.assertRaises(None, APIException): unsign_signed_blob(blob, 60)
def test_light_one_bad_colour(self): """Test it throws an exception with a bad colour.""" with TestCase.assertRaises(self, KeyError) as context: self.lights.light_one(10, 'maroon') assert str(context.exception) == "'maroon'" assert self.lights.pixels[10] == (0, 0, 0)
def test_get_duplicate_key(self, api_object): start_time, end_time = self._get_start_end_times() tester = TestCase() with tester.assertRaises(KeyError): api_object.get(start_time=start_time, startTime=start_time, endTime=end_time)
def _assert_parse_raises(put: unittest.TestCase, files_condition: FilesConditionArg): for case in FULL_AND_NON_FULL_CASES: source = case.arguments_for_fc(files_condition).as_remaining_source with put.subTest(case.name): with put.assertRaises(SingleInstructionInvalidArgumentException): sut.parsers().full.parse(source)
def test_start_diagnostics_job_error(mock_uuid): responses.add( responses.PUT, 'http://leader.mesos/system/health/v1/diagnostics/f053c58c-b9ce-11e9-8c5b-38d54714bf36', json={ 'code': 507, 'error': 'could not create bundle f053c58c-b9ce-11e9-8c5b-38d54714bf36 workdir', }, status=507) args = dcos_api.DcosApiSession.get_args_from_env() dcos_api_session = dcos_api.DcosApiSession(**args) health_url = dcos_api_session.default_url.copy(path='system/health/v1', ) diagnostics = Diagnostics( default_url=health_url, masters=[], all_slaves=[], session=dcos_api_session.copy().session, ) with TestCase.assertRaises(TestCase(), HTTPError): response = diagnostics.start_diagnostics_job() check_json(response)
def test002_set_password(password): """TC565 Test case for getting redis client with/without password. **Test scenario** #. Start redis server on unixsocket with password. #. Try to get redis client with/without password, should succeed/fail. """ info("Start redis server on unixsocket with password.") start_redis_server(password=True) wait_for_server() info(f"Try to get redis client with password={password}") name = rand_string() if password: redis_client = j.clients.redis_config.get(name=name, unixsocket="/tmp/redis.sock", port=0, addr=None, secret_="test") cl = redis_client.redis assert cl.ping() else: redis_client = j.clients.redis_config.get(name=name, unixsocket="/tmp/redis.sock", port=0, addr=None) t = TestCase() with t.assertRaises((ResponseError, AuthenticationError)) as e: cl = redis_client.redis assert "Authentication required" in e.exception.args[0]
def test_queue_implementation_2(): tc = TestCase() q = Queue(10) for i in range(6): q.enqueue(i) tc.assertEqual(q.data.count(None), 4) for i in range(5): q.dequeue() tc.assertFalse(q.empty()) tc.assertEqual(q.data.count(None), 9) tc.assertEqual(q.head, q.tail) tc.assertEqual(q.head, 5) for i in range(9): q.enqueue(i) with tc.assertRaises(RuntimeError): q.enqueue(10) for x, y in zip(q, [5] + list(range(9))): tc.assertEqual(x, y) tc.assertEqual(q.dequeue(), 5) for i in range(9): tc.assertEqual(q.dequeue(), i) tc.assertTrue(q.empty())
def test_queue_implementation_3(): tc = TestCase() q = Queue(5) for i in range(5): q.enqueue(i) for i in range(4): q.dequeue() for i in range(5, 9): q.enqueue(i) with tc.assertRaises(RuntimeError): q.enqueue(10) q.resize(10) for x, y in zip(q, range(4, 9)): tc.assertEqual(x, y) for i in range(9, 14): q.enqueue(i) for i in range(4, 14): tc.assertEqual(q.dequeue(), i) tc.assertTrue(q.empty()) tc.assertEqual(q.head, -1)
def test_single_element_manipulation(): say_test("test_single_element_manipulation") tc = TestCase() lst = LinkedList() data = [] 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) for i in range(100): tc.assertEqual(data[i], lst[i]) for _ in range(50): pop_idx = random.randrange(len(data)) tc.assertEqual(data.pop(pop_idx), lst.pop(pop_idx)) for i in range(50): tc.assertEqual(data[i], lst[i]) for _ in range(25): to_rem = data[random.randrange(len(data))] data.remove(to_rem) lst.remove(to_rem) for i in range(25): tc.assertEqual(data[i], lst[i]) with tc.assertRaises(ValueError): lst.remove(9999)
def test_light_all_bad_colour(self): """Test it throws an exception with a bad colour.""" with TestCase.assertRaises(self, KeyError) as context: self.lights.light_all('violet') assert str(context.exception) == "'violet'" assert all(x == (0, 0, 0) for x in self.lights.pixels)
def check_and_expect_exception(put: unittest.TestCase, arrangement: Arrangement, expected_exception: ValueAssertion[Exception]): with tmp_dir_as_cwd(arrangement.cwd_dir_contents): with put.assertRaises(Exception) as cm: # ACT & ASSERT # sut.parse(arrangement.sections_configuration, arrangement.root_file) expected_exception.apply_with_message(put, cm.exception, 'Exception')
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]) ## check if this is the correct test case pass suc()
def test_subscript_access(): say_test("test_subscript_access") tc = TestCase() data = [1, 2, 3, 4] lst = LinkedList() for d in data: lst.append(d) 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 = LinkedList() for d in data: lst.append(d) 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])
def check_invalid_arguments( self, put: unittest.TestCase, invalid_source: ParseSource, ): with put.assertRaises(SingleInstructionInvalidArgumentException) as cx: self.parser.parse(ARBITRARY_FS_LOCATION_INFO, invalid_source) put.assertIsInstance(cx.exception.error_message, str, 'error message')
def test_getitem(): tc = TestCase() h = ExtensibleHashTable() for i in range(0,100): h[i] = i * 2 with tc.assertRaises(KeyError): h[200]
def _apply(self, put: unittest.TestCase, value: T, message_builder: MessageBuilder): with put.assertRaises(HardErrorException) as cx: self._method_that_should_raise(value) asrt_text_doc.is_any_text().apply( put, cx.exception.error, message_builder.for_sub_component('error message'), )
def test_light_many_bad_colour(self): """Test it throws an exception with a bad colour.""" data = ['red', 'red', 'green', 'azure', 'red'] with TestCase.assertRaises(self, KeyError) as context: self.lights.light_many(data) assert str(context.exception) == "'azure'" assert self.lights.pixels[0] == [0, 255, 0] assert self.lights.pixels[3] == (0, 0, 0)
def test_assertRaises_error(self): """Checks that an exception raised during the *setup* of assertRaises bubbles up correctly. Raises an exception when `savepoint()` calls `flush()` during setup. """ # ensure we catch the error with the "base" method to avoid any interference with mock.patch.object(BaseCursor, 'flush', side_effect=CustomError), \ TestCase.assertRaises(self, CustomError): with self.assertRaises(CustomError): raise NotImplementedError
def test_deletion(): tc = TestCase() h = ExtensibleHashTable(n_buckets=100000) random.seed(1234) keys = [ random.randint(0,1000000) for i in range(10) ] for k in keys: h[k] = 1 for k in keys: del h[k] tc.assertEqual(len(h), 0) with tc.assertRaises(KeyError): h[keys[0]] with tc.assertRaises(KeyError): h[keys[3]] with tc.assertRaises(KeyError): h[keys[5]]
def assert_invalid_board_parameters_should_raise_exception(create_board, row_count: int, column_count: int, expected_minimum_row_count: int, expected_minimum_column_count: int, test_case: TestCase): with test_case.assertRaises(InvalidBoard) as exception_context: create_board(row_count=row_count, column_count=column_count, observer=None) exception = exception_context.exception test_case.assertEqual(exception.requested_row_count, row_count) test_case.assertEqual(exception.requested_column_count, column_count) test_case.assertEqual(exception.minimum_row_count, expected_minimum_row_count) test_case.assertEqual(exception.minimum_column_count, expected_minimum_column_count)
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()
def check_fail__must_be_on_current_line( put: unittest.TestCase, parser_maker: ParserMaker, grammars: List[NameAndValue[Grammar]], cases_w_lines_after_empty_line: Sequence[NameAndValue[List[str]]], ): for grammar_case in grammars: parser = parser_maker.make(grammar_case.value, must_be_on_current_line=True) for case in cases_w_lines_after_empty_line: with put.subTest(grammar=grammar_case.name, case_name=case.name): source = remaining_source('', case.value) with put.assertRaises( SingleInstructionInvalidArgumentException): parser.parse(source)
def check(setup: Setup, put: unittest.TestCase): # ARRANGE # with tempfile.TemporaryDirectory(prefix=program_info.PROGRAM_NAME + '-test-') as tmp_dir: with preserved_cwd(): tmp_dir_path = resolved_path(tmp_dir) os.chdir(str(tmp_dir_path)) setup.file_structure_to_read().write_to(tmp_dir_path) # ACT & ASSERT # with put.assertRaises(Exception) as cm: # ACT # Reader(default_environment()).apply(setup.root_suite_based_at(tmp_dir_path)) # ASSERT # setup.check_exception(tmp_dir_path, cm.exception, put)
def check_invalid_syntax( self, put: unittest.TestCase, mk_source_variants: SourceStr2SourceVariants, source: AbstractSyntax, sub_test_identifiers: Mapping[str, Any] = MappingProxyType({}), ): for formatting_case in abs_stx_utils.formatting_cases( OptionallyOnNewLine(source)): for source_case in mk_source_variants(formatting_case.value): with put.subTest(zz_source_formatting=formatting_case.name, zz_source_variant=source_case.name, **sub_test_identifiers): with put.assertRaises( SingleInstructionInvalidArgumentException): self._parser.parse(source_case.source)
def check(setup: Setup, put: unittest.TestCase): # ARRANGE # with tempfile.TemporaryDirectory(prefix=program_info.PROGRAM_NAME + '-test-') as tmp_dir: with preserved_cwd(): tmp_dir_path = resolved_path(tmp_dir) os.chdir(str(tmp_dir_path)) setup.file_structure_to_read().write_to(tmp_dir_path) # ACT & ASSERT # with put.assertRaises(Exception) as cm: # ACT # Reader(default_environment()).apply( setup.root_suite_based_at(tmp_dir_path)) # ASSERT # setup.check_exception(tmp_dir_path, cm.exception, put)
def test_queue_implementation_1(): tc = TestCase() q = Queue(5) tc.assertEqual(q.data, [None] * 5) for i in range(5): q.enqueue(i) with tc.assertRaises(RuntimeError): q.enqueue(5) for i in range(5): tc.assertEqual(q.dequeue(), i) tc.assertTrue(q.empty())
def test_bulk_operations(): say_test("test_bulk_operations") tc = TestCase() lst = LinkedList() lst2 = LinkedList() lst3 = lst + lst2 tc.assertIsInstance(lst3, LinkedList) tc.assertEqual(0, len(lst3)) import random data = [random.randrange(1000) for _ in range(50)] data2 = [random.randrange(1000) for _ in range(50)] for d in data: lst.append(d) for d in data2: lst2.append(d) lst3 = lst + lst2 tc.assertEqual(100, len(lst3)) data3 = data + data2 for i in range(len(data3)): tc.assertEqual(data3[i], lst3[i]) lst.clear() tc.assertEqual(0, len(lst)) with tc.assertRaises(IndexError): lst[0] for d in data: lst.append(d) lst2 = lst.copy() tc.assertIsNot(lst, lst2) tc.assertIsNot(lst.head.next, lst2.head.next) for i in range(len(data)): tc.assertEqual(lst[i], lst2[i]) tc.assertEqual(lst, lst2) lst.clear() lst.extend(range(10)) lst.extend(range(10, 0, -1)) lst.extend(data.copy()) tc.assertEqual(70, len(lst)) data = list(range(10)) + list(range(10, 0, -1)) + data for i in range(len(data)): tc.assertEqual(data[i], lst[i])
def test_same_website_message(self): # Use a test cursor because retrying() does commit. self.env.registry.enter_test_mode(self.env.cr) self.addCleanup(self.env.registry.leave_test_mode) env = self.env(context={'lang': 'en_US'}, cr=self.env.registry.cursor()) def create_user_pou(): return new_test_user(env, login='******', website_id=self.website_1.id) # First user creation works. create_user_pou() # Second user creation fails with ValidationError instead of # IntegrityError. Do not use self.assertRaises as it would try # to create and rollback to a savepoint that is removed by the # rollback in retrying(). with TestCase.assertRaises(self, ValidationError), mute_logger('odoo.sql_db'): retrying(create_user_pou, env)
def check_fail__expr_on_following_line_is_accepted( put: unittest.TestCase, parser_maker: ParserMaker, grammars: List[NameAndValue[Grammar]], cases: Sequence[NameAndValue[str]]): for grammar_case in grammars: for case in cases: # Source is on first line for must_be_on_current_line in [False, True]: with put.subTest( grammar=grammar_case.name, case_name=case.name, source='is on first line', must_be_on_current_line=must_be_on_current_line): # ACT & ASSERT # parse_source = remaining_source_string(case.value) parser = parser_maker.make( grammar_case.value, must_be_on_current_line=must_be_on_current_line) with put.assertRaises( SingleInstructionInvalidArgumentException): parser.parse(parse_source)
def assert_raises_invalid_argument_exception( self, put: unittest.TestCase, source_string: str, test_name: str = '', path_suffix_is_required_cases: Sequence[bool] = (False, True), ): for path_suffix_is_required in path_suffix_is_required_cases: rel_opt_arg_conf = ARBITRARY_REL_OPT_ARG_CONF.config_for( path_suffix_is_required) for source_file_location in [None, Path('/source/file/location')]: with put.subTest( test_name=test_name, path_suffix_is_required=path_suffix_is_required, source_file_location=source_file_location): token_stream = TokenStream(source_string) with put.assertRaises( SingleInstructionInvalidArgumentException): sut.parse_path( token_stream, rel_opt_arg_conf, source_file_location=source_file_location)
def test_failure_when_fewer_than_25_rows_returned_from_nation(self, unused_sleep_mock): self.presto_client_mock.get_rows.return_value = [['master']] TestCase.assertRaises(self, RuntimeError, smoketest_presto, self.presto_client_mock, ['master'])
def test_failure_when_nodes_are_not_up(self, ensure_nodes_are_up_mock): TestCase.assertRaises(self, RuntimeError, smoketest_presto, self.presto_client_mock, ['master'])
def test_failure_when_catalogs_are_not_available(self, ensure_catalogs_are_available_mock, unused_sleep_mock): TestCase.assertRaises(self, RuntimeError, smoketest_presto, self.presto_client_mock, ['master'])
def test_invalid_multinode(self): # pylint: disable=too-many-locals user = self.factory.make_user() device_type = self.factory.make_device_type() submission = yaml.load(open( os.path.join(os.path.dirname(__file__), 'kvm-multinode.yaml'), 'r')) tag_list = [ self.factory.ensure_tag('usb-flash'), self.factory.ensure_tag('usb-eth') ] self.factory.make_device(device_type, 'fakeqemu1') self.factory.make_device(device_type, 'fakeqemu2') self.factory.make_device(device_type, 'fakeqemu3', tags=tag_list) deploy = [action['deploy'] for action in submission['actions'] if 'deploy' in action] # replace working image with a broken URL for block in deploy: block['images'] = { 'rootfs': { 'url': 'http://localhost/unknown/invalid.gz', 'image_arg': '{rootfs}' } } job_object_list = _pipeline_protocols(submission, user, yaml.dump(submission)) self.assertEqual(len(job_object_list), 2) self.assertEqual( job_object_list[0].sub_id, "%d.%d" % (int(job_object_list[0].id), 0)) # FIXME: dispatcher master needs to make this kind of test more accessible. for job in job_object_list: definition = yaml.load(job.definition) self.assertNotEqual(definition['protocols']['lava-multinode']['sub_id'], '') job.actual_device = Device.objects.get(hostname='fakeqemu1') job_def = yaml.load(job.definition) job_ctx = job_def.get('context', {}) parser = JobParser() device = None device_object = None if not job.dynamic_connection: device = job.actual_device try: device_config = device.load_device_configuration(job_ctx, system=False) # raw dict except (jinja2.TemplateError, yaml.YAMLError, IOError) as exc: # FIXME: report the exceptions as useful user messages self.fail("[%d] jinja2 error: %s" % (job.id, exc)) if not device_config or not isinstance(device_config, dict): # it is an error to have a pipeline device without a device dictionary as it will never get any jobs. msg = "Administrative error. Device '%s' has no device dictionary." % device.hostname self.fail('[%d] device-dictionary error: %s' % (job.id, msg)) device_object = PipelineDevice(device_config, device.hostname) # equivalent of the NewDevice in lava-dispatcher, without .yaml file. # FIXME: drop this nasty hack once 'target' is dropped as a parameter if 'target' not in device_object: device_object.target = device.hostname device_object['hostname'] = device.hostname validate_list = job.sub_jobs_list if job.is_multinode else [job] for check_job in validate_list: parser_device = None if job.dynamic_connection else device_object try: # pass (unused) output_dir just for validation as there is no zmq socket either. pipeline_job = parser.parse( check_job.definition, parser_device, check_job.id, None, None, None, output_dir=check_job.output_dir) except (AttributeError, JobError, NotImplementedError, KeyError, TypeError) as exc: self.fail('[%s] parser error: %s' % (check_job.sub_id, exc)) with TestCase.assertRaises(self, (JobError, InfrastructureError)) as check: pipeline_job.pipeline.validate_actions() check_missing_path(self, check, 'qemu-system-x86_64') for job in job_object_list: job = TestJob.objects.get(id=job.id) self.assertNotEqual(job.sub_id, '')
def test_failure_when_nodes_returned_dont_match_nodes_specified(self, unused_sleep_mock): self.presto_client_mock.get_rows.return_value = [['bad_host']] TestCase.assertRaises(self, RuntimeError, smoketest_presto, self.presto_client_mock, ['master'])
def assertRaises(*args, **kwargs): return TestCase.assertRaises(None, *args, **kwargs)