Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow installing packages from private indexes #1040

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/nox_poetry/poetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ def export(self) -> str:
"--dev",
*[f"--extras={extra}" for extra in self.config.extras],
"--without-hashes",
"--with-credentials",
external=True,
silent=True,
stderr=None,
Expand Down
2 changes: 2 additions & 0 deletions src/nox_poetry/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ def _split_extras(arg: str) -> Tuple[str, Optional[str]]:

def to_constraint(requirement_string: str, line: int) -> Optional[str]:
"""Convert requirement to constraint."""
if requirement_string.startswith("--extra-index-url"):
return requirement_string
if any(
requirement_string.startswith(prefix)
for prefix in ("-", "file://", "git+https://", "http://", "https://")
Expand Down
17 changes: 17 additions & 0 deletions tests/functional/data/simple503/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="generator" content="simple503 version 0.3.2" />
<meta name="pypi:repository-version" content="1.0" />
<meta charset="UTF-8" />
<title>
Simple Package Repository
</title>
</head>
<body>
<a href="thispackagedoesnotexist/">
thispackagedoesnotexist
</a>
<br />
</body>
</html>
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Metadata-Version: 2.1
Name: thispackagedoesnotexist
Version: 0.1.0
Summary: thispackagedoesnotexist
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
20 changes: 20 additions & 0 deletions tests/functional/data/simple503/thispackagedoesnotexist/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="generator" content="simple503 version 0.3.2" />
<meta name="pypi:repository-version" content="1.0" />
<meta charset="UTF-8" />
<title>
Links for thispackagedoesnotexist
</title>
</head>
<body>
<h1>
Links for thispackagedoesnotexist
</h1>
<a href="../thispackagedoesnotexist-0.1.0-py2.py3-none-any.whl#sha256=bbd24e74682c7c5b4e11d7a626b8686dd6c25d38756474f770395d2466439c99" data-dist-info-metadata="sha256=6c5168e003a63613a58d72a54fb710f5bca4bea0a8bd1b8237c5f6cc5ab664d3">
thispackagedoesnotexist-0.1.0-py2.py3-none-any.whl
</a>
<br />
</body>
</html>
142 changes: 142 additions & 0 deletions tests/functional/test_installroot.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
"""Functional tests for ``installroot``."""
import base64
import os
import tempfile
from functools import partial
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
from pathlib import Path
from threading import Thread
from typing import Any
from typing import Tuple

import nox_poetry
from tests.functional.conftest import Project
from tests.functional.conftest import list_packages
Expand Down Expand Up @@ -79,3 +90,134 @@ def test(session: nox_poetry.Session) -> None:
packages = list_packages(project, test)

assert set(expected) == set(packages)


class AuthenticatingSimpleHTTPRequestHandler(SimpleHTTPRequestHandler):
"""A version of SimpleHTTPRequestHandler that throws a 401 error if the request
does not come with the specified username and password sent via basic http
authentication. See RFC 7617 for details. This is designed for tests, and does not
offer any real protection."""

def __init__(
self,
request: Any,
client_address: Any,
server: Any,
directory: Any,
username: str,
password: str,
):
authstring = f"{username}:{password}"
self.encoded_authstring = base64.b64encode(authstring.encode("utf-8")).decode(
"utf-8"
)
super().__init__(request, client_address, server, directory=directory)

def is_authenticated(self) -> bool:
if "Authorization" in self.headers:
return bool(
self.headers["Authorization"] == f"Basic {self.encoded_authstring}"
)
return False

def send_auth_error(self) -> None:
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="everything"')
self.end_headers()

def do_GET(self) -> None:
if self.is_authenticated():
super().do_GET()
else:
self.send_auth_error()

def do_HEAD(self) -> None:
if self.is_authenticated():
super().do_HEAD()
else:
self.send_auth_error()


def get_pyproject(address: str) -> str:
return f"""\
[tool.poetry]
name = "foo"
version = "0.1.1"
description = "foo"
authors = []

[tool.poetry.dependencies]
"thispackagedoesnotexist" = {{version = "0.1.0", source = "baz"}}

[[tool.poetry.source]]
name = "baz"
url = "{address}"
default = false
secondary = true
"""


def serve_directory_with_http_and_auth(
directory: str, username: str, password: str
) -> Tuple[HTTPServer, str]:
hostname = "localhost"
port = 0
handler = partial(
AuthenticatingSimpleHTTPRequestHandler,
directory=directory,
username=username,
password=password,
)
httpd = HTTPServer((hostname, port), handler, False)
httpd.timeout = 0.5

httpd.server_bind()
address = "http://%s:%d" % (hostname, httpd.server_port)

httpd.server_activate()

def serve_forever(httpd: HTTPServer) -> None:
with httpd: # to make sure httpd.server_close is called
httpd.serve_forever()

thread = Thread(target=serve_forever, args=(httpd,))
thread.setDaemon(True)
thread.start()

return httpd, address


def test_dependency_from_private_index(shared_datadir: Path) -> None:
input_dir = tempfile.TemporaryDirectory()

server, address = serve_directory_with_http_and_auth(
str(shared_datadir / "simple503"), username="alice", password="password"
)

with open(os.path.join(input_dir.name, "pyproject.toml"), "w") as pyproject_file:
pyproject_file.write(get_pyproject(address))
(Path(input_dir.name) / "foo").mkdir()
(Path(input_dir.name) / "foo" / "__init__.py").touch()

@nox_poetry.session
def test(session: nox_poetry.Session) -> None:
session.run_always(
"poetry",
"config",
"http-basic.baz",
"alice",
"password",
external=True,
silent=True,
stderr=None,
)
session.run_always("poetry", "lock")
session.poetry.installroot()

project = Project(Path(input_dir.name))

try:
run_nox_with_noxfile(project, [test], [nox_poetry])

finally:
server.shutdown()
17 changes: 17 additions & 0 deletions tests/unit/data/simple503/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="generator" content="simple503 version 0.3.2" />
<meta name="pypi:repository-version" content="1.0" />
<meta charset="UTF-8" />
<title>
Simple Package Repository
</title>
</head>
<body>
<a href="thispackagedoesnotexist/">
thispackagedoesnotexist
</a>
<br />
</body>
</html>
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Metadata-Version: 2.1
Name: thispackagedoesnotexist
Version: 0.1.0
Summary: thispackagedoesnotexist
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
20 changes: 20 additions & 0 deletions tests/unit/data/simple503/thispackagedoesnotexist/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="generator" content="simple503 version 0.3.2" />
<meta name="pypi:repository-version" content="1.0" />
<meta charset="UTF-8" />
<title>
Links for thispackagedoesnotexist
</title>
</head>
<body>
<h1>
Links for thispackagedoesnotexist
</h1>
<a href="../thispackagedoesnotexist-0.1.0-py2.py3-none-any.whl#sha256=bbd24e74682c7c5b4e11d7a626b8686dd6c25d38756474f770395d2466439c99" data-dist-info-metadata="sha256=c6b5792edd9de24e917d54939c976167d32264f283af8a815fd1b2d4f82b76fe">
thispackagedoesnotexist-0.1.0-py2.py3-none-any.whl
</a>
<br />
</body>
</html>
83 changes: 83 additions & 0 deletions tests/unit/test_poetry.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
"""Unit tests for the poetry module."""
import os
import pdb
import tempfile
from functools import partial
from http.server import HTTPServer
from http.server import SimpleHTTPRequestHandler
from pathlib import Path
from threading import Thread
from typing import Any
from typing import Dict
from typing import Tuple

import nox._options
import nox.command
Expand Down Expand Up @@ -61,3 +69,78 @@ def _run(*args: Any, **kwargs: Any) -> str:

output = poetry.Poetry(session).export()
assert output == requirements


def get_pyproject(address: str) -> str:
return f"""\
[tool.poetry]
name = "foo"
version = "0.1.0"
description = "foo"
authors = []

[tool.poetry.dependencies]
"thispackagedoesnotexist" = {{version = "0.1.0", source = "baz"}}

[[tool.poetry.source]]
name = "baz"
url = "{address}"
default = false
secondary = true
"""


def serve_directory_with_http(directory: str) -> Tuple[HTTPServer, str]:
hostname = "localhost"
port = 0
handler = partial(SimpleHTTPRequestHandler, directory=directory)
httpd = HTTPServer((hostname, port), handler, False)
httpd.timeout = 0.5

httpd.server_bind()
address = "http://%s:%d" % (hostname, httpd.server_port)

httpd.server_activate()

def serve_forever(httpd: HTTPServer) -> None:
with httpd: # to make sure httpd.server_close is called
httpd.serve_forever()

thread = Thread(target=serve_forever, args=(httpd,))
thread.setDaemon(True)
thread.start()

return httpd, address


@nox.session
def test_export_with_source_credentials(
session: nox.Session, shared_datadir: Path
) -> None:
input_dir = tempfile.TemporaryDirectory()

server, address = serve_directory_with_http(str(shared_datadir / "simple503"))

with open(os.path.join(input_dir.name, "pyproject.toml"), "w") as pyproject_file:
pyproject_file.write(get_pyproject(address))

cwd = os.getcwd()
try:
os.chdir(input_dir.name)
session.run_always(
"poetry",
"config",
"http-basic.baz",
"alice",
"password",
external=True,
silent=True,
stderr=None,
)
test_poetry = poetry.Poetry(session)
resources_file = test_poetry.export()
expected_index = "http://alice:password@" + address.lstrip("http://")
assert f"--extra-index-url {expected_index}" in resources_file
finally:
os.chdir(cwd)
server.shutdown()
14 changes: 12 additions & 2 deletions tests/unit/test_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,10 @@ def test_session_build_package(proxy: nox_poetry.Session) -> None:
'regex==2020.10.28; python_version == "3.5"',
),
("-e ../lib/foo", ""),
("--extra-index-url https://example.com/pypi/simple", ""),
(
"--extra-index-url https://example.com/pypi/simple",
"--extra-index-url https://example.com/pypi/simple",
),
(
dedent(
"""
Expand All @@ -170,7 +173,14 @@ def test_session_build_package(proxy: nox_poetry.Session) -> None:
boltons==20.2.1
"""
),
"boltons==20.2.1",
dedent(
"""
--extra-index-url https://example.com/pypi/simple
boltons==20.2.1
"""
)
.lstrip("\n")
.rstrip("\n"),
),
],
)
Expand Down