Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/omg-beta1-conformance.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 5 additions & 1 deletion conformance/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion conformance/provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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 = []

Expand Down
42 changes: 37 additions & 5 deletions conformance/test_interoperability.py
Original file line number Diff line number Diff line change
@@ -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"])
Expand All @@ -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)
37 changes: 23 additions & 14 deletions src/sysmlv2_client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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
Expand All @@ -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
Expand All @@ -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}"
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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]:
Expand All @@ -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 ---
Expand All @@ -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]:
Expand All @@ -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 ---
Expand Down Expand Up @@ -251,4 +260,4 @@ def list_relationships(
elif isinstance(response_data, dict):
return response_data.get('elements', [])
else:
return []
return []
Loading
Loading