def print_with_result(mocker): """ The expected result for this setup should look like: ################################# # Result Summary: # ################################# Shorter text ################################# ################################# # Violations Details: # ################################# Some summary table should be here ################################# """ violation = mocker.MagicMock() violation.empty = False v_list = mocker.MagicMock() v_list.pritify = mocker.MagicMock(return_value="Some detailed table should be here") v_list.data = ["Some detailed table should be here"] v_list.headline = "Violations Details:" v_sum = mocker.MagicMock() v_sum.data["Shorter text"] v_sum.headline = "Result Summary:" violation.violations_list = v_list violation.summary = v_sum violation.displayable = [v_list, v_sum] return print_results(violation).split('\n')
def test_cli_main_cli_amount_menu_input_invalid(self, mocker, command): """Positive-Test-Cases""" # Setup donor_entered = "spam" inst = cli_main.Cli() # Mock def mocked_add_donation(amount): if amount <= 0: raise ValueError mocked_donor = mocker.MagicMock() mocked_donor.donations = [] mocked_donor.add_donation = mocked_add_donation inst.record = mocker.MagicMock() inst.record.donors = {donor_entered: mocked_donor} inst._thank_you_donor = donor_entered # pylint: disable=protected-access inst.unrecognized_command = mocker.MagicMock() # Execute result = inst.amount_menu_input(command) # Assert assert result == "" assert inst.unrecognized_command.call_count == 1 assert inst.unrecognized_command.call_args[0][0] == command
def print_with_no_result(mocker): """ The expected result for this setup should look like #################################################################################################### # No Violations Detected # #################################################################################################### """ violation = mocker.MagicMock() violation.summary.get = mocker.MagicMock(return_value=[]) return print_results(violation).split('\n')
def mock_all(): return [ mocker.MagicMock(publication_recid=1, invitation_cookie='c00kie1', role='TestRole1'), mocker.MagicMock(publication_recid=2, invitation_cookie='c00kie2', role='TestRole2') ]
def command_dispatch(self, mocker): """Dispatch Menu Fixture""" called_once = mocker.MagicMock() called_twice = mocker.MagicMock() called_quit = mocker.MagicMock(return_value="quit") called_key_error = mocker.MagicMock() command_dispatch = { "1": called_once, "2": called_twice, "0": called_quit, "_prompt": "spam", "_key_error": called_key_error, } return command_dispatch
def test_processGame_writes_duplicated_id(self, mocker): (mockS3, mockSQS, mockDynamo, mockContext, mockGameController, mockTime) = getMocks(mocker) mocker.patch.object(L, 's3', mockS3) mocker.patch.object(L, 'dynamodb', mockDynamo) mocker.patch.object(L, 'GameController', mockGameController) mocker.patch.object(L, 'getDatetime', mockTime) mockBatch = mocker.Mock() mockTable = mocker.MagicMock() mockTable.batch_writer.return_value.__enter__.return_value = mockBatch mockDynamo.Table.return_value = mockTable pg1 = ParsedGame(1) pg2 = ParsedGame(1) mockGameController.processPGNText.return_value = [pg1, pg2] L.lambda_handler(lambdaEvent, mockContext) mockDynamo.Table.assert_any_call('chess_games') mockDynamo.Table.assert_any_call(mock_tablePgnSucceeded) mockDynamo.Table.assert_any_call(mock_tableChessGamesFailed) # good game assert (mockBatch.put_item.call_count == 1) mockBatch.put_item.assert_any_call(Item=mockSuccessDbItem(pg1)) # file things assert (mockTable.put_item.call_count == 2) mockTable.put_item.assert_any_call(Item=mockAddedDbItem(1)) mockTable.put_item.assert_any_call( Item=mockFailedDbItem('Duplicated Key: 1'))
def test_zip_file(self, new_scan_service, mocker): """ Given that an zip folder of dicoms is passed to the scan service upload method When the upload method calls _process file 1) _process_file returns a two tuple: (the file object, True) 2) _generate_xnat_identifers returns a dict in which the 'resource' type is 'DICOM' 3) xnat_put is called with expected args, including imp=True """ with open('/Users/katie/spiro/cookiecutter_mbam/files/DICOM.zip', 'rb') as f: file = FileStorage(f) file.save('/Users/katie/spiro/cookiecutter_mbam/files/DICOM1.zip') print(type(file)) print(file.filename) print("hey ", type(file)) file_object, import_service = new_scan_service._process_file(file) assert import_service xc = XNATConnection() xc.xnat_put = mocker.MagicMock() mocker.spy(new_scan_service.xc, 'xnat_put') mocker.spy(new_scan_service, '_generate_xnat_identifiers') new_scan_service.upload(f) new_scan_service._generate_xnat_identifiers.assert_called_with( dcm=True) xnat_ids = new_scan_service._generate_xnat_identifiers(dcm=True) assert xnat_ids['resource']['xnat_id'] == 'DICOM' new_scan_service.xc.xnat_put.assert_called_with( file=f, imp=True, project='MBAM_TEST', subject='000001', experiment='000001_MR2')
def test_ProteinVCFSeqExtractor_correctquery(mocker): protein_vcf_seq = TestExtractor(gtf_file, fasta_file, vcf_file) protein_vcf_seq.extract_query = mocker.MagicMock( return_value=( 'LATTGLWGP', iter([ ('ID', ['Var_Mutation_Mock']), ('HR', ['Var_Mutation_Mock']) ]) ) ) protein_ref_seq, protein_alt_seqs = protein_vcf_seq.extract(intervals) query = list(protein_vcf_seq.extract_query.call_args[1]["variant_interval_queryable"].variant_intervals) variants = list(query[0][0]) assert len(variants) == 1 assert variants[0].pos == 596 interval = query[0][1] assert interval.start == 580 variants = list(query[1][0]) assert len(variants) == 1 assert variants[0].pos == 598 interval = query[1][1] assert interval.start == 597
def test_processGame_writes_andFail(self, mocker): (mockS3, mockSQS, mockDynamo, mockContext, mockGameController, mockTime) = getMocks(mocker) mocker.patch.object(L, 's3', mockS3) mocker.patch.object(L, 'dynamodb', mockDynamo) mocker.patch.object(L, 'GameController', mockGameController) mocker.patch.object(L, 'getDatetime', mockTime) mockBatch = mocker.Mock() mockTable = mocker.MagicMock() mockDynamo.Table.return_value = mockTable mockTable.batch_writer.return_value.__enter__.return_value = mockBatch mockBatch.put_item.side_effect = mocker.Mock( side_effect=Exception('put item failed')) pg = ParsedGame(1) mockGameController.processPGNText.return_value = [pg] with pytest.raises(Exception) as e_info: L.lambda_handler(lambdaEvent, mockContext) item = mockSuccessDbItem(pg) mockBatch.put_item.assert_called_once() mockBatch.put_item.assert_called_once_with(Item=item) assert (mockDynamo.Table.call_count == 2) mockDynamo.Table.assert_any_call('chess_games') mockDynamo.Table.assert_any_call(mock_tablePgnFailed) failedItem = mockFailedDbItem('writing') mockTable.put_item.assert_called_once() mockTable.put_item.assert_called_once_with(Item=failedItem)
def test_cli_main_cli_run_menu_quit_queue(self, mocker, command_dispatch, queue_input): """ Positive-Test-Cases, menu can return a queue of callables after quit-command. Overrides command "1" to return a queue of commands to run next without requiring user input. Assert these commands are called the correct number of times without having to put them into the command_list that gets put into mocked_input to simulate user entry. """ # Setup command_list = ["1"] inst = cli_main.Cli() # Mock command_dispatch["1"] = mocker.MagicMock(return_value=queue_input) mocked_input = mocker.patch.object(cli_main, "input", side_effect=command_list) # Execute returned_queue = inst.run_menu(menu=command_dispatch) # Assert assert command_dispatch["1"].call_count == 1 assert returned_queue == queue_input[1:] with pytest.raises(StopIteration): # Assert command list was emptied mocked_input()
def test_cli_main_cli_run_menu_invalid_input_unrecognized( self, mocker, command_dispatch, ): """Positive-Test-Cases, invalid input: unrecognized command""" # Setup inst = cli_main.Cli() command_list = ["spam", "0"] # Mock mocked_input = mocker.patch.object(cli_main, "input", side_effect=command_list) command_dispatch["_key_error"] = mocker.MagicMock() # Execute inst.run_menu(menu=command_dispatch) # Assert assert command_dispatch["0"].call_count == 1 # quit called once assert command_dispatch["_key_error"].call_count == 1 assert command_dispatch["_key_error"].call_args[0][0] == command_list[ 0] with pytest.raises(StopIteration): # Assert command list was emptied mocked_input()
def test_processGame_writes_1(self, mocker): (mockS3, mockSQS, mockDynamo, mockContext, mockGameController, mockTime) = getMocks(mocker) mocker.patch.object(L, 's3', mockS3) mocker.patch.object(L, 'dynamodb', mockDynamo) mocker.patch.object(L, 'GameController', mockGameController) mocker.patch.object(L, 'getDatetime', mockTime) mockBatch = mocker.Mock() mockTable = mocker.MagicMock() mockTable.batch_writer.return_value.__enter__.return_value = mockBatch mockDynamo.Table.return_value = mockTable pg = ParsedGame(1) mockGameController.processPGNText.return_value = [pg] L.lambda_handler(lambdaEvent, mockContext) mockBatch.put_item.assert_called_once() mockBatch.put_item.assert_called_once_with(Item=mockSuccessDbItem(pg)) assert (mockDynamo.Table.call_count == 2) mockDynamo.Table.assert_any_call('chess_games') mockDynamo.Table.assert_any_call(mock_tablePgnSucceeded) mockTable.put_item.assert_called_once() mockTable.put_item.assert_called_once_with(Item=mockAddedDbItem(1))
def test_cli_main_cli_run_menu_key_error_queue(self, mocker, command_dispatch, queue_input): """ Positive-Test-Cases, menu_key_error can return a queue of callables. Overrides the unrecognized command to send a queue of commands to be run by the parent menu. """ # Setup command_list = ["1", "eggs", "0"] inst = cli_main.Cli() # Mock mocked_input = mocker.patch.object(cli_main, "input", side_effect=command_list) command_dispatch["_key_error"] = mocker.MagicMock( return_value=queue_input) # Execute inst.run_menu(menu=command_dispatch) # Assert assert command_dispatch["1"].call_count == 1 assert "2" not in command_list # Assert test-case is setup properly assert command_dispatch["2"].call_count == queue_input.count("2") assert command_dispatch["0"].call_count == 1 with pytest.raises(StopIteration): # Assert command list was emptied mocked_input()
def test_cli_main_cli_run_menu_invalid_input_empty(self, mocker, command_dispatch): """ Positive-Test-Cases, invalid input: empty command Empty command (user just pressed enter) re-prompts, doesn't call menu_key_error """ # Setup inst = cli_main.Cli() command_list = ["", "0"] # Mock mocked_input = mocker.patch.object(cli_main, "input", side_effect=command_list) inst.unrecognized_command = mocker.MagicMock() # Execute inst.run_menu(menu=command_dispatch) # Assert assert command_dispatch["0"].call_count == 1 # quit called once assert inst.unrecognized_command.call_count == 0 with pytest.raises(StopIteration): # Assert command list was emptied mocked_input()
def test_cli_main_cli_amount_menu_input_unrecognized(self, mocker): """Positive-Test-Cases""" # Setup command = "spam" inst = cli_main.Cli() # Mock inst.record = mocker.MagicMock() inst.unrecognized_command = mocker.MagicMock() # Execute result = inst.amount_menu_input(command) # Assert assert result == "" assert inst.unrecognized_command.call_count == 1 assert inst.unrecognized_command.call_args[0][0] == command
def test_cli_main_cli_thanks_menu_input_invalid_donor_id( self, mocker, command, result_goal, name_goal): """Positive-Test-Cases, invalid donor_id, things a new donor is being added""" # TODO should it recognize a donor_id was attempted? # Setup donor_list = ["spam", "eggs"] inst = cli_main.Cli() # Mock inst.record = mocker.MagicMock() inst.record.donor_list = donor_list inst.unrecognized_command = mocker.MagicMock() # Execute result = inst.thanks_menu_input(command) # Assert assert inst._thank_you_donor == name_goal assert result == result_goal
def test_cli_main_cli_print_thanks(self, mocker, mocked_print): """Positive-Test-Cases, print thank-you""" # Setup donor_name = "spam" message = "eggs" inst = cli_main.Cli() # Mock inst.record = mocker.MagicMock() mocked_donor = mocker.MagicMock() mocked_donor.thank_you_latest = mocker.MagicMock(return_value=message) inst.record.donors = {donor_name: mocked_donor} inst._thank_you_donor = donor_name # Execute inst.print_thanks() # Assert assert mocked_print.call_count == 1 assert mocked_print.call_args[0][0] == message
def test_cli_main_main(self, mocker): """Positive-Test-Cases""" # Mock mocked_cli_instance = mocker.MagicMock() mocker.patch.object(cli_main, "Cli", return_value=mocked_cli_instance) # Execute cli_main.main() # Assert assert mocked_cli_instance.run_menu.call_count == 1
async def test_subwatcher_watch(mocker, subwatcher): outqueue_mock = mocker.patch.object(subwatcher, '_outqueue', new=CoroutineMock(name='put_mock')) outqueue_mock.put = CoroutineMock() stream_target_mock = mocker.MagicMock(name='stream_target') stream_target_mock.return_value = iter(['a', 'b', None, 'c']) await subwatcher.watch(pause_after=-1, stream_target=stream_target_mock) stream_target_mock.assert_called_with(pause_after=-1) outqueue_mock.put.assert_has_calls([call('a'), call('b'), call('c')])
def test_cli_main_cli_amount_menu_input(self, mocker, donation_entries): """Positive-Test-Cases""" # pylint: disable=protected-access # Setup donor_entered = "spam" inst = cli_main.Cli() donations_float = [] result_list = [] # Mock mocked_donor = mocker.MagicMock() mocked_donor.donations = [] inst.record = mocker.MagicMock() inst.record.donors = {donor_entered: mocked_donor} inst._thank_you_donor = donor_entered def mocked_add_donation(amount): """Mocks the record.add_donor method""" mocked_donor.donations.append(amount) mocked_donor.add_donation = mocked_add_donation # Execute for donation_entry in donation_entries: result = inst.amount_menu_input(donation_entry) result_list.append(result) # Strip currency symbols and commas from amount donation_entry = regex.sub("\\p{Currency_Symbol}", "", donation_entry) donation_entry = regex.sub(",", "", donation_entry) donations_float.append(float(donation_entry)) # Assert assert inst.record.donors[donor_entered].donations == donations_float assert all(("quit" in result_item) for result_item in result_list)
def test_cli_main_cli_save_emails(self, mocker, mocked_print): """Positive-Test-Cases""" # Setup inst = cli_main.Cli() # Mock inst.record = mocker.MagicMock() # Execute inst.save_emails() # Assert assert inst.record.save_all_donor_emails.call_count == 1 assert mocked_print.call_count == 1 assert "saved" in mocked_print.call_args[0][0]
def test_menu_selection(self, mocker): """Positive-Test-Cases""" # Setup command_list = ["spam", "1", "2", "2", "3"] input_list = (n for n in command_list) # Mock def mocked_input(*_): return next(input_list) called_once = mocker.MagicMock() called_twice = mocker.MagicMock() called_quit = mocker.MagicMock(return_value="quit") command_dispatch = { "1": called_once, "2": called_twice, "3": called_quit, } mocked_print = mocker.patch.object(mailroom, "print") mocker.patch.object(mailroom, "input", new=mocked_input) # Execute mailroom.menu_selection("", dispatch_dict=command_dispatch) # Assert assert called_once.call_count == 1 assert called_twice.call_count == 2 assert called_quit.call_count == 1 for argument_string in [ "Unrecognized", command_list[0], ]: # Assert contents of error message printed assert argument_string in mocked_print.call_args.args[0] with pytest.raises(StopIteration): # Assert command list was emptied mocked_input()
def test_cli_main_cli_find_donor(self, mocker, donor_entered): """Positive-Test-Cases""" donor_list = ["spam", "eggs"] inst = cli_main.Cli() # Mock inst.record = mocker.MagicMock() inst.record.donor_list = donor_list # Execute donor_name, result = inst.find_donor(donor_entered) # Assert assert donor_name == donor_entered if donor_entered in donor_list: assert result == "amount_menu" else: assert result == "new_donor"
def test_cli_main_cli_thanks_menu_input_name(self, mocker, result_goal): """Positive-Test-Cases, name entered""" # Setup command = "spam" inst = cli_main.Cli() # Mock inst.find_donor = mocker.MagicMock(return_value=(command, result_goal)) # Execute first_value = inst._thank_you_donor result = inst.thanks_menu_input(command) second_value = inst._thank_you_donor # Assert assert first_value == "" assert second_value == command assert result == result_goal
def test_cli_main_cli_donor_list(self, mocker, mocked_print, donor_list): """Positive-Test-Cases""" # Setup inst = cli_main.Cli() # Mock inst.record = mocker.MagicMock() inst.record.donor_list = donor_list # Execute inst.donor_list() # Assert for i, donor in enumerate(donor_list): # List printed in order printed_item = mocked_print.call_args_list[i].args[0] assert f"{i:d}" in printed_item assert donor in printed_item if not donor_list: # Empty List prints special message printed_item = mocked_print.call_args[0][0] assert "No donors" in printed_item
def test_cli_main_Cli_add_donor(self, mocker): """Positive-Test-Cases""" donor_entered = "spam" inst = cli_main.Cli() # Mock inst.record = mocker.MagicMock() inst.record.donor_list = [] inst._thank_you_donor = donor_entered # pylint: disable=protected-access def mocked_add_donor(name): """Mocks the record.add_donor method""" inst.record.donor_list.append(name) inst.record.add_donor = mocked_add_donor # Execute inst.add_donor() # Assert assert donor_entered in inst.record.donor_list
async def test_subwatcher_watch_default(mocker, subwatcher): outqueue_mock = mocker.patch.object(subwatcher, '_outqueue', new=CoroutineMock(name='put_mock')) outqueue_mock.put = CoroutineMock() stream_target_mock = mocker.MagicMock(name='stream_target') stream_target_mock.return_value = iter(['a', 'b', None, 'c']) mocker.patch.object(subwatcher, '_streams', new=[ stream_target_mock, ]) await subwatcher.watch(pause_after=-1) # we need to gather everything EXCEPT the current task or we create # a deadlock # took me like an hour to figure that one out. I blame the angry orchard. pending = asyncio.Task.all_tasks() current = asyncio.Task.current_task() await asyncio.gather(*(pending - {current})) stream_target_mock.assert_called_with(pause_after=-1) outqueue_mock.put.assert_has_calls([call('a'), call('b'), call('c')])
def test_cli_main_cli_thanks_menu_input_valid_donor_id( self, mocker, command): """Positive-Test-Cases, valid donor_id""" # Setup donor_list = ["spam", "eggs"] inst = cli_main.Cli() donor_id = abs(int(command[1:])) # Mock inst.record = mocker.MagicMock() inst.record.donor_list = donor_list # Execute first_value = inst._thank_you_donor result = inst.thanks_menu_input(command) second_value = inst._thank_you_donor # Assert assert result == "amount_menu" assert first_value == "" assert second_value == donor_list[donor_id]
def test_save_all_donors_emails(self, mocker): """Positive-Test-Cases""" # Setup all_files = {"spam": "eggs", "foo": "bar"} # Mock mocked_file = mocker.MagicMock() mocked_file.__enter__.return_value = mocked_file # Context Manager Mock mocker.patch.object( mailroom, "compose_all_donors_emails", return_value=all_files, ) mocked_open = mocker.patch.object(mailroom, "open", return_value=mocked_file) # Execute mailroom.save_all_donor_emails() # Assert assert mocked_open.call_count == len(all_files) for i, (file_name, file_contents) in enumerate(all_files.items()): assert file_name in mocked_open.call_args_list[i].args[0] assert file_contents == mocked_file.write.call_args_list[i].args[0]
def test_record_save_all_donors_emails(self, mocker, DonorMock): # , mocker): """Positive-Test-Cases""" # pylint: disable=protected-access # Setup record = donor_models.Record() donors_data = [("spam", "eggs"), ("foo", "bar")] # Mock for donor_name, message in donors_data: donor = DonorMock(donor_name) donor.thank_you_message = message record.donors[donor.name] = donor zero_donor = DonorMock( "zero_donor") # Donor with $0 causes LookupError mocker.patch.object(zero_donor, "thank_you_overall", side_effect=LookupError) record.donors[zero_donor.name] = zero_donor mocked_file = mocker.MagicMock() mocked_file.__enter__.return_value = mocked_file # Context Manager Mock mocked_open = mocker.patch.object(donor_models, "open", return_value=mocked_file) # Execute record.save_all_donor_emails() # Assert assert mocked_open.call_count == len( donors_data) # Correct # of open() calls for i, (donor_name, message) in enumerate(donors_data): # Correct call args assert donor_name in mocked_open.call_args_list[i].args[0] assert message == mocked_file.write.call_args_list[i].args[0] for file_name in mocked_open.call_args_list: # Assert $0 Donor is excluded assert zero_donor not in file_name