From 2a9f96dca09796bc6b95f4ad7b68d6c05b6c86b7 Mon Sep 17 00:00:00 2001 From: wobrschalek Date: Thu, 19 Nov 2026 15:19:57 -0800 Subject: [PATCH] Support Flexo service tokens and Beta 1 write statuses --- .github/workflows/omg-beta1-conformance.yml | 1 + README.md | 12 ++++ conformance/README.md | 2 + conformance/conftest.py | 6 +- conformance/provider.py | 4 +- conformance/test_interoperability.py | 42 ++++++++++-- src/sysmlv2_client/client.py | 37 +++++++---- tests/test_client.py | 74 ++++++++++++++++----- 8 files changed, 142 insertions(+), 36 deletions(-) diff --git a/.github/workflows/omg-beta1-conformance.yml b/.github/workflows/omg-beta1-conformance.yml index 84d5bfe..1bd1dd8 100644 --- a/.github/workflows/omg-beta1-conformance.yml +++ b/.github/workflows/omg-beta1-conformance.yml @@ -25,6 +25,7 @@ jobs: env: SYSML_CONFORMANCE_URL: ${{ vars.SYSML_CONFORMANCE_URL }} SYSML_CONFORMANCE_TOKEN: ${{ secrets.SYSML_CONFORMANCE_TOKEN }} + SYSML_CONFORMANCE_SVC_TOKEN: ${{ secrets.SYSML_CONFORMANCE_SVC_TOKEN }} PROVIDER_BUILD: ${{ inputs.provider_build }} - uses: actions/upload-artifact@v4 if: always() diff --git a/README.md b/README.md index 9aeb032..8c6e1a9 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,18 @@ Unit tests are implemented using `pytest` and `requests-mock`. The [OMG Beta 1 REST/HTTP conformance suite](conformance/README.md) includes live provider tests, a Python client interoperability test, and traceability matrices. +For a Flexo gateway that requires `X-SysMLv2-Svc-Token`, pass the token through the `svc_token` keyword: + +```python +import os + +from sysmlv2_client import SysMLV2Client + +client = SysMLV2Client("http://127.0.0.1:62859", svc_token=os.environ["SYSML_SVC_TOKEN"]) +``` + +If your deployment also requires Bearer authentication, supply `bearer_token` as well. Automatic redirects are disabled when a service token is configured. + ## API ### Basic v2 API * get_projects diff --git a/conformance/README.md b/conformance/README.md index 420feda..920cfc2 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -18,6 +18,8 @@ python -m pytest -c conformance/pytest.ini conformance -m "live and not interope python -m pytest -c conformance/pytest.ini conformance -m interoperability --live --provider-build "provider name and deployed revision" --junitxml=conformance/results/client.xml ``` +For the Flexo gateway, set `SYSML_CONFORMANCE_SVC_TOKEN` to the opaque token sent in the `X-SysMLv2-Svc-Token` header. Set both credential variables if the deployment requires both headers. For GitHub Actions, use a secret with the same name. + Use `-k PIM-PS` for the Annex A.1 slice or select the pytest nodes in the matrices. Some scenarios use other services to create their fixtures. A blocked fixture provides no result for the operation it was meant to exercise. Raw HTTP evidence in JUnit records operation IDs and statuses. Result files are ignored by Git. For manual CI runs, configure the `sysml-conformance` GitHub environment with the URL variable and optional token secret named above, then dispatch **OMG Beta 1 REST conformance** with the provider revision. The workflow uploads JUnit results even when tests fail. diff --git a/conformance/conftest.py b/conformance/conftest.py index 3f920a7..c458dd7 100644 --- a/conformance/conftest.py +++ b/conformance/conftest.py @@ -39,7 +39,11 @@ def api(pytestconfig, record_property): if not pytestconfig.getoption("--live"): pytest.skip("Live provider run requires --live") record_property("provider_build", pytestconfig.getoption("--provider-build")) - server = Provider(os.environ["SYSML_CONFORMANCE_URL"], os.getenv("SYSML_CONFORMANCE_TOKEN")) + server = Provider( + os.environ["SYSML_CONFORMANCE_URL"], + os.getenv("SYSML_CONFORMANCE_TOKEN"), + svc_token=os.getenv("SYSML_CONFORMANCE_SVC_TOKEN"), + ) try: yield server finally: diff --git a/conformance/provider.py b/conformance/provider.py index 60eb504..b508a82 100644 --- a/conformance/provider.py +++ b/conformance/provider.py @@ -99,7 +99,7 @@ def bind(value): class Provider: - def __init__(self, base_url, token): + def __init__(self, base_url, token, *, svc_token=None): self.url = base_url.rstrip("/") parts = urlsplit(self.url) if parts.scheme not in ("http", "https") or not parts.hostname or ( @@ -117,6 +117,8 @@ def __init__(self, base_url, token): raise ValueError("Set one raw JWT or one Bearer token") if credential: self.session.headers["Authorization"] = "Bearer " + credential[0] + if svc_token: + self.session.headers["X-SysMLv2-Svc-Token"] = svc_token self.projects = [] self.evidence = [] diff --git a/conformance/test_interoperability.py b/conformance/test_interoperability.py index ba73cd0..8ad7f93 100644 --- a/conformance/test_interoperability.py +++ b/conformance/test_interoperability.py @@ -1,17 +1,26 @@ import pytest -from .scenarios import expect_ids, model +from sysmlv2_client import SysMLV2Client, SysMLV2NotFoundError + +from .provider import ref, uid +from .scenarios import change, expect_ids, model, package pytestmark = [pytest.mark.live, pytest.mark.interoperability] -def test_client_reads_seeded_model(api): - from sysmlv2_client import SysMLV2Client +@pytest.fixture +def client(api): + svc_token = api.session.headers.get("X-SysMLv2-Svc-Token") + bearer_token = api.session.headers.get("Authorization") + # The local pilot accepts a placeholder when neither credential is configured. + if svc_token is None and bearer_token is None: + bearer_token = "Bearer pilot" + return SysMLV2Client(api.url, bearer_token, svc_token=svc_token) + +def test_client_reads_seeded_model(api, client): project = api.project() commit, parent, child, membership, dependency = model(api, project) - # The client requires a Bearer header even for a local unauthenticated pilot. - client = SysMLV2Client(api.url, api.session.headers.get("Authorization", "Bearer pilot")) assert client.get_project_by_id(project["@id"])["@id"] == project["@id"] assert client.get_commit_by_id(project["@id"], commit["@id"])["@id"] == commit["@id"] element = client.get_element(project["@id"], parent["@id"], commit["@id"]) @@ -21,3 +30,26 @@ def test_client_reads_seeded_model(api): parent, child, membership, dependency) expect_ids(client.list_relationships(project["@id"], parent["@id"], commit["@id"], "both"), membership, dependency) + + +def test_client_writes_project_lifecycle(api, client): + name = f"omg-beta1-{uid()}" + project = client.create_project({"name": name}) + project_id = project["@id"] + api.projects.append(project_id) + assert client.get_project_by_id(project_id)["name"] == name + + element = package("Client-created package") + commit = client.create_commit(project_id, {"change": [change(element)]}) + branch = client.create_branch(project_id, {"name": "test-branch", "head": ref(commit)}) + tag = client.create_tag(project_id, {"name": "test-tag", "taggedCommit": ref(commit)}) + assert client.get_element(project_id, element["@id"], commit["@id"])["@id"] == element["@id"] + assert client.get_branch_by_id(project_id, branch["@id"])["head"] == ref(commit) + assert client.get_tag_by_id(project_id, tag["@id"])["taggedCommit"] == ref(commit) + + client.delete_tag(project_id, tag["@id"]) + client.delete_branch(project_id, branch["@id"]) + client.delete_project(project_id) + with pytest.raises(SysMLV2NotFoundError): + client.get_project_by_id(project_id) + api.projects.remove(project_id) diff --git a/src/sysmlv2_client/client.py b/src/sysmlv2_client/client.py index 122f9a5..02af8da 100644 --- a/src/sysmlv2_client/client.py +++ b/src/sysmlv2_client/client.py @@ -12,19 +12,26 @@ ) class SysMLV2Client: - def __init__(self, base_url: str, bearer_token: str): + def __init__(self, base_url: str, bearer_token: str | None = None, *, svc_token: str | None = None): if not base_url: raise ValueError("base_url cannot be empty.") - if not bearer_token or not bearer_token.lower().startswith("bearer "): + if svc_token is not None and (not svc_token or any(char.isspace() for char in svc_token)): + raise ValueError("svc_token must be a nonempty token without whitespace.") + if (bearer_token is not None or svc_token is None) and ( + not bearer_token or not bearer_token.lower().startswith("bearer ") + ): raise ValueError("bearer_token must be provided and start with 'Bearer '.") self.base_url = base_url.rstrip('/') self._bearer_token = bearer_token self._headers = { - "Authorization": self._bearer_token, "Content-Type": "application/json", "Accept": "application/json", } + if bearer_token: + self._headers["Authorization"] = bearer_token + if svc_token: + self._headers["X-SysMLv2-Svc-Token"] = svc_token self._session = requests.Session() self._session.headers.update(self._headers) @@ -34,7 +41,7 @@ def _request( endpoint: str, params: Optional[Dict[str, Any]] = None, data: Optional[Dict[str, Any]] = None, - expected_status: int = 200, + expected_status: int | tuple[int, ...] = 200, ) -> Dict[str, Any]: url = f"{self.base_url}{endpoint}" json_data = data @@ -45,6 +52,8 @@ def _request( url=url, params=params, json=json_data, + # Requests does not strip custom credentials on cross-origin redirects. + allow_redirects="X-SysMLv2-Svc-Token" not in self._headers, ) # Check for specific error codes first @@ -61,8 +70,8 @@ def _request( if response.status_code == 409: raise SysMLV2ConflictError(f"Conflict detected for {endpoint}: {response.text}") - # Check if the status code matches the expected one - if response.status_code != expected_status: + allowed_statuses = (expected_status,) if isinstance(expected_status, int) else expected_status + if response.status_code not in allowed_statuses: raise SysMLV2APIError( status_code=response.status_code, message=f"Unexpected status code for {method} {endpoint}. Response: {response.text}" @@ -97,14 +106,14 @@ def create_project(self, project_data: Dict[str, Any]) -> Dict[str, Any]: method="POST", endpoint="/projects", data=project_data, - expected_status=200 + expected_status=(200, 201) ) def delete_project(self, project_id: str): return self._request( method="DELETE", endpoint=f"/projects/{project_id}", - expected_status=200 + expected_status=(200, 204) ) def get_project_by_id(self, project_id: str) -> Dict[str, Any]: @@ -147,7 +156,7 @@ def create_commit(self, project_id: str, commit_data: Dict[str, Any], branch_id: method="POST", endpoint=endpoint, data=commit_data, - expected_status=200 + expected_status=(200, 201) ) def get_commit_by_id(self, project_id: str, commit_id: str) -> Dict[str, Any]: @@ -182,7 +191,7 @@ def create_branch(self, project_id: str, branch_data: Dict[str, Any]) -> Dict[st method="POST", endpoint=endpoint, data=branch_data, - expected_status=200 + expected_status=(200, 201) ) def get_branch_by_id(self, project_id: str, branch_id: str) -> Dict[str, Any]: @@ -191,7 +200,7 @@ def get_branch_by_id(self, project_id: str, branch_id: str) -> Dict[str, Any]: def delete_branch(self, project_id: str, branch_id: str) -> None: endpoint = f"/projects/{project_id}/branches/{branch_id}" - self._request(method="DELETE", endpoint=endpoint, expected_status=204) + self._request(method="DELETE", endpoint=endpoint, expected_status=(200, 204)) return None # --- Tag Management --- @@ -212,7 +221,7 @@ def create_tag(self, project_id: str, tag_data: Dict[str, Any]) -> Dict[str, Any method="POST", endpoint=endpoint, data=tag_data, - expected_status=200 + expected_status=(200, 201) ) def get_tag_by_id(self, project_id: str, tag_id: str) -> Dict[str, Any]: @@ -221,7 +230,7 @@ def get_tag_by_id(self, project_id: str, tag_id: str) -> Dict[str, Any]: def delete_tag(self, project_id: str, tag_id: str) -> None: endpoint = f"/projects/{project_id}/tags/{tag_id}" - self._request(method="DELETE", endpoint=endpoint, expected_status=204) + self._request(method="DELETE", endpoint=endpoint, expected_status=(200, 204)) return None # --- Element/Relationship Listing --- @@ -251,4 +260,4 @@ def list_relationships( elif isinstance(response_data, dict): return response_data.get('elements', []) else: - return [] \ No newline at end of file + return [] diff --git a/tests/test_client.py b/tests/test_client.py index f7a4595..f8edf9f 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -60,6 +60,34 @@ def test_client_initialization_invalid_url(): SysMLV2Client(base_url="", bearer_token=TEST_BEARER_TOKEN) +@pytest.mark.parametrize("bearer_token", [None, TEST_BEARER_TOKEN]) +def test_service_token_header(requests_mock, bearer_token): + client = SysMLV2Client(TEST_BASE_URL, bearer_token, svc_token="example-service-token") + requests_mock.get(f"{TEST_BASE_URL}/projects", json=[]) + + assert client.get_projects() == [] + headers = requests_mock.last_request.headers + assert headers["X-SysMLv2-Svc-Token"] == "example-service-token" + assert headers.get("Authorization") == bearer_token + + +def test_service_token_is_not_forwarded_on_redirect(requests_mock): + client = SysMLV2Client(TEST_BASE_URL, svc_token="example-service-token") + requests_mock.get(f"{TEST_BASE_URL}/projects", status_code=302, + headers={"Location": "http://other.example.org/projects"}) + + with pytest.raises(SysMLV2APIError) as error: + client.get_projects() + assert error.value.status_code == 302 + assert requests_mock.call_count == 1 + + +@pytest.mark.parametrize("svc_token", ["", " ", "token\nextra"]) +def test_client_rejects_invalid_service_token(svc_token): + with pytest.raises(ValueError, match="svc_token"): + SysMLV2Client(TEST_BASE_URL, svc_token=svc_token) + + # --- Test Get Projects --- def test_get_projects_success(client, requests_mock): @@ -121,12 +149,13 @@ def test_get_projects_api_error(client, requests_mock): # --- Test Create Project --- -def test_create_project_success(client, requests_mock): +@pytest.mark.parametrize("status", [200, 201]) +def test_create_project_success(client, requests_mock, status): """Tests successfully creating a project.""" mock_url = f"{TEST_BASE_URL}/projects" request_data = {"name": "New Project", "description": "A test project"} response_data = {"id": "new_proj_id", **request_data} - requests_mock.post(mock_url, json=response_data, status_code=200) + requests_mock.post(mock_url, json=response_data, status_code=status) created_project = client.create_project(request_data) @@ -175,14 +204,18 @@ def test_create_project_api_error(client, requests_mock): with pytest.raises(SysMLV2APIError, match="Unexpected status code for POST /projects"): client.create_project(request_data) -def test_delete_project_success(client, requests_mock): +@pytest.mark.parametrize("status", [200, 204]) +def test_delete_project_success(client, requests_mock, status): """Tests successfully deleting a project.""" mock_url = f"{TEST_BASE_URL}/projects/{TEST_PROJECT_ID}" - requests_mock.delete(mock_url, json={}, status_code=200) + if status == 204: + requests_mock.delete(mock_url, status_code=status) + else: + requests_mock.delete(mock_url, status_code=status, json={"@id": TEST_PROJECT_ID}) result = client.delete_project(TEST_PROJECT_ID) - assert result == {} + assert result == ({"@id": TEST_PROJECT_ID} if status == 200 else {}) assert requests_mock.last_request.url == mock_url assert requests_mock.last_request.method == "DELETE" @@ -270,12 +303,13 @@ def test_get_owned_elements_success_unexpected_scalar_response(client, monkeypat # --- Test Create Commit --- -def test_create_commit_success(client, requests_mock): +@pytest.mark.parametrize("status", [200, 201]) +def test_create_commit_success(client, requests_mock, status): """Tests successfully creating a commit.""" mock_url = f"{TEST_BASE_URL}/projects/{TEST_PROJECT_ID}/commits" request_data = {"message": "Initial commit", "parentCommitId": None} response_data = {"id": "new_commit_id", **request_data} - requests_mock.post(mock_url, json=response_data, status_code=200) + requests_mock.post(mock_url, json=response_data, status_code=status) created_commit = client.create_commit(TEST_PROJECT_ID, request_data) @@ -457,11 +491,12 @@ def test_list_branches_success_unexpected_scalar_response(client, monkeypatch): branches = client.list_branches(TEST_PROJECT_ID) assert branches == [] -def test_create_branch_success(client, requests_mock): +@pytest.mark.parametrize("status", [200, 201]) +def test_create_branch_success(client, requests_mock, status): mock_url = f"{TEST_BASE_URL}/projects/{TEST_PROJECT_ID}/branches" request_data = {"name": "feature-branch", "head": {"@id": TEST_COMMIT_ID}} response_data = {"id": "new_branch_id", **request_data} - requests_mock.post(mock_url, json=response_data, status_code=200) + requests_mock.post(mock_url, json=response_data, status_code=status) branch = client.create_branch(TEST_PROJECT_ID, request_data) assert branch == response_data assert requests_mock.last_request.json() == request_data @@ -473,9 +508,13 @@ def test_get_branch_by_id_success(client, requests_mock): branch = client.get_branch_by_id(TEST_PROJECT_ID, TEST_BRANCH_ID) assert branch == response_data -def test_delete_branch_success(client, requests_mock): +@pytest.mark.parametrize("status", [200, 204]) +def test_delete_branch_success(client, requests_mock, status): mock_url = f"{TEST_BASE_URL}/projects/{TEST_PROJECT_ID}/branches/{TEST_BRANCH_ID}" - requests_mock.delete(mock_url, status_code=204) + if status == 204: + requests_mock.delete(mock_url, status_code=status) + else: + requests_mock.delete(mock_url, status_code=status, json={}) result = client.delete_branch(TEST_PROJECT_ID, TEST_BRANCH_ID) assert result is None @@ -509,11 +548,12 @@ def test_list_tags_success_unexpected_scalar_response(client, monkeypatch): tags = client.list_tags(TEST_PROJECT_ID) assert tags == [] -def test_create_tag_success(client, requests_mock): +@pytest.mark.parametrize("status", [200, 201]) +def test_create_tag_success(client, requests_mock, status): mock_url = f"{TEST_BASE_URL}/projects/{TEST_PROJECT_ID}/tags" request_data = {"name": "v1.0-release", "taggedCommit": {"@id": TEST_COMMIT_ID}} response_data = {"id": "new_tag_id", **request_data} - requests_mock.post(mock_url, json=response_data, status_code=200) + requests_mock.post(mock_url, json=response_data, status_code=status) tag = client.create_tag(TEST_PROJECT_ID, request_data) assert tag == response_data assert requests_mock.last_request.json() == request_data @@ -525,9 +565,13 @@ def test_get_tag_by_id_success(client, requests_mock): tag = client.get_tag_by_id(TEST_PROJECT_ID, TEST_TAG_ID) assert tag == response_data -def test_delete_tag_success(client, requests_mock): +@pytest.mark.parametrize("status", [200, 204]) +def test_delete_tag_success(client, requests_mock, status): mock_url = f"{TEST_BASE_URL}/projects/{TEST_PROJECT_ID}/tags/{TEST_TAG_ID}" - requests_mock.delete(mock_url, status_code=204) + if status == 204: + requests_mock.delete(mock_url, status_code=status) + else: + requests_mock.delete(mock_url, status_code=status, json={}) result = client.delete_tag(TEST_PROJECT_ID, TEST_TAG_ID) assert result is None