def test_extract_brackets_expression_2(self): dd: Optional[Dict[int, int]] = Calculator.extract_brackets_expression("aaaa(bb ccc)d(d)") expected = {4: 11, 13: 15} TestCase.assertDictEqual(self, expected, dd) pure = Calculator.purify_from_included_brackets(dd) TestCase.assertDictEqual(self, expected, pure)
def test_count_seqs_per_variant_type(self): import pandas as pd input_df = pd.DataFrame.from_dict({ 'id': ['sequence1', 'sequence2', 'sequence3', 'sequence4', 'sequence5'], 'variant_type': ['VT001', 'VT002', 'VT001', 'VT002', 'VT001'] }) d = {'variant_type': ['AT', 2], 'count': [3, 4], 'VT': [3, 4]} expected = pd.DataFrame(data=d) file_path = "" # assert_dict_equal(expected, my_func(input).to_dict(), "oops, there's a bug...") df1 = pd.DataFrame({'a': [1, 2, 3, 4, 5]}) df2 = pd.DataFrame({'a': [6, 7, 8, 9, 10]}) expected_res = pd.Series([7, 9, 11, 13, 15]) pd.testing.assert_series_equal((df1['a'] + df2['a']), expected_res, check_names=False) df_test = count_seqs_per_variant_type(input_df, file_path) TestCase.assertDictEqual( df_test, count_seqs_per_variant_type(input_df).to_dict(), "oops, there's a bug...")
def lambda_function_as_expected(test_case: unittest.TestCase, function_name: str, handler: str, state: str = 'Active', runtime: str = 'python3.8', memory_size: int = 128, timeout: int = 10, env_vars: dict = None) -> None: """ Test that an AWS Lambda function is configured as expected. :param test_case: Instance of a unittest test case. This object is used to make assertions. :param function_name: Name of the AWS Lambda function. :param handler: Handler method name (entrypoint to the AWS Lambda function). :param state: State of the lambda function. :param runtime: Runtime (programming language + version) used by the AWS Lambda function. :param memory_size: Amount of memory (in MBs) allocated for the AWS Lambda function. :param timeout: Maximum execution time for the AWS Lambda function. :param env_vars: A dictionary of environment variables created for the AWS Lambda function. """ lambda_function_response = aws_lambda.get_function(FunctionName=function_name) lambda_function: dict = lambda_function_response.get('Configuration') test_case.assertEqual(function_name, lambda_function.get('FunctionName')) test_case.assertEqual(state, lambda_function.get('State')) test_case.assertEqual(runtime, lambda_function.get('Runtime')) test_case.assertEqual(handler, lambda_function.get('Handler')) test_case.assertEqual(memory_size, lambda_function.get('MemorySize')) test_case.assertEqual(timeout, lambda_function.get('Timeout')) if env_vars is not None: test_case.assertDictEqual(env_vars, lambda_function.get('Environment').get('Variables'))
def test_extract_brackets_expression_1(self): dd: Optional[Dict[int, int]] = Calculator.extract_brackets_expression("aaaa(bb()()ccc)dd") expected = {4: 14, 7: 8, 9: 10} TestCase.assertDictEqual(self, expected, dd) pure = Calculator.purify_from_included_brackets(dd) TestCase.assertDictEqual(self, {4: 14}, pure)
def test_resolve_final_image_info(self, anchore_db): input_string = "anchore/test_images@sha256:2dceaabe73ee43341b0ab79aaa10f8d0c79b7866d9b4c31e1923a32e9cc4b586" session = get_thread_scoped_session() actual_image_info = catalog_impl.resolve_final_image_info( "admin", input_string, [], session, {}) test_case = TestCase() test_case.maxDiff = None test_case.assertDictEqual(self.expected_full_image_info, actual_image_info)
def compare(self, a, b): a = json.loads(a) b = json.loads(b) t = TestCase() t.maxDiff = None try: self.ttx += 1 t.assertDictEqual(a, b) except AssertionError as e: self.ptx += 1 print('[{} / {}] compared {} : FAILURE'.format(self.ptx, self.ttx, a['txid']))
def tmp_dir_is_correct_for_each_instruction( recordings: Dict[PhaseEnum, List[pathlib.Path]], num_instructions_per_phase: int, put: unittest.TestCase, actual: Result): sds = actual.sds def dirs_for_validation(phase: Phase) -> List[pathlib.Path]: file_space_factory = PhaseTmpFileSpaceFactory(sds.internal_tmp_dir) return [ file_space_factory.instruction__validation( phase, n).root_dir__may_not_exist for n in range(1, num_instructions_per_phase + 1) ] def dirs_for_main(phase: Phase) -> List[pathlib.Path]: file_space_factory = PhaseTmpFileSpaceFactory(sds.internal_tmp_dir) return [ file_space_factory.instruction__main(phase, n).root_dir__may_not_exist for n in range(1, num_instructions_per_phase + 1) ] def dirs_for_act() -> List[pathlib.Path]: space_factory__v = PhaseTmpFileSpaceFactory(sds.internal_tmp_dir) space_factory__m = PhaseTmpFileSpaceFactory(sds.internal_tmp_dir) return [ space_factory__v.for_phase__validation( phase_identifier.ACT).root_dir__may_not_exist, space_factory__m.for_phase__main( phase_identifier.ACT).root_dir__may_not_exist, space_factory__m.for_phase__main( phase_identifier.ACT).root_dir__may_not_exist, ] put.assertFalse(actual.partial_result.is_failure) expected = { PhaseEnum.SETUP: dirs_for_main(phase_identifier.SETUP) + dirs_for_validation(phase_identifier.SETUP), PhaseEnum.ACT: dirs_for_act(), PhaseEnum.BEFORE_ASSERT: dirs_for_validation(phase_identifier.BEFORE_ASSERT) + dirs_for_main(phase_identifier.BEFORE_ASSERT), PhaseEnum.ASSERT: dirs_for_validation(phase_identifier.ASSERT) + dirs_for_main(phase_identifier.ASSERT), PhaseEnum.CLEANUP: dirs_for_main(phase_identifier.CLEANUP), } put.assertDictEqual(expected, recordings, 'Tmp directory per phase')
def test_config_and_options_match(translations): config = translations["config"]["step"]["choose_entities"]["data"] options = translations["options"]["step"]["user"]["data"] # remove expected differences config.pop("name", None) options.pop("host", None) options.pop("local_key", None) test = TestCase() test.maxDiff = None test.assertDictEqual(config, options)
def log_dir_is_correct_for_each_phase(recordings: dict, put: unittest.TestCase, actual: Result): put.assertFalse(actual.partial_result.is_failure) sds = actual.sds expected = { PhaseEnum.SETUP: sds_log_phase_dir(sds, phase_identifier.SETUP.identifier), PhaseEnum.BEFORE_ASSERT: sds_log_phase_dir(sds, phase_identifier.BEFORE_ASSERT.identifier), PhaseEnum.ASSERT: sds_log_phase_dir(sds, phase_identifier.ASSERT.identifier), PhaseEnum.CLEANUP: sds_log_phase_dir(sds, phase_identifier.CLEANUP.identifier), } put.assertDictEqual(expected, recordings, 'Log directory per phase')
def compare_properties(self, schema): """Compares two schemas. The schema used to call the method will be the one we compare from, in advance 'source schema'. The schema passed as parameter will be the 'target schema'. Returns -- dictionary {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. """ test_case = TestCase('__init__') test_case.maxDiff = None status = 'OK' correct = [] missing = [] distinct = [] msg = '' for pname, pvalue in self.get_properties().items(): if pname not in schema.get_properties(): missing.append(pname) msg = msg + '\n' + '* Missing property: ' + pname status = 'KO' else: try: test_case.assertDictEqual(pvalue, schema.get_properties()[pname]) correct.append(pname) except AssertionError as e: distinct.append(pname) msg = "%s\n* Type mismatch: \n\t%s: %s" %\ (msg, pname, str(e).replace('\n', '\n\t')) status = 'KO' return { 'status': status, 'correct': correct, 'missing': missing, 'distinct': distinct, 'msg': msg }
def test_tensorboard_content(test: unittest.TestCase, output_dir: str, logs: Dict[str, Any], trainer): tb_data_handler = TensorBoardDataHandler(trainer.scenario.keras_train_model) from tensorflow.python.summary.summary_iterator import summary_iterator all_event_files = glob.glob(os.path.join(output_dir, "**", "events.out.*"), recursive=True) logs_to_find = logs.copy() def rename(s: str) -> str: return s.replace("@", "_") logs_to_find = {rename(k): v for k, v in logs_to_find.items()} for event_file in all_event_files: log_type = os.path.split(os.path.relpath(event_file, output_dir))[0] test.assertTrue(log_type in {"train", "validation"} or log_type.startswith("lav_")) def add_prefix(k: str): if log_type == "train": return k if log_type == "validation": return "val_" + k return log_type + "_" + k additional_outputs_per_event = set(tb_data_handler.tensorboard_handlers.keys()) if log_type in "train": additional_outputs_per_event.add("lr") # Check that (at least for step 0) all metrics/losses are written to the tensorboard log for e in summary_iterator(event_file): if e.step != 0: continue if len(e.summary.value) != 1: continue value = e.summary.value[0] if value.tag.startswith("epoch_") == 0: continue tag = value.tag[6:] # no epoch_ if tag in additional_outputs_per_event: additional_outputs_per_event.remove(tag) continue tag = add_prefix(tag) del logs_to_find[tag] test.assertSetEqual(set(), additional_outputs_per_event) test.assertDictEqual({}, logs_to_find)
def compare_properties(self, schema): """Compares two schemas. The schema used to call the method will be the one we compare from, in advance 'source schema'. The schema passed as parameter will be the 'target schema'. Returns -- dictionary {status, correct, missing, distinct, message} being: status 'OK' if all properties in source schema exist in target schema with same values. 'KO' in other case. correct: list of properties that matches. missing: list of properties missing from target schema. distinct: list of properties in both schemas but having with different values. message: a string with additional information. """ test_case = TestCase('__init__') test_case.maxDiff = None status = 'OK' correct = [] missing = [] distinct = [] msg = '' for pname, pvalue in self.get_properties().items(): if pname not in schema.get_properties(): missing.append(pname) msg = msg + '\n' + '* Missing property: ' + pname status = 'KO' else: try: test_case.assertDictEqual(pvalue, schema.get_properties()[pname]) correct.append(pname) except AssertionError as e: distinct.append(pname) msg = "%s\n* Type mismatch: \n\t%s: %s" %\ (msg, pname, str(e).replace('\n', '\n\t')) status = 'KO' return {'status': status, 'correct': correct, 'missing': missing, 'distinct': distinct, 'msg': msg}
def test_images(tmp_path: Path): statmap_path = tmp_path / "statmap.nii.gz" statmap_path.touch() result: ResultDict = { "tags": { "task": "faces", "feature": "taskBased1", "taskcontrast": "facesGtScrambled", "run": "07", "sub": "01", }, "images": { "variance": statmap_path, "effect": statmap_path, "mask": statmap_path, "dof": statmap_path, "z": statmap_path, }, "vals": { "dummy_scans": 0, }, "metadata": { "acquisition_orientation": "LAS", }, } save_images([result], tmp_path) index = BIDSIndex() index.put(tmp_path / "derivatives" / "halfpipe") (actual,) = load_images(index) test_case = TestCase() test_case.maxDiff = None test_case.assertDictEqual(result["tags"], actual["tags"]) test_case.assertDictEqual(result["vals"], actual["vals"]) test_case.assertDictEqual(result["metadata"], actual["metadata"]) assert result["images"].keys() == actual["images"].keys()
def test_test_draw(tmpdir, model, rescale): """Verify that the `test_draw` method works. This method checks that samples can be drawn from the flow and then resets the flows. This test makes sure the flow is correctly reset. """ output = tmpdir.mkdir('test') fp = FlowProposal(model, output=output, poolsize=100, rescale_parameters=rescale) fp.initialise() # Call these since they are worked out the first time they're called fp.x_dtype, fp.x_prime_dtype orig_state = fp.__getstate__() t = TestCase() t.maxDiff = None t.assertDictEqual(fp.__getstate__(), orig_state) fp.test_draw() t.assertDictEqual(fp.__getstate__(), orig_state)
def test_xml2dict(xml, to_lower, expected): tc = TestCase() tc.maxDiff = None tc.assertDictEqual(functions.xml2dict(xml, to_lower=to_lower), expected)
def test_get_full_profile_information_from_gdpr_api( rest_api_client, requests_mock, settings ): customer_profile = CustomerProfileFactory() boat = BoatFactory(owner=customer_profile) berth_application = BerthApplicationFactory(customer=customer_profile) berth_lease = BerthLeaseFactory( customer=customer_profile, boat=boat, status=LeaseStatus.PAID ) winter_storage_application = WinterStorageApplicationFactory( customer=customer_profile ) winter_storage_lease = WinterStorageLeaseFactory( customer=customer_profile, boat=boat ) order = OrderFactory(lease=berth_lease) berth_switch_offer = BerthSwitchOfferFactory( customer=customer_profile, lease=berth_lease ) organization = OrganizationFactory(customer=customer_profile) auth_header = get_api_token_for_user_with_scopes( customer_profile.user, [settings.GDPR_API_QUERY_SCOPE], requests_mock ) rest_api_client.credentials(HTTP_AUTHORIZATION=auth_header) response = rest_api_client.get( reverse("helsinki_gdpr:gdpr_v1", kwargs={"pk": customer_profile.id}) ) resp = json.loads(response.content) assert response.status_code == 200 assert { "key": "INVOICING_TYPE", "value": dict(InvoicingType.choices)[customer_profile.invoicing_type], } in resp["children"] assert {"key": "COMMENT", "value": customer_profile.comment} in resp["children"] assert { "key": "CREATED_AT", "value": customer_profile.created_at.strftime("%d-%m-%Y %H:%M:%S"), } in resp["children"] assert { "key": "MODIFIED_AT", "value": customer_profile.modified_at.strftime("%d-%m-%Y %H:%M:%S"), } in resp["children"] berth_applications_dict = {} berth_leases_dict = {} boats_dict = {} offers_dict = {} orders_dict = {} organization_dict = {} winter_storage_applications_dict = {} winter_storage_leases_dict = {} for child_dict in resp["children"]: if child_dict["key"] == "BERTH_APPLICATIONS": berth_applications_dict = child_dict elif child_dict["key"] == "BERTH_LEASES": berth_leases_dict = child_dict elif child_dict["key"] == "BOATS": boats_dict = child_dict elif child_dict["key"] == "OFFERS": offers_dict = child_dict elif child_dict["key"] == "ORDERS": orders_dict = child_dict elif child_dict["key"] == "ORGANIZATION": organization_dict = child_dict elif child_dict["key"] == "WINTER_STORAGE_APPLICATIONS": winter_storage_applications_dict = child_dict elif child_dict["key"] == "WINTER_STORAGE_LEASES": winter_storage_leases_dict = child_dict # Using a TestCase here since assertDictEqual is better for comparing dicts test_case = TestCase() test_case.assertDictEqual( { "key": "BERTH_APPLICATIONS", "children": [ { "key": "BERTHAPPLICATION", "children": [ {"key": "ID", "value": berth_application.id}, { "key": "CREATED_AT", "value": berth_application.created_at.strftime( "%d-%m-%Y %H:%M:%S" ), }, { "key": "STATUS", "value": dict(ApplicationStatus.choices)[ berth_application.status ], }, {"key": "LANGUAGE", "value": berth_application.language}, {"key": "FIRST_NAME", "value": berth_application.first_name}, {"key": "LAST_NAME", "value": berth_application.last_name}, {"key": "EMAIL", "value": berth_application.email}, { "key": "PHONE_NUMBER", "value": berth_application.phone_number, }, {"key": "ADDRESS", "value": berth_application.address}, {"key": "ZIP_CODE", "value": berth_application.zip_code}, { "key": "MUNICIPALITY", "value": berth_application.municipality, }, { "key": "COMPANY_NAME", "value": berth_application.company_name, }, {"key": "BUSINESS_ID", "value": berth_application.business_id}, {"key": "BOAT_TYPE", "value": berth_application.boat_type.name}, { "key": "BOAT_REGISTRATION_NUMBER", "value": berth_application.boat_registration_number, }, {"key": "BOAT_NAME", "value": berth_application.boat_name}, {"key": "BOAT_MODEL", "value": berth_application.boat_model}, { "key": "BOAT_LENGTH", "value": float(berth_application.boat_length), }, { "key": "BOAT_WIDTH", "value": float(berth_application.boat_width), }, { "key": "ACCEPT_BOATING_NEWSLETTER", "value": berth_application.accept_boating_newsletter, }, { "key": "ACCEPT_FITNESS_NEWS", "value": berth_application.accept_fitness_news, }, { "key": "ACCEPT_LIBRARY_NEWS", "value": berth_application.accept_library_news, }, { "key": "ACCEPT_OTHER_CULTURE_NEWS", "value": berth_application.accept_other_culture_news, }, { "key": "INFORMATION_ACCURACY_CONFIRMED", "value": berth_application.information_accuracy_confirmed, }, { "key": "APPLICATION_CODE", "value": berth_application.application_code, }, {"key": "HARBORCHOICE_SET", "value": []}, { "key": "BERTH_SWITCH", "value": berth_application.berth_switch, }, { "key": "BOAT_DRAUGHT", "value": berth_application.boat_draught, }, {"key": "BOAT_WEIGHT", "value": berth_application.boat_weight}, { "key": "ACCESSIBILITY_REQUIRED", "value": berth_application.accessibility_required, }, { "key": "BOAT_PROPULSION", "value": berth_application.boat_propulsion, }, { "key": "BOAT_HULL_MATERIAL", "value": berth_application.boat_hull_material, }, { "key": "BOAT_INTENDED_USE", "value": berth_application.boat_intended_use, }, { "key": "RENTING_PERIOD", "value": berth_application.renting_period, }, {"key": "RENT_FROM", "value": berth_application.rent_from}, {"key": "RENT_TILL", "value": berth_application.rent_till}, { "key": "BOAT_IS_INSPECTED", "value": berth_application.boat_is_inspected, }, { "key": "BOAT_IS_INSURED", "value": berth_application.boat_is_insured, }, { "key": "AGREE_TO_TERMS", "value": berth_application.agree_to_terms, }, ], } ], }, berth_applications_dict, ) test_case.assertDictEqual( { "key": "BERTH_LEASES", "children": [ { "key": "BERTHLEASE", "children": [ {"key": "ID", "value": str(berth_lease.id)}, {"key": "BOAT", "value": str(boat.id)}, { "key": "STATUS", "value": dict(LeaseStatus.choices)[berth_lease.status], }, {"key": "ORDERS", "value": [str(order.id)]}, {"key": "COMMENT", "value": berth_lease.comment}, { "key": "BERTH", "value": { "key": "BERTH", "children": [ { "key": "NUMBER", "value": berth_lease.berth.number, }, { "key": "PIER", "value": { "key": "PIER", "children": [ { "key": "IDENTIFIER", "value": berth_lease.berth.pier.identifier, } ], }, }, ], }, }, {"key": "APPLICATION", "value": None}, { "key": "START_DATE", "value": berth_lease.start_date.strftime("%d-%m-%Y"), }, { "key": "END_DATE", "value": berth_lease.end_date.strftime("%d-%m-%Y"), }, ], } ], }, berth_leases_dict, ) test_case.assertDictEqual( { "key": "BOATS", "children": [ { "key": "BOAT", "children": [ {"key": "ID", "value": str(boat.id)}, {"key": "CERTIFICATES", "children": []}, { "key": "REGISTRATION_NUMBER", "value": boat.registration_number, }, {"key": "LENGTH", "value": float(boat.length)}, {"key": "WIDTH", "value": float(boat.width)}, {"key": "DRAUGHT", "value": boat.draught}, ], } ], }, boats_dict, ) test_case.assertDictEqual( { "key": "OFFERS", "children": [ { "key": "BERTHSWITCHOFFER", "children": [ {"key": "ID", "value": str(berth_switch_offer.id)}, { "key": "STATUS", "value": dict(OfferStatus.choices)[ berth_switch_offer.status ], }, { "key": "DUE_DATE", "value": berth_switch_offer.due_date.strftime("%d-%m-%Y") if berth_switch_offer.due_date else None, }, { "key": "CUSTOMER_FIRST_NAME", "value": berth_switch_offer.customer_first_name, }, { "key": "CUSTOMER_LAST_NAME", "value": berth_switch_offer.customer_last_name, }, { "key": "CUSTOMER_EMAIL", "value": berth_switch_offer.customer_email, }, { "key": "CUSTOMER_PHONE", "value": berth_switch_offer.customer_phone, }, { "key": "APPLICATION", "value": berth_switch_offer.application.id, }, {"key": "LEASE", "value": str(berth_switch_offer.lease.id)}, {"key": "BERTH", "value": str(berth_switch_offer.berth.id)}, ], } ], }, offers_dict, ) test_case.assertDictEqual( { "key": "ORDERS", "children": [ { "key": "ORDER", "children": [ {"key": "ID", "value": str(order.id)}, { "key": "PRODUCT", "value": { "key": "BERTHPRODUCT", "children": [ { "key": "MIN_WIDTH", "value": float(order.product.min_width), }, { "key": "MAX_WIDTH", "value": float(order.product.max_width), }, { "key": "TIER_1_PRICE", "value": float(order.product.tier_1_price), }, { "key": "TIER_2_PRICE", "value": float(order.product.tier_2_price), }, { "key": "TIER_3_PRICE", "value": float(order.product.tier_3_price), }, { "key": "PRICE_UNIT", "value": order.product.price_unit, }, { "key": "TAX_PERCENTAGE", "value": float(order.product.tax_percentage), }, ], }, }, {"key": "LEASE", "value": str(order.lease.id)}, { "key": "STATUS", "value": dict(OrderStatus.choices)[order.status], }, {"key": "COMMENT", "value": order.comment}, {"key": "PRICE", "value": float(order.price)}, {"key": "TAX_PERCENTAGE", "value": float(order.tax_percentage)}, {"key": "PRETAX_PRICE", "value": float(order.pretax_price)}, {"key": "TOTAL_PRICE", "value": float(order.total_price)}, { "key": "TOTAL_PRETAX_PRICE", "value": float(order.total_pretax_price), }, { "key": "TOTAL_TAX_PERCENTAGE", "value": float(order.total_tax_percentage), }, { "key": "DUE_DATE", "value": order.due_date.strftime("%d-%m-%Y"), }, {"key": "ORDER_LINES", "children": []}, {"key": "LOG_ENTRIES", "children": []}, {"key": "PAID_AT", "value": None}, {"key": "CANCELLED_AT", "value": None}, {"key": "REJECTED_AT", "value": None}, ], } ], }, orders_dict, ) test_case.assertDictEqual( { "key": "ORGANIZATION", "children": [ {"key": "ID", "value": str(organization.id)}, {"key": "BUSINESS_ID", "value": organization.business_id}, {"key": "NAME", "value": organization.name}, {"key": "ADDRESS", "value": organization.address}, {"key": "POSTAL_CODE", "value": organization.postal_code}, {"key": "CITY", "value": organization.city}, ], }, organization_dict, ) test_case.assertDictEqual( { "key": "WINTER_STORAGE_APPLICATIONS", "children": [ { "key": "WINTERSTORAGEAPPLICATION", "children": [ {"key": "ID", "value": winter_storage_application.id}, { "key": "CREATED_AT", "value": winter_storage_application.created_at.strftime( "%d-%m-%Y %H:%M:%S" ), }, { "key": "STATUS", "value": dict(ApplicationStatus.choices)[ winter_storage_application.status ], }, { "key": "LANGUAGE", "value": winter_storage_application.language, }, { "key": "FIRST_NAME", "value": winter_storage_application.first_name, }, { "key": "LAST_NAME", "value": winter_storage_application.last_name, }, {"key": "EMAIL", "value": winter_storage_application.email}, { "key": "PHONE_NUMBER", "value": winter_storage_application.phone_number, }, {"key": "ADDRESS", "value": winter_storage_application.address}, { "key": "ZIP_CODE", "value": winter_storage_application.zip_code, }, { "key": "MUNICIPALITY", "value": winter_storage_application.municipality, }, {"key": "COMPANY_NAME", "value": ""}, {"key": "BUSINESS_ID", "value": ""}, { "key": "BOAT_TYPE", "value": winter_storage_application.boat_type.name, }, {"key": "BOAT_REGISTRATION_NUMBER", "value": ""}, {"key": "BOAT_NAME", "value": ""}, {"key": "BOAT_MODEL", "value": ""}, { "key": "BOAT_LENGTH", "value": float(winter_storage_application.boat_length), }, { "key": "BOAT_WIDTH", "value": float(winter_storage_application.boat_width), }, {"key": "ACCEPT_BOATING_NEWSLETTER", "value": False}, {"key": "ACCEPT_FITNESS_NEWS", "value": False}, {"key": "ACCEPT_LIBRARY_NEWS", "value": False}, {"key": "ACCEPT_OTHER_CULTURE_NEWS", "value": False}, {"key": "INFORMATION_ACCURACY_CONFIRMED", "value": False}, {"key": "APPLICATION_CODE", "value": ""}, {"key": "AREA_TYPE", "value": None}, {"key": "WINTERSTORAGEAREACHOICE_SET", "value": []}, { "key": "STORAGE_METHOD", "value": dict(WinterStorageMethod.choices)[ winter_storage_application.storage_method ], }, {"key": "TRAILER_REGISTRATION_NUMBER", "value": ""}, ], } ], }, winter_storage_applications_dict, ) test_case.assertDictEqual( { "key": "WINTER_STORAGE_LEASES", "children": [ { "key": "WINTERSTORAGELEASE", "children": [ {"key": "ID", "value": str(winter_storage_lease.id)}, {"key": "BOAT", "value": str(boat.id)}, { "key": "STATUS", "value": dict(LeaseStatus.choices)[ winter_storage_lease.status ], }, {"key": "ORDERS", "value": []}, {"key": "COMMENT", "value": winter_storage_lease.comment}, { "key": "PLACE", "value": { "key": "WINTERSTORAGEPLACE", "children": [ { "key": "NUMBER", "value": winter_storage_lease.place.number, }, { "key": "WINTER_STORAGE_SECTION", "value": { "key": "WINTERSTORAGESECTION", "children": [ { "key": "IDENTIFIER", "value": ( winter_storage_lease.place.winter_storage_section.identifier ), } ], }, }, ], }, }, {"key": "SECTION", "value": None}, {"key": "APPLICATION", "value": None}, { "key": "START_DATE", "value": winter_storage_lease.start_date.strftime( "%d-%m-%Y" ), }, { "key": "END_DATE", "value": winter_storage_lease.end_date.strftime("%d-%m-%Y"), }, {"key": "STICKER_NUMBER", "value": None}, {"key": "STICKER_POSTED", "value": None}, ], } ], }, winter_storage_leases_dict, )
pattern_dict[pattern] = [0, 0] if int(guess) == 1: pattern_dict[pattern][0] += 1 else: pattern_dict[pattern][1] += 1 # In[ ]: # (5 points) from unittest import TestCase tc = TestCase() d = {} record_guess(d, '121', '1') tc.assertDictEqual(d, {'121': [1, 0]}) record_guess(d, '222', '2') record_guess(d, '121', '1') tc.assertDictEqual(d, {'121': [2, 0], '222': [0, 1]}) record_guess(d, '122', '2') record_guess(d, '121', '2') record_guess(d, '222', '2') tc.assertDictEqual(d, {'121': [2, 1], '122': [0, 1], '222': [0, 2]}) # ### `next_placement` # # The next function you'll write will take a dictionary of pattern → counts mappings and a string representing the pattern of most recent guesses, and return the next best location (either '1' or '2') for the poison (i.e., to try and outwit the player). If the pattern hasn't been seen previously or the counts are tied, the function should return '2'. # In[ ]:
def test_parse_connection_string(test_input, expected_output): output = parse_connection_string(test_input) tc = TestCase() tc.assertDictEqual(output, expected_output)