diff --git a/HISTORY.rst b/HISTORY.rst index 1a55312..c60bfc5 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -5,6 +5,12 @@ History 1.7.0 (unreleased) ------------------ +* ``upload_license_file`` now returns the installed license as a ``LicenseInfo`` instead of ``None``, + or the new ``PendingLicense`` when the server keeps a license that requires activation pending + and the previous license keeps masking. +* Added ``abandon_pending_license``, which removes the pending license. +* Added ``requires_activation`` and ``is_activated`` to ``LicenseInfo``, + both ``None`` on a server without license activation. * Added an optional ``instance`` field to ``DatabaseConnectionConfig``: the SQL Server named instance, taken from the Instance input in the connection form's advanced settings. It round-trips through ``list_connections`` and ``create_or_update_connection``, diff --git a/datamasque/client/__init__.py b/datamasque/client/__init__.py index f8ccc63..87019bf 100644 --- a/datamasque/client/__init__.py +++ b/datamasque/client/__init__.py @@ -134,7 +134,7 @@ RulesetPlanPartialUpdateRequest, RulesetPlanUpdateRequest, ) -from datamasque.client.models.license import LicenseInfo, SwitchableLicenseMetadata +from datamasque.client.models.license import LicenseInfo, PendingLicense, SwitchableLicenseMetadata from datamasque.client.models.project import ( Project, ProjectCreateRequest, @@ -338,6 +338,7 @@ "PatternComposition", "PatternEntry", "PatternsStatistics", + "PendingLicense", "Project", "ProjectCreateRequest", "ProjectDeleteConflict", diff --git a/datamasque/client/license.py b/datamasque/client/license.py index 46b7de6..87b4c60 100644 --- a/datamasque/client/license.py +++ b/datamasque/client/license.py @@ -1,7 +1,8 @@ import logging +from typing import Union from datamasque.client.base import BaseClient, FileOrContent, UploadFile, read_file_or_content -from datamasque.client.models.license import LicenseInfo +from datamasque.client.models.license import LicenseInfo, PendingLicense logger = logging.getLogger(__name__) @@ -9,18 +10,22 @@ class LicenseClient(BaseClient): """License management API methods. Mixed into `DataMasqueClient`.""" - def upload_license_file(self, license_file: FileOrContent) -> None: + def upload_license_file(self, license_file: FileOrContent) -> Union[LicenseInfo, PendingLicense]: """ Uploads a DataMasque license. Specify the path to a license (.dmlicense) filename, or pass a `StringIO` or `BytesIO` containing the license content. + + Returns the installed license as a `LicenseInfo`. + A license that requires activation does not replace the installed license: + the server keeps it pending, and this returns it as a `PendingLicense`. """ license_file_name, content = read_file_or_content(license_file, "license.lic") content.seek(0) - self.make_request( + response = self.make_request( method="POST", path="/api/license-upload/", files=[ @@ -32,10 +37,29 @@ def upload_license_file(self, license_file: FileOrContent) -> None: ), ], ) + body = response.json() + # A server without pending licenses sends no `status`, and always installs the license. + if body.get("status") == "pending": + logger.info("License uploaded and pending activation.") + return PendingLicense.model_validate(body) + logger.info("License upload successful.") + return LicenseInfo.model_validate(body) def get_current_license_info(self) -> LicenseInfo: """Returns information about the license currently installed on the server.""" response = self.make_request("GET", "/api/license/") return LicenseInfo.model_validate(response.json()) + + def abandon_pending_license(self) -> None: + """ + Removes the license that is pending activation. + + The license installed before the upload stays in effect. + Raises `DataMasqueApiError` with status 404 when no license is pending, + or when the server predates pending licenses. + """ + + self.make_request("DELETE", "/api/license/pending/") + logger.info("Pending license abandoned.") diff --git a/datamasque/client/models/license.py b/datamasque/client/models/license.py index 9739507..fa1559f 100644 --- a/datamasque/client/models/license.py +++ b/datamasque/client/models/license.py @@ -1,6 +1,6 @@ -"""Typed response shape for the license endpoint.""" +"""Typed response shapes for the license endpoints.""" -from datetime import datetime +from datetime import date, datetime from typing import Optional from pydantic import BaseModel, ConfigDict @@ -32,7 +32,9 @@ class SwitchableLicenseMetadata(BaseModel): class LicenseInfo(BaseModel): """ - License information returned by `GET /api/license/`. + The license in effect on the server. + + Returned by `GET /api/license/` and by `upload_license_file`. Core fields (`uuid`, `name`, `type`, `is_expired`, `uploadable`) are always present in the server response. @@ -58,3 +60,41 @@ class LicenseInfo(BaseModel): is_contract_product: Optional[bool] = None contract_license_type: Optional[str] = None switchable_license_metadata: Optional[SwitchableLicenseMetadata] = None + requires_activation: Optional[bool] = None + """ + `True` when the license cannot mask until this deployment has activated it. + `None` on a server without license activation. + A license with `requires_activation` `True` and `is_activated` `False` cannot mask; + other checks, such as expiry, also apply. + """ + is_activated: Optional[bool] = None + """ + `True` when this deployment has a verified activation. + Always `False` when `requires_activation` is `False`, + and `None` on a server without license activation. + """ + + +class PendingLicense(BaseModel): + """ + A license that requires activation, uploaded but not yet activated. + + The server keeps the previous license in effect while this one is pending, + and the pending license grants nothing until it is activated. + This library cannot activate a license; + `abandon_pending_license` removes the pending license. + """ + + model_config = ConfigDict(extra="allow") + + uuid: str + name: str + type: str + """The license type the server applies, such as `foundation`.""" + raw_type: str + """The license type as written in the license file, such as `FOUNDATION`.""" + platform_name: str + """The platform the license is issued for, such as `Docker` or `AWS Marketplace BYOL`.""" + start_date: date + expiry_date: Optional[date] = None + """`None` when the license does not expire.""" diff --git a/tests/test_license.py b/tests/test_license.py index 53738fd..ffd743e 100644 --- a/tests/test_license.py +++ b/tests/test_license.py @@ -5,15 +5,42 @@ from pathlib import Path from unittest.mock import mock_open, patch +import pytest import requests_mock -from datamasque.client.models.license import LicenseInfo +from datamasque.client import DataMasqueClient +from datamasque.client.exceptions import DataMasqueApiError +from datamasque.client.models.license import LicenseInfo, PendingLicense + +INSTALLED_LICENSE_JSON = { + "uuid": "0f6f2c1e-9a53-4b8e-8d0c-2f1d6f0f8a11", + "name": "Test License", + "type": "enterprise", + "is_expired": False, + "uploadable": True, + "requires_activation": False, + "is_activated": False, +} + +PENDING_LICENSE_JSON = { + "uuid": "6b1f4d2a-3c7e-4f19-a0b5-9e8d7c6b5a42", + "name": "Test License", + "type": "foundation", + "raw_type": "FOUNDATION", + "platform_name": "Docker", + "start_date": "2026-12-01", + "expiry_date": "2027-12-01", + "status": "pending", +} + +# What `POST /api/license-upload/` sends for an installed license: the license plus its upload `status`. +INSTALLED_UPLOAD_JSON = {**INSTALLED_LICENSE_JSON, "status": "installed"} def test_upload_license_file(client): with patch("datamasque.client.base.open", mock_open(read_data=b"license content")) as m_open: with requests_mock.Mocker() as m_request: - m_request.post("http://test-server/api/license-upload/", status_code=200) + m_request.post("http://test-server/api/license-upload/", json=INSTALLED_UPLOAD_JSON, status_code=200) client.upload_license_file(Path("path/to/test_license_file")) m_open.assert_called_once_with(Path("path/to/test_license_file"), "rb") @@ -23,13 +50,62 @@ def test_upload_license_file(client): def test_upload_license_file_stringio(client): with requests_mock.Mocker() as m_request: - m_request.post("http://test-server/api/license-upload/", status_code=200) + m_request.post("http://test-server/api/license-upload/", json=INSTALLED_UPLOAD_JSON, status_code=200) client.upload_license_file(StringIO("license content")) assert "Content-Type: application/octet-stream" in m_request.request_history[0].text assert "license content" in m_request.request_history[0].text +def test_upload_license_file_returns_installed_license(client: DataMasqueClient) -> None: + with requests_mock.Mocker() as m_request: + m_request.post("http://test-server/api/license-upload/", json=INSTALLED_UPLOAD_JSON, status_code=200) + result = client.upload_license_file(StringIO("license content")) + + assert isinstance(result, LicenseInfo) + assert result.uuid == INSTALLED_LICENSE_JSON["uuid"] + + +def test_upload_license_file_returns_pending_license(client: DataMasqueClient) -> None: + with requests_mock.Mocker() as m_request: + m_request.post("http://test-server/api/license-upload/", json=PENDING_LICENSE_JSON, status_code=200) + result = client.upload_license_file(StringIO("license content")) + + assert isinstance(result, PendingLicense) + assert result.uuid == PENDING_LICENSE_JSON["uuid"] + + +def test_upload_license_file_on_server_without_upload_status(client: DataMasqueClient) -> None: + """A server without pending licenses sends the license with no `status`, and has installed it.""" + with requests_mock.Mocker() as m_request: + m_request.post("http://test-server/api/license-upload/", json=INSTALLED_LICENSE_JSON, status_code=200) + result = client.upload_license_file(StringIO("license content")) + + assert isinstance(result, LicenseInfo) + + +def test_abandon_pending_license(client: DataMasqueClient) -> None: + with requests_mock.Mocker() as m_request: + m_request.delete("http://test-server/api/license/pending/", status_code=204) + client.abandon_pending_license() + + assert m_request.call_count == 1 + assert m_request.request_history[0].method == "DELETE" + + +def test_abandon_pending_license_when_none_pending(client: DataMasqueClient) -> None: + with requests_mock.Mocker() as m_request: + m_request.delete( + "http://test-server/api/license/pending/", + json={"error": "No license is pending activation."}, + status_code=404, + ) + with pytest.raises(DataMasqueApiError) as exc_info: + client.abandon_pending_license() + + assert exc_info.value.response.status_code == 404 + + def test_get_current_license_info(client): license_data = { "uuid": str(uuid.uuid4()), @@ -45,3 +121,15 @@ def test_get_current_license_info(client): assert isinstance(result, LicenseInfo) assert result.uuid == license_data["uuid"] assert result.name == "Test License" + + +def test_get_current_license_info_activation_fields(client: DataMasqueClient) -> None: + """The activation fields are declared under the names the server sends, so none land in the extras.""" + license_data = {**INSTALLED_LICENSE_JSON, "requires_activation": True, "is_activated": True} + with requests_mock.Mocker() as m: + m.get("http://test-server/api/license/", json=license_data, status_code=200) + result = client.get_current_license_info() + + assert result.requires_activation is True + assert result.is_activated is True + assert result.model_extra == {}