diff --git a/src/tests/__init__.py b/src/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tests/test_commands.py b/src/tests/test_commands.py new file mode 100644 --- /dev/null +++ b/src/tests/test_commands.py @@ -0,0 +1,182 @@ +from pathlib import Path +import pytest +from typer.testing import CliRunner +import docker + +from starpack.__main__ import app +from starpack.client import StarpackClient + + +class FakeContainer: + labels = { + "desktop.docker.io/wsl-distro": "Ubuntu-20.04", + "app": "starpack-engine", + } + attrs = { + "HostConfig": { + "PortBindings": {"1976/tcp": [{"HostIp": "", "HostPort": "1976"}]}, + } + } + + status = "running" + + def remove(*args, **kwargs): + ... + + def put_archive(*args, **kwargs): + ... + + +class FakeContainerModule: + def list(*args, **kwargs): + return [FakeContainer] + + def run(*args, **kwargs): + pass + + +class FakeImageModule: + def pull(*args): + pass + + +class FakeVolume: + def remove(*args, **kwargs): + ... + + +class FakeVolumesModule: + def get(*args, **kwargs): + return FakeVolume() + + def create(*args, **kwargs): + ... + + +class FakeDockerClient: + def __init__(self, *args, **kwargs) -> None: + self.containers = FakeContainerModule + self.images = FakeImageModule + self.volumes = FakeVolumesModule + + +@pytest.fixture(autouse=True) +def mock_docker(monkeypatch, requests_mock): + monkeypatch.setattr(docker, "from_env", FakeDockerClient) + requests_mock.get( + "http://localhost:1976/healthcheck", text='{"healthy": "true"}', status_code=200 + ) + + +@pytest.fixture +def test_runner(monkeypatch): + return CliRunner() + + +def test_command_init(tmp_path: Path, test_runner: CliRunner): + """Tests `starpack init $PATH`""" + result = test_runner.invoke(app, ["init", str(tmp_path)]) + assert result.exit_code == 0 + assert "Completed initializing project directory:" in result.stdout + + +def test_command_init_overwrite(tmp_path: Path, test_runner: CliRunner): + """Tests `starpack init $PATH` with duplicate files""" + _ = test_runner.invoke(app, ["init", str(tmp_path)]) + result = test_runner.invoke(app, ["init", str(tmp_path)], "y\nn\ny\n") + assert result.exit_code == 0 + assert "Completed initializing project directory:" in result.stdout + assert "predict.py already exists" in result.stdout + + +def test_command_version(test_runner: CliRunner): + result = test_runner.invoke(app, ["--version"]) + assert result.exit_code == 0 + assert "Starpack CLI version" in result.stdout + + +def test_command_engine_start(test_runner: CliRunner): + result = test_runner.invoke(app, ["engine", "start"]) + assert result.exit_code == 0 + + +def test_command_upload(tmp_path: Path, test_runner: CliRunner): + result = test_runner.invoke(app, ["upload", str(tmp_path)]) + assert result.exit_code == 0 + + +def test_command_terminate(test_runner: CliRunner): + + result = test_runner.invoke(app, ["engine", "terminate"]) + + assert result.exit_code == 0 + + +fake_payload = """ +package: + metadata: + # Set the package name to use later for the deployment + name: &package_name starpack_test + description: "Testing package" + version: 0.0.1 + author: Andromeda 360, Inc. + author_email: irvin.shen@andromeda360.com + artifacts: + root_location: starpack_test + validation_data: + training_data: + inference: + function_name: predict + script_name: predict.py + model_data: pred_heart_disease.pkl + dependencies: requirements.txt + steps: + - name: fastapi + version: 1.0.0 + - name: docker_desktop_push + labels: + image_name: "irvin-killed-it" # optional, defaults to metadata name + image_tags: # optional + - latest + +deployment: + metadata: + name: final_test + version: 1.0.0 + steps: + - name: local_docker_find + version: 1.0.0 + image: + name: *package_name + tag: latest + - name: local_docker_deploy + version: 1.0.0 + port: # optional +""" + + +# @pytest.mark.parametrize() +def test_command_package(test_runner: CliRunner, tmp_path, monkeypatch, requests_mock): + url = "http://localhost:1976/package" + requests_mock.post(url, status_code=200, text="") + + yaml_path = tmp_path / "starpack.yaml" + yaml_path.write_text(fake_payload) + + monkeypatch.setattr(StarpackClient, "package", lambda x, y: ...) + result = test_runner.invoke(app, ["package", str(tmp_path)]) + + assert result.exit_code == 0 + + +def test_command_deploy(test_runner: CliRunner, tmp_path, monkeypatch, requests_mock): + requests_mock.post("http://localhost:1976/deploy", status_code=200, text="") + requests_mock.post("http://localhost:1976/package", status_code=200, text="") + + yaml_path = tmp_path / "starpack.yaml" + yaml_path.write_text(fake_payload) + + monkeypatch.setattr(StarpackClient, "deploy", lambda x, y: ...) + result = test_runner.invoke(app, ["deploy", str(tmp_path)]) + + assert result.exit_code == 0 diff --git a/src/tests/test_core.py b/src/tests/test_core.py new file mode 100644 --- /dev/null +++ b/src/tests/test_core.py @@ -0,0 +1,2 @@ +from starpack import core +import pytest diff --git a/src/tests/test_engine_client.py b/src/tests/test_engine_client.py new file mode 100644 --- /dev/null +++ b/src/tests/test_engine_client.py @@ -0,0 +1,72 @@ +from starpack.client import StarpackClient +import requests +import pytest +from typing import Optional + + +@pytest.fixture +def starpack_client(): + client = StarpackClient() + + return client + + +def test_client_initialization(): + client = StarpackClient(host="http://google.com", port=80) + + assert client.url == "http://google.com:80" + + +@pytest.mark.parametrize( + ("status_code", "output", "exception"), + [(200, True, None), (404, False, None), (200, False, requests.ConnectionError)], +) +def test_client_healthcheck( + starpack_client, + requests_mock, + status_code: int, + output: bool, + exception: Optional[Exception], +): + url = "http://localhost:1976/healthcheck" + if exception: + requests_mock.get(url, exc=exception) + else: + requests_mock.get(url, text="nice", status_code=status_code) + assert starpack_client.check_health() == output + + +@pytest.mark.parametrize( + ("status_code", "output"), + [(200, "http://localhost:2000"), (500, "500"), (300, "300")], +) +def test_client_deploy( + starpack_client, requests_mock, capsys, status_code: int, output: str +): + url = "http://localhost:1976/deploy" + payload = {"deployment": {"metadata": {"name": "test"}}} + requests_mock.post( + url, + status_code=status_code, + json={"endpoints": {"fastapi": "http://localhost:2000"}}, + ) + starpack_client.deploy(payload) + print_out = capsys.readouterr().out + + assert output in print_out + + +@pytest.mark.parametrize( + ("status_code", "output"), + [(200, "Successfully packaged"), (500, "500"), (300, "300")], +) +def test_client_package( + starpack_client, requests_mock, capsys, status_code: int, output: str +): + url = "http://localhost:1976/package" + payload = {"package": {"metadata": {"name": "test"}}} + requests_mock.post(url, status_code=status_code, text="") + starpack_client.package(payload) + print_out = capsys.readouterr().out + + assert output in print_out diff --git a/src/tests/test_errors.py b/src/tests/test_errors.py new file mode 100644 --- /dev/null +++ b/src/tests/test_errors.py @@ -0,0 +1,35 @@ +import pytest +from pathlib import Path +from starpack import errors + + +def test_docker_not_found_error() -> None: + with pytest.raises(errors.DockerNotFoundError) as e: + raise errors.DockerNotFoundError() + + assert e.value.exit_code == 1 + + +def test_local_only_error() -> None: + with pytest.raises(errors.LocalOnlyError) as e: + raise errors.LocalOnlyError() + + assert e.value.exit_code == 1 + + +def test_path_exists_error(capsys) -> None: + with pytest.raises(errors.PathExistsError) as e: + path = Path() + raise errors.PathExistsError(path) + + output = capsys.readouterr() + + assert str(path) in output.out + assert e.value.exit_code == 1 + + +def test_engine_initialization_error() -> None: + with pytest.raises(errors.EngineInitializationError) as e: + raise errors.EngineInitializationError() + + assert e.value.exit_code == 1 diff --git a/src/tests/README.md b/src/tests/README.md new file mode 100644 --- /dev/null +++ b/src/tests/README.md @@ -0,0 +1,3 @@ +# Testing and Notes for Developers + +TBD