How to use the twine.package function in twine

To help you get started, we’ve selected a few twine examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github pypa / twine / tests / test_package.py View on Github external
def test_sign_file(monkeypatch):
    replaced_check_call = pretend.call_recorder(lambda args: None)
    monkeypatch.setattr(package_file.subprocess, "check_call", replaced_check_call)
    filename = "tests/fixtures/deprecated-pypirc"

    package = package_file.PackageFile(
        filename=filename,
        comment=None,
        metadata=pretend.stub(name="deprecated-pypirc"),
        python_version=None,
        filetype=None,
    )
    try:
        package.sign("gpg2", None)
    except IOError:
        pass
    args = ("gpg2", "--detach-sign", "-a", filename)
    assert replaced_check_call.calls == [pretend.call(args)]
github pypa / twine / tests / test_upload.py View on Github external
def test_make_package_unsigned_dist(upload_settings, monkeypatch, capsys):
    """Create a PackageFile and print path, size, and Twine-generated signature."""
    filename = helpers.NEW_WHEEL_FIXTURE
    expected_size = "21.9 KB"
    signatures = {}

    upload_settings.sign = True
    upload_settings.verbose = True

    def stub_sign(package, *_):
        package.gpg_signature = (package.signed_basefilename, b"signature")

    monkeypatch.setattr(package_file.PackageFile, "sign", stub_sign)

    package = upload._make_package(filename, signatures, upload_settings)

    assert package.filename == filename
    assert package.gpg_signature is not None

    captured = capsys.readouterr()
    assert captured.out.count(f"{filename} ({expected_size})") == 1
    assert captured.out.count(f"Signed with {package.signed_filename}") == 1
github pypa / twine / tests / test_check.py View on Github external
def test_check_passing_distribution(monkeypatch):
    renderer = pretend.stub(render=pretend.call_recorder(lambda *a, **kw: "valid"))
    package = pretend.stub(
        metadata_dictionary=lambda: {
            "description": "blah",
            "description_content_type": "text/markdown",
        }
    )
    output_stream = io.StringIO()
    warning_stream = ""

    monkeypatch.setattr(check, "_RENDERERS", {None: renderer})
    monkeypatch.setattr(commands, "_find_dists", lambda a: ["dist/dist.tar.gz"])
    monkeypatch.setattr(
        package_file,
        "PackageFile",
        pretend.stub(from_filename=lambda *a, **kw: package),
    )
    monkeypatch.setattr(check, "_WarningStream", lambda: warning_stream)

    assert not check.check(["dist/*"], output_stream=output_stream)
    assert output_stream.getvalue() == "Checking dist/dist.tar.gz: PASSED\n"
    assert renderer.render.calls == [pretend.call("blah", stream=warning_stream)]
github pypa / twine / tests / test_package.py View on Github external
def test_sign_file(monkeypatch):
    replaced_check_call = pretend.call_recorder(lambda args: None)
    monkeypatch.setattr(package_file.subprocess, "check_call", replaced_check_call)
    filename = "tests/fixtures/deprecated-pypirc"

    package = package_file.PackageFile(
        filename=filename,
        comment=None,
        metadata=pretend.stub(name="deprecated-pypirc"),
        python_version=None,
        filetype=None,
    )
    try:
        package.sign("gpg2", None)
    except IOError:
        pass
    args = ("gpg2", "--detach-sign", "-a", filename)
    assert replaced_check_call.calls == [pretend.call(args)]
github pypa / twine / tests / test_upload.py View on Github external
def test_skip_upload_doesnt_match(response_kwargs):
    assert not upload.skip_upload(
        response=pretend.stub(**response_kwargs),
        skip_existing=True,
        package=package_file.PackageFile.from_filename(helpers.WHEEL_FIXTURE, None),
    )
github pypa / twine / tests / test_check.py View on Github external
def test_check_failing_distribution(monkeypatch):
    renderer = pretend.stub(render=pretend.call_recorder(lambda *a, **kw: None))
    package = pretend.stub(
        metadata_dictionary=lambda: {
            "description": "blah",
            "description_content_type": "text/markdown",
        }
    )
    output_stream = io.StringIO()
    warning_stream = "WARNING"

    monkeypatch.setattr(check, "_RENDERERS", {None: renderer})
    monkeypatch.setattr(commands, "_find_dists", lambda a: ["dist/dist.tar.gz"])
    monkeypatch.setattr(
        package_file,
        "PackageFile",
        pretend.stub(from_filename=lambda *a, **kw: package),
    )
    monkeypatch.setattr(check, "_WarningStream", lambda: warning_stream)

    assert check.check(["dist/*"], output_stream=output_stream)
    assert output_stream.getvalue() == (
        "Checking dist/dist.tar.gz: FAILED\n"
        "  `long_description` has syntax errors in markup and would not be "
        "rendered on PyPI.\n"
        "    WARNING"
    )
    assert renderer.render.calls == [pretend.call("blah", stream=warning_stream)]
github pypa / twine / tests / test_package.py View on Github external
assert result["project_urls"] == meta.project_urls
    assert result["provides_dist"] == meta.provides_dist
    assert result["obsoletes_dist"] == meta.obsoletes_dist
    assert result["requires_dist"] == meta.requires_dist
    assert result["requires_external"] == meta.requires_external
    assert result["requires_python"] == meta.requires_python

    # Metadata 2.1
    assert result["provides_extras"] == meta.provides_extras
    assert result["description_content_type"] == meta.description_content_type

    # GPG signature
    assert result.get("gpg_signature") == gpg_signature


TWINE_1_5_0_WHEEL_HEXDIGEST = package_file.Hexdigest(
    "1919f967e990bee7413e2a4bc35fd5d1",
    "d86b0f33f0c7df49e888b11c43b417da5520cbdbce9f20618b1494b600061e67",
    "b657a4148d05bd0098c1d6d8cc4e14e766dbe93c3a5ab6723b969da27a87bac0",
)


def test_hash_manager():
    """Generate hexdigest via HashManager."""
    filename = "tests/fixtures/twine-1.5.0-py2.py3-none-any.whl"
    hasher = package_file.HashManager(filename)
    hasher.hash()
    assert hasher.hexdigest() == TWINE_1_5_0_WHEEL_HEXDIGEST


def test_fips_hash_manager(monkeypatch):
    """Generate hexdigest without MD5 when hashlib is using FIPS mode."""
github pypa / twine / twine / commands / check.py View on Github external
def _check_file(
    filename: str, render_warning_stream: _WarningStream
) -> Tuple[List[str], bool]:
    """Check given distribution."""
    warnings = []
    is_ok = True

    package = package_file.PackageFile.from_filename(filename, comment=None)

    metadata = package.metadata_dictionary()
    description = cast(Optional[str], metadata["description"])
    description_content_type = cast(Optional[str], metadata["description_content_type"])

    if description_content_type is None:
        warnings.append(
            "`long_description_content_type` missing. defaulting to `text/x-rst`."
        )
        description_content_type = "text/x-rst"

    content_type, params = cgi.parse_header(description_content_type)
    renderer = _RENDERERS.get(content_type, _RENDERERS[None])

    if description in {None, "UNKNOWN\n\n\n"}:
        warnings.append("`long_description` missing.")
github pypa / twine / twine / commands / upload.py View on Github external
def _make_package(
    filename: str, signatures: Dict[str, str], upload_settings: settings.Settings
) -> package_file.PackageFile:
    """Create and sign a package, based off of filename, signatures and settings."""
    package = package_file.PackageFile.from_filename(filename, upload_settings.comment)

    signed_name = package.signed_basefilename
    if signed_name in signatures:
        package.add_gpg_signature(signatures[signed_name], signed_name)
    elif upload_settings.sign:
        package.sign(upload_settings.sign_with, upload_settings.identity)

    file_size = utils.get_file_size(package.filename)
    logger.info(f"  {package.filename} ({file_size})")
    if package.gpg_signature:
        logger.info(f"  Signed with {package.signed_filename}")

    return package
github pypa / twine / twine / commands / register.py View on Github external
def register(register_settings: settings.Settings, package: str) -> None:
    repository_url = cast(str, register_settings.repository_config["repository"])
    print(f"Registering package to {repository_url}")
    repository = register_settings.create_repository()

    if not os.path.exists(package):
        raise exceptions.PackageNotFound(
            f'"{package}" does not exist on the file system.'
        )

    resp = repository.register(
        package_file.PackageFile.from_filename(package, register_settings.comment)
    )
    repository.close()

    if resp.is_redirect:
        raise exceptions.RedirectDetected.from_args(
            repository_url, resp.headers["location"],
        )

    resp.raise_for_status()