Beispiel #1
0
    def test_exmod_module_directory(self) -> None:
        """Tests `exmod` module whence directory"""

        with TemporaryDirectory() as tempdir, self.assertRaises(NotImplementedError):
            exmod(
                module=tempdir,
                emit_name=None,
                blacklist=["foo", "bar"],
                whitelist=tuple(),
                output_directory=tempdir,
                dry_run=False,
            )
Beispiel #2
0
    def test_exmod_whitelist(self) -> None:
        """Tests `exmod` whitelist"""

        with TemporaryDirectory() as tempdir, self.assertRaises(NotImplementedError):
            exmod(
                module="unittest",
                emit_name=None,
                blacklist=tuple(),
                whitelist=("unittest.TestCase",),
                output_directory=tempdir,
                dry_run=False,
            )
Beispiel #3
0
    def test_exmod_output_directory_nonexistent(self) -> None:
        """Tests `exmod` module whence directory does not exist"""

        with TemporaryDirectory() as tempdir, self.assertRaises(AssertionError):
            output_directory = path.join(tempdir, "stuff")
            self.assertFalse(path.isdir(output_directory))
            exmod(
                module=output_directory,
                emit_name=None,
                blacklist=tuple(),
                whitelist=tuple(),
                output_directory=output_directory,
                dry_run=False,
            )
Beispiel #4
0
    def test_exmod(self) -> None:
        """Tests `exmod`"""

        try:
            with TemporaryDirectory(
                prefix="gold", suffix="gold"
            ) as existent_module_dir, TemporaryDirectory(
                prefix="gen", suffix="gen"
            ) as new_module_dir:
                self.create_fs(existent_module_dir)
                self._pip(["install", "."], existent_module_dir)
                exmod(
                    module=self.module_name,
                    emit_name="class",
                    blacklist=tuple(),
                    whitelist=tuple(),
                    output_directory=new_module_dir,
                    dry_run=False,
                )
                self.check_emission(new_module_dir)
        finally:
            self._pip(["uninstall", "-y", self.module_name])
Beispiel #5
0
def main(cli_argv=None, return_args=False):
    """
    Run the CLI parser

    :param cli_argv: CLI arguments. If None uses `sys.argv`.
    :type cli_argv: ```Optional[List[str]]```

    :param return_args: Primarily use is for tests. Returns the args rather than executing anything.
    :type return_args: ```bool```

    :returns: the args if `return_args`, else None
    :rtype: ```Optional[Namespace]```
    """
    _parser = _build_parser()
    args = _parser.parse_args(args=cli_argv)
    command = args.command
    args_dict = {k: v for k, v in vars(args).items() if k != "command"}
    if command == "sync":
        args = Namespace(
            **{
                k: v if k == "truth" or isinstance(v, list) or v is None else [v]
                for k, v in args_dict.items()
            }
        )

        truth_file = getattr(args, pluralise(args.truth))
        require_file_existent(
            _parser, truth_file[0] if truth_file else truth_file, name="truth"
        )
        truth_file = path.realpath(path.expanduser(truth_file[0]))

        number_of_files = sum(
            len(val)
            for key, val in vars(args).items()
            if isinstance(val, list) and not key.endswith("_names")
        )

        if number_of_files < 2:
            _parser.error(
                "Two or more of `--argparse-function`, `--class`, and `--function` must"
                " be specified"
            )
        require_file_existent(_parser, truth_file, name="truth")

        return args if return_args else ground_truth(args, truth_file)
    elif command == "sync_properties":
        deque(
            (
                setattr(
                    args, fname, path.realpath(path.expanduser(getattr(args, fname)))
                )
                for fname in ("input_filename", "output_filename")
                if path.isfile(getattr(args, fname))
            ),
            maxlen=0,
        )

        for filename, arg_name in (args.input_filename, "input-file"), (
            args.output_filename,
            "output-file",
        ):
            require_file_existent(_parser, filename, name=arg_name)
        sync_properties(**args_dict)
    elif command == "gen":
        if path.isfile(args.output_filename):
            raise IOError(
                "File exists and this is a destructive operation. Delete/move {output_filename!r} then"
                " rerun.".format(output_filename=args.output_filename)
            )
        gen(**args_dict)
    elif command == "gen_routes":
        if args.route is None:
            args.route = "/api/{model_name}".format(model_name=args.model_name.lower())

        (
            lambda routes__primary_key: upsert_routes(
                app=args.app_name,
                route=args.route,
                routes=routes__primary_key[0],
                routes_path=getattr(args, "routes_path", None),
                primary_key=routes__primary_key[1],
            )
        )(
            gen_routes(
                app=args.app_name,
                crud=args.crud,
                model_name=args.model_name,
                model_path=args.model_path,
                route=args.route,
            )
        )
    elif command == "openapi":
        openapi_bulk(
            app_name=args.app_name,
            model_paths=args.model_paths,
            routes_paths=args.routes_paths,
        )
    elif command == "doctrans":
        require_file_existent(_parser, args.filename, name="filename")
        doctrans(
            filename=args.filename,
            docstring_format=args.format,
            type_annotations=args.type_annotations,
        )
    elif command == "exmod":
        exmod(
            module=args.module,
            emit_name=args.emit,
            blacklist=args.blacklist,
            whitelist=args.whitelist,
            output_directory=args.output_directory,
            dry_run=args.dry_run,
        )
Beispiel #6
0
    def test_exmod_dry_run(self) -> None:
        """Tests `exmod` dry_run"""

        try:
            with TemporaryDirectory(
                prefix="gold", suffix="gold"
            ) as existent_module_dir, TemporaryDirectory(
                prefix="gen", suffix="gen"
            ) as new_module_dir:
                self.create_fs(existent_module_dir)
                self._pip(["install", "."], existent_module_dir)

                with patch("sys.stdout", new_callable=StringIO) as f:
                    exmod(
                        module=self.module_name,
                        emit_name="class",
                        blacklist=tuple(),
                        whitelist=tuple(),
                        output_directory=new_module_dir,
                        dry_run=True,
                    )
                    r = f.getvalue()

                result = dict(
                    map(
                        lambda k_v: (
                            k_v[0],
                            tuple(
                                sorted(
                                    set(
                                        map(
                                            partial(
                                                relative_filename,
                                                remove_hints=(
                                                    (
                                                        lambda directory: unquote(
                                                            repr(directory)
                                                        )
                                                        + path.sep
                                                        if platform == "win32"
                                                        else directory
                                                    )(
                                                        path.join(
                                                            new_module_dir,
                                                            path.basename(
                                                                new_module_dir
                                                            ),
                                                        ),
                                                    ),
                                                ),
                                            ),
                                            map(unquote, map(itemgetter(1), k_v[1])),
                                        )
                                    )
                                )
                            ),
                        ),
                        groupby(
                            map(rpartial(str.split, "\t", 2), sorted(r.splitlines())),
                            key=itemgetter(0),
                        ),
                    )
                )

                all_tests_running = len(result["write"]) == 7

                key_counts = (
                    (("mkdir", 7), ("touch", 4), ("write", 7))
                    if all_tests_running
                    else (("mkdir", 7), ("touch", 4), ("write", 4))
                )

                for key, count in key_counts:
                    self.assertEqual(len(result[key]), count, key)

                gold_module_name = next(
                    map(
                        lambda p: p.partition(path.sep)[0],
                        filter(rpartial(str.startswith, "gold"), result["write"]),
                    ),
                    "",
                )

                expect = {
                    k: tuple(map(unquote, map(repr, v)))
                    for k, v in {
                        "mkdir": (
                            new_module_dir,
                            self.module_hierarchy[0][1],
                            self.module_hierarchy[1][1],
                            path.join(
                                self.module_hierarchy[1][1],
                                self.module_hierarchy[1][0],
                            ),
                            self.module_hierarchy[2][1],
                            path.join(
                                self.module_hierarchy[2][1],
                                self.module_hierarchy[2][0],
                            ),
                            path.join(
                                self.module_hierarchy[0][1],
                                self.module_hierarchy[0][0],
                            ),
                        ),
                        "touch": (
                            "__init__{extsep}py".format(extsep=extsep),
                            path.join(
                                self.module_hierarchy[0][1],
                                "__init__{extsep}py".format(extsep=extsep),
                            ),
                            path.join(
                                self.module_hierarchy[1][1],
                                "__init__{extsep}py".format(extsep=extsep),
                            ),
                            path.join(
                                self.module_hierarchy[2][1],
                                "__init__{extsep}py".format(extsep=extsep),
                            ),
                        ),
                        "write": (
                            lambda write_block: tuple(
                                sorted(
                                    chain.from_iterable(
                                        (
                                            map(
                                                partial(path.join, gold_module_name),
                                                write_block[1:],
                                            ),
                                            write_block,
                                        )
                                    )
                                )
                            )
                            if all_tests_running
                            else write_block
                        )(
                            (
                                "__init__{extsep}py".format(extsep=extsep),
                                path.join(
                                    self.module_hierarchy[1][1],
                                    "{name}{extsep}py".format(
                                        name=self.module_hierarchy[1][0],
                                        extsep=extsep,
                                    ),
                                ),
                                path.join(
                                    self.module_hierarchy[2][1],
                                    "{name}{extsep}py".format(
                                        name=self.module_hierarchy[2][0],
                                        extsep=extsep,
                                    ),
                                ),
                                path.join(
                                    self.module_hierarchy[0][1],
                                    "{name}{extsep}py".format(
                                        name=self.module_hierarchy[0][0],
                                        extsep=extsep,
                                    ),
                                ),
                            )
                        ),
                    }.items()
                }

                self.assertDictEqual(result, expect)

                self.check_emission(new_module_dir, dry_run=True)
        finally:
            self._pip(["uninstall", "-y", self.module_name])