def test_default_input_apply_single_nothing(self): action = TestAction() args = [ self.console_printer, Section(''), [action.get_metadata()], { 'TestAction': action }, set(), Result('origin', 'message'), {}, {}, {} ] with simulate_console_inputs(1, 'a') as generator: apply_single = 'Do (N)othing' se = Section('cli') args = [ self.console_printer, se, [action.get_metadata()], { 'TestAction': action }, set(), Result('origin', 'message'), {}, {}, {}, apply_single ] self.assertFalse(ask_for_action_and_apply(*args)) with simulate_console_inputs('') as generator: self.assertFalse(ask_for_action_and_apply(*args))
def test_fill_settings(self): sections = {'test': self.section} with simulate_console_inputs() as generator: fill_settings(sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info={}) self.assertEqual(generator.last_input, -1) self.section.append(Setting('bears', 'BearC')) with simulate_console_inputs('True'), bear_test_module(): local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info={}) self.assertEqual(len(local_bears['test']), 1) self.assertEqual(len(global_bears['test']), 0) self.assertEqual(bool(self.section['use_spaces']), True) self.assertEqual(len(self.section.contents), 3)
def test_ask_for_actions_and_apply2(self): failed_actions = set() action = ApplyPatchAction() action2 = ChainPatchAction() args = [ self.console_printer, Section(''), [action.get_metadata(), action2.get_metadata()], { 'ApplyPatchAction': action, 'ChainPatchAction': action2 }, failed_actions, Result('origin', 'message'), {}, {}, {} ] with simulate_console_inputs('c', 'a') as generator: ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 1) self.assertIn('ApplyPatchAction', failed_actions) with simulate_console_inputs('c', 'n') as generator: ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 1) self.assertNotIn('ChainPatchAction', failed_actions) with simulate_console_inputs('c', 'x') as generator: ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 0) self.assertNotIn('ChainPatchAction', failed_actions) with simulate_console_inputs('c', 'o') as generator: ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 0) self.assertNotIn('ChainPatchAction', failed_actions)
def test_acquire_actions_and_apply_single(self): with make_temp() as testfile_path: file_dict = {testfile_path: ['1\n', '2\n', '3\n']} diff = Diff(file_dict[testfile_path]) diff.delete_line(2) diff.change_line(3, '3\n', '3_changed\n') with simulate_console_inputs('a', 'n') as generator: with retrieve_stdout() as sio: ApplyPatchAction.is_applicable = staticmethod( lambda *args: True) acquire_actions_and_apply(self.console_printer, Section(''), self.file_diff_dict, Result( 'origin', 'message', diffs={testfile_path: diff}), file_dict, apply_single=True) self.assertEqual(generator.last_input, -1) self.assertIn('', sio.getvalue()) class InvalidateTestAction(ResultAction): is_applicable = staticmethod(lambda *args: True) def apply(*args, **kwargs): ApplyPatchAction.is_applicable = staticmethod( lambda *args: 'ApplyPatchAction cannot be applied.') old_applypatch_is_applicable = ApplyPatchAction.is_applicable ApplyPatchAction.is_applicable = staticmethod(lambda *args: True) cli_actions = [ApplyPatchAction(), InvalidateTestAction()] with simulate_console_inputs('a') as generator: with retrieve_stdout() as sio: acquire_actions_and_apply(self.console_printer, Section(''), self.file_diff_dict, Result( 'origin', 'message', diffs={testfile_path: diff}), file_dict, cli_actions=cli_actions, apply_single=True) self.assertEqual(generator.last_input, -1) action_fail = 'Failed to execute the action' self.assertNotIn(action_fail, sio.getvalue()) apply_path_desc = ApplyPatchAction().get_metadata().desc self.assertEqual(sio.getvalue().count(apply_path_desc), 0) ApplyPatchAction.is_applicable = old_applypatch_is_applicable
def test_filter_relevant_bears_with_non_optional_settings(self): sys.argv.append('--no-filter-by-capabilities') with bear_test_module(): languages = [] res_1 = filter_relevant_bears( languages, self.printer, self.arg_parser, {}) # results with extracted information res_2 = [] with generate_files(context_filenames, context_file_contents, self.project_dir): with simulate_console_inputs("Yes") as generator: extracted_info = collect_info(self.project_dir) res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info) self.assertEqual(generator.last_input, 0) # Comparing both the scenarios additional_bears_by_lang = { "All": ["NonOptionalSettingBear"] } for lang in res_1: additional_bears = [bear.name for bear in res_2[lang] if bear not in res_1[lang]] for bear in additional_bears_by_lang[lang]: self.assertIn(bear, additional_bears) # Simulating the situation when user rejects the bear res_2 = [] with generate_files(context_filenames, context_file_contents, self.project_dir): with simulate_console_inputs( "Some random text which will not be accepted", "No") as generator: extracted_info = collect_info(self.project_dir) res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info) self.assertEqual(generator.last_input, 1) # This time there will be no additional bears additional_bears_by_lang = { "All": [] } for lang in res_1: additional_bears = [bear.name for bear in res_2[lang] if bear not in res_1[lang]] for bear in additional_bears_by_lang[lang]: self.assertIn(bear, additional_bears)
def test_simulate_console_inputs(self): with simulate_console_inputs(0, 1, 2) as generator: self.assertEqual(input(), 0) self.assertEqual(generator.last_input, 0) generator.inputs.append(3) self.assertEqual(input(), 1) self.assertEqual(input(), 2) self.assertEqual(input(), 3) self.assertEqual(generator.last_input, 3) with simulate_console_inputs('test'), self.assertRaises(ValueError): self.assertEqual(input(), 'test') input()
def test_simulate_console_inputs(self): with simulate_console_inputs(0, 1, 2) as generator: self.assertEqual(input(), 0) self.assertEqual(generator.last_input, 0) generator.inputs.append(3) self.assertEqual(input(), 1) self.assertEqual(input(), 2) self.assertEqual(input(), 3) self.assertEqual(generator.last_input, 3) with simulate_console_inputs("test"), self.assertRaises(ValueError): self.assertEqual(input(), "test") input()
def test_filter_relevant_bears_with_capabilities(self): # Clear the IMPORTANT_BEARS_LIST import coala_quickstart.generation.Bears as Bears Bears.IMPORTANT_BEARS_LIST = {} with bear_test_module(): languages = [] capability_to_select = 'Smell' cap_number = ( sorted(ALL_CAPABILITIES).index(capability_to_select) + 1) res = [] with simulate_console_inputs('1000', str(cap_number)) as generator: res = filter_relevant_bears(languages, self.printer, self.arg_parser, {}) # 1000 was not a valid option, so there will be two prompts self.assertEqual(generator.last_input, 1) expected_results = { "All": set(["SmellCapabilityBear"]) } for lang, lang_bears in expected_results.items(): for bear in lang_bears: res_bears = [b.name for b in res[lang]] self.assertIn(bear, res_bears)
def test_caching_multi_results(self): """ Integration test to assert that results are not dropped when coala is ran multiple times with caching enabled and one section yields a result and second one doesn't. """ filename = 'tests/misc/test_caching_multi_results/' with bear_test_module(): with simulate_console_inputs('0'): retval, stdout, stderr = execute_coala(coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr) retval, stdout, stderr = execute_coala(coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertIn('During execution of coala', stderr) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr)
def test_apply_no_input(self): with retrieve_stdout() as stdout: with simulate_console_inputs('', '0') as generator: self.assertEqual( self.uut.apply_from_section(self.test_result, self.file_dict, {}, self.section), False)
def test_fill_settings_section_match_with_conflicts(self): self.section = Section('test1') self.section["files"] = "hello.py" sections = {'test1': self.section} self.section.append(Setting('bears', 'BearC')) with simulate_console_inputs("False") as generator, \ bear_test_module(), retrieve_stdout() as sio: with generate_files([".editorconfig", "hello.py"], [editorconfig_4, "pass"], self.project_dir): extracted_info = collect_info(self.project_dir) local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info=extracted_info) self.assertEqual(len(local_bears['test1']), 1) self.assertEqual(len(global_bears['test1']), 0) prompt_msg = ( 'coala-quickstart has detected multiple potential values ' 'for the setting "use_spaces"') self.assertIn(prompt_msg, sio.getvalue()) self.assertEqual(generator.last_input, 0) self.assertEqual(bool(self.section['use_spaces']), False)
def test_filter_bears_ci_mode(self): sys.argv.append('--ci') with bear_test_module(): languages = [] res_1 = filter_relevant_bears(languages, self.printer, self.arg_parser, {}) res_2 = [] with generate_files(context_filenames, context_file_contents, self.project_dir): with simulate_console_inputs("Yes") as generator: extracted_info = collect_info(self.project_dir) res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info) # Make sure there was no prompt self.assertEqual(generator.last_input, -1) # The NonOptionalSettingBear is not selected due to non-optional # setting value in non-interactive mode. additional_bears_by_lang = {"All": []} for lang in res_1: additional_bears = [ bear.name for bear in res_2[lang] if bear not in res_1[lang] ] for bear in additional_bears_by_lang[lang]: self.assertIn(bear, additional_bears)
def test_caching_multi_results(self): """ Integration test to assert that results are not dropped when coala is ran multiple times with caching enabled and one section yields a result and second one doesn't. """ filename = 'tests/misc/test_caching_multi_results/' with bear_test_module(): with simulate_console_inputs('n'): retval, stdout, stderr = execute_coala(coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr) retval, stdout, stderr = execute_coala(coala.main, 'coala', '--non-interactive', '--no-color', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertEqual(2, len(stderr.splitlines())) self.assertIn( 'LineCountTestBear: This result has no patch attached.', stderr) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr)
def test_get_project_files(self): orig_cwd = os.getcwd() os.chdir(os.path.dirname(os.path.realpath(__file__))) os.makedirs("file_globs_testfiles", exist_ok=True) os.chdir("file_globs_testfiles") os.makedirs("src", exist_ok=True) os.makedirs("ignore_dir", exist_ok=True) open(os.path.join("src", "file.c"), "w").close() open("root.c", "w").close() open(os.path.join("ignore_dir", "src.c"), "w").close() open(os.path.join("ignore_dir", "src.js"), "w").close() with retrieve_stdout() as custom_stdout, \ simulate_console_inputs("ignore_dir/**"): res, _ = get_project_files(self.log_printer, self.printer, os.getcwd(), self.file_path_completer) self.assertIn(GLOB_HELP, custom_stdout.getvalue()) self.assertIn(os.path.normcase( os.path.join(os.getcwd(), "src", "file.c")), res) self.assertIn(os.path.normcase( os.path.join(os.getcwd(), "root.c")), res) self.assertNotIn(os.path.normcase( os.path.join(os.getcwd(), "ignore_dir/src.c")), res) self.assertNotIn(os.path.normcase( os.path.join(os.getcwd(), "ignore_dir/src.js")), res) os.chdir(orig_cwd)
def test_get_project_files(self): orig_cwd = os.getcwd() os.chdir(os.path.dirname(os.path.realpath(__file__))) os.makedirs("file_globs_testfiles", exist_ok=True) os.chdir("file_globs_testfiles") os.makedirs("src", exist_ok=True) os.makedirs("ignore_dir", exist_ok=True) open(os.path.join("src", "file.c"), "w").close() open("root.c", "w").close() open(os.path.join("ignore_dir", "src.c"), "w").close() open(os.path.join("ignore_dir", "src.js"), "w").close() with retrieve_stdout() as custom_stdout, \ simulate_console_inputs("ignore_dir/**"): res, _ = get_project_files(self.log_printer, self.printer, os.getcwd(), self.file_path_completer) self.assertIn(GLOB_HELP, custom_stdout.getvalue()) self.assertIn( os.path.normcase(os.path.join(os.getcwd(), "src", "file.c")), res) self.assertIn( os.path.normcase(os.path.join(os.getcwd(), "root.c")), res) self.assertNotIn( os.path.normcase(os.path.join(os.getcwd(), "ignore_dir/src.c")), res) self.assertNotIn( os.path.normcase(os.path.join(os.getcwd(), "ignore_dir/src.js")), res) os.chdir(orig_cwd)
def test_fill_section(self): # Use the same value for both because order isn't predictable (uses # dict) with simulate_console_inputs(0, 0): new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear]) self.assertEqual(int(new_section['local name']), 0) self.assertEqual(int(new_section['global name']), 0) self.assertEqual(new_section['key'].value, 'val') self.assertEqual(len(new_section.contents), 3) # Shouldnt change anything the second time new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear]) self.assertTrue('local name' in new_section) self.assertTrue('global name' in new_section) self.assertEqual(new_section['key'].value, 'val') self.assertEqual(len(new_section.contents), 3)
def test_dependency_resolving(self): sections = {'test': self.section} self.section['bears'] = 'DependentBear' with simulate_console_inputs('True'), bear_test_module(): fill_settings(sections, acquire_settings, self.log_printer) self.assertEqual(bool(self.section['use_spaces']), True)
def test_require_settings(self): curr_section = Section('') self.assertRaises(TypeError, acquire_settings, self.log_printer, 0, curr_section) with simulate_console_inputs(0, 1, 2) as generator: self.assertEqual(acquire_settings(self.log_printer, {'setting': ['help text', 'SomeBear']}, curr_section), {'setting': 0}) self.assertEqual(acquire_settings(self.log_printer, {'setting': ['help text', 'SomeBear', 'AnotherBear']}, curr_section), {'setting': 1}) self.assertEqual(acquire_settings(self.log_printer, {'setting': ['help text', 'SomeBear', 'AnotherBear', 'YetAnotherBear']}, curr_section), {'setting': 2}) self.assertEqual(generator.last_input, 2)
def test_caching_results(self): """ A simple integration test to assert that results are not dropped when coala is ran multiple times with caching enabled. """ with bear_test_module(), \ prepare_file(['a=(5,6)'], None) as (lines, filename): with simulate_console_inputs('0'): retval, output = execute_coala(coala.main, 'coala', '-c', os.devnull, '--disable-caching', '--flush-cache', '-f', re.escape(filename), '-b', 'LineCountTestBear', '-L', 'DEBUG') self.assertIn('This file has', output) # Due to the change in configuration from the removal of # ``--flush-cache`` this run will not be sufficient to # assert this behavior. retval, output = execute_coala(coala.main, 'coala', '-c', os.devnull, '-f', re.escape(filename), '-b', 'LineCountTestBear') self.assertIn('This file has', output) retval, output = execute_coala(coala.main, 'coala', '-c', os.devnull, '-f', re.escape(filename), '-b', 'LineCountTestBear') self.assertIn('This file has', output)
def test_default_input_apply_single_fail(self): action = TestAction() args = [self.console_printer, Section(''), [action.get_metadata()], {'TestAction': action}, set(), Result('origin', 'message'), {}, {}] with simulate_console_inputs(5, 0) as generator: apply_single = 'Test (X)ction' se = Section('cli') args = [self.console_printer, se, [action.get_metadata()], {'TestAction': action}, set(), Result('origin', 'message'), {}, {}, {}, apply_single] with simulate_console_inputs('a') as generator: self.assertFalse(ask_for_action_and_apply(*args))
def test_caching_multi_results(self): """ Integration test to assert that results are not dropped when coala is ran multiple times with caching enabled and one section yields a result and second one doesn't. """ filename = 'tests/misc/test_caching_multi_results/' with bear_test_module(): with simulate_console_inputs('0'): retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr) retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertIn('During execution of coala', stderr) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr)
def test_print_result_no_input(self): with make_temp() as testfile_path: file_dict = {testfile_path: ['1\n', '2\n', '3\n']} diff = Diff(file_dict[testfile_path]) diff.delete_line(2) diff.change_line(3, '3\n', '3_changed\n') with simulate_console_inputs(1, 2, 3) as generator, \ retrieve_stdout() as stdout: ApplyPatchAction.is_applicable = staticmethod( lambda *args: True) print_results_no_input(self.log_printer, Section('someSection'), [Result('origin', 'message', diffs={ testfile_path: diff})], file_dict, self.file_diff_dict, self.console_printer) self.assertEqual(generator.last_input, -1) self.assertEqual(stdout.getvalue(), """ Project wide: **** origin [Section: someSection] **** ! ! [Severity: NORMAL] ! ! {}\n""".format(highlight_text(self.no_color, 'message', style=BackgroundMessageStyle)))
def test_caching_multi_results(self): """ Integration test to assert that results are not dropped when coala is ran multiple times with caching enabled and one section yields a result and second one doesn't. """ filename = 'tests/misc/test_caching_multi_results/' with bear_test_module(): with simulate_console_inputs('n'): retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr) retval, stdout, stderr = execute_coala( coala.main, 'coala', '--non-interactive', '--no-color', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', stdout) self.assertEqual(2, len(stderr.splitlines())) self.assertIn( 'LineCountTestBear: This result has no patch attached.', stderr) self.assertIn( 'Implicit \'Default\' section inheritance is deprecated', stderr)
def test_ask_for_actions_and_apply(self): failed_actions = set() action = TestAction() do_nothing_action = DoNothingAction() args = [ self.console_printer, Section(''), [do_nothing_action.get_metadata(), action.get_metadata()], { 'DoNothingAction': do_nothing_action, 'TestAction': action }, failed_actions, Result('origin', 'message'), {}, {}, {} ] with simulate_console_inputs('a', 'param1', 'a', 'param2') as generator: action.apply = unittest.mock.Mock(side_effect=AssertionError) ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 1) self.assertIn('TestAction', failed_actions) action.apply = lambda *args, **kwargs: {} ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 3) self.assertNotIn('TestAction', failed_actions)
def test_filter_bears_ci_mode(self): sys.argv.append('--ci') with bear_test_module(): languages = [] res_1 = filter_relevant_bears( languages, self.printer, self.arg_parser, {}) res_2 = [] with generate_files(context_filenames, context_file_contents, self.project_dir): with simulate_console_inputs("Yes") as generator: extracted_info = collect_info(self.project_dir) res_2 = filter_relevant_bears(languages, self.printer, self.arg_parser, extracted_info) # Make sure there was no prompt self.assertEqual(generator.last_input, -1) # The NonOptionalSettingBear is not selected due to non-optional # setting value in non-interactive mode. additional_bears_by_lang = { "All": [] } for lang in res_1: additional_bears = [bear.name for bear in res_2[lang] if bear not in res_1[lang]] for bear in additional_bears_by_lang[lang]: self.assertIn(bear, additional_bears)
def test_fill_settings_section_match_no_conflicts(self): self.section = Section('test') self.section["files"] = "*.py" sections = {'test': self.section} self.section.append(Setting('bears', 'BearC')) with simulate_console_inputs() as generator, bear_test_module(): with generate_files([".editorconfig", "hello.py"], [editorconfig_3, "pass"], self.project_dir) as gen_files: extracted_info = collect_info(self.project_dir) local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info=extracted_info) self.assertEqual(len(local_bears['test']), 1) self.assertEqual(len(global_bears['test']), 0) # The value for the setting is automatically taken # from .editorconfig file. self.assertEqual(generator.last_input, -1) self.assertEqual(bool(self.section['use_spaces']), True)
def test_ask_yes_no(self): with simulate_console_inputs( 'yes'), retrieve_stdout() as custom_stdout: response = ask_yes_no(self.question_text, printer=self.printer) self.assertIn(self.question_text, custom_stdout.getvalue()) self.assertIn(' [y/n] ', custom_stdout.getvalue()) self.assertTrue(response)
def test_invalid_answer_type(self): with simulate_console_inputs("test", "42"), \ retrieve_stdout() as custom_stdout: response = ask_question(self.question_text, typecast=int) self.assertIn("Please enter a", custom_stdout.getvalue()) self.assertEqual(response, 42)
def test_question_caption(self): with simulate_console_inputs(""), retrieve_stdout() as custom_stdout: response = ask_question(self.question_text, default=self.caption) self.assertIn( self.question_text + " \x1b[0m[" + self.caption + "]", custom_stdout.getvalue()) self.assertEqual(response, self.caption)
def test_fill_section_boolean_setting(self): self.section = Section('test') sections = {'test': self.section} self.section.append(Setting('bears', 'BearC')) with simulate_console_inputs(" hell yeah!!! ") as generator, \ bear_test_module(): local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info={}) self.assertEqual(generator.last_input, 0) self.assertEqual(bool(self.section['use_spaces']), True) self.section = Section('test') sections = {'test': self.section} self.section.append(Setting('bears', 'BearC')) with simulate_console_inputs("not in a million years") as generator, \ bear_test_module(): local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info={}) self.assertEqual(generator.last_input, 0) self.assertEqual(bool(self.section['use_spaces']), False) self.section = Section('test') sections = {'test': self.section} self.section.append(Setting('bears', 'BearC')) with simulate_console_inputs("don't know", "nah") as generator, \ bear_test_module(): local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info={}) self.assertEqual(generator.last_input, 1) self.assertEqual(bool(self.section['use_spaces']), False)
def test_apply_no_input(self): with retrieve_stdout() as stdout: with simulate_console_inputs('', '0') as generator: self.assertEqual(self.uut.apply_from_section(self.test_result, self.file_dict, {}, self.section), False)
def test_ask_question(self): with simulate_console_inputs(self.simulated_input),\ retrieve_stdout() as custom_stdout: response = ask_question(self.question_text, default=None, printer=self.printer) self.assertIn(self.question_text, custom_stdout.getvalue()) self.assertEqual(response, self.simulated_input)
def test_yes_no_change_default(self): with simulate_console_inputs('No'), retrieve_stdout() as custom_stdout: response = ask_yes_no(self.question_text, default='yes', printer=self.printer) self.assertIn(self.question_text, custom_stdout.getvalue()) self.assertIn(' [Y/n] ', custom_stdout.getvalue()) self.assertFalse(response)
def test_default_input(self): action = TestAction() args = [self.console_printer, Section(''), [action.get_metadata()], {'TestAction': action}, set(), Result('origin', 'message'), {}, {}] with simulate_console_inputs('') as generator: self.assertFalse(ask_for_action_and_apply(*args))
def test_ask_to_select_languages(self): languages = [('lang1', 50), ('lang2', 25), ('language3', 25)] res = [] with simulate_console_inputs('1 2') as generator: res = ask_to_select_languages(languages, self.printer, False) self.assertEqual(generator.last_input, 0) self.assertEqual(res, [('lang1', 50), ('lang2', 25)]) with simulate_console_inputs('6', '1') as generator: res = ask_to_select_languages(languages, self.printer, False) self.assertEqual(generator.last_input, 1) self.assertEqual(res, [('lang1', 50)]) with simulate_console_inputs('\n') as generator: res = ask_to_select_languages(languages, self.printer, False) self.assertEqual(generator.last_input, 0) self.assertEqual(res, [('lang1', 50), ('lang2', 25), ('language3', 25)])
def test_fill_settings(self): sections = {'test': self.section} with simulate_console_inputs() as generator: fill_settings(sections, acquire_settings, self.log_printer) self.assertEqual(generator.last_input, -1) self.section.append(Setting('bears', 'SpaceConsistencyTestBear')) with simulate_console_inputs('True'), bear_test_module(): local_bears, global_bears = fill_settings(sections, acquire_settings, self.log_printer) self.assertEqual(len(local_bears['test']), 1) self.assertEqual(len(global_bears['test']), 0) self.assertEqual(bool(self.section['use_spaces']), True) self.assertEqual(len(self.section.contents), 3)
def test_fill_settings(self): sections = {'test': self.section} targets = [] with simulate_console_inputs() as generator: fill_settings(sections, targets, acquire_settings, self.log_printer) self.assertEqual(generator.last_input, -1) self.section.append(Setting('bears', 'SpaceConsistencyTestBear')) with simulate_console_inputs('True'), bear_test_module(): local_bears, global_bears = fill_settings(sections, targets, acquire_settings, self.log_printer) self.assertEqual(len(local_bears['test']), 1) self.assertEqual(len(global_bears['test']), 0) self.assertEqual(bool(self.section['use_spaces']), True) self.assertEqual(len(self.section.contents), 3)
def test_fill_section_invalid_type(self): with simulate_console_inputs("fd", "fd", 0, 0) as generator: new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear], {}) self.assertEqual(generator.last_input, 3) self.assertEqual(int(new_section['local name']), 0) self.assertEqual(int(new_section['global name']), 0) self.assertEqual(new_section['key'].value, 'val') self.assertEqual(len(new_section.contents), 3)
def test_bears_no_filter_by_capability_mode(self): languages = [] with bear_test_module(): # Results without filtering sys.argv.append('--no-filter-by-capabilities') res = [] with simulate_console_inputs() as generator: res = filter_relevant_bears(languages, self.printer, self.arg_parser, {}) self.assertEqual(generator.last_input, -1) self.assertEqual(res, {"All": set()})
def test_default_input_apply_single_test(self): action = TestAction() do_nothing_action = DoNothingAction() apply_single = 'Test (A)ction' se = Section('cli') args = [self.console_printer, se, [do_nothing_action.get_metadata(), action.get_metadata()], {'DoNothingAction': do_nothing_action, 'TestAction': action}, set(), Result('origin', 'message'), {}, {}, {}, apply_single] with simulate_console_inputs('a') as generator: self.assertFalse(ask_for_action_and_apply(*args))
def test_language_setting_autofill(self): self.section = Section('ruby') sections = {'ruby': self.section} self.section.append(Setting('bears', 'LanguageSettingBear')) with simulate_console_inputs() as generator, bear_test_module(): local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info={}) self.assertEqual(generator.last_input, -1) self.assertEqual(str(self.section['language']), 'ruby')
def test_caching_results(self): """ A simple integration test to assert that results are not dropped when coala is ran multiple times with caching enabled. """ with bear_test_module(): with prepare_file(['a=(5,6)'], None) as (lines, filename): with simulate_console_inputs('n'): retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', os.devnull, '--disable-caching', '--flush-cache', '-f', filename, '-b', 'LineCountTestBear', '-L', 'DEBUG') self.assertIn('This file has', stdout) self.assertIn('Running bear LineCountTestBear', stderr) # Due to the change in configuration from the removal of # ``--flush-cache`` this run will not be sufficient to # assert this behavior. retval, stdout, stderr = execute_coala( coala.main, 'coala', '--non-interactive', '--no-color', '-c', os.devnull, '-f', filename, '-b', 'LineCountTestBear') self.assertIn('This file has', stdout) self.assertEqual(1, len(stderr.splitlines())) self.assertIn( 'LineCountTestBear: This result has no patch attached.', stderr) retval, stdout, stderr = execute_coala( coala.main, 'coala', '--non-interactive', '--no-color', '-c', os.devnull, '-f', filename, '-b', 'LineCountTestBear') self.assertIn('This file has', stdout) self.assertEqual(1, len(stderr.splitlines())) self.assertIn( 'LineCountTestBear: This result has no patch attached.', stderr)
def test_ask_for_actions_and_apply(self): failed_actions = set() action = TestAction() args = [self.console_printer, Section(''), [action.get_metadata()], {'TestAction': action}, failed_actions, Result('origin', 'message'), {}, {}] with simulate_console_inputs(1, 'param1', 1, 'param2') as generator: action.apply = unittest.mock.Mock(side_effect=AssertionError) ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 1) self.assertIn('TestAction', failed_actions) action.apply = lambda *args, **kwargs: {} ask_for_action_and_apply(*args) self.assertEqual(generator.last_input, 3) self.assertNotIn('TestAction', failed_actions)
def test_fill_section(self): # Use the same value for both because order isn't predictable (uses # dict) with simulate_console_inputs(0, 0): new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear]) self.assertEqual(int(new_section['local name']), 0) self.assertEqual(int(new_section['global name']), 0) self.assertEqual(new_section['key'].value, 'val') self.assertEqual(len(new_section.contents), 3) # Shouldnt change anything the second time new_section = fill_section(self.section, acquire_settings, self.log_printer, [LocalTestBear, GlobalTestBear]) self.assertTrue('local name' in new_section) self.assertTrue('global name' in new_section) self.assertEqual(new_section['key'].value, 'val') self.assertEqual(len(new_section.contents), 3) # test the deprecation of calling acquire_settings with LogCapture() as capture: fill_section(self.empty_section, lambda param_1, param_2: {}, self.log_printer, [LocalTestBear, GlobalTestBear]) capture.check() with LogCapture() as capture: fill_section(self.empty_section, lambda param_1, param_2, param_3: {}, self.log_printer, [LocalTestBear, GlobalTestBear]) capture.check( ('root', 'WARNING', 'acquire_settings: section parameter is deprecated.') )
def test_coala4(self): with bear_test_module(), retrieve_stdout() as sio: with prepare_file(['#fixme'], None) as (lines, filename): with simulate_console_inputs('x', 'n') as generator: retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', os.devnull, '--non-interactive', '--no-color', '-f', filename, '-b', 'LineCountTestBear', '-A') self.assertIn('', stdout, '') self.assertEqual(1, len(stderr.splitlines())) self.assertIn( 'LineCountTestBear: This result has no patch ' 'attached.', stderr) self.assertNotEqual(retval, 0, 'coala must return nonzero when ' 'errors occured')
def test_apply(self): with prepare_file(['fixme '], None) as (lines, filename): dir_path = os.path.dirname(filename) file_path = os.path.basename(filename) newfilename = os.path.join(dir_path, file_path + '.py') os.rename(filename, newfilename) file_dict = {newfilename: ['fixme ']} diff_dict = {newfilename: Diff(file_dict[newfilename])} diff_dict[newfilename].add_line(1, ['test\n']) test_result = Result('origin', 'message', diffs=diff_dict) section = Section('name') section.append(Setting('no_color', 'True')) with simulate_console_inputs('1', 'True', '0') as generator: with retrieve_stdout() as stdout: self.uut.apply_from_section(test_result, file_dict, {}, section) self.assertIn('[ ] *0. Do Nothing\n' '[ ] 1. Apply patch ' '(\'SpaceConsistencyBear\')\n' '[ ]', stdout.getvalue()) os.rename(newfilename, filename)
def test_caching_results(self): """ A simple integration test to assert that results are not dropped when coala is ran multiple times with caching enabled. """ with bear_test_module(), \ prepare_file(['a=(5,6)'], None) as (lines, filename): with simulate_console_inputs('0'): retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', os.devnull, '--disable-caching', '--flush-cache', '-f', re.escape(filename), '-b', 'LineCountTestBear', '-L', 'DEBUG') self.assertIn('This file has', stdout) self.assertIn('Running bear LineCountTestBear', stderr) # Due to the change in configuration from the removal of # ``--flush-cache`` this run will not be sufficient to # assert this behavior. retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', os.devnull, '-f', re.escape(filename), '-b', 'LineCountTestBear') self.assertIn('This file has', stdout) self.assertIn(' During execution of coala', stderr) retval, stdout, stderr = execute_coala( coala.main, 'coala', '-c', os.devnull, '-f', re.escape(filename), '-b', 'LineCountTestBear') self.assertIn('This file has', stdout) self.assertIn('During execution of coala', stderr)
def test_caching_multi_results(self): """ Integration test to assert that results are not dropped when coala is ran multiple times with caching enabled and one section yields a result and second one doesn't. """ filename = 'tests/misc/test_caching_multi_results/' with bear_test_module(): with simulate_console_inputs('0'): retval, output = execute_coala( coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', output) retval, output = execute_coala( coala.main, 'coala', '-c', filename + '.coafile', '-f', filename + 'test.py') self.assertIn('This file has', output)
def test_fill_settings_autofill(self): self.section = Section('test') sections = {'test': self.section} self.section.append(Setting('bears', 'BearC')) with simulate_console_inputs() as generator, bear_test_module(): with generate_files([".editorconfig"], [editorconfig_1], self.project_dir) as gen_files: extracted_info = collect_info(self.project_dir) local_bears, global_bears = fill_settings( sections, acquire_settings, self.log_printer, fill_section_method=fill_section, extracted_info=extracted_info) self.assertEqual(len(local_bears['test']), 1) self.assertEqual(len(global_bears['test']), 0) # The value for the setting is automatically taken # from .editorconfig file. self.assertEqual(generator.last_input, -1) self.assertEqual(bool(self.section['use_spaces']), False)