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_print_results_for_file(self): with retrieve_stdout() as stdout: print_results( self.log_printer, Section(''), [Result.from_values('SpaceConsistencyBear', 'Trailing whitespace found', file='filename', line=2)], {abspath('filename'): ['test line\n', 'line 2\n', 'line 3\n']}, {}, self.console_printer) self.assertEqual(""" filename [ 2] {0} **** SpaceConsistencyBear [Section: | Severity: NORMAL] **** ! ! {1}\n""".format(highlight_text(self.no_color, 'line 2', NoColorStyle, self.lexer), highlight_text(self.no_color, 'Trailing whitespace found', style=BackgroundMessageStyle), ''), stdout.getvalue()) with retrieve_stdout() as stdout: print_results( self.log_printer, Section(''), [Result.from_values('SpaceConsistencyBear', 'Trailing whitespace found', file='filename', line=5)], {abspath('filename'): ['test line\n', 'line 2\n', 'line 3\n', 'line 4\n', 'line 5\n']}, {}, self.console_printer) self.assertEqual(""" filename [ 5] {0} **** SpaceConsistencyBear [Section: | Severity: NORMAL] **** ! ! {1}\n""".format(highlight_text(self.no_color, 'line 5', NoColorStyle, self.lexer), highlight_text(self.no_color, 'Trailing whitespace found', style=BackgroundMessageStyle), ''), stdout.getvalue())
def test_show_bear_minimal(self): with retrieve_stdout() as stdout: show_bear( SomelocalBear, False, False, self.console_printer) self.assertEqual(stdout.getvalue(), 'SomelocalBear\n') self.logs.check(*self.deprecation_messages)
def test_apply_with_rename(self): with retrieve_stdout() as stdout: previous_diffs = {"a": Diff(self.file_dict["a"])} previous_diffs["a"].change_line(2, "b\n", "b_changed\n") diff_dict = {"a": Diff(self.file_dict["a"], rename="a.rename"), "b": Diff(self.file_dict["b"], delete=True)} diff_dict["a"].add_lines(1, ["test\n"]) diff_dict["a"].delete_line(3) diff_dict["b"].add_lines(0, ["first\n"]) test_result = Result("origin", "message", diffs=diff_dict) self.assertEqual( self.uut.apply_from_section(test_result, self.file_dict, previous_diffs, self.section), previous_diffs ) self.assertEqual( stdout.getvalue(), "|----| | a\n" "| |++++| a.rename\n" "| 1| 1| a\n" "| | 2|+test\n" "| 2| 3| b_changed\n" "| 3| |-c\n" "|----| | b\n" "| |++++| /dev/null\n" "| 1| |-old_first\n", )
def test_show_bears_with_json(self): args = default_arg_parser().parse_args(['--json']) with retrieve_stdout() as stdout: show_bears({}, {}, True, True, self.console_printer, args) self.assertEqual('{\n "bears": []\n}\n', stdout.getvalue()) self.logs.check(*self.deprecation_messages)
def test_apply_with_rename(self): with retrieve_stdout() as stdout: previous_diffs = {'a': Diff(self.file_dict['a'])} previous_diffs['a'].modify_line(2, 'b_changed\n') diff_dict = {'a': Diff(self.file_dict['a'], rename='a.rename'), 'b': Diff(self.file_dict['b'], delete=True)} diff_dict['a'].add_lines(1, ['test\n']) diff_dict['a'].delete_line(3) diff_dict['b'].add_lines(0, ['first\n']) test_result = Result('origin', 'message', diffs=diff_dict) self.assertEqual(self.uut.apply_from_section(test_result, self.file_dict, previous_diffs, self.section), previous_diffs) self.assertEqual(stdout.getvalue(), '[----] a\n' '[++++] a.rename\n' '[ 2] test\n' '[ 3] c\n' '[----] b\n' '[++++] /dev/null\n' '[ 1] old_first\n')
def test_print_results_sorting(self): with retrieve_stdout() as stdout: print_results(self.log_printer, Section(''), [Result.from_values('SpaceConsistencyBear', 'Trailing whitespace found', file='file', line=5), Result.from_values('SpaceConsistencyBear', 'Trailing whitespace found', file='file', line=2)], {abspath('file'): ['test line\n', '\t\n', 'line 3\n', 'line 4\n', 'line 5\t\n']}, {}, self.console_printer) self.assertEqual(""" file | 2| {0} | | [NORMAL] SpaceConsistencyBear: | | {1} file | 5| {2} | | [NORMAL] SpaceConsistencyBear: | | {1}\n""".format(highlight_text(self.no_color, '\t', self.lexer), highlight_text(self.no_color, 'Trailing whitespace found', style=BackgroundMessageStyle), highlight_text(self.no_color, 'line 5\t', self.lexer)), stdout.getvalue())
def test_show_bear_desc_only(self): with retrieve_stdout() as stdout: show_bear( SomelocalBear, True, False, self.console_printer) self.assertEqual( stdout.getvalue(), 'SomelocalBear\n Some local-bear Description.\n\n')
def test_print_results_missing_line(self): with retrieve_stdout() as stdout: print_results( self.log_printer, Section(''), [Result.from_values('t', 'msg', file='file', line=5), Result.from_values('t', 'msg', file='file', line=6)], {abspath('file'): ['line ' + str(i + 1) for i in range(5)]}, {}, self.console_printer) self.assertEqual('\n' 'file\n' '| 5| {0}\n' '| | [NORMAL] t:\n' '| | {1}\n' '\n' 'file\n' '| 6| {2}\n' '| | [NORMAL] t:\n' '| | {1}\n'.format( highlight_text(self.no_color, 'line 5', self.lexer), highlight_text(self.no_color, 'msg', style=BackgroundMessageStyle), STR_LINE_DOESNT_EXIST), stdout.getvalue())
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_show_bears_capabilities(self): with retrieve_stdout() as stdout: show_language_bears_capabilities( {'some_language': ( {'Formatting', 'Security'}, {'Formatting'})}, self.console_printer) self.assertIn('coala can do the following for SOME_LANGUAGE\n' ' Can detect only: Formatting, Security\n' ' Can fix : Formatting\n', stdout.getvalue()) show_language_bears_capabilities( {'some_language': (set(), set())}, self.console_printer) self.assertIn('coala does not support some_language', stdout.getvalue()) show_language_bears_capabilities( {}, self.console_printer) self.assertIn( 'There is no bear available for this language', stdout.getvalue()) show_language_bears_capabilities( {'some_language': ({'Formatting', 'Security'}, set())}, self.console_printer) self.assertIn('coala can do the following for SOME_LANGUAGE\n' ' Can detect only: Formatting, Security\n', stdout.getvalue())
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_apply_renaming_only(self): with retrieve_stdout() as stdout: test_result = Result("origin", "message", diffs={"a": Diff([], rename="b")}) file_dict = {"a": []} self.assertEqual(self.uut.apply_from_section(test_result, file_dict, {}, self.section), {}) self.assertEqual( stdout.getvalue(), "|----| | " + join("a", "a") + "\n" "| |++++| " + join("b", "b") + "\n" )
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_apply(self): with retrieve_stdout() as stdout: self.assertEqual(self.uut.apply_from_section(self.test_result, {}, {}, Section('name')), {}) self.assertEqual(stdout.getvalue(), self.test_result.debug_msg+'\n')
def test_good_format(self): self.section.append(Setting('format', '{origin}')) with retrieve_stdout() as stdout: print_results_formatted(self.logger, self.section, [Result('1', '2')], None, None) self.assertEqual(stdout.getvalue(), '1\n')
def test_apply(self): with retrieve_stdout() as stdout: self.assertEqual(self.uut.apply_from_section(self.test_result, {}, {}, Section('name')), {}) self.assertEqual(stdout.getvalue(), type(self.test_aspect).__qualname__ + '\n' + type(self.test_aspect).docs.definition + '\n')
def test_show_bear_settings_only(self): with retrieve_stdout() as stdout: args = default_arg_parser().parse_args(['--show-settings']) show_bear(TestBear, False, False, self.console_printer, args) self.assertEqual(stdout.getvalue(), 'TestBear\n' ' Needed Settings:\n' ' * setting1: Required Setting.\n\n' ' Optional Settings:\n' ' * setting2: Optional Setting. (' "Optional, defaults to 'None'.)\n\n")
def test_apply_empty(self): with retrieve_stdout() as stdout: test_result = Result('origin', 'message', diffs={'a': Diff([])}) file_dict = {'a': []} self.assertEqual(self.uut.apply_from_section(test_result, file_dict, {}, self.section), {}) self.assertEqual(stdout.getvalue(), '')
def test_bears_ci_mode(self): sys.argv.append('--ci') orig_cwd = os.getcwd() os.chdir(os.path.dirname(os.path.realpath(__file__))) os.chdir("bears_ci_testfiles") with retrieve_stdout() as custom_stdout: main() self.assertIn("usable", custom_stdout.getvalue()) os.remove('.coafile') os.chdir(orig_cwd)
def test_print_used_languages(self): with retrieve_stdout() as custom_stdout: print_used_languages(self.printer, [('Python', 100)]) res = custom_stdout.getvalue() self.assertIn("Python", res) self.assertIn("100%", res) print_used_languages(self.printer, [('Python', 100)], False) res = custom_stdout.getvalue() self.assertIn("Python", res) self.assertIn("100%", res) ask_to_select_languages([('Python', 100)], self.printer, True) res = custom_stdout.getvalue() self.assertIn("Python", res) self.assertIn("100%", res) with retrieve_stdout() as custom_stdout: print_used_languages(self.printer, [('Python', 75), ('C++', 25)]) self.assertIn("75%\n", custom_stdout.getvalue())
def test_print_affected_files(self): with retrieve_stdout() as stdout, make_temp() as some_file: file_dict = {some_file: ['1\n', '2\n', '3\n']} affected_code = (SourceRange.from_values(some_file),) print_affected_files(self.console_printer, self.log_printer, Result('origin', 'message', affected_code=affected_code), file_dict) self.assertEqual(stdout.getvalue(), '\n'+relpath(some_file)+'\n')
def test_default_format(self): expected_string = ('id:-?[0-9]+:origin:1:file:None:line:None:' 'column:None:end_line:None:end_column:None:' 'severity:1:severity_str:NORMAL:message:2\n') with retrieve_stdout() as stdout: print_results_formatted(self.logger, self.section, [Result('1', '2')], None, None) self.assertRegex(stdout.getvalue(), expected_string) self.section.append(Setting('format', 'True')) with retrieve_stdout() as stdout: print_results_formatted(self.logger, self.section, [Result('1', '2')], None, None) self.assertRegex(stdout.getvalue(), expected_string)
def test_default_section_deprecation_warning(self): logger = logging.getLogger() with self.assertLogs(logger, "WARNING") as cm: # This gathers the configuration from the '.coafile' of this repo. gather_configuration(lambda *args: True, self.log_printer, arg_list=[]) self.assertIn("WARNING", cm.output[0]) with retrieve_stdout() as stdout: load_configuration(["--no-config"], self.log_printer) self.assertNotIn("WARNING", stdout.getvalue())
def test_source_lines(self): self.section.append(Setting(key='format', value='{source_lines}')) affected_code = (SourceRange.from_values('file', 2, end_line=2),) with retrieve_stdout() as stdout: print_results_formatted( self.logger, self.section, [Result('SpaceConsistencyBear', message='msg', affected_code=affected_code)], {abspath('file'): ('def fun():\n', ' pass \n')}) self.assertEqual(stdout.getvalue(), "(' pass \\n',)\n")
def test_print_side_by_side(self): with retrieve_stdout() as custom_stdout: print_side_by_side( self.printer, ["Left side content."], ["Right side content", "that is longer than the", "left side."], limit=80) self.assertIn( "side content.\x1b[0m \x1b[34mRight side", custom_stdout.getvalue())
def test_apply_renaming_only(self): with retrieve_stdout() as stdout: test_result = Result('origin', 'message', diffs={'a': Diff([], rename='b')}) file_dict = {'a': []} self.assertEqual(self.uut.apply_from_section(test_result, file_dict, {}, self.section), {}) self.assertEqual(stdout.getvalue(), '[----] ' + join('a', 'a') + '\n' '[++++] ' + join('b', 'b') + '\n')
def test_print_results_project_wide(self): with retrieve_stdout() as stdout: print_results(self.log_printer, Section(''), [Result('origin', 'message')], {}, {}, self.console_printer) self.assertEqual( '\n{}\n| | [NORMAL] origin:\n| | {}\n'.format( STR_PROJECT_WIDE, highlight_text(self.no_color, 'message', style=BackgroundMessageStyle)), stdout.getvalue())
def test_show_bears_sorted(self): local_bears = OrderedDict([('default', [SomelocalBear]), ('test', [aSomelocalBear])]) global_bears = OrderedDict([('default', [SomeglobalBear]), ('test', [BSomeglobalBear])]) with retrieve_stdout() as stdout: show_bears(local_bears, global_bears, False, False, self.console_printer) self.assertEqual(stdout.getvalue(), 'aSomelocalBear\n' 'BSomeglobalBear\n' 'SomeglobalBear\n' 'SomelocalBear\n')
def test_print_diffs_info(self): file_dict = {'a': ['a\n', 'b\n', 'c\n'], 'b': ['old_first\n']} diff_dict = {'a': Diff(file_dict['a']), 'b': Diff(file_dict['b'])} diff_dict['a'].add_lines(1, ['test\n']) diff_dict['a'].delete_line(3) diff_dict['b'].add_lines(0, ['first\n']) previous_diffs = {'a': Diff(file_dict['a'])} previous_diffs['a'].change_line(2, 'b\n', 'b_changed\n') with retrieve_stdout() as stdout: print_diffs_info(diff_dict, self.console_printer) self.assertEqual(stdout.getvalue(), '| | +1 -1 in a\n' '| | +1 -0 in b\n')
def test_print_results_empty(self): with retrieve_stdout() as stdout: print_results(self.log_printer, Section(''), [], {}, {}, self.console_printer) self.assertEqual(stdout.getvalue(), '')
def test_print_welcome_message(self): with retrieve_stdout() as custom_stdout: print_welcome_message(self.printer) self.assertIn("o88Oo", custom_stdout.getvalue())
def test_apply(self): self.assertEqual(self.uut1.description, 'Show Alternate Patch 1') self.assertEqual(self.uut2.description, 'Show Alternate Patch 2') self.assertEqual(self.uut3.description, 'Show Alternate Patch 3') with retrieve_stdout() as stdout: self.uut1.apply_from_section(self.result, self.original_file_dict, {}, self.section) self.assertEqual( stdout.getvalue(), '[----] filename\n' '[++++] filename\n' '[ 1] coler\n' '[ 1] colour\n') self.uut1.diffs = self.original_diff self.result.diffs = self.alternate_diff1 self.assertEqual(self.uut1.description, 'Show Original Patch') self.assertEqual(self.uut2.description, 'Show Alternate Patch 2') self.assertEqual(self.uut3.description, 'Show Alternate Patch 3') with retrieve_stdout() as stdout: self.uut2.apply_from_section(self.result, self.original_file_dict, {}, self.section) self.assertEqual( stdout.getvalue(), '[----] filename\n' '[++++] filename\n' '[ 1] coler\n' '[ 1] cooler\n') self.uut2.diffs = self.alternate_diff1 self.result.diffs = self.alternate_diff2 self.assertEqual(self.uut1.description, 'Show Original Patch') self.assertEqual(self.uut2.description, 'Show Alternate Patch 1') self.assertEqual(self.uut3.description, 'Show Alternate Patch 3') with retrieve_stdout() as stdout: self.uut3.apply_from_section(self.result, self.original_file_dict, {}, self.section) self.assertEqual( stdout.getvalue(), '[----] filename\n' '[++++] filename\n' '[ 1] coler\n' '[ 1] coder\n') self.uut3.diffs = self.alternate_diff2 self.result.diffs = self.alternate_diff3 self.assertEqual(self.uut1.description, 'Show Original Patch') self.assertEqual(self.uut2.description, 'Show Alternate Patch 1') self.assertEqual(self.uut3.description, 'Show Alternate Patch 2') with retrieve_stdout() as stdout: self.uut3.apply_from_section(self.result, self.original_file_dict, {}, self.section) self.assertEqual( stdout.getvalue(), '[----] filename\n' '[++++] filename\n' '[ 1] coler\n' '[ 1] cooler\n') self.uut3.diffs = self.alternate_diff3 self.result.diffs = self.alternate_diff2 self.assertEqual(self.uut1.description, 'Show Original Patch') self.assertEqual(self.uut2.description, 'Show Alternate Patch 1') self.assertEqual(self.uut3.description, 'Show Alternate Patch 3') with retrieve_stdout() as stdout: self.uut2.apply_from_section(self.result, self.original_file_dict, {}, self.section) self.assertEqual( stdout.getvalue(), '[----] filename\n' '[++++] filename\n' '[ 1] coler\n' '[ 1] colour\n') self.uut2.diffs = self.alternate_diff2 self.result.diffs = self.alternate_diff1 self.assertEqual(self.uut1.description, 'Show Original Patch') self.assertEqual(self.uut2.description, 'Show Alternate Patch 2') self.assertEqual(self.uut3.description, 'Show Alternate Patch 3') with retrieve_stdout() as stdout: self.uut1.apply_from_section(self.result, self.original_file_dict, {}, self.section) self.assertEqual( stdout.getvalue(), '[----] filename\n' '[++++] filename\n' '[ 1] coler\n' '[ 1] color\n') self.uut1.diffs = self.alternate_diff1 self.result.diffs = self.original_diff self.assertEqual(self.uut1.description, 'Show Alternate Patch 1') self.assertEqual(self.uut2.description, 'Show Alternate Patch 2') self.assertEqual(self.uut3.description, 'Show Alternate Patch 3')
def test_yes_no_default(self): with simulate_console_inputs(''), retrieve_stdout() as custom_stdout: response = ask_yes_no(self.question_text, default='no') self.assertIn(self.question_text, custom_stdout.getvalue()) self.assertIn(' [y/N] ', custom_stdout.getvalue()) self.assertFalse(response)
def test_show_bears_with_json(self): args = default_arg_parser().parse_args(['--json']) with retrieve_stdout() as stdout: show_bears({}, {}, True, True, self.console_printer, args) self.assertEqual('{\n "bears": []\n}\n', stdout.getvalue())
def test_show_bear_minimal(self): with retrieve_stdout() as stdout: show_bear(SomelocalBear, False, False, self.console_printer) self.assertEqual(stdout.getvalue(), 'SomelocalBear\n') self.logs.check(*self.deprecation_messages)
def test_retrieve_stdout(self): with retrieve_stdout() as sio: print("test", file=sys.stdout) self.assertEqual(sio.getvalue(), "test\n")
def test_print_ask_dir_help_message(self): with retrieve_stdout() as custom_stdout: self.printer.print(PROJECT_DIR_HELP) self.assertIn(PROJECT_DIR_HELP, custom_stdout.getvalue())
def test_show_bears_empty(self): with retrieve_stdout() as stdout: show_bears({}, {}, True, True, self.console_printer) self.assertIn('No bears to show.', stdout.getvalue()) self.logs.check(*self.deprecation_messages)
def test_print_coala_quickstart_version_long(self): sys.argv.append('--version') with retrieve_stdout() as custom_stdout: with self.assertRaises(SystemExit) as cm: main() self.assertEquals('0.4.0\n', custom_stdout.getvalue())
def test_print_section_beginning(self): with retrieve_stdout() as stdout: print_section_beginning(self.console_printer, Section('name')) self.assertEqual(stdout.getvalue(), 'Executing section name...\n')
def test_print_relevant_bears(self): with retrieve_stdout() as custom_stdout: print_relevant_bears(self.printer, filter_relevant_bears( [('Python', 70), ('Unknown', 30)])) self.assertIn("PycodestyleBear", custom_stdout.getvalue())
def test_show_bear_minimal(self): with retrieve_stdout() as stdout: show_bear(SomelocalBear, False, False, self.console_printer) self.assertEqual(stdout.getvalue(), 'SomelocalBear\n')
def test_show_bear_desc_only(self): with retrieve_stdout() as stdout: show_bear(SomelocalBear, True, False, self.console_printer) self.assertEqual( stdout.getvalue(), 'SomelocalBear\n Some local-bear Description.\n\n')
def test_show_bears_empty(self): with retrieve_stdout() as stdout: show_bears({}, {}, True, True, self.console_printer) self.assertIn('No bears to show.', stdout.getvalue())
def test_no_results(self): with retrieve_stdout() as custom_stdout: print_used_languages(self.printer, []) self.assertNotIn("following langauges", custom_stdout.getvalue())
def test_apply(self): with retrieve_stdout() as stdout: self.assertEqual(self.uut.apply(self.test_result, self.file_dict, {}), None)