Skip to content

Commit

Permalink
Tests: api-server in test_context and not as arg
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Vrachev <[email protected]>
  • Loading branch information
MVrachev committed Jun 17, 2024
1 parent 06bf664 commit 7c832d4
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 69 deletions.
18 changes: 5 additions & 13 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,15 @@
_PROMPT = "rich.console.Console.input"


def _create_test_context(api_url: Optional[str]) -> Dict[str, Any]:
def _create_test_context() -> Dict[str, Any]:
setting_file = os.path.join(TemporaryDirectory().name, "test_settings.yml")
test_settings = Dynaconf(settings_files=[setting_file])
if api_url:
test_settings.SERVER = api_url

return {"settings": test_settings, "config": setting_file}


@pytest.fixture
def test_context() -> Dict[str, Any]:
return _create_test_context(None)
return _create_test_context()


def _create_client() -> CliRunner:
Expand Down Expand Up @@ -302,8 +299,8 @@ def invoke_command(
cmd: Command,
inputs: List[str],
args: List[str],
std_err_empty: bool = True,
test_context: Optional[Context] = None,
std_err_empty: bool = True,
) -> Result:
client = _create_client()
out_file_name = "out_file.json"
Expand All @@ -315,15 +312,10 @@ def invoke_command(
else:
out_args = ["--out", out_file_name]

api_url = None
if "--api-server" in args:
api_server_flag_index = args.index("--api-server")
api_url = args.pop(api_server_flag_index + 1)
args.remove("--api-server")
if not test_context:
test_context = _create_test_context()

context = test_context
if test_context is None:
context = _create_test_context(api_url)

with client.isolated_filesystem():
result_obj = client.invoke(
Expand Down
6 changes: 4 additions & 2 deletions tests/unit/cli/admin/test_ceremony.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,19 +112,21 @@ def test_ceremony_api_server(
monkeypatch,
patch_getpass,
patch_utcnow,
test_context,
):
fake_task_id = "123ab"
fake_send_payload = pretend.call_recorder(lambda **kw: fake_task_id)
monkeypatch.setattr(ceremony, "send_payload", fake_send_payload)
fake_task_status = pretend.call_recorder(lambda *a: None)
monkeypatch.setattr(ceremony, "task_status", fake_task_status)
input_step1, input_step2, input_step3, input_step4 = ceremony_inputs
args = ["--api-server", "http://localhost:80"]
test_context["settings"].SERVER = "http://localhost:80"

result = invoke_command(
ceremony.ceremony,
input_step1 + input_step2 + input_step3 + input_step4,
args,
[],
test_context,
)

with open(_PAYLOADS / "ceremony.json") as f:
Expand Down
49 changes: 31 additions & 18 deletions tests/unit/cli/admin/test_import_artifacts.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def test__get_succinct_roles_failed_parsing(self, monkeypatch):


class TestImportArtifactsGroupCLI:
def test_import_artifacts(self):
def test_import_artifacts(self, test_context):
# Required to properly mock functions imported inside import_artifacts
import sqlalchemy

Expand Down Expand Up @@ -293,16 +293,18 @@ def test_import_artifacts(self):
)

args = [
"--api-server",
"http://127.0.0.1",
"--db-uri",
"postgresql://postgres:[email protected]:5433",
"--csv",
"artifacts1of2.csv",
"--csv",
"artifacts2of2.csv",
]
result = invoke_command(import_artifacts.import_artifacts, [], args)
test_context["settings"].SERVER = "http://127.0.0.1"

result = invoke_command(
import_artifacts.import_artifacts, [], args, test_context
)
assert result.exit_code == 0, result.output
assert "Finished." in result.output
assert import_artifacts.bootstrap_status.calls == [
Expand Down Expand Up @@ -343,7 +345,7 @@ def test_import_artifacts_no_api_server_config_no_param(self):
assert result.exit_code == 1, result.stderr
assert "Requires '--api-server' " in result.stderr

def test_import_artifacts_skip_publish_artifacts(self):
def test_import_artifacts_skip_publish_artifacts(self, test_context):
# Required to properly mock functions imported inside import_artifacts
import sqlalchemy

Expand Down Expand Up @@ -379,8 +381,6 @@ def test_import_artifacts_skip_publish_artifacts(self):
)

args = [
"--api-server",
"http://127.0.0.1",
"--db-uri",
"postgresql://postgres:[email protected]:5433",
"--csv",
Expand All @@ -389,7 +389,11 @@ def test_import_artifacts_skip_publish_artifacts(self):
"artifacts2of2.csv",
"--skip-publish-artifacts",
]
result = invoke_command(import_artifacts.import_artifacts, [], args)
test_context["settings"].SERVER = "http://127.0.0.1"

result = invoke_command(
import_artifacts.import_artifacts, [], args, test_context
)
assert result.exit_code == 0, result.output
assert "Finished." in result.output
assert "No artifacts published" in result.output
Expand All @@ -408,7 +412,7 @@ def test_import_artifacts_skip_publish_artifacts(self):
assert import_artifacts.publish_artifacts.calls == []
assert import_artifacts.task_status.calls == []

def test_import_artifacts_sqlalchemy_import_fails(self):
def test_import_artifacts_sqlalchemy_import_fails(self, test_context):
import builtins

real_import = builtins.__import__
Expand All @@ -423,60 +427,69 @@ def fake_import(name, *args, **kwargs):

builtins.__import__ = fake_import

args = ["--api-server", "", "--db-uri", "", "--csv", ""]
args = ["--db-uri", "", "--csv", ""]
test_context["settings"].SERVER = ""
with pytest.raises(ModuleNotFoundError) as exc:
invoke_command(
import_artifacts.import_artifacts,
[],
args,
test_context,
std_err_empty=False,
)

# Return the original import to not cause other exceptions.
builtins.__import__ = real_import
assert "pip install repository-service-tuf[sqlalchemy" in str(exc)

def test_import_artifacts_bootstrap_check_failed(self):
def test_import_artifacts_bootstrap_check_failed(self, test_context):

import_artifacts.bootstrap_status = pretend.raiser(
import_artifacts.click.ClickException("Server ERROR")
)

args = [
"--api-server",
"http://127.0.0.1",
"--db-uri",
"postgresql://postgres:[email protected]:5433",
"--csv",
"artifacts1of2.csv",
"--csv",
"artifacts2of2.csv",
]
test_context["settings"].SERVER = "http://127.0.0.1"

result = invoke_command(
import_artifacts.import_artifacts, [], args, std_err_empty=False
import_artifacts.import_artifacts,
[],
args,
test_context,
std_err_empty=False,
)
assert result.exit_code == 1
assert "Server ERROR" in result.stderr, result.stderr

def test_import_artifacts_without_bootstrap(self):
def test_import_artifacts_without_bootstrap(self, test_context):

import_artifacts.bootstrap_status = pretend.call_recorder(
lambda *a: {"data": {"bootstrap": False}, "message": "some msg"}
)

args = [
"--api-server",
"http://127.0.0.1",
"--db-uri",
"postgresql://postgres:[email protected]:5433",
"--csv",
"artifacts1of2.csv",
"--csv",
"artifacts2of2.csv",
]
test_context["settings"].SERVER = "http://127.0.0.1"

result = invoke_command(
import_artifacts.import_artifacts, [], args, std_err_empty=False
import_artifacts.import_artifacts,
[],
args,
test_context,
std_err_empty=False,
)
assert result.exit_code == 1, result.stderr
assert (
Expand Down
67 changes: 31 additions & 36 deletions tests/unit/cli/admin/test_sign.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@


class TestSign:
def test_sign_with_previous_root(self, patch_getpass):
def test_sign_with_previous_root(self, test_context, patch_getpass):
inputs = [
"1", # Please enter signing key index
f"{_PEMS / 'JH.ed25519'}", # Please enter path to encrypted private key # noqa
Expand All @@ -31,9 +31,10 @@ def test_sign_with_previous_root(self, patch_getpass):
)
sign.send_payload = pretend.call_recorder(lambda *a: "fake-taskid")
sign.task_status = pretend.call_recorder(lambda *a: "OK")
args = ["--api-server", "http://127.0.0.1"]
api_server = "http://127.0.0.1"
test_context["settings"].SERVER = api_server

result = invoke_command(sign.sign, inputs, args)
result = invoke_command(sign.sign, inputs, [], test_context)

with open(_PAYLOADS / "sign.json") as f:
expected = json.load(f)
Expand All @@ -44,11 +45,7 @@ def test_sign_with_previous_root(self, patch_getpass):
)
assert "Metadata Signed and sent to the API! 🔑" in result.stdout
assert sign.request_server.calls == [
pretend.call(
"http://127.0.0.1",
"api/v1/metadata/sign/",
Methods.GET,
)
pretend.call(api_server, "api/v1/metadata/sign/", Methods.GET)
]
assert sign.send_payload.calls == [
pretend.call(
Expand All @@ -73,7 +70,7 @@ def test_sign_with_previous_root(self, patch_getpass):
)
]

def test_sign_bootstap_root(self, patch_getpass):
def test_sign_bootstap_root(self, test_context, patch_getpass):
inputs = [
"1", # Please enter signing key index
f"{_PEMS / 'JH.ed25519'}", # Please enter path to encrypted private key # noqa
Expand All @@ -94,9 +91,10 @@ def test_sign_bootstap_root(self, patch_getpass):
)
sign.send_payload = pretend.call_recorder(lambda *a: "fake-taskid")
sign.task_status = pretend.call_recorder(lambda *a: "OK")
args = ["--api-server", "http://127.0.0.1"]
api_server = "http://127.0.0.1"
test_context["settings"].SERVER = api_server

result = invoke_command(sign.sign, inputs, args)
result = invoke_command(sign.sign, inputs, [], test_context)

expected = {
"keyid": "c6d8bf2e4f48b41ac2ce8eca21415ca8ef68c133b47fc33df03d4070a7e1e9cc", # noqa
Expand All @@ -107,11 +105,7 @@ def test_sign_bootstap_root(self, patch_getpass):
assert result.data["signature"]["keyid"] == expected["keyid"]
assert "Metadata Signed and sent to the API! 🔑" in result.stdout
assert sign.request_server.calls == [
pretend.call(
"http://127.0.0.1",
"api/v1/metadata/sign/",
Methods.GET,
)
pretend.call(api_server, "api/v1/metadata/sign/", Methods.GET)
]
assert sign.send_payload.calls == [
pretend.call(
Expand Down Expand Up @@ -167,17 +161,20 @@ def test_sign_input_option_and_custom_out(
assert result.data["signature"]["sig"] == expected["sig"]
assert f"Saved result to '{custom_path}'" in result.stdout

def test_sign_with_input_option_and_api_server_set(self, patch_getpass):
def test_sign_with_input_option_and_api_server_set(
self, test_context, patch_getpass
):
inputs = [
"1", # Please enter signing key index
f"{_PEMS / 'JH.ed25519'}", # Please enter path to encrypted private key # noqa
]
sign.send_payload = pretend.call_recorder(lambda *a: "fake-taskid")
sign.task_status = pretend.call_recorder(lambda *a: "OK")
sign_input_path = f"{_PAYLOADS / 'sign_pending_roles.json'}"
api_server = "http://localhost:80"
args = ["--api-server", api_server, "--in", sign_input_path]
result = invoke_command(sign.sign, inputs, args)
test_context["settings"].SERVER = "http://localhost:80"
args = ["--in", sign_input_path]

result = invoke_command(sign.sign, inputs, args, test_context)

expected = {
"keyid": "c6d8bf2e4f48b41ac2ce8eca21415ca8ef68c133b47fc33df03d4070a7e1e9cc", # noqa
Expand Down Expand Up @@ -217,7 +214,9 @@ def test_sign_no_api_server_and_no_input_option(self):


class TestSignError:
def test_sign_with_previous_root_but_wrong_version(self, patch_getpass):
def test_sign_with_previous_root_but_wrong_version(
self, test_context, patch_getpass
):
inputs = [
"1", # Please enter signing key index
f"{_PEMS / 'JH.ed25519'}", # Please enter path to encrypted private key # noqa
Expand All @@ -239,22 +238,20 @@ def test_sign_with_previous_root_but_wrong_version(self, patch_getpass):
sign.request_server = pretend.call_recorder(
lambda *a, **kw: fake_response
)
args = ["--api-server", "http://127.0.0.1"]
api_server = "http://127.0.0.1"
test_context["settings"].SERVER = api_server

test_result = invoke_command(
sign.sign, inputs, args, std_err_empty=False
sign.sign, inputs, [], test_context, std_err_empty=False
)

assert test_result.exit_code == 1, test_result.stdout
assert "Previous root v1 needed to sign root v2" in test_result.stderr
assert sign.request_server.calls == [
pretend.call(
"http://127.0.0.1",
"api/v1/metadata/sign/",
Methods.GET,
)
pretend.call(api_server, "api/v1/metadata/sign/", Methods.GET)
]

def test_sign_fully_signed_metadata(self, patch_getpass):
def test_sign_fully_signed_metadata(self, test_context, patch_getpass):
inputs = [
"1", # Please enter signing key index
f"{_PEMS / 'JH.ed25519'}", # Please enter path to encrypted private key # noqa
Expand All @@ -276,19 +273,17 @@ def test_sign_fully_signed_metadata(self, patch_getpass):
sign.request_server = pretend.call_recorder(
lambda *a, **kw: fake_response
)
args = ["--api-server", "http://127.0.0.1"]
api_server = "http://127.0.0.1"
test_context["settings"].SERVER = api_server

test_result = invoke_command(
sign.sign, inputs, args, std_err_empty=False
sign.sign, inputs, [], test_context, std_err_empty=False
)

assert test_result.exit_code == 1, test_result.stdout
assert "Metadata already fully signed." in test_result.stderr
assert sign.request_server.calls == [
pretend.call(
"http://127.0.0.1",
"api/v1/metadata/sign/",
Methods.GET,
)
pretend.call(api_server, "api/v1/metadata/sign/", Methods.GET)
]


Expand Down

0 comments on commit 7c832d4

Please sign in to comment.