Skip to content

Commit f162376

Browse files
authored
Merge pull request #1573 from mathbunnyru/asalikhov/add_typing
Add some typing to tests
2 parents ee77b78 + 3b63836 commit f162376

24 files changed

+199
-136
lines changed

.gitattributes

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1 @@
11
* text=auto eol=lf
2-

all-spark-notebook/test/test_spark_notebooks.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,22 @@
44
import logging
55

66
import pytest
7-
import os
7+
from pathlib import Path
8+
9+
from conftest import TrackedContainer
810

911
LOGGER = logging.getLogger(__name__)
10-
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
12+
THIS_DIR = Path(__file__).parent.resolve()
1113

1214

1315
@pytest.mark.parametrize(
1416
"test_file",
1517
# TODO: add local_sparklyr
1618
["local_pyspark", "local_spylon", "local_sparkR", "issue_1168"],
1719
)
18-
def test_nbconvert(container, test_file):
20+
def test_nbconvert(container: TrackedContainer, test_file: str) -> None:
1921
"""Check if Spark notebooks can be executed"""
20-
host_data_dir = os.path.join(THIS_DIR, "data")
22+
host_data_dir = THIS_DIR / "data"
2123
cont_data_dir = "/home/jovyan/data"
2224
output_dir = "/tmp"
2325
timeout_ms = 600
@@ -29,7 +31,7 @@ def test_nbconvert(container, test_file):
2931
+ f"--execute {cont_data_dir}/{test_file}.ipynb"
3032
)
3133
c = container.run(
32-
volumes={host_data_dir: {"bind": cont_data_dir, "mode": "ro"}},
34+
volumes={str(host_data_dir): {"bind": cont_data_dir, "mode": "ro"}},
3335
tty=True,
3436
command=["start.sh", "bash", "-c", command],
3537
)

base-notebook/test/test_container_options.py

Lines changed: 22 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@
44
import logging
55

66
import pytest
7+
import requests
8+
9+
from conftest import TrackedContainer
710

811
LOGGER = logging.getLogger(__name__)
912

1013

11-
def test_cli_args(container, http_client):
14+
def test_cli_args(container: TrackedContainer, http_client: requests.Session) -> None:
1215
"""Container should respect notebook server command line args
1316
(e.g., disabling token security)"""
1417
c = container.run(command=["start-notebook.sh", "--NotebookApp.token=''"])
@@ -26,7 +29,9 @@ def test_cli_args(container, http_client):
2629

2730

2831
@pytest.mark.filterwarnings("ignore:Unverified HTTPS request")
29-
def test_unsigned_ssl(container, http_client):
32+
def test_unsigned_ssl(
33+
container: TrackedContainer, http_client: requests.Session
34+
) -> None:
3035
"""Container should generate a self-signed SSL certificate
3136
and notebook server should use it to enable HTTPS.
3237
"""
@@ -48,7 +53,7 @@ def test_unsigned_ssl(container, http_client):
4853
assert warnings[0].startswith("WARNING: Jupyter Notebook deprecation notice")
4954

5055

51-
def test_uid_change(container):
56+
def test_uid_change(container: TrackedContainer) -> None:
5257
"""Container should change the UID of the default user."""
5358
c = container.run(
5459
tty=True,
@@ -65,7 +70,7 @@ def test_uid_change(container):
6570
assert "uid=1010(jovyan)" in c.logs(stdout=True).decode("utf-8")
6671

6772

68-
def test_gid_change(container):
73+
def test_gid_change(container: TrackedContainer) -> None:
6974
"""Container should change the GID of the default user."""
7075
c = container.run(
7176
tty=True,
@@ -82,7 +87,7 @@ def test_gid_change(container):
8287
assert "groups=110(jovyan),100(users)" in logs
8388

8489

85-
def test_nb_user_change(container):
90+
def test_nb_user_change(container: TrackedContainer) -> None:
8691
"""Container should change the user name (`NB_USER`) of the default user."""
8792
nb_user = "nayvoj"
8893
running_container = container.run(
@@ -131,7 +136,7 @@ def test_nb_user_change(container):
131136
), f"Hidden folder .jupyter was not copied properly to {nb_user} home folder. stat: {output}, expected {expected_output}"
132137

133138

134-
def test_chown_extra(container):
139+
def test_chown_extra(container: TrackedContainer) -> None:
135140
"""Container should change the UID/GID of a comma separated
136141
CHOWN_EXTRA list of folders."""
137142
c = container.run(
@@ -160,7 +165,7 @@ def test_chown_extra(container):
160165
assert "/opt/conda/bin/jupyter:1010:101" in logs
161166

162167

163-
def test_chown_home(container):
168+
def test_chown_home(container: TrackedContainer) -> None:
164169
"""Container should change the NB_USER home directory owner and
165170
group to the current value of NB_UID and NB_GID."""
166171
c = container.run(
@@ -183,7 +188,7 @@ def test_chown_home(container):
183188
assert "/home/kitten/.bashrc:1010:101" in logs
184189

185190

186-
def test_sudo(container):
191+
def test_sudo(container: TrackedContainer) -> None:
187192
"""Container should grant passwordless sudo to the default user."""
188193
c = container.run(
189194
tty=True,
@@ -199,7 +204,7 @@ def test_sudo(container):
199204
assert "uid=0(root)" in logs
200205

201206

202-
def test_sudo_path(container):
207+
def test_sudo_path(container: TrackedContainer) -> None:
203208
"""Container should include /opt/conda/bin in the sudo secure_path."""
204209
c = container.run(
205210
tty=True,
@@ -215,7 +220,7 @@ def test_sudo_path(container):
215220
assert logs.rstrip().endswith("/opt/conda/bin/jupyter")
216221

217222

218-
def test_sudo_path_without_grant(container):
223+
def test_sudo_path_without_grant(container: TrackedContainer) -> None:
219224
"""Container should include /opt/conda/bin in the sudo secure_path."""
220225
c = container.run(
221226
tty=True,
@@ -230,7 +235,7 @@ def test_sudo_path_without_grant(container):
230235
assert logs.rstrip().endswith("/opt/conda/bin/jupyter")
231236

232237

233-
def test_group_add(container):
238+
def test_group_add(container: TrackedContainer) -> None:
234239
"""Container should run with the specified uid, gid, and secondary
235240
group. It won't be possible to modify /etc/passwd since gid is nonzero, so
236241
additionally verify that setting gid=0 is suggested in a warning.
@@ -252,7 +257,7 @@ def test_group_add(container):
252257
assert "uid=1010 gid=1010 groups=1010,100(users)" in logs
253258

254259

255-
def test_set_uid(container):
260+
def test_set_uid(container: TrackedContainer) -> None:
256261
"""Container should run with the specified uid and NB_USER.
257262
The /home/jovyan directory will not be writable since it's owned by 1000:users.
258263
Additionally verify that "--group-add=users" is suggested in a warning to restore
@@ -274,7 +279,7 @@ def test_set_uid(container):
274279
assert "--group-add=users" in warnings[0]
275280

276281

277-
def test_set_uid_and_nb_user(container):
282+
def test_set_uid_and_nb_user(container: TrackedContainer) -> None:
278283
"""Container should run with the specified uid and NB_USER."""
279284
c = container.run(
280285
user="1010",
@@ -294,7 +299,7 @@ def test_set_uid_and_nb_user(container):
294299
assert "user is kitten but home is /home/jovyan" in warnings[0]
295300

296301

297-
def test_container_not_delete_bind_mount(container, tmp_path):
302+
def test_container_not_delete_bind_mount(container: TrackedContainer, tmp_path) -> None:
298303
"""Container should not delete host system files when using the (docker)
299304
-v bind mount flag and mapping to /home/jovyan.
300305
"""
@@ -324,7 +329,9 @@ def test_container_not_delete_bind_mount(container, tmp_path):
324329

325330

326331
@pytest.mark.parametrize("enable_root", [False, True])
327-
def test_jupyter_env_vars_to_unset_as_root(container, enable_root):
332+
def test_jupyter_env_vars_to_unset_as_root(
333+
container: TrackedContainer, enable_root: bool
334+
) -> None:
328335
"""Environment variables names listed in JUPYTER_ENV_VARS_TO_UNSET
329336
should be unset in the final environment."""
330337
root_args = {"user": "root"} if enable_root else {}

base-notebook/test/test_package_managers.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import logging
55
import pytest
66

7+
from conftest import TrackedContainer
8+
79
LOGGER = logging.getLogger(__name__)
810

911

@@ -17,7 +19,9 @@
1719
("pip", "--version"),
1820
],
1921
)
20-
def test_package_manager(container, package_manager, version_arg):
22+
def test_package_manager(
23+
container: TrackedContainer, package_manager: str, version_arg: tuple[str, ...]
24+
) -> None:
2125
"""Test the notebook start-notebook script"""
2226
LOGGER.info(
2327
f"Test that the package manager {package_manager} is working properly ..."

base-notebook/test/test_pandoc.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33

44
import logging
55

6+
from conftest import TrackedContainer
7+
68
LOGGER = logging.getLogger(__name__)
79

810

9-
def test_pandoc(container):
11+
def test_pandoc(container: TrackedContainer) -> None:
1012
"""Pandoc shall be able to convert MD to HTML."""
1113
c = container.run(
1214
tty=True,

base-notebook/test/test_python.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,14 @@
44

55
from packaging import version
66

7+
from conftest import TrackedContainer
8+
79
LOGGER = logging.getLogger(__name__)
810

911

10-
def test_python_version(container, python_next_version="3.10"):
12+
def test_python_version(
13+
container: TrackedContainer, python_next_version: str = "3.10"
14+
) -> None:
1115
"""Check that python version is lower than the next version"""
1216
LOGGER.info(f"Checking that python version is lower than {python_next_version}")
1317
c = container.run(

base-notebook/test/test_start_container.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@
33

44
import logging
55
import pytest
6+
import requests
7+
8+
from conftest import TrackedContainer
69

710
LOGGER = logging.getLogger(__name__)
811

@@ -14,7 +17,12 @@
1417
(None, "notebook"),
1518
],
1619
)
17-
def test_start_notebook(container, http_client, env, expected_server):
20+
def test_start_notebook(
21+
container: TrackedContainer,
22+
http_client: requests.Session,
23+
env,
24+
expected_server: str,
25+
) -> None:
1826
"""Test the notebook start-notebook script"""
1927
LOGGER.info(
2028
f"Test that the start-notebook launches the {expected_server} server from the env {env} ..."
@@ -46,7 +54,9 @@ def test_start_notebook(container, http_client, env, expected_server):
4654
assert msg in logs, f"Expected warning message {msg} not printed"
4755

4856

49-
def test_tini_entrypoint(container, pid=1, command="tini"):
57+
def test_tini_entrypoint(
58+
container: TrackedContainer, pid: int = 1, command: str = "tini"
59+
) -> None:
5060
"""Check that tini is launched as PID 1
5161
5262
Credits to the following answer for the ps options used in the test:

conftest.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# Distributed under the terms of the Modified BSD License.
33
import os
44
import logging
5+
import typing
56

67
import docker
78
import pytest
@@ -15,7 +16,7 @@
1516

1617

1718
@pytest.fixture(scope="session")
18-
def http_client():
19+
def http_client() -> requests.Session:
1920
"""Requests session with retries and backoff."""
2021
s = requests.Session()
2122
retries = Retry(total=5, backoff_factor=1)
@@ -25,13 +26,13 @@ def http_client():
2526

2627

2728
@pytest.fixture(scope="session")
28-
def docker_client():
29+
def docker_client() -> docker.DockerClient:
2930
"""Docker client configured based on the host environment"""
3031
return docker.from_env()
3132

3233

3334
@pytest.fixture(scope="session")
34-
def image_name():
35+
def image_name() -> str:
3536
"""Image name to test"""
3637
return os.getenv("TEST_IMAGE")
3738

@@ -50,13 +51,15 @@ class TrackedContainer:
5051
Default keyword arguments to pass to docker.DockerClient.containers.run
5152
"""
5253

53-
def __init__(self, docker_client, image_name, **kwargs):
54+
def __init__(
55+
self, docker_client: docker.DockerClient, image_name: str, **kwargs: typing.Any
56+
):
5457
self.container = None
5558
self.docker_client = docker_client
5659
self.image_name = image_name
5760
self.kwargs = kwargs
5861

59-
def run(self, **kwargs):
62+
def run(self, **kwargs: typing.Any):
6063
"""Runs a docker container using the preconfigured image name
6164
and a mix of the preconfigured container options and those passed
6265
to this method.
@@ -74,9 +77,7 @@ def run(self, **kwargs):
7477
-------
7578
docker.Container
7679
"""
77-
all_kwargs = {}
78-
all_kwargs.update(self.kwargs)
79-
all_kwargs.update(kwargs)
80+
all_kwargs = self.kwargs | kwargs
8081
LOGGER.info(f"Running {self.image_name} with args {all_kwargs} ...")
8182
self.container = self.docker_client.containers.run(
8283
self.image_name,
@@ -91,7 +92,7 @@ def remove(self):
9192

9293

9394
@pytest.fixture(scope="function")
94-
def container(docker_client, image_name):
95+
def container(docker_client: docker.DockerClient, image_name: str):
9596
"""Notebook container with initial configuration appropriate for testing
9697
(e.g., HTTP port exposed to the host for HTTP calls).
9798

datascience-notebook/test/test_julia.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22
# Distributed under the terms of the Modified BSD License.
33
import logging
44

5+
from conftest import TrackedContainer
6+
57
LOGGER = logging.getLogger(__name__)
68

79

8-
def test_julia(container):
10+
def test_julia(container: TrackedContainer) -> None:
911
"""Basic julia test"""
1012
LOGGER.info("Test that julia is correctly installed ...")
1113
running_container = container.run(

minimal-notebook/test/test_inkscape.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33

44
import logging
55

6+
from conftest import TrackedContainer
7+
68
LOGGER = logging.getLogger(__name__)
79

810

9-
def test_inkscape(container):
11+
def test_inkscape(container: TrackedContainer) -> None:
1012
"""Inkscape shall be installed to be able to convert SVG files."""
1113
LOGGER.info("Test that inkscape is working by printing its version ...")
1214
c = container.run(

0 commit comments

Comments
 (0)