Beispiel #1
0
def test_email_invalid(email_input, error_msg):
    with pytest.raises(EmailSyntaxError) as exc_info:
        validate_email(email_input)
    # print(f'({email_input!r}, {str(exc_info.value)!r}),')

    if isinstance(error_msg, set):
        assert str(exc_info.value) in error_msg
    else:
        assert str(exc_info.value) == error_msg
Beispiel #2
0
def test_main_single_good_input(monkeypatch, capsys):
    # stdlib
    import json
    test_email = "*****@*****.**"
    monkeypatch.setattr("sys.argv", ["email_validator", test_email])
    validator_main()
    stdout, _ = capsys.readouterr()
    output = json.loads(str(stdout))
    assert isinstance(output, dict)
    assert validate_email(
        test_email).original_email == output["original_email"]
Beispiel #3
0
def test_email_valid(
    email_input: str,
    output: ValidatedEmail,
    advanced_file_regression: AdvancedFileRegressionFixture,
):
    # print(f'({email_input!r}, {validate_email(email_input)!r}),')
    assert validate_email(email_input) == output

    data = output.as_dict()
    data["__repr__"] = repr(output)
    data["__str__"] = str(output)
    advanced_file_regression.check(json.dumps(data), extension=".json")
    def _parse_authors(config: Dict[str, TOML_TYPES],
                       key_name: str = "authors") -> List[Author]:
        all_authors: List[Author] = []

        for idx, author in enumerate(config[key_name]):
            name = author.get("name", None)
            email = author.get("email", None)

            if name is not None and ',' in name:
                raise BadConfigError(
                    f"The 'project.{key_name}[{idx}].name' key cannot contain commas."
                )

            if email is not None:
                try:
                    email = validate_email(email).email
                except EmailSyntaxError as e:
                    raise BadConfigError(f"Invalid email {email!r}: {e} ")

            all_authors.append({"name": name, "email": email})

        return all_authors
Beispiel #5
0
def wizard() -> None:
    """
	Run the wizard 🧙 to create a 'repo_helper.yml' file.
	"""

    # stdlib
    import datetime
    import getpass
    import os
    import socket

    # 3rd party
    from apeye.email_validator import EmailSyntaxError, validate_email
    from consolekit.terminal_colours import Fore
    from domdf_python_tools.paths import PathPlus
    from dulwich.errors import NotGitRepository
    from ruamel.yaml import scalarstring
    from southwark.repo import Repo

    # this package
    from repo_helper.utils import _round_trip_dump, license_lookup

    path = PathPlus.cwd()
    config_file = path / "repo_helper.yml"

    try:
        r = Repo(path)
    except NotGitRepository:

        with Fore.RED:
            click.echo(f"The directory {path} is not a git repository.")
            click.echo(
                "You may need to run 'git init' in that directory first.")

        raise click.Abort

    # ---------- intro ----------
    click.echo(
        "This wizard 🧙‍will guide you through creating a 'repo_helper.yml' configuration file."
    )
    click.echo(f"This will be created in '{config_file}'.")
    if not confirm("Do you want to continue?"):
        raise click.Abort()

    # ---------- file exists warning ----------
    if config_file.is_file():
        click.echo(
            f"\nWoah! That file already exists. It will be overwritten if you continue!"
        )
        if not confirm("Are you sure you want to continue?"):
            raise click.Abort()

    click.echo("\nDefault options are indicated in [square brackets].")

    # ---------- modname ----------
    click.echo("\nThe name of the library/project.")
    modname = prompt("Name")

    # ---------- name ----------
    click.echo("\nThe name of the author.")
    click.echo("The author is usually the person who wrote the library.")

    git_config = r.get_config_stack()

    try:
        default_author = git_config.get(("user", ), "name").decode("UTF-8")
    except KeyError:
        try:
            getpass_user = getpass.getuser()
            default_author = os.getenv(
                "GIT_AUTHOR_NAME",
                default=os.getenv("GIT_COMMITTER_NAME", default=getpass_user),
            )
        except ImportError:
            # Usually USERNAME is not set when trying getpass.getuser()
            default_author = ''

    author = prompt("Name", default=default_author)

    # ---------- email ----------
    try:
        default_email = git_config.get(("user", ), "email").decode("UTF-8")
    except KeyError:
        default_email = os.getenv(
            "GIT_AUTHOR_EMAIL",
            default=os.getenv("GIT_COMMITTER_EMAIL",
                              default=f"{author}@{socket.gethostname()}"))

    click.echo(
        "\nThe email address of the author. This will be shown on PyPI, amongst other places."
    )

    while True:
        try:
            email = validate_email(prompt("Email",
                                          default=default_email)).email
            break
        except EmailSyntaxError:
            click.echo("That is not a valid email address.")

    # ---------- username ----------
    click.echo("\nThe username of the author.")
    click.echo(
        "(repo_helper naïvely assumes that you use the same username on GitHub as on other sites.)"
    )
    username = prompt("Username", default=author)
    # TODO: validate username

    # ---------- version ----------
    click.echo("\nThe version number of the library, in semver format.")
    version = prompt("Version number", default="0.0.0")

    # ---------- copyright_years ----------
    click.echo("\nThe copyright years for the library.")
    copyright_years = prompt("Copyright years",
                             default=str(datetime.datetime.today().year),
                             type=str)

    # ---------- license_ ----------
    click.echo("""
The SPDX identifier for the license this library is distributed under.
Not all SPDX identifiers are allowed as not all map to PyPI Trove classifiers."""
               )
    while True:
        license_ = prompt("License")

        if license_ in license_lookup:
            break
        else:
            click.echo("That is not a valid identifier.")

    # ---------- short_desc ----------
    click.echo("\nEnter a short, one-line description for the project.")
    short_desc = prompt("Description")

    # ---------- writeout ----------

    data = {
        "modname": modname,
        "copyright_years": copyright_years,
        "author": author,
        "email": email,
        "username": username,
        "version": str(version),
        "license": license_,
        "short_desc": short_desc,
    }

    data = {
        k: scalarstring.SingleQuotedScalarString(v)
        for k, v in data.items()
    }

    config_file.write_lines([
        "# Configuration for 'repo_helper' (https://github.com/repo-helper/repo_helper)",
        "---",
        _round_trip_dump(data),
        "enable_conda: false",
    ])

    click.echo(f"""
The options you provided have been written to the file {config_file}.
You can configure additional options in that file.

The schema for the Yaml file can be found at:
	https://github.com/repo-helper/repo_helper/blob/master/repo_helper/repo_helper_schema.json
You may be able to configure your code editor to validate your configuration file against that schema.

repo_helper can now be run with the 'repo_helper' command in the repository root.

Be seeing you!
""")
Beispiel #6
0
def test_dict_accessor():
    input_email = "*****@*****.**"
    valid_email = validate_email(input_email)
    assert isinstance(valid_email.as_dict(), dict)
    assert valid_email.as_dict()["original_email"] == input_email