Beispiel #1
0
def check_pycolor_main(self, args: typing.List[str], mocked_data_dir: str,
                       test_name: str, **kwargs):
    stdin: typing.TextIO = kwargs.get('stdin', sys.stdin)
    patch_stdout: bool = kwargs.get('patch_stdout', False)
    patch_stderr: bool = kwargs.get('patch_stderr', False)
    print_output: bool = kwargs.get('print_output', False)
    write_output: bool = kwargs.get('write_output', False)
    no_load_args: bool = kwargs.get('no_load_args', False)
    patch_sample_config_dir: bool = kwargs.get('patch_sample_config_dir', True)

    filename_prefix = os.path.join(mocked_data_dir, test_name)
    stdout = textstream()
    stderr = textstream()

    if not no_load_args:
        args = ['--load-file', filename_prefix + '.json'] + args
    args = ['--color', 'always'] + args

    stdout_in = open_fstream(filename_prefix + '.txt')
    stderr_in = open_fstream(filename_prefix + '.err.txt')

    with ExitStack() as stack:
        stack.enter_context(
            execute_patch(pycolor_class.execute, stdout_in, stderr_in))
        if patch_stdout:
            stack.enter_context(patch(sys, 'stdout', stdout))
        if patch_stderr:
            stack.enter_context(patch(sys, 'stderr', stderr))
        if patch_sample_config_dir:
            stack.enter_context(
                patch(pycolor.config, 'SAMPLE_CONFIG_DIR', None))

        try:
            pycolor.main(args,
                         stdout_stream=stdout,
                         stderr_stream=stderr,
                         stdin_stream=stdin)
        except SystemExit as sexc:
            if sexc.code != 0:
                raise sexc
        finally:
            if stdout_in is not None:
                stdout_in.close()
            if stderr_in is not None:
                stderr_in.close()

    output_expected = read_file(filename_prefix + '.out.txt')
    output_expected_err = read_file(filename_prefix + '.out.err.txt')

    test_stream(self, stdout, filename_prefix + '.out.txt', output_expected,
                print_output, write_output)
    test_stream(self, stderr, filename_prefix + '.out.err.txt',
                output_expected_err, print_output, write_output)
    def test_copy_sample_config(self):
        self.assertTrue(os.path.isdir(SAMPLE_CONFIG_DIR))

        with tempfile.TemporaryDirectory() as tmpdir:
            tmpconfig = os.path.join(tmpdir, 'config')
            with patch(sys, 'stdout',
                       textstream()), patch(pycolor, 'CONFIG_DIR', tmpconfig):
                check_pycolor_main(self, ['--version'],
                                   MOCKED_DATA,
                                   'empty',
                                   patch_sample_config_dir=False)
                self.assertListEqual(sorted(os.listdir(SAMPLE_CONFIG_DIR)),
                                     sorted(os.listdir(tmpconfig)))
    def test_load_sample_config(self):
        self.assertTrue(os.path.isdir(SAMPLE_CONFIG_DIR))

        with patch(pycolor, 'CONFIG_DIR', SAMPLE_CONFIG_DIR),\
        patch(pycolor, 'CONFIG_DEFAULT', os.path.join(SAMPLE_CONFIG_DIR, 'rsync.json')):
            stdin = textstream()
            with open(os.path.join(MOCKED_DATA, 'load_sample_config.txt'),
                      'r') as file:
                stdin.write(file.read())
                stdin.seek(0)

            check_pycolor_main(self, ['--stdin', 'rsync'],
                               MOCKED_DATA,
                               'load_sample_config',
                               stdin=stdin,
                               no_load_args=True)
Beispiel #4
0
    def test_get_profile_by_command_which(self):
        loader = ProfileLoader()
        loader.load_file(
            os.path.join(MOCKED_DATA, 'get-profile-by-command-which.json'))

        with patch(profileloader, 'which', lambda x: '/usr/bin/date'):
            self.assertEqual(loader.get_profile_by_command('date', []),
                             loader.get_profile_by_name('which'))
        self.assertIsNone(loader.get_profile_by_command('noexist', []))
Beispiel #5
0
    def test_debug_color(self):
        #pylint: disable=invalid-name
        def get_terminal_size(_=None):
            TerminalSize = namedtuple('terminal_size', ['columns', 'lines'])
            return TerminalSize(80, 24)

        with patch(os, 'get_terminal_size', get_terminal_size):
            check_pycolor_main(self, ['--debug-color'],
                               MOCKED_DATA,
                               'debug_color',
                               patch_stdout=True)
Beispiel #6
0
    def test_load_file_same_profile_name(self):
        loader = ProfileLoader()

        with patch_stderr() as stderr, patch(printmsg, 'is_color_enabled',
                                             lambda x: True):
            loader.load_file(
                os.path.join(MOCKED_DATA, 'load-file-same-profile-name.json'))

        stderr.seek(0)
        self.assertEqual(
            '\x1b[93mwarn\x1b[0m: conflicting profiles with the name "test"\n',
            stderr.read())
Beispiel #7
0
def execute_patch(obj, stdout_stream, stderr_stream):
    def popen(args, **kwargs):
        class MockProcess:
            def __init__(self, args, **kwargs):
                self.args = args

                def set_stream(name, stream):
                    res = kwargs.get(name)
                    if isinstance(res, int) and res != -1:
                        if stream is not None:
                            os.write(res, stream.read())
                    else:
                        res = stream if stream else textstream()
                    return res

                self.stdin = set_stream('stdin', None)
                self.stdout = set_stream('stdout', stdout_stream)
                self.stderr = set_stream('stderr', stderr_stream)

                self.returncode: typing.Optional[int] = None
                self.polled: int = 0

            def poll(self) -> typing.Optional[int]:
                if self.polled > 1:
                    self.returncode = 0
                self.polled += 1
                return self.returncode

            def __enter__(self):
                return self

            def __exit__(self, exc_type, val, trbk):
                pass

        return MockProcess(args, **kwargs)

    with patch(getattr(obj, 'subprocess'), 'Popen', popen):
        yield
Beispiel #8
0
def patch_color(enabled: bool):
    with patch(pkg_printmsg, 'is_color_enabled', lambda x: enabled):
        yield