Exemplo n.º 1
0
def test_dispatch_to_subcommand(monkeypatch):
    replaced_main = pretend.call_recorder(lambda args: None)
    monkeypatch.setattr(twine.commands.upload, "main", replaced_main)

    cli.dispatch(["upload", "path/to/file"])

    assert replaced_main.calls == [pretend.call(["path/to/file"])]
Exemplo n.º 2
0
def test_dispatch_to_subcommand(monkeypatch):
    replaced_main = pretend.call_recorder(lambda args: None)
    monkeypatch.setattr(upload, "main", replaced_main)

    cli.dispatch(["upload", "path/to/file"])

    assert replaced_main.calls == [pretend.call(["path/to/file"])]
Exemplo n.º 3
0
    def build_and_upload(
        self,
        twine_password: str,
        clean: bool = True,
        repository_url: str = "https://test.pypi.org/legacy/",
    ):

        # Create the __init__ file if it does not exist
        create_file(path=os.path.join(self.target_directory, "__init__.py"),
                    content=None)
        # Create the README file if it does not exist
        create_file(path=os.path.join(self.target_directory, "README.md"),
                    content=self.readme)
        # Change to the target directory and generate the build artifacts
        print(f"Changing directory to {self.target_directory}")
        print(f"Dist path: {self.target_directory}/dist/*")
        os.chdir(self.target_directory)
        dist = setuptools.setup(**self.setup_params)
        command = [
            "upload",
            "--repository-url",
            repository_url,
            "--username",
            "__token__",
            "--password",
            twine_password,
            f"{self.target_directory}/dist/*",
        ]
        try:
            twine_cli.dispatch(command)
        except requests.exceptions.HTTPError as error:
            logger.info(error)
Exemplo n.º 4
0
def test_devpi_upload(devpi_server, uploadable_dist):
    command = [
        'upload',
        '--repository-url', devpi_server.url,
        '--username', devpi_server.username,
        '--password', devpi_server.password,
        str(uploadable_dist),
    ]
    dispatch(command)
Exemplo n.º 5
0
def test_pypi_upload(sampleproject_dist):
    command = [
        "upload",
        "--repository-url",
        "https://test.pypi.org/legacy/",
        "--username",
        "__token__",
        "--password",
        sampleproject_token,
        str(sampleproject_dist),
    ]
    cli.dispatch(command)
Exemplo n.º 6
0
def test_devpi_upload(devpi_server, uploadable_dist):
    command = [
        "upload",
        "--repository-url",
        devpi_server.url,
        "--username",
        devpi_server.username,
        "--password",
        devpi_server.password,
        str(uploadable_dist),
    ]
    cli.dispatch(command)
Exemplo n.º 7
0
def test_pypiserver_upload(pypiserver_instance, uploadable_dist):
    command = [
        'upload',
        '--repository-url',
        pypiserver_instance.url,
        '--username',
        'any',
        '--password',
        'any',
        str(uploadable_dist),
    ]
    dispatch(command)
Exemplo n.º 8
0
def test_pypi_upload(sampleproject_dist):
    command = [
        'upload',
        '--repository-url',
        'https://test.pypi.org/legacy/',
        '--username',
        '__token__',
        '--password',
        twine_sampleproject_token,
        str(sampleproject_dist),
    ]
    dispatch(command)
Exemplo n.º 9
0
def test_pypiserver_upload(pypiserver_instance, uploadable_dist):
    command = [
        "upload",
        "--repository-url",
        pypiserver_instance.url,
        "--username",
        "any",
        "--password",
        "any",
        str(uploadable_dist),
    ]
    cli.dispatch(command)
Exemplo n.º 10
0
def test_values_from_env(monkeypatch):
    def none_upload(*args, **kwargs):
        pass

    replaced_upload = pretend.call_recorder(none_upload)
    monkeypatch.setattr(twine.commands.upload, "upload", replaced_upload)
    testenv = {"TWINE_USERNAME": "******",
               "TWINE_PASSWORD": "******",
               "TWINE_CERT": "/foo/bar.crt"}
    with helpers.set_env(**testenv):
        cli.dispatch(["upload", "path/to/file"])
    upload_settings = replaced_upload.calls[0].args[0]
    assert "pypipassword" == upload_settings.password
    assert "pypiuser" == upload_settings.username
    assert "/foo/bar.crt" == upload_settings.cacert
Exemplo n.º 11
0
def test_password_and_username_from_env(monkeypatch):
    def none_upload(*args, **kwargs):
        pass

    replaced_upload = pretend.call_recorder(none_upload)
    monkeypatch.setattr(twine.commands.upload, "upload", replaced_upload)
    testenv = {"TWINE_USERNAME": "******", "TWINE_PASSWORD": "******"}
    with helpers.set_env(**testenv):
        cli.dispatch(["upload", "path/to/file"])
    cli.dispatch(["upload", "path/to/file"])
    result_kwargs = replaced_upload.calls[0].kwargs
    assert "pypipassword" == result_kwargs["password"]
    assert "pypiuser" == result_kwargs["username"]
    result_kwargs = replaced_upload.calls[1].kwargs
    assert None is result_kwargs["password"]
    assert None is result_kwargs["username"]
Exemplo n.º 12
0
def main():
    try:
        return dispatch(sys.argv[1:])
    except (exceptions.TwineException, requests.exceptions.HTTPError) as exc:
        return '{0}: {1}'.format(
            exc.__class__.__name__,
            exc.args[0],
        )
Exemplo n.º 13
0
def test_values_from_env(monkeypatch):
    """Test calling main via cli"""
    def none_register(*args, **settings_kwargs):
        pass

    replaced_register = pretend.call_recorder(none_register)
    monkeypatch.setattr(register, "register", replaced_register)
    testenv = {
        "TWINE_USERNAME": "******",
        "TWINE_PASSWORD": "******",
        "TWINE_CERT": "/foo/bar.crt",
    }
    with helpers.set_env(**testenv):
        cli.dispatch(["register", helpers.WHEEL_FIXTURE])
    register_settings = replaced_register.calls[0].args[0]
    assert "pypipassword" == register_settings.password
    assert "pypiuser" == register_settings.username
    assert "/foo/bar.crt" == register_settings.cacert
Exemplo n.º 14
0
def test_dispatch_to_subcommand(monkeypatch):
    process = pretend.stub(
        wait=pretend.call_recorder(lambda: None),
        returncode=0,
    )
    popen = pretend.call_recorder(lambda args: process)
    monkeypatch.setattr(cli.subprocess, "Popen", popen)

    rcode = cli.dispatch(["upload"])

    assert popen.calls == [pretend.call(["twine-upload"])]
    assert process.wait.calls == [pretend.call()]
    assert rcode == process.returncode
Exemplo n.º 15
0
def main() -> Any:
    try:
        result = cli.dispatch(sys.argv[1:])
    except requests.HTTPError as exc:
        status_code = exc.response.status_code
        status_phrase = http.HTTPStatus(status_code).phrase
        result = (f"{exc.__class__.__name__}: {status_code} {status_phrase} "
                  f"from {exc.response.url}\n"
                  f"{exc.response.reason}")
    except exceptions.TwineException as exc:
        result = f"{exc.__class__.__name__}: {exc.args[0]}"

    return _format_error(result) if isinstance(result, str) else result
Exemplo n.º 16
0
def deploy_pkg(ctx):
    is_branch(ctx, "master")
    environ["TWINE_USERNAME"] = "******"
    if environ.get(TWINE_PASSWORD) is None:
        raise Exit(f"missing environment variable {TWINE_PASSWORD}", code=1)

    tar_gz_wildcard: str = TAR_GZ_WILDCARD.format(version=PROJECT_VERSION)
    tar_gz_assets: List[str] = list(
        str(p) for p in DIST_PATH.glob(tar_gz_wildcard))
    if len(tar_gz_assets) != 1:
        raise Exit(
            f"invalid number of assets: dist/{tar_gz_wildcard} (required: 1)",
            code=1)

    whl_wildcard: str = WHL_WILDCARD.format(version=PROJECT_VERSION)
    whl_assets: List[str] = list(str(p) for p in DIST_PATH.glob(whl_wildcard))
    if len(whl_assets) != 1:
        raise Exit(
            f"invalid number of assets: dist/{whl_wildcard} (required: 1)",
            code=1)

    assets: List[str] = tar_gz_assets + whl_assets

    dispatch(['upload', *assets])
Exemplo n.º 17
0
def main():
    return dispatch(sys.argv[1:])
Exemplo n.º 18
0
def test_catches_enoent():
    with pytest.raises(SystemExit):
        cli.dispatch(["non-existant-command"])
Exemplo n.º 19
0
def main():
    try:
        return cli.dispatch(sys.argv[1:])
    except (exceptions.TwineException, requests.HTTPError) as exc:
        return "{}: {}".format(exc.__class__.__name__, exc.args[0])
Exemplo n.º 20
0
def main():
    return dispatch(sys.argv[1:])
Exemplo n.º 21
0
def upload_to_pypi():
    try:
        return dispatch(["upload", "dist/*"])
    except HTTPError as error:
        handle_http_error(error)
Exemplo n.º 22
0
def test_catches_enoent():
    with pytest.raises(SystemExit):
        cli.dispatch(["non-existent-command"])
Exemplo n.º 23
0
from distutils.core import run_setup
from twine import cli as twine_cli
import semver


def rmrf(folder):
    for filename in listdir(folder):
        file_path = path.join(folder, filename)
        try:
            if path.isfile(file_path) or path.islink(file_path):
                unlink(file_path)
            elif path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            print('Failed to delete %s. Reason: %s' % (file_path, e))
    shutil.rmtree(folder)


if __name__ == "__main__":
    for p in ['build', 'dist', 'algolab.egg-info']:
        rmrf(p) if path.exists(p) else None

    with open("version", "r") as fh:
        version_str = fh.read()
    with open("version", "w") as fh:
        version = semver.VersionInfo.parse(version_str)
        fh.write(str(version.bump_patch()))

    run_setup('setup.py', script_args=['sdist', 'bdist_wheel'])
    twine_cli.dispatch(['upload', '--non-interactive', 'dist/*'])
Exemplo n.º 24
0
            with open(init_file, "w") as outfile:
                outfile.write("".join(package_init))
            reload(pyrsched.server)
            setup_version, git_version, pypi_version = get_versions()

    if pypi_version < setup_version:
        print("The package on PyPI needs to be updated.")
        r = input("Build Package and update on PyPI? [Yn] ") or "Y"
        if r.upper() == "Y":
            # clear dist directory
            dist_path = Path("dist").resolve()
            for f in dist_path.iterdir():
                f.unlink()
            
            # build package
            from setuptools.sandbox import run_setup
            run_setup("setup.py", ["sdist", "bdist_wheel"])

            # upload package
            from twine import cli
            from twine import exceptions

            try:
                twine_res = cli.dispatch(["upload", "dist/*"])
            except (exceptions.TwineException, requests.HTTPError) as exc:
                print("{}: {}".format(exc.__class__.__name__, exc.args[0]))

            print(f"Twine response: {twine_res}")
            setup_version, git_version, pypi_version = get_versions()

    print("all done...")