diff --git a/packages/syft-bg/src/syft_bg/api/api.py b/packages/syft-bg/src/syft_bg/api/api.py
index 45a7b2eb3fa..7e2982f8f1b 100644
--- a/packages/syft-bg/src/syft_bg/api/api.py
+++ b/packages/syft-bg/src/syft_bg/api/api.py
@@ -538,7 +538,9 @@ def set_policies(
)
except (ApiNotFoundError, ValueError) as e:
return ApiResult(success=False, error=str(e))
- return ApiResult.from_api(name, obj)
+ result = ApiResult.from_api(name, obj)
+ result.state_cleared = reset_state
+ return result
def run_policy(
diff --git a/packages/syft-bg/src/syft_bg/api/results.py b/packages/syft-bg/src/syft_bg/api/results.py
index 8ec088844bc..5dc3a9a8ec2 100644
--- a/packages/syft-bg/src/syft_bg/api/results.py
+++ b/packages/syft-bg/src/syft_bg/api/results.py
@@ -294,6 +294,8 @@ class ApiResult(BaseModel):
file_paths: list[str] = Field(default_factory=list)
peers: list[str] = Field(default_factory=list)
policies: list[str] = Field(default_factory=list) # e.g. ["input", "output"]
+ args: list[str] = Field(default_factory=list) # e.g. ["a: int = 1"]
+ state_cleared: bool = False # set_policies() cleared the api's state
error: str | None = None
@classmethod
@@ -306,6 +308,7 @@ def from_api(cls, name: str, obj: ApiDefinition) -> ApiResult:
file_paths=obj.file_paths,
peers=obj.peers,
policies=policies,
+ args=[a.describe() for a in obj.args],
)
def __repr__(self) -> str:
@@ -318,14 +321,23 @@ def __repr__(self) -> str:
lines.append(f" - {s}")
if self.file_paths:
lines.append(f" file_paths: {', '.join(self.file_paths)}")
+ if self.args:
+ lines.append(" args:")
+ for a in self.args:
+ lines.append(f" - {a}")
if self.peers:
lines.append(f" peers: {', '.join(self.peers)}")
else:
lines.append(" peers: (any)")
if self.policies:
lines.append(f" policies: {', '.join(self.policies)}")
+ if self.state_cleared:
+ lines.append(" state: cleared (pass reset_state=False to keep it)")
else:
lines.append("ApiResult: FAILED")
if self.error:
lines.append(f" error: {self.error}")
return "\n".join(lines)
+
+ def __str__(self) -> str:
+ return self.__repr__()
diff --git a/packages/syft-enclave/src/syft_enclaves/enclave_job_info.py b/packages/syft-enclave/src/syft_enclaves/enclave_job_info.py
index 70ec6585c4d..b6f68667071 100644
--- a/packages/syft-enclave/src/syft_enclaves/enclave_job_info.py
+++ b/packages/syft-enclave/src/syft_enclaves/enclave_job_info.py
@@ -322,6 +322,11 @@ def update_read_permissions(
self._save_own_approval(approval)
return approved
+ def _log_release_hint(self, log_file: str) -> str:
+ """The data owners release a log by requesting it, see ``request_log``."""
+ method = "request_stderr" if log_file == "stderr.txt" else "request_stdout"
+ return f"The data owners can release it with {method}."
+
def request_log(
self,
log_file: str,
diff --git a/packages/syft-enclave/tests/test_read_permissions.py b/packages/syft-enclave/tests/test_read_permissions.py
index 188b11e5161..7eb629ea3f7 100644
--- a/packages/syft-enclave/tests/test_read_permissions.py
+++ b/packages/syft-enclave/tests/test_read_permissions.py
@@ -956,6 +956,24 @@ def test_one_owner_requesting_log_shares_nothing():
assert not has_file(ds, "stderr.txt")
+def test_unshared_log_points_to_log_requests():
+ enclave, do1, do2, ds = run_crash_sharing_nothing()
+
+ job = ds.jobs["j"]
+ not_shared_message = (
+ "stderr.txt is not shared with you. "
+ "The data owners can release it with request_stderr."
+ )
+ assert str(job.stderr) == not_shared_message
+ assert not_shared_message in job.stderr._repr_html_()
+ assert str(job.stdout) == (
+ "stdout.txt is not shared with you. "
+ "The data owners can release it with request_stdout."
+ )
+ # The enclave ran the job, so it has the log.
+ assert "ValueError" in str(enclave.jobs["j"].stderr)
+
+
def test_log_request_defaults_to_data_owners():
enclave, do1, do2, ds = run_crash_sharing_nothing()
for do in (do1, do2):
diff --git a/packages/syft-job/src/syft_job/job.py b/packages/syft-job/src/syft_job/job.py
index 223d8920563..2289190d0ab 100644
--- a/packages/syft-job/src/syft_job/job.py
+++ b/packages/syft-job/src/syft_job/job.py
@@ -276,6 +276,27 @@ def _log_path(self, log_file: str) -> Path:
"""Where the viewers read ``log_file`` ("stdout.txt" or "stderr.txt")."""
return self.job_review_path / log_file
+ def _missing_log_message(self, log_file: str) -> str:
+ """What to tell a reader who has no ``log_file`` of this finished job.
+
+ The datasite owner keeps every log the job wrote. Anyone else reads a
+ log only once it is shared with them.
+ """
+ if self.current_user_email == self.datasite_owner_email:
+ return f"No {Path(log_file).stem} file found"
+ if self.policy_error:
+ # The policy may have refused the call before it ran, so the log
+ # may not exist.
+ return (
+ f"{log_file} is not shared with you: the data owner's policy "
+ "refused the call. The reason is in job.policy_error."
+ )
+ return f"{log_file} is not shared with you. {self._log_release_hint(log_file)}"
+
+ def _log_release_hint(self, log_file: str) -> str:
+ """Who can share ``log_file`` with a reader who does not have it."""
+ return "The data owner can share it with share_job_results."
+
@property
def files(self) -> List[Path]:
"""Get list of relevant files across both inbox and review."""
diff --git a/packages/syft-job/src/syft_job/job_repr.py b/packages/syft-job/src/syft_job/job_repr.py
index 5ceba837a3c..9eb5e6efee8 100644
--- a/packages/syft-job/src/syft_job/job_repr.py
+++ b/packages/syft-job/src/syft_job/job_repr.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import json
import re
from html import escape
from typing import TYPE_CHECKING, List
@@ -66,7 +67,7 @@ def __str__(self) -> str:
stderr_file = self.job_info._log_path("stderr.txt")
if not stderr_file.exists():
- return "No stderr file found"
+ return self.job_info._missing_log_message("stderr.txt")
try:
with open(stderr_file, "r") as f:
@@ -98,7 +99,7 @@ def _repr_html_(self) -> str:
stderr_file = self.job_info._log_path("stderr.txt")
if not stderr_file.exists():
- error_msg = "No stderr file found"
+ error_msg = escape(self.job_info._missing_log_message("stderr.txt"))
else:
try:
with open(stderr_file, "r") as f:
@@ -431,6 +432,8 @@ def job_info_repr_html(job: "JobInfo") -> str:
except Exception:
pass
+ params_section = _params_html(job)
+
status_emoji_map = {
"received": "📨",
"pending": "📥",
@@ -741,7 +744,7 @@ def job_info_repr_html(job: "JobInfo") -> str:
📜 Script
{script_content}
-
{code_section}{policy_section}{outputs_section}
+ {code_section}{params_section}{policy_section}{outputs_section}
"""
@@ -758,6 +761,24 @@ def _detail_html(label: str, value: str) -> str:
"""
+def _params_html(job: "JobInfo") -> str:
+ """A section with code/params.json, the arguments the job runs with."""
+ try:
+ params = (job.code_dir / "params.json").read_text()
+ except (OSError, ValueError):
+ return ""
+ try:
+ params = json.dumps(json.loads(params), indent=2, ensure_ascii=False)
+ except ValueError:
+ pass # not JSON: show it as it is
+ return f"""
+
+
Parameters
+
code/params.json
+
{escape(params)}
+
"""
+
+
def _policy_html(job: "JobInfo") -> tuple[str, str]:
"""Detail rows (api, policy error) and a section with the policies' code."""
details = ""
diff --git a/packages/syft-job/src/syft_job/job_stdout.py b/packages/syft-job/src/syft_job/job_stdout.py
index e89b2236b8e..c4b0d0e677b 100644
--- a/packages/syft-job/src/syft_job/job_stdout.py
+++ b/packages/syft-job/src/syft_job/job_stdout.py
@@ -2,6 +2,7 @@
import html
import re
+from html import escape
from typing import TYPE_CHECKING
if TYPE_CHECKING:
@@ -75,7 +76,7 @@ def __str__(self) -> str:
stdout_file = self.job_info._log_path("stdout.txt")
if not stdout_file.exists():
- return "No stdout file found"
+ return self.job_info._missing_log_message("stdout.txt")
try:
with open(stdout_file, "r") as f:
@@ -108,7 +109,7 @@ def _repr_html_(self) -> str:
stdout_file = self.job_info._log_path("stdout.txt")
if not stdout_file.exists():
- error_msg = "No stdout file found"
+ error_msg = escape(self.job_info._missing_log_message("stdout.txt"))
else:
try:
with open(stdout_file, "r") as f:
diff --git a/packages/syft-job/tests/test_policies.py b/packages/syft-job/tests/test_policies.py
index 648f0088d78..e1d1db9ec21 100644
--- a/packages/syft-job/tests/test_policies.py
+++ b/packages/syft-job/tests/test_policies.py
@@ -1,6 +1,7 @@
"""Api calls (requests), and the input and output policies run around them."""
import json
+from html import escape
from pathlib import Path
import pytest
@@ -290,6 +291,26 @@ def test_timed_out_api_call_shares_nothing(env):
assert not env.reads(DS_EMAIL, "call.job", "returncode.txt")
+def test_unshared_log_says_not_shared(env):
+ """A reader without a log is told it is not shared, not that none exists."""
+ job = env.call("echo private; exit 3")
+ assert not env.reads(DS_EMAIL, "call.job", "stderr.txt")
+ # The DS and the DO share one SyftBox here: the DS would not have the logs.
+ for log_file in ("stdout.txt", "stderr.txt"):
+ (job.job_review_path / log_file).unlink()
+
+ not_shared_message = (
+ "stderr.txt is not shared with you. "
+ "The data owner can share it with share_job_results."
+ )
+ ds_job = _ds_job(env)
+ assert str(ds_job.stderr) == not_shared_message
+ assert not_shared_message in ds_job.stderr._repr_html_()
+ assert str(ds_job.stdout).startswith("stdout.txt is not shared with you.")
+ # The data owner keeps every log, so a missing one was never written.
+ assert str(job.stderr) == "No stderr file found"
+
+
def test_output_policy_with_bad_read_permissions_denies(env):
env.apis.output_code = _read_permissions_policy(["not", "a", "dict"])
@@ -346,6 +367,21 @@ def test_api_call_ignores_share_flags(env):
assert job.outputs_withheld
+def test_job_view_shows_params_escaped(env):
+ (env.apis.files_dir / "run.sh").write_text("echo hi\n")
+ params = {"code/params.json": b'{"word": "privacy", "n": 3}'}
+ env.ds_client.submit_api_request(DO_EMAIL, "call.job", API_NAME, params)
+ env.ds_client.submit_bash_job(DO_EMAIL, "echo hi", "plain.job")
+
+ html = env.do_job("call.job")._repr_html_()
+
+ assert "Parameters
" in html
+ pretty_params = '{\n "word": "privacy",\n "n": 3\n}'
+ assert escape(pretty_params) in html and "privacy" not in html
+ # A job without code/params.json has no such section.
+ assert "Parameters
" not in env.do_job("plain.job")._repr_html_()
+
+
def test_request_becomes_approved_job_with_api_code(env):
job = env.call("cp code/params.json code/outputs/params.json")
diff --git a/packages/syft-rds/src/syft_rds/apis/repr.py b/packages/syft-rds/src/syft_rds/apis/repr.py
index 170accb4e73..bd477b40a07 100644
--- a/packages/syft-rds/src/syft_rds/apis/repr.py
+++ b/packages/syft-rds/src/syft_rds/apis/repr.py
@@ -58,6 +58,13 @@ def _args_html(api: Api) -> str:
)
+def _policy_kinds(api: Api) -> str:
+ """The policies the api has, e.g. "input, output", or "-"."""
+ definition = api.definition
+ kinds = [k for k in ("input", "output") if getattr(definition, f"{k}_policy")]
+ return ", ".join(kinds) or "-"
+
+
def _row_html(index: int, api: Api) -> str:
call = escape(api.call_signature)
code = escape(api.python_file or "-")
@@ -67,6 +74,7 @@ def _row_html(index: int, api: Api) -> str:
f'{escape(api.name)} | '
f'{escape(api.datasite)} | '
f'{_args_html(api)} | '
+ f'{escape(_policy_kinds(api))} | '
f'{code} | '
f'{call} | '
""
@@ -76,7 +84,7 @@ def _row_html(index: int, api: Api) -> str:
def api_collection_repr_html(apis: Sequence[Api]) -> str:
if not apis:
return _EMPTY_HTML
- headers = ["#", "Name", "Datasite", "Args", "Code", "Call"]
+ headers = ["#", "Name", "Datasite", "Args", "Policies", "Code", "Call"]
head = "".join(f'{h} | ' for h in headers)
rows = "".join(_row_html(i, api) for i, api in enumerate(apis))
return f"""{_STYLE}
@@ -97,7 +105,10 @@ def api_collection_repr_str(apis: Sequence[Api]) -> str:
lines = [f"Apis ({len(apis)}):"]
for i, api in enumerate(apis):
call = api.call_signature
- lines.append(f" [{i}] {api.name} (from {api.datasite}) -> {call}")
+ policies = _policy_kinds(api)
+ lines.append(
+ f" [{i}] {api.name} (from {api.datasite}) -> {call} | policies: {policies}"
+ )
return "\n".join(lines)
diff --git a/packages/syft-rds/src/syft_rds/client.py b/packages/syft-rds/src/syft_rds/client.py
index 5d9268b16a1..ba74344e451 100644
--- a/packages/syft-rds/src/syft_rds/client.py
+++ b/packages/syft-rds/src/syft_rds/client.py
@@ -122,6 +122,16 @@ def _peer_schema_lookup(
return lambda email: peer_store.protocol_schema(email, protocol_name)
+def _print_call_result(job: Any) -> None:
+ """Report how the job of a blocking api call ended, and why a policy stopped it."""
+ print(f"Job '{job.name}' finished with status: {job.status}")
+ if job.policy_error:
+ print(f" The data owner's policy refused the call: {job.policy_error}")
+ elif job.status == "done" and job.outputs_withheld:
+ print(" The data owner's output policy held the outputs back.")
+ print(" The data owner can still share them with you later.")
+
+
class SyftRDSClient(BaseModel):
# Holds live service objects (sync engine + RDS-owned managers), not
# serializable data, so arbitrary types are allowed.
@@ -550,7 +560,7 @@ def _wait_for_call(self, job_name: str, poll_interval: float = 2.0) -> Any:
self.sync_engine.sync()
job = _named(self.job_client.jobs, job_name)
if job is not None and job.status in FINISHED_JOB_STATUSES:
- print(f"Job '{job_name}' finished with status: {job.status}")
+ _print_call_result(job)
return job
request = _named(self.job_client.requests, job_name)
if request is not None and request.status == "rejected":
diff --git a/packages/syft-rds/tests/test_api_policies.py b/packages/syft-rds/tests/test_api_policies.py
index e235dbfd625..3f9d50e1ab9 100644
--- a/packages/syft-rds/tests/test_api_policies.py
+++ b/packages/syft-rds/tests/test_api_policies.py
@@ -5,12 +5,17 @@
from contextlib import contextmanager
from dataclasses import replace
from pathlib import Path
+from typing import Any, NamedTuple
from unittest.mock import patch
from syft_bg.api import create_api_from_job
+from syft_bg.api.results import ApiResult
from syft_bg.approve.handlers.job import ApprovedJobHandler
from syft_bg.common.config import get_default_paths
from syft_rds import SyftRDSClient
+from syft_rds.apis import Api, ApiDefinition, FileEntry
+from syft_rds.apis.repr import api_collection_repr_html, api_collection_repr_str
+from syft_rds.client import _print_call_result
ADDER_CODE = """import json
with open("params.json") as f:
@@ -37,6 +42,12 @@
raise ValueError("Sum too large to share")
"""
+# Approves no reader for any file, so the outputs are held back.
+HOLD_BACK_POLICY = """import os
+from pathlib import Path
+Path(os.environ["SYFT_POLICY_READ_PERMISSIONS_PATH"]).write_text("{}")
+"""
+
@contextmanager
def _temp_config_paths():
@@ -92,53 +103,151 @@ def _ds_job(ds_manager, name: str):
return next(j for j in ds_manager.jobs if j.name == name)
-def test_api_policies_allow_block_and_show():
+class _ApiSetup(NamedTuple):
+ ds_manager: SyftRDSClient
+ do_manager: SyftRDSClient
+ job: Any # the job the api was built from
+ api_result: ApiResult
+ config_path: Path # the syft-bg config the approve service reads
+
+
+@contextmanager
+def _adder_api(input_policy: str | None = None, output_policy: str | None = None):
+ """Pair a DS and a DO, and turn an adder job into an api with these policies."""
ds_manager, do_manager = SyftRDSClient.pair_with_mock_drive_service_connection(
use_in_memory_cache=False,
sync_automatically=False,
)
job = _submit_adder_job(ds_manager, do_manager, {"a": 1, "b": 2})
-
with _temp_config_paths() as (paths, tmp):
- result = create_api_from_job(
- job,
- input_policy=_write(tmp / "rate_limit.py", RATE_LIMIT_POLICY),
- output_policy=_write(tmp / "block_large.py", BLOCK_LARGE_SUM_POLICY),
+ input_path = _write(tmp / "input.py", input_policy) if input_policy else None
+ output_path = (
+ _write(tmp / "output.py", output_policy) if output_policy else None
)
- assert result.success and result.policies == ["input", "output"]
-
+ api_result = create_api_from_job(
+ job, input_policy=input_path, output_policy=output_path
+ )
+ assert api_result.success
do_manager.sync()
ds_manager.sync()
- api = ds_manager.api.adder
+ yield _ApiSetup(ds_manager, do_manager, job, api_result, paths.config)
+
+
+def test_api_view_shows_policy_source():
+ with _adder_api(RATE_LIMIT_POLICY, BLOCK_LARGE_SUM_POLICY) as setup:
+ assert setup.api_result.policies == ["input", "output"]
+ api = setup.ds_manager.api.adder
+ # The DS sees each policy's source code, which contains these error texts.
assert "Rate limit reached" in repr(api)
assert "Sum too large to share" in api._repr_html_()
- # A call is a request: it carries the params, not the api's code. The
- # DO's client turns it into an approved job, which the approve service
- # runs. The job the api was built from is a whole job, which nothing
- # approves. A call over 100 passes the input policy and is blocked on
- # output.
- large = api(100, b=1, block=False)
- assert large.job is None
- code_files = sorted(p.name for p in (large.request_path / "code").iterdir())
+
+def test_api_call_runs_as_request():
+ with _adder_api(RATE_LIMIT_POLICY, BLOCK_LARGE_SUM_POLICY) as setup:
+ # A call is a request: it carries the params, not the api's code.
+ call = setup.ds_manager.api.adder(1, b=2, block=False)
+ assert call.job is None
+ code_files = sorted(p.name for p in (call.request_path / "code").iterdir())
assert code_files == ["params.json"]
- assert _run_calls(do_manager, paths.config) == {large.name}
- blocked = _ds_job(ds_manager, large.name)
- assert blocked.status == "failed"
- assert blocked.policy_error == "ValueError: Sum too large to share"
- assert blocked.output_paths == []
-
- # The rate limit of one call is used up.
- second = api(1, b=2, block=False)
- _run_calls(do_manager, paths.config)
- limited = _ds_job(ds_manager, second.name)
- assert limited.status == "failed"
- assert limited.policy_error == "ValueError: Rate limit reached: 1 call"
+ # The DO's client turns the call into an approved job, which the approve
+ # service runs. Nothing approves the job the api was built from.
+ assert _run_calls(setup.do_manager, setup.config_path) == {call.name}
+ do_jobs = {j.name: j for j in setup.do_manager.jobs}
+ assert do_jobs[setup.job.name].status == "pending"
# The DO's view of a call shows the api and its policies.
- do_job = next(j for j in do_manager.jobs if j.name == large.name)
+ do_job = do_jobs[call.name]
assert do_job.api_name == "adder"
html = do_job._repr_html_()
- assert "adder" in html and "Input policy" in html and "Output policy" in html
- original = next(j for j in do_manager.jobs if j.name == job.name)
- assert original.status == "pending"
+ assert "Input policy" in html and "Output policy" in html
+
+
+def test_output_policy_refuses_large_sum(capsys):
+ with _adder_api(output_policy=BLOCK_LARGE_SUM_POLICY) as setup:
+ large_call = setup.ds_manager.api.adder(100, b=1, block=False)
+ _run_calls(setup.do_manager, setup.config_path)
+ blocked_job = _ds_job(setup.ds_manager, large_call.name)
+
+ assert blocked_job.status == "failed"
+ assert blocked_job.policy_error == "ValueError: Sum too large to share"
+ # A refused call shares no log; the DS is sent to the policy's reason.
+ assert str(blocked_job.stderr) == (
+ "stderr.txt is not shared with you: the data owner's policy "
+ "refused the call. The reason is in job.policy_error."
+ )
+ assert blocked_job.output_paths == []
+ capsys.readouterr()
+ _print_call_result(blocked_job)
+ assert capsys.readouterr().out == (
+ f"Job '{large_call.name}' finished with status: failed\n"
+ " The data owner's policy refused the call: "
+ "ValueError: Sum too large to share\n"
+ )
+
+
+def test_input_policy_refuses_call_over_rate_limit(capsys):
+ with _adder_api(input_policy=RATE_LIMIT_POLICY) as setup:
+ first_call = setup.ds_manager.api.adder(1, b=2, block=False)
+ _run_calls(setup.do_manager, setup.config_path)
+ assert _ds_job(setup.ds_manager, first_call.name).status == "done"
+ # The first call used up the rate limit of one call.
+ second_call = setup.ds_manager.api.adder(1, b=2, block=False)
+ _run_calls(setup.do_manager, setup.config_path)
+ limited_job = _ds_job(setup.ds_manager, second_call.name)
+
+ assert limited_job.status == "failed"
+ assert limited_job.policy_error == "ValueError: Rate limit reached: 1 call"
+ capsys.readouterr()
+ _print_call_result(limited_job)
+ assert (
+ "refused the call: ValueError: Rate limit reached: 1 call"
+ in capsys.readouterr().out
+ )
+
+
+def test_held_back_outputs_point_to_policy(capsys):
+ with _adder_api(output_policy=HOLD_BACK_POLICY) as setup:
+ call = setup.ds_manager.api.adder(1, b=2, block=False)
+ _run_calls(setup.do_manager, setup.config_path)
+ held_job = _ds_job(setup.ds_manager, call.name)
+
+ assert held_job.status == "done" and held_job.outputs_withheld
+ assert held_job.output_paths == []
+ capsys.readouterr()
+ _print_call_result(held_job)
+ assert capsys.readouterr().out == (
+ f"Job '{call.name}' finished with status: done\n"
+ " The data owner's output policy held the outputs back.\n"
+ " The data owner can still share them with you later.\n"
+ )
+
+
+def _policy_entry(kind: str) -> list[FileEntry]:
+ return [FileEntry(relative_path=f"policies/{kind}/run.sh", hash="sha256:0")]
+
+
+def test_api_table_shows_policies(tmp_path):
+ definitions = {
+ "plain": ApiDefinition(),
+ "checked": ApiDefinition(input_policy=_policy_entry("input")),
+ "filtered": ApiDefinition(output_policy=_policy_entry("output")),
+ "both": ApiDefinition(
+ input_policy=_policy_entry("input"),
+ output_policy=_policy_entry("output"),
+ ),
+ }
+ apis = [
+ Api(name, "do@test.org", tmp_path, definition, client=None)
+ for name, definition in definitions.items()
+ ]
+
+ lines = api_collection_repr_str(apis).splitlines()[1:]
+ assert [line.split(" | ")[1] for line in lines] == [
+ "policies: -",
+ "policies: input",
+ "policies: output",
+ "policies: input, output",
+ ]
+ html = api_collection_repr_html(apis)
+ for policies in ("-", "input", "output", "input, output"):
+ assert f'{policies} | ' in html
diff --git a/tests/unit/syft_bg/test_api_result.py b/tests/unit/syft_bg/test_api_result.py
new file mode 100644
index 00000000000..273b47d9603
--- /dev/null
+++ b/tests/unit/syft_bg/test_api_result.py
@@ -0,0 +1,47 @@
+"""What ApiResult shows the DO: an api's arguments, and a cleared state."""
+
+from syft_bg.api.api import set_policies
+from syft_bg.api.results import ApiResult
+from syft_rds.apis import ApiArg, ApiDefinition
+
+from tests.unit.syft_bg.test_create_api import _create, _patched_paths, _write_project
+
+ARGS = [
+ {"name": "dataset", "type": "str", "default": "adult"},
+ {"name": "n", "type": "int", "required": True},
+]
+STATE_CLEARED = "state: cleared (pass reset_state=False to keep it)"
+
+
+def test_create_api_lists_args(temp_dir):
+ with _patched_paths(temp_dir):
+ result = _create(_write_project(temp_dir), allow_any_peer=True, args=ARGS)
+
+ assert result.args == ["dataset: str = 'adult'", "n: int"]
+ assert " args:\n - dataset: str = 'adult'\n - n: int\n" in repr(result)
+ assert not result.state_cleared and STATE_CLEARED not in repr(result)
+
+
+def test_set_policies_says_when_state_cleared(temp_dir):
+ policy_path = temp_dir / "policy.py"
+ policy_path.write_text("pass\n")
+ with _patched_paths(temp_dir):
+ _create(_write_project(temp_dir), allow_any_peer=True, args=ARGS)
+ cleared_result = set_policies("main", input_policy=policy_path)
+ kept_result = set_policies("main", output_policy=policy_path, reset_state=False)
+
+ assert cleared_result.state_cleared and STATE_CLEARED in repr(cleared_result)
+ assert not kept_result.state_cleared
+ assert STATE_CLEARED not in repr(kept_result)
+ assert kept_result.args == ["dataset: str = 'adult'", "n: int"]
+
+
+def test_api_result_str_matches_repr():
+ ok_result = ApiResult.from_api(
+ "main", ApiDefinition(args=[ApiArg(name="a", default=1)])
+ )
+ failed_result = ApiResult(success=False, error="No policy at x.py")
+
+ assert str(ok_result) == repr(ok_result)
+ assert str(ok_result).startswith("ApiResult: OK [main]")
+ assert str(failed_result) == "ApiResult: FAILED\n error: No policy at x.py"