diff options
| author | Charles Cabergs <me@cacharle.xyz> | 2021-02-28 11:04:52 +0100 |
|---|---|---|
| committer | Charles Cabergs <me@cacharle.xyz> | 2021-02-28 11:04:52 +0100 |
| commit | b6eb06aeee0fda77395d7b3172c44b999b70cdee (patch) | |
| tree | 9e29f32a94df7340fcc335e1740062003be393cd /minishell_test | |
| parent | 348da189c00bdef866d2b597ea0250fc0f0e88dc (diff) | |
| download | minishell_test-b6eb06aeee0fda77395d7b3172c44b999b70cdee.tar.gz minishell_test-b6eb06aeee0fda77395d7b3172c44b999b70cdee.tar.bz2 minishell_test-b6eb06aeee0fda77395d7b3172c44b999b70cdee.zip | |
Refactoring config in a class to have a testable environment
Diffstat (limited to 'minishell_test')
| -rwxr-xr-x | minishell_test/__main__.py | 29 | ||||
| -rw-r--r-- | minishell_test/args.py | 8 | ||||
| -rw-r--r-- | minishell_test/config.py | 221 | ||||
| -rw-r--r-- | minishell_test/hooks.py | 16 | ||||
| -rw-r--r-- | minishell_test/sandbox.py | 10 | ||||
| -rw-r--r-- | minishell_test/suite/suite.py | 20 | ||||
| -rw-r--r-- | minishell_test/suites/builtin.py | 8 | ||||
| -rw-r--r-- | minishell_test/suites/cmd.py | 6 | ||||
| -rw-r--r-- | minishell_test/suites/flow.py | 18 | ||||
| -rw-r--r-- | minishell_test/suites/preprocess.py | 8 | ||||
| -rw-r--r-- | minishell_test/test/captured.py | 6 | ||||
| -rw-r--r-- | minishell_test/test/result.py | 10 | ||||
| -rw-r--r-- | minishell_test/test/test.py | 26 |
13 files changed, 212 insertions, 174 deletions
diff --git a/minishell_test/__main__.py b/minishell_test/__main__.py index b5761d0..4ebaec3 100755 --- a/minishell_test/__main__.py +++ b/minishell_test/__main__.py @@ -18,7 +18,7 @@ import shutil import distutils.spawn import subprocess -from minishell_test import config +from minishell_test.config import Config from minishell_test import sandbox from minishell_test.args import parse_args from minishell_test.suite.suite import Suite, SuiteException @@ -27,32 +27,33 @@ from minishell_test.test import Test def main(argv=None): - args = parse_args() + args = parse_args(sys.argv[1:]) + Config.init(args) if args.list: Suite.list() sys.exit(0) # running ``make`` in minishell directory - if config.MAKE or args.make: - print("{:=^{width}}".format("MAKE", width=config.TERM_COLS)) + if Config.make or args.make: + print("{:=^{width}}".format("MAKE", width=Config.term_cols)) try: subprocess.run( - ["make", *config.MAKE_ARGS, "--no-print-directory", "-C", config.MINISHELL_DIR], + ["make", *Config.make_args, "--no-print-directory", "-C", Config.minishell_dir], check=True, env=os.environ, ) except subprocess.CalledProcessError: sys.exit(1) - print("=" * config.TERM_COLS) + print("=" * Config.term_cols) if args.make: sys.exit(0) # setup available commands - if not config.SHELL_AVAILABLE_COMMANDS_DIR.exists(): - config.SHELL_AVAILABLE_COMMANDS_DIR.mkdir(parents=True, exist_ok=True) - for cmd in config.SHELL_AVAILABLE_COMMANDS: - copied_path = config.SHELL_AVAILABLE_COMMANDS_DIR / cmd + if not Config.shell_available_commands_dir.exists(): + Config.shell_available_commands_dir.mkdir(parents=True, exist_ok=True) + for cmd in Config.shell_available_commands: + copied_path = Config.shell_available_commands_dir / cmd if copied_path.exists(): continue cmd_path = distutils.spawn.find_executable(cmd) @@ -80,14 +81,14 @@ def main(argv=None): Suite.summarize() Suite.save_log() - print("See", config.LOG_PATH, "for more information") - if config.CHECK_LEAKS: + print("See", Config.log_path, "for more information") + if Config.check_leaks: print("HELP: Valgrind is really slow the -x and --range options could be useful" " ({} -h for more details)".format(sys.argv[0])) - if config.PAGER: + if Config.pager: # TODO {} replaced by filename in pager config var - subprocess.run([config.PAGER_PROG, config.LOG_PATH]) + subprocess.run([Config.pager_prog, Config.log_path]) if __name__ == "__main__": diff --git a/minishell_test/args.py b/minishell_test/args.py index 8aca64b..6ffb242 100644 --- a/minishell_test/args.py +++ b/minishell_test/args.py @@ -6,17 +6,15 @@ # By: charles <charles.cabergs@gmail.com> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/07/15 18:24:32 by charles #+# #+# # -# Updated: 2021/02/27 20:16:56 by cacharle ### ########.fr # +# Updated: 2021/02/28 09:06:53 by cacharle ### ########.fr # # # # ############################################################################ # import argparse import textwrap -import functools -@functools.lru_cache(maxsize=1) -def parse_args(): +def parse_args(argv): """Parse command line arguments""" parser = argparse.ArgumentParser( @@ -85,4 +83,4 @@ def parse_args(): (e.g ./run int -> ./run preprocess/interpolation) """) ) - return parser.parse_args() + return parser.parse_args(argv) diff --git a/minishell_test/config.py b/minishell_test/config.py index 2cc96b7..db98ce5 100644 --- a/minishell_test/config.py +++ b/minishell_test/config.py @@ -6,7 +6,7 @@ # By: cacharle <me@cacharle.xyz> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2021/02/26 09:40:36 by cacharle #+# #+# # -# Updated: 2021/02/27 16:16:07 by cacharle ### ########.fr # +# Updated: 2021/02/28 10:53:38 by cacharle ### ########.fr # # # # ############################################################################ # @@ -17,12 +17,14 @@ import inspect import shutil import distutils from pathlib import Path +from typing import cast, List, Tuple import minishell_test.data from minishell_test.args import parse_args DATA_DIR = Path(inspect.getfile(minishell_test.data)).parent +CONFIG_FILENAME = Path('minishell_test.cfg') class ConfigParser(configparser.ConfigParser): @@ -42,93 +44,130 @@ class ConfigParser(configparser.ConfigParser): return self.get(section, options).strip().split('\n') -args = parse_args() -MINISHELL_DIR = Path(args.path).resolve() - -CONFIG_FILENAME = Path('minishell_test.cfg') - -config = ConfigParser() -config.read(DATA_DIR / 'default.cfg') -user_config = ConfigParser() -user_config.read(MINISHELL_DIR / CONFIG_FILENAME) - -for section in user_config: - if section not in config: - raise RuntimeError(f"Unknown section name: {section}") - for key in user_config[section]: - if key not in config[section]: - raise RuntimeError(f"Unknown key name: {key}") - -config.read_dict({**config, **user_config}) - -BONUS = config.getboolean('minishell_test', 'bonus') -EXEC_NAME = config.get('minishell_test', 'exec_name') -MAKE = config.getboolean('minishell_test', 'make') -MAKE_ARGS = config.getargs('minishell_test', 'make_args') -PAGER = config.getboolean('minishell_test', 'pager') -PAGER_PROG = config.get('minishell_test', 'pager_prog') -LOG_PATH = config.getpath('minishell_test', 'log_path') -CHECK_ERROR_MESSAGES = config.getboolean('minishell_test', 'check_error_messages') - -SHELL_AVAILABLE_COMMANDS = config.getmultiline('shell', 'available_commands') -SHELL_PATH_VARIABLE = config.get('shell', 'path_variable') - - -SHELL_REFERENCE_PATH = config.getpath('shell:reference', 'path') -SHELL_REFERENCE_ARGS = config.getargs('shell:reference', 'args') - -TIMEOUT_TEST = config.getfloat('timeout', 'test') -TIMEOUT_LEAKS = config.getfloat('timeout', 'leaks') - -xdg_cache_home = os.environ.get('XDG_CACHE_HOME') -home = os.environ.get('HOME') -if xdg_cache_home is not None: - CACHE_DIR = Path(xdg_cache_home) / 'minishell_test' -elif home is not None: - CACHE_DIR = Path(home) / '.cache' / 'minishell_test' -else: - CACHE_DIR = Path('.cache', 'minishell_test') - -SANDBOX_DIR = CACHE_DIR / 'sandbox' -SHELL_AVAILABLE_COMMANDS_DIR = CACHE_DIR / 'bin' - -SHELL_PATH_VARIABLE = SHELL_PATH_VARIABLE.format(shell_available_commands_dir=SHELL_AVAILABLE_COMMANDS_DIR) - -with open(DATA_DIR / 'lorem') as f: - LOREM = ' '.join(f.read().split('\n')) - -MINISHELL_EXEC_PATH = MINISHELL_DIR / EXEC_NAME - -MINISHELL_PREFIX = EXEC_NAME + ": " -SHELL_REFERENCE_PREFIX = str(SHELL_REFERENCE_PATH) + ": " - -EXIT_FIRST = args.exit_first -RANGE = args.range -CHECK_LEAKS = args.check_leaks - -if RANGE is not None or CHECK_LEAKS: - SHOW_RANGE = True -else: - SHOW_RANGE = args.show_range - -if CHECK_LEAKS: - valgrind_path = distutils.spawn.find_executable("valgrind") - if valgrind_path is None: - raise RuntimeError("Could not find valgrind command on your system") - VALGRIND_CMD = [ - str(valgrind_path), - "--trace-children=no", - "--leak-check=yes", - "--child-silent-after-fork=yes", - "--show-leak-kinds=definite", - str(MINISHELL_EXEC_PATH), - ] - -TERM_COLS = shutil.get_terminal_size().columns -if TERM_COLS < 40: - raise RuntimeError("You're terminal isn't wide enough 40 cols minimum required") - -PLATFORM = sys.platform -supported = ['linux', 'darwin'] -if PLATFORM not in supported: - raise RuntimeError("Your platform ({PLATFORM}) is not supported, supported platforms are: {', '.join(supported)}") +class Config(): + minishell_dir = cast(Path, None) + bonus = cast(bool, None) + exec_name = cast(str, None) + make = cast(bool, None) + make_args = cast(List[str], None) + pager = cast(bool, None) + pager_prog = cast(Path, None) + log_path = cast(Path, None) + check_error_messages = cast(bool, None) + shell_available_commands = cast(List[str], None) + shell_path_variable = cast(str, None) + shell_reference_path = cast(Path, None) + shell_reference_args = cast(List[str], None) + timeout_test = cast(float, None) + timeout_leaks = cast(float, None) + cache_dir = cast(Path, None) + sandbox_dir = cast(Path, None) + shell_available_commands_dir = cast(Path, None) + lorem = cast(str, None) + minishell_exec_path = cast(Path, None) + minishell_prefix = cast(str, None) + shell_reference_prefix = cast(str, None) + exit_first = cast(bool, None) + range = cast(Tuple[int, int], None) + check_leaks = cast(bool, None) + show_range = cast(bool, None) + valgrind_cmd = cast(List[str], None) + term_cols = cast(int, None) + platform = cast(str, None) + + @classmethod + def init(cls, args): + if isinstance(args, list): + args = parse_args(sys.argv[1:]) + + cls.minishell_dir = Path(args.path).resolve() + + cfg = cls._load_cfg() + + cls.bonus = cfg.getboolean('minishell_test', 'bonus') + cls.exec_name = cfg.get('minishell_test', 'exec_name') + cls.make = cfg.getboolean('minishell_test', 'make') + cls.make_args = cfg.getargs('minishell_test', 'make_args') + cls.pager = cfg.getboolean('minishell_test', 'pager') + cls.pager_prog = cfg.get('minishell_test', 'pager_prog') + cls.log_path = cfg.getpath('minishell_test', 'log_path') + cls.check_error_messages = cfg.getboolean('minishell_test', 'check_error_messages') + + cls.shell_available_commands = cfg.getmultiline('shell', 'available_commands') + cls.shell_path_variable = cfg.get('shell', 'path_variable') + + cls.shell_reference_path = cfg.getpath('shell:reference', 'path') + cls.shell_reference_args = cfg.getargs('shell:reference', 'args') + + cls.timeout_test = cfg.getfloat('timeout', 'test') + cls.timeout_leaks = cfg.getfloat('timeout', 'leaks') + + xdg_cache_home = os.environ.get('XDG_CACHE_HOME') + home = os.environ.get('HOME') + if xdg_cache_home is not None: + cls.cache_dir = Path(xdg_cache_home) / 'minishell_test' + elif home is not None: + cls.cache_dir = Path(home) / '.cache' / 'minishell_test' + else: + cls.cache_dir = Path('.cache', 'minishell_test') + + cls.sandbox_dir = cls.cache_dir / 'sandbox' + cls.shell_available_commands_dir = cls.cache_dir / 'bin' + + cls.shell_path_variable = cls.shell_path_variable.format(shell_available_commands_dir=cls.shell_available_commands_dir) + + with open(DATA_DIR / 'lorem') as f: + cls.lorem = ' '.join(f.read().split('\n')) + + cls.minishell_exec_path = cls.minishell_dir / cls.exec_name + + cls.minishell_prefix = cls.exec_name + ": " + cls.shell_reference_prefix = str(cls.shell_reference_path) + ": " + + cls.exit_first = args.exit_first + cls.range = args.range + cls.check_leaks = args.check_leaks + + if cls.range is not None or cls.check_leaks: + cls.show_range = True + else: + cls.show_range = args.show_range + + if cls.check_leaks: + valgrind_path = distutils.spawn.find_executable("valgrind") + if valgrind_path is None: + raise RuntimeError("could not find valgrind command on your system") + cls.valgrind_cmd = [ + str(valgrind_path), + "--trace-children=no", + "--leak-check=yes", + "--child-silent-after-fork=yes", + "--show-leak-kinds=definite", + str(cls.minishell_exec_path), + ] + + cls.term_cols = shutil.get_terminal_size().columns + if cls.term_cols < 40: + raise RuntimeError("You're terminal isn't wide enough 40 cols minimum required") + + cls.platform = sys.platform + supported = ['linux', 'darwin'] + if cls.platform not in supported: + raise RuntimeError("Your platform ({cls.platform}) is not supported, supported platforms are: {', '.join(supported)}") + + @classmethod + def _load_cfg(cls): + cfg = ConfigParser() + cfg.read(DATA_DIR / 'default.cfg') + user_cfg = ConfigParser() + user_cfg.read(cls.minishell_dir / CONFIG_FILENAME) + + for section in user_cfg: + if section not in cfg: + raise RuntimeError(f"Unknown section name: {section}") + for key in user_cfg[section]: + if key not in cfg[section]: + raise RuntimeError(f"Unknown key name: {key}") + + cfg.read_dict({**cfg, **user_cfg}) + return cfg diff --git a/minishell_test/hooks.py b/minishell_test/hooks.py index a1447cd..67c3f84 100644 --- a/minishell_test/hooks.py +++ b/minishell_test/hooks.py @@ -12,7 +12,7 @@ import re -from minishell_test import config +from minishell_test.config import Config def sort_lines(output): @@ -22,16 +22,16 @@ def sort_lines(output): def error_line0(output): """Replace "/bin/bash: -c: line n:" by "minishell:" and delete the second line""" - if not config.CHECK_ERROR_MESSAGES: + if not Config.check_error_messages: return "DISCARDED BY TEST" lines = output.split('\n') if len(lines) != 3: return output - prefix = config.SHELL_REFERENCE_PREFIX + "-c: " + prefix = Config.shell_reference_prefix + "-c: " if not lines[0].startswith(prefix): return output - return lines[0].replace(prefix, config.MINISHELL_PREFIX, 1) + "\n" + return lines[0].replace(prefix, Config.minishell_prefix, 1) + "\n" def discard(output): @@ -41,7 +41,7 @@ def discard(output): def export_singleton(output): """Remove variable that are not set to anything in a call to export without arguments""" - prefix = "export " if ("--posix" in config.SHELL_REFERENCE_ARGS) else "declare -x " + prefix = "export " if ("--posix" in Config.shell_reference_args) else "declare -x " return sort_lines( '\n'.join([line for line in output.split('\n') if re.match("^{}[a-zA-Z_][a-zA-Z0-9_]*$".format(prefix), line) is None]) @@ -57,9 +57,9 @@ def replace_double(s): def platform_status(darwin_status, linux_status, windows_status=None): def hook(status): - if config.PLATFORM == "darwin": + if Config.platform == "darwin": return status - elif config.PLATFORM == "linux": + elif Config.platform == "linux": return (darwin_status if status == linux_status else status) return status return hook @@ -68,7 +68,7 @@ def platform_status(darwin_status, linux_status, windows_status=None): def linux_only(func): """ Decorator for hooks that only need to be executed on linux """ def hook(output): - if not config.PLATFORM == "linux": + if not Config.platform == "linux": return output return func(output) return hook diff --git a/minishell_test/sandbox.py b/minishell_test/sandbox.py index 980cfe7..d579847 100644 --- a/minishell_test/sandbox.py +++ b/minishell_test/sandbox.py @@ -14,13 +14,13 @@ import shutil import subprocess from contextlib import contextmanager -from minishell_test import config +from minishell_test.config import Config def create(): """Create a new sandbox directory""" try: - config.SANDBOX_DIR.mkdir(parents=True, exist_ok=True) + Config.sandbox_dir.mkdir(parents=True, exist_ok=True) except OSError: pass @@ -30,10 +30,10 @@ def remove(): Brute force rm -rf if clean removal doesn't work due to permissions. """ try: - shutil.rmtree(config.SANDBOX_DIR) + shutil.rmtree(Config.sandbox_dir) except PermissionError: - subprocess.run(["chmod", "777", *config.SANDBOX_DIR.glob("*")], check=True) - shutil.rmtree(config.SANDBOX_DIR) + subprocess.run(["chmod", "777", *Config.sandbox_dir.glob("*")], check=True) + shutil.rmtree(Config.sandbox_dir) except FileNotFoundError: pass diff --git a/minishell_test/suite/suite.py b/minishell_test/suite/suite.py index 5d36600..b1aba4f 100644 --- a/minishell_test/suite/suite.py +++ b/minishell_test/suite/suite.py @@ -12,7 +12,7 @@ from typing import List, Tuple, Optional, Callable -from minishell_test import config +from minishell_test.config import Config from minishell_test.test import Test @@ -49,7 +49,7 @@ class Suite: def run_all(cls): """Run all available suites""" for s in cls.available: - if not s.run() and config.EXIT_FIRST: + if not s.run() and Config.exit_first: break @classmethod @@ -57,7 +57,7 @@ class Suite: """ Remove not asked suite from available suites Tries to autocomplete the asked names """ - if not config.BONUS: + if not Config.bonus: cls.available = [s for s in cls.available if not s.bonus] if len(asked_names) == 0: asked_names = [s.name for s in cls.available] @@ -143,14 +143,14 @@ class Suite: self.BLUE_CHARS, " " + self.name + " ", self.CLOSE_CHARS, - width=config.TERM_COLS + width=Config.term_cols )) for i, t in enumerate(self.tests): - if config.RANGE is not None: - if not (config.RANGE[0] <= i <= config.RANGE[1]): + if Config.range is not None: + if not (Config.range[0] <= i <= Config.range[1]): continue t.run(i) - if config.EXIT_FIRST and t.result is not None and t.result.failed: + if Config.exit_first and t.result is not None and t.result.failed: return False return True @@ -177,14 +177,14 @@ class Suite: pass_sum += pass_total fail_sum += fail_total print("{:.<{width}} \033[32m{:4} [PASS]\033[0m \033[31m{:4} [FAIL]\033[0m" - .format(s.name + " ", pass_total, fail_total, width=config.TERM_COLS - 24)) + .format(s.name + " ", pass_total, fail_total, width=Config.term_cols - 24)) print("{:.<{width}} \033[32m{:4} [PASS]\033[0m \033[31m{:4} [FAIL]\033[0m" - .format("TOTAL ", pass_sum, fail_sum, width=config.TERM_COLS - 24)) + .format("TOTAL ", pass_sum, fail_sum, width=Config.term_cols - 24)) @classmethod def save_log(cls): """Save the result of all suites to a file""" - with open(config.LOG_PATH, "w") as log_file: + with open(Config.log_path, "w") as log_file: for s in cls.available: for t in s.tests: if t.result is not None and t.result.failed: diff --git a/minishell_test/suites/builtin.py b/minishell_test/suites/builtin.py index 2591bc3..900bd93 100644 --- a/minishell_test/suites/builtin.py +++ b/minishell_test/suites/builtin.py @@ -13,7 +13,7 @@ import os -from minishell_test import config +from minishell_test.config import Config from minishell_test import hooks from minishell_test.suite.decorator import suite from minishell_test.hooks import linux_discard @@ -26,12 +26,12 @@ def suite_echo(test): test("echo bonjour") test("echo lalalala lalalalal alalalalal alalalala") test("echo lalalala lalalalal alalalalal alalalala") - test("echo " + config.LOREM) + test("echo " + Config.lorem) test("echo -n") test("echo -n bonjour") test("echo -n lalalala lalalalal alalalalal alalalala") test("echo -n lalalala lalalalal alalalalal alalalala") - test("echo -n " + config.LOREM) + test("echo -n " + Config.lorem) test("echo bonjour -n") test("echo -n bonjour -n") test(" echo bonjour je") @@ -393,7 +393,7 @@ def suite_exit(test): test("exit bonjour 0", hook_status=hooks.platform_status(255, 2)) test("exit 0 1") test("exit 0 1 2 3 4 5 6 7 8 9") - test("exit " + config.LOREM, hook_status=hooks.platform_status(255, 2)) + test("exit " + Config.lorem, hook_status=hooks.platform_status(255, 2)) test("exit bonjoru; echo should have exited", hook_status=hooks.platform_status(255, 2)) test("exit 99999999999999999999999999999999999999999999999999999; echo should have exited", hook_status=hooks.platform_status(255, 2)) test("exit 9999; echo should have exited") diff --git a/minishell_test/suites/cmd.py b/minishell_test/suites/cmd.py index 8d2bc09..66acf97 100644 --- a/minishell_test/suites/cmd.py +++ b/minishell_test/suites/cmd.py @@ -13,7 +13,7 @@ import distutils from minishell_test import hooks -from minishell_test import config +from minishell_test.config import Config from minishell_test.suite.decorator import suite @@ -105,8 +105,8 @@ def suite_cmd(test): "asd f asd f asdf asdf asdf asd f asd f asd f asd f as df as df a" "asd f asd f asdf asdf asdf asd f asd f asd f asd f as df as df a" "asd f asd f asdf asdf asdf asd f asd f asd f asd f as df as df a") - test("echo " + config.LOREM * 10) - test("echo " + config.LOREM * 20) + test("echo " + Config.lorem * 10) + test("echo " + Config.lorem * 20) @suite() diff --git a/minishell_test/suites/flow.py b/minishell_test/suites/flow.py index aa6d395..ff3b51f 100644 --- a/minishell_test/suites/flow.py +++ b/minishell_test/suites/flow.py @@ -10,7 +10,7 @@ # # # ############################################################################ # -from minishell_test import config +from minishell_test.config import Config from minishell_test.suite.decorator import suite from minishell_test.hooks import ( error_line0, @@ -241,10 +241,10 @@ def suite_syntax_error(test): test("> a ; a", hook=error_line0) test("< a ; a", hook=error_line0) test(">> a ; a", hook=error_line0) - test(config.LOREM + " > >" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) - test(config.LOREM + " < <" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) - test(config.LOREM + " ; |" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) - test(config.LOREM + " | ;" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " > >" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " < <" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " ; |" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " | ;" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) @suite(bonus=True) @@ -289,8 +289,8 @@ def suite_syntax_error_bonus(test): test("() a", hook=error_line0, hook_status=platform_status(2, 1)) test("( a", hook=[error_line0, error_eof_to_expected_token], hook_status=platform_status(2, 1)) test(") a", hook=error_line0, hook_status=platform_status(2, 1)) - test(config.LOREM + " && &&" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) - test(config.LOREM + " || ||" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) - test(config.LOREM + " ( (" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) - test(config.LOREM + " ) )" + config.LOREM, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " && &&" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " || ||" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " ( (" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) + test(Config.lorem + " ) )" + Config.lorem, hook=error_line0, hook_status=platform_status(2, 1)) test("(); () ;() ;() ;() ;() ;() ;() ;() ;() ;a", hook=error_line0, hook_status=platform_status(2, 1)) diff --git a/minishell_test/suites/preprocess.py b/minishell_test/suites/preprocess.py index c296dcb..e3b5ff5 100644 --- a/minishell_test/suites/preprocess.py +++ b/minishell_test/suites/preprocess.py @@ -10,7 +10,7 @@ # # # **************************************************************************** # -from minishell_test import config +from minishell_test.config import Config from minishell_test import hooks from minishell_test.suite.decorator import suite @@ -128,9 +128,9 @@ def suite_interpolation(test): test('echo $A\\ ', exports={"A": "bonjour je suis splited"}) test('echo $A\\ ', exports={"A": " bonjour je suis splited "}) test('echo $A$A$A', exports={"A": " bonjour je suis splited "}) - test("echo $A", exports={"A": "'" + config.LOREM + "'"}) - test('echo "$A"', exports={"A": "'" + config.LOREM + "'"}) - test("echo '$A'", exports={"A": "'" + config.LOREM + "'"}) + test("echo $A", exports={"A": "'" + Config.lorem + "'"}) + test('echo "$A"', exports={"A": "'" + Config.lorem + "'"}) + test("echo '$A'", exports={"A": "'" + Config.lorem + "'"}) test("$ECHO $ECHO", exports={"ECHO": "echo"}) test("$A$B bonjour", exports={"A": "ec", "B": "ho"}) test("$LS", exports={"LS": "ls -l"}, setup="touch a b c") diff --git a/minishell_test/test/captured.py b/minishell_test/test/captured.py index 6ba861b..8c217a3 100644 --- a/minishell_test/test/captured.py +++ b/minishell_test/test/captured.py @@ -13,7 +13,7 @@ import re from typing import List, Optional -from minishell_test import config +from minishell_test.config import Config class Captured: @@ -34,8 +34,8 @@ class Captured: lines = output.split('\n') for i, line in enumerate(lines): lines[i] = line = re.sub("line [01]: ", "", lines[i], 1) - if line.startswith(config.SHELL_REFERENCE_PREFIX): - lines[i] = config.MINISHELL_PREFIX + line[len(config.SHELL_REFERENCE_PREFIX):] + if line.startswith(Config.shell_reference_prefix): + lines[i] = Config.minishell_prefix + line[len(Config.shell_reference_prefix):] self.output = '\n'.join(lines) self.status = status diff --git a/minishell_test/test/result.py b/minishell_test/test/result.py index 87eeb5d..93c576a 100644 --- a/minishell_test/test/result.py +++ b/minishell_test/test/result.py @@ -13,7 +13,7 @@ import re from typing import Match, List, Optional -from minishell_test import config +from minishell_test.config import Config from minishell_test.test.captured import Captured @@ -42,12 +42,12 @@ class BaseResult: def __repr__(self): """Returns a representation of the result based on the verbosity""" printed = self._escaped_cmd[:] - if config.SHOW_RANGE: + if Config.show_range: printed = "{:2}: ".format(self.index) + printed - if len(printed) > config.TERM_COLS - 7: - printed = printed[:config.TERM_COLS - 10] + "..." + if len(printed) > Config.term_cols - 7: + printed = printed[:Config.term_cols - 10] + "..." fmt = self.green("{:{width}} [PASS]") if self.passed else self.red("{:{width}} [FAIL]") - return fmt.format(printed, width=config.TERM_COLS - 7) + return fmt.format(printed, width=Config.term_cols - 7) def put(self, index: int) -> None: """Print a summary of the result""" diff --git a/minishell_test/test/test.py b/minishell_test/test/test.py index c0e402f..e502588 100644 --- a/minishell_test/test/test.py +++ b/minishell_test/test/test.py @@ -6,7 +6,7 @@ # By: charles <charles.cabergs@gmail.com> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2020/06/16 21:48:50 by charles #+# #+# # -# Updated: 2021/02/27 12:19:15 by cacharle ### ########.fr # +# Updated: 2021/02/28 10:42:37 by cacharle ### ########.fr # # # # ############################################################################ # @@ -16,7 +16,7 @@ import subprocess from pathlib import Path from typing import Optional, List, Dict, Union, Callable -from minishell_test import config +from minishell_test.config import Config from minishell_test.test.captured import Captured from minishell_test.test.result import Result, LeakResult from minishell_test import sandbox @@ -32,7 +32,7 @@ class Test: setup: str = "", files: List[str] = [], exports: Dict[str, str] = {}, - timeout: float = config.TIMEOUT_TEST, + timeout: float = -1, hook: HookType = [], hook_status: HookStatusType = [], ): @@ -50,7 +50,7 @@ class Test: self.files = files self.exports = exports self.result: Optional[Union[Result, LeakResult]] = None - self.timeout = timeout + self.timeout = timeout if timeout < 0 else Config.timeout_test if not isinstance(hook, list): hook = [hook] if not isinstance(hook_status, list): @@ -61,16 +61,16 @@ class Test: def run(self, index: int) -> None: """ Run the test for minishell and the reference shell and print the result out """ - if config.CHECK_LEAKS: + if Config.check_leaks: self.hook = [] self.hook_status = [] - captured = self._run_sandboxed([*config.VALGRIND_CMD, "-c"]) + captured = self._run_sandboxed([*Config.valgrind_cmd, "-c"]) self.result = LeakResult(self.full_cmd, captured) self.result.put(index) return - expected = self._run_sandboxed([config.SHELL_REFERENCE_PATH, *config.SHELL_REFERENCE_ARGS, "-c"]) - actual = self._run_sandboxed([config.MINISHELL_EXEC_PATH, "-c"]) + expected = self._run_sandboxed([Config.shell_reference_path, *Config.shell_reference_args, "-c"]) + actual = self._run_sandboxed([Config.minishell_exec_path, "-c"]) self.result = Result(self.full_cmd, self.files, expected, actual) self.result.put(index) @@ -82,7 +82,7 @@ class Test: subprocess.run( self.setup, shell=True, - cwd=config.SANDBOX_DIR, + cwd=Config.sandbox_dir, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, check=True @@ -105,9 +105,9 @@ class Test: [*shell_cmd, self.cmd], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, - cwd=config.SANDBOX_DIR, + cwd=Config.sandbox_dir, env={ - 'PATH': config.SHELL_PATH_VARIABLE, + 'PATH': Config.shell_path_variable, 'TERM': 'xterm-256color', **self.exports, }, @@ -116,7 +116,7 @@ class Test: # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.communicate try: stdout, _ = process.communicate( - timeout=(self.timeout if not config.CHECK_LEAKS else config.TIMEOUT_LEAKS)) + timeout=(self.timeout if not Config.check_leaks else Config.timeout_leaks)) except subprocess.TimeoutExpired: process.kill() # _, _ = process.communicate(timeout=2) @@ -130,7 +130,7 @@ class Test: files_content: List[Optional[str]] = [] for file_name in self.files: try: - with open(os.path.join(config.SANDBOX_DIR, file_name), "rb") as f: + with open(os.path.join(Config.sandbox_dir, file_name), "rb") as f: files_content.append(f.read().decode()) except FileNotFoundError: files_content.append(None) |
