diff --git a/.config/mise.toml b/.config/mise.toml index 2528379..21ca295 100644 --- a/.config/mise.toml +++ b/.config/mise.toml @@ -101,4 +101,4 @@ run = ["mise run generate", "mise run check"] [tasks.examples] description = "Run live mdtest examples (creates real UpCloud resources, requires UPCLOUD_TOKEN)" usage = 'arg "[name]..." var=#true help="Directory under examples/ (default: all)"' -run = 'bash generator/scripts/run_examples.sh ${usage_name:-file-storage object-storage tag kubernetes}' +run = 'bash generator/scripts/run_examples.sh ${usage_name:-file-storage object-storage tag kubernetes network}' diff --git a/examples/network/test_network.md b/examples/network/test_network.md new file mode 100644 index 0000000..4886c36 --- /dev/null +++ b/examples/network/test_network.md @@ -0,0 +1,395 @@ +# Testing the Network and Router APIs + +This example demonstrates how to use the UpCloud Python SDK to create a private network with labels, attach it to a router, and clean everything up again. We'll create a test script that: + +- Authenticates a client using a bearer token +- Creates a router +- Creates a private network with labels, attached to the router +- Verifies the network's labels +- Verifies the network is attached to the router +- Cleans up by deleting the test network and the test router + +## Prerequisites + +This test creates and destroys its own router and network, so only `UPCLOUD_TOKEN` is required. + +## The Python Test Script + +Let's build the test script step by step. + +### Imports and Module Docstring + +First, we define the script's purpose and import the necessary modules. We need the UpCloud SDK client, the network and router API functions, and the models for creating networks, labels, and routers. + +```py filename=test_network_test.py +#!/usr/bin/env python3 +""" +Test script for Network and Router APIs. + +Tests: +- Authenticate client +- Create a router +- Create a private network with labels, attached to the router +- Get the network and verify its labels +- Get the router and verify the network is attached +- Delete the test network +- Delete the test router +""" + +import os +import sys +import time +import traceback +from uuid import UUID + +from upcloud_api import AuthenticatedClient +from upcloud_api.api.network import create_network, delete_network, get_network_details +from upcloud_api.api.router import create_router, delete_router, get_router +from upcloud_api.models import ( + CreateNetworkRequest, + CreateNetworkRequestNetwork, + CreateNetworkRequestNetworkIpNetworks, + CreateNetworkRequestNetworkIpNetworksIpNetworkItem, + NetworkBooleanYesno, + NetworkIpFamily, + NetworkLabel, + NetworkType, + RouterCreate, + RouterCreateRouter, +) +``` + +### Main Function Setup + +The `main()` function starts by reading configuration from environment variables. The `UPCLOUD_TOKEN` is required for authentication, while the zone and network CIDR have sensible defaults. + +```py filename=test_network_test.py + +def main(): + """Run the Network and Router API test.""" + token = os.environ.get("UPCLOUD_TOKEN") + zone = os.environ.get("NETWORK_ZONE", "fi-hel1") + network_cidr = os.environ.get("NETWORK_CIDR", "10.0.0.0/24") + + if not token: + print("ERROR: UPCLOUD_TOKEN environment variable is required") + sys.exit(1) + + print("1. Authenticating client...") + try: + client = AuthenticatedClient(token=token) + print(" Client authenticated successfully") + except Exception as e: + print(f" Error: {e}") + sys.exit(1) +``` + +### Step 2: Create a Router + +The network will be attached to a router, so we create the router first. We keep its UUID for the network payload, for verification, and for cleanup. + +```py filename=test_network_test.py + + print("\n2. Creating a router...") + print(" Testing SDK function: create_router.sync_detailed()") + test_router_name = f"test-router-{int(time.time())}" + created_router_uuid = None + + try: + router_payload = RouterCreate(router=RouterCreateRouter(name=test_router_name)) + + response = create_router.sync_detailed(client=client, body=router_payload) + + if response.status_code == 201 and response.parsed is not None: + created_router_uuid = response.parsed.router.uuid + print(f" Router '{test_router_name}' created successfully ({created_router_uuid})") + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) +``` + +### Step 3: Create a Private Network with Labels + +Now we create a private network with one IPv4 subnet and DHCP enabled. We add labels through the `labels` field of the network and attach the network to the router through the `router` field. We generate a unique name using a timestamp to avoid conflicts. + +```py filename=test_network_test.py + + print("\n3. Creating a private network with labels, attached to the router...") + print(" Testing SDK function: create_network.sync_detailed()") + test_network_name = f"test-net-{int(time.time())}" + created_network_uuid = None + network_labels = [ + NetworkLabel(key="env", value="test"), + NetworkLabel(key="purpose", value="sdk-example"), + ] + + try: + network_payload = CreateNetworkRequest( + network=CreateNetworkRequestNetwork( + type_=NetworkType.PRIVATE, + name=test_network_name, + zone=zone, + ip_networks=CreateNetworkRequestNetworkIpNetworks( + ip_network=[ + CreateNetworkRequestNetworkIpNetworksIpNetworkItem( + family=NetworkIpFamily.IPV4, + address=network_cidr, + dhcp=NetworkBooleanYesno.YES, + ) + ] + ), + router=created_router_uuid, + labels=network_labels, + ) + ) + + response = create_network.sync_detailed(client=client, body=network_payload) + + if response.status_code == 201 and response.parsed is not None: + created_network_uuid = response.parsed.network.uuid + print( + f" Network '{test_network_name}' created successfully ({created_network_uuid})" + ) + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) +``` + +### Step 4: Get the Network and Verify Its Labels + +We fetch the network by UUID and check that it is in the expected zone, is attached to our router, and carries the labels we sent. The network details response returns `labels` as a list of `key`/`value` pairs, which the SDK exposes as `network.labels`. If the API does not return them, the script reports that instead of failing. + +```py filename=test_network_test.py + + print("\n4. Getting network details and verifying labels...") + print(" Testing SDK function: get_network_details.sync_detailed()") + + try: + response = get_network_details.sync_detailed( + client=client, + uuid=UUID(str(created_network_uuid)), + ) + + if response.status_code == 200 and response.parsed is not None: + network = response.parsed.network + print(f" Network '{network.name}' found in zone '{network.zone}'") + + if str(network.router) == str(created_router_uuid): + print(" Network is attached to the test router") + else: + print( + f" Warning: Network router is {network.router}, expected {created_router_uuid}" + ) + + returned_labels = network.labels or [] + if returned_labels: + for label in returned_labels: + print(f" - {label.key}={label.value}") + returned_pairs = {(label.key, label.value) for label in returned_labels} + expected_pairs = {(label.key, label.value) for label in network_labels} + if returned_pairs == expected_pairs: + print(" Verification passed: all labels are present") + else: + print( + f" Warning: Expected labels {expected_pairs}, found {returned_pairs}" + ) + else: + print(" Note: Labels were not returned in the network details response") + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) +``` + +### Step 5: Get the Router and Verify the Attachment + +Next, we fetch the router and check that the network appears in its list of attached networks. + +```py filename=test_network_test.py + + print("\n5. Getting router details and verifying network attachment...") + print(" Testing SDK function: get_router.sync_detailed()") + + try: + response = get_router.sync_detailed( + router=UUID(str(created_router_uuid)), + client=client, + ) + + if response.status_code == 200 and response.parsed is not None: + router_details = response.parsed.router + attached_uuids = [ + str(attached.uuid) for attached in router_details.attached_networks.network + ] + print( + f" Router '{router_details.name}' has {len(attached_uuids)} attached network(s)" + ) + + if str(created_network_uuid) in attached_uuids: + print(" Verification passed: test network is attached to the router") + else: + print(" Warning: test network is not listed as attached to the router") + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) +``` + +### Step 6: Cleanup - Delete the Network and the Router + +Finally, we clean up. A router with attached networks cannot be deleted, so we delete the network first and then the router. + +```py filename=test_network_test.py + + print("\n6. Cleaning up - deleting test network...") + print(" Testing SDK function: delete_network.sync_detailed()") + try: + if not created_network_uuid: + print(" No network UUID found from create response; skipping delete") + else: + response = delete_network.sync_detailed( + client=client, + uuid=UUID(str(created_network_uuid)), + ) + + if response.status_code == 204: + print(f" Network '{test_network_name}' deleted successfully") + elif response.status_code == 404: + print(" Network not found for deletion (may have been auto-deleted)") + else: + print(f" Failed to delete (status: {response.status_code})") + print( + f" Note: Manual cleanup may be required for network '{test_network_name}'" + ) + except Exception as e: + print(f" Error during cleanup: {e}") + traceback.print_exc() + print(f" Note: Manual cleanup may be required for network '{test_network_name}'") + sys.exit(1) + + print("\n6. Cleaning up - deleting test router...") + print(" Testing SDK function: delete_router.sync_detailed()") + try: + if not created_router_uuid: + print(" No router UUID found from create response; skipping delete") + else: + response = delete_router.sync_detailed( + router=UUID(str(created_router_uuid)), + client=client, + ) + + if response.status_code == 204: + print(f" Router '{test_router_name}' deleted successfully") + elif response.status_code == 404: + print(" Router not found for deletion (may have been auto-deleted)") + else: + print(f" Failed to delete (status: {response.status_code})") + print(f" Note: Manual cleanup may be required for router '{test_router_name}'") + except Exception as e: + print(f" Error during cleanup: {e}") + traceback.print_exc() + print(f" Note: Manual cleanup may be required for router '{test_router_name}'") + sys.exit(1) + + print("\n" + "=" * 50) + print(" Network and Router API validation completed") + print("=" * 50) +``` + +### Entry Point + +The script's entry point calls the `main()` function when executed directly. + +```py filename=test_network_test.py + + +if __name__ == "__main__": + main() +``` + +## Running the Test + +Now that we have the Python script, let's build the shell script that will set up the environment and run the test. + +### Shell Script Header + +The script uses strict mode (`set -euo pipefail`) to exit on any error, undefined variable, or pipeline failure. + +```sh filename=test.sh +#!/usr/bin/env bash +set -euo pipefail + +# Test Network and Router APIs +# Tests: create_router, create_network (with labels), get_network_details, +# get_router, delete_network, delete_router +``` + +### Configuration Variables + +mdtest runs the shell script in a temporary directory. Point it at the repository root with `UPCLOUD_SDK_PATH`. + +```sh filename=test.sh + +SDK_DIR="${UPCLOUD_SDK_PATH:?Set UPCLOUD_SDK_PATH to the repository root}" +``` + +### Test Header Output + +Display a header to indicate the start of the Network and Router API test. + +```sh filename=test.sh + +echo "======================================" +echo "Testing Network and Router APIs" +echo "======================================" +``` + +### Environment Variable Check + +The test requires the `UPCLOUD_TOKEN` environment variable to be set with a valid UpCloud API bearer token. + +```sh filename=test.sh + +# Check for required environment variables +if [[ -z "${UPCLOUD_TOKEN:-}" ]]; then + echo "ERROR: UPCLOUD_TOKEN environment variable is required" + exit 1 +fi +``` + +### Run the Python Test + +Run the test against the checked-out SDK in a uv-managed, isolated environment. + +```sh filename=test.sh + +echo "" +echo "== Test Network and Router APIs with local SDK ==" +uv run --no-cache --no-project --with "$SDK_DIR" python test_network_test.py +``` + +## Execute the Test + +Finally, we run the shell script to execute the complete test. + +```sh +bash test.sh +``` diff --git a/examples/network/test_network.py b/examples/network/test_network.py new file mode 100755 index 0000000..bea7cae --- /dev/null +++ b/examples/network/test_network.py @@ -0,0 +1,253 @@ +#!/usr/bin/env python3 +""" +Test script for Network and Router APIs. + +Tests: +- Authenticate client +- Create a router +- Create a private network with labels, attached to the router +- Get the network and verify its labels +- Get the router and verify the network is attached +- Delete the test network +- Delete the test router +""" + +import os +import sys +import time +import traceback +from uuid import UUID + +from upcloud_api import AuthenticatedClient +from upcloud_api.api.network import create_network, delete_network, get_network_details +from upcloud_api.api.router import create_router, delete_router, get_router +from upcloud_api.models import ( + CreateNetworkRequest, + CreateNetworkRequestNetwork, + CreateNetworkRequestNetworkIpNetworks, + CreateNetworkRequestNetworkIpNetworksIpNetworkItem, + NetworkBooleanYesno, + NetworkIpFamily, + NetworkLabel, + NetworkType, + RouterCreate, + RouterCreateRouter, +) + + +def main(): + """Run the Network and Router API test.""" + token = os.environ.get("UPCLOUD_TOKEN") + zone = os.environ.get("NETWORK_ZONE", "fi-hel1") + network_cidr = os.environ.get("NETWORK_CIDR", "10.0.0.0/24") + + if not token: + print("ERROR: UPCLOUD_TOKEN environment variable is required") + sys.exit(1) + + print("1. Authenticating client...") + try: + client = AuthenticatedClient(token=token) + print(" Client authenticated successfully") + except Exception as e: + print(f" Error: {e}") + sys.exit(1) + + print("\n2. Creating a router...") + print(" Testing SDK function: create_router.sync_detailed()") + test_router_name = f"test-router-{int(time.time())}" + created_router_uuid = None + + try: + router_payload = RouterCreate(router=RouterCreateRouter(name=test_router_name)) + + response = create_router.sync_detailed(client=client, body=router_payload) + + if response.status_code == 201 and response.parsed is not None: + created_router_uuid = response.parsed.router.uuid + print(f" Router '{test_router_name}' created successfully ({created_router_uuid})") + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) + + print("\n3. Creating a private network with labels, attached to the router...") + print(" Testing SDK function: create_network.sync_detailed()") + test_network_name = f"test-net-{int(time.time())}" + created_network_uuid = None + network_labels = [ + NetworkLabel(key="env", value="test"), + NetworkLabel(key="purpose", value="sdk-example"), + ] + + try: + network_payload = CreateNetworkRequest( + network=CreateNetworkRequestNetwork( + type_=NetworkType.PRIVATE, + name=test_network_name, + zone=zone, + ip_networks=CreateNetworkRequestNetworkIpNetworks( + ip_network=[ + CreateNetworkRequestNetworkIpNetworksIpNetworkItem( + family=NetworkIpFamily.IPV4, + address=network_cidr, + dhcp=NetworkBooleanYesno.YES, + ) + ] + ), + router=created_router_uuid, + labels=network_labels, + ) + ) + + response = create_network.sync_detailed(client=client, body=network_payload) + + if response.status_code == 201 and response.parsed is not None: + created_network_uuid = response.parsed.network.uuid + print( + f" Network '{test_network_name}' created successfully ({created_network_uuid})" + ) + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) + + print("\n4. Getting network details and verifying labels...") + print(" Testing SDK function: get_network_details.sync_detailed()") + + try: + response = get_network_details.sync_detailed( + client=client, + uuid=UUID(str(created_network_uuid)), + ) + + if response.status_code == 200 and response.parsed is not None: + network = response.parsed.network + print(f" Network '{network.name}' found in zone '{network.zone}'") + + if str(network.router) == str(created_router_uuid): + print(" Network is attached to the test router") + else: + print( + f" Warning: Network router is {network.router}, expected {created_router_uuid}" + ) + + returned_labels = network.labels or [] + if returned_labels: + for label in returned_labels: + print(f" - {label.key}={label.value}") + returned_pairs = {(label.key, label.value) for label in returned_labels} + expected_pairs = {(label.key, label.value) for label in network_labels} + if returned_pairs == expected_pairs: + print(" Verification passed: all labels are present") + else: + print( + f" Warning: Expected labels {expected_pairs}, found {returned_pairs}" + ) + else: + print(" Note: Labels were not returned in the network details response") + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) + + print("\n5. Getting router details and verifying network attachment...") + print(" Testing SDK function: get_router.sync_detailed()") + + try: + response = get_router.sync_detailed( + router=UUID(str(created_router_uuid)), + client=client, + ) + + if response.status_code == 200 and response.parsed is not None: + router_details = response.parsed.router + attached_uuids = [ + str(attached.uuid) for attached in router_details.attached_networks.network + ] + print( + f" Router '{router_details.name}' has {len(attached_uuids)} attached network(s)" + ) + + if str(created_network_uuid) in attached_uuids: + print(" Verification passed: test network is attached to the router") + else: + print(" Warning: test network is not listed as attached to the router") + else: + print(f" Failed with status: {response.status_code}") + print(f" Parsed: {response.parsed}") + sys.exit(1) + except Exception as e: + print(f" Error: {e}") + traceback.print_exc() + sys.exit(1) + + print("\n6. Cleaning up - deleting test network...") + print(" Testing SDK function: delete_network.sync_detailed()") + try: + if not created_network_uuid: + print(" No network UUID found from create response; skipping delete") + else: + response = delete_network.sync_detailed( + client=client, + uuid=UUID(str(created_network_uuid)), + ) + + if response.status_code == 204: + print(f" Network '{test_network_name}' deleted successfully") + elif response.status_code == 404: + print(" Network not found for deletion (may have been auto-deleted)") + else: + print(f" Failed to delete (status: {response.status_code})") + print( + f" Note: Manual cleanup may be required for network '{test_network_name}'" + ) + except Exception as e: + print(f" Error during cleanup: {e}") + traceback.print_exc() + print(f" Note: Manual cleanup may be required for network '{test_network_name}'") + sys.exit(1) + + print("\n6. Cleaning up - deleting test router...") + print(" Testing SDK function: delete_router.sync_detailed()") + try: + if not created_router_uuid: + print(" No router UUID found from create response; skipping delete") + else: + response = delete_router.sync_detailed( + router=UUID(str(created_router_uuid)), + client=client, + ) + + if response.status_code == 204: + print(f" Router '{test_router_name}' deleted successfully") + elif response.status_code == 404: + print(" Router not found for deletion (may have been auto-deleted)") + else: + print(f" Failed to delete (status: {response.status_code})") + print(f" Note: Manual cleanup may be required for router '{test_router_name}'") + except Exception as e: + print(f" Error during cleanup: {e}") + traceback.print_exc() + print(f" Note: Manual cleanup may be required for router '{test_router_name}'") + sys.exit(1) + + print("\n" + "=" * 50) + print(" Network and Router API validation completed") + print("=" * 50) + + +if __name__ == "__main__": + main() diff --git a/examples/network/test_network.sh b/examples/network/test_network.sh new file mode 100755 index 0000000..7cfa5b1 --- /dev/null +++ b/examples/network/test_network.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SDK_DIR="${UPCLOUD_SDK_PATH:-$(cd "$SCRIPT_DIR/../.." && pwd)}" + +echo "======================================" +echo "Testing Network and Router APIs" +echo "======================================" + +if [[ -z "${UPCLOUD_TOKEN:-}" ]]; then + echo "ERROR: UPCLOUD_TOKEN environment variable is required" + exit 1 +fi + +echo "== Test Network and Router APIs with local SDK ==" +uv run --no-cache --no-project --with "$SDK_DIR" python "$SCRIPT_DIR/test_network.py" diff --git a/generator/openapi/overlay.yaml b/generator/openapi/overlay.yaml index d6ad757..8ec4ded 100644 --- a/generator/openapi/overlay.yaml +++ b/generator/openapi/overlay.yaml @@ -336,3 +336,35 @@ actions: - direction: out action: drop family: IPv6 + + # Network create and modify requests send labels as a plain array of key/value pairs, + # not the {"label": [...]} wrapper that the networkLabels schema describes. + # Source fix needed: define the request labels property as an array of networkLabel. + - target: $.components.schemas.createNetworkRequest.properties.network.properties.labels + remove: true + - target: $.components.schemas.createNetworkRequest.properties.network.properties + update: + labels: + type: array + description: Key/value labels attached to the network. + items: + $ref: "#/components/schemas/networkLabel" + - target: $.components.schemas.modifyNetworkRequest.properties.network.properties.labels + remove: true + - target: $.components.schemas.modifyNetworkRequest.properties.network.properties + update: + labels: + type: array + description: Key/value labels attached to the network. + items: + $ref: "#/components/schemas/networkLabel" + + # Network details responses return labels as a plain array of key/value pairs. + # Source fix needed: declare the labels property on networkDetails as an array of networkLabel. + - target: $.components.schemas.networkDetails.properties + update: + labels: + type: array + description: Key/value labels attached to the network. + items: + $ref: "#/components/schemas/networkLabel" diff --git a/generator/openapi/spec.patched.json b/generator/openapi/spec.patched.json index f56fe33..9e0f097 100644 --- a/generator/openapi/spec.patched.json +++ b/generator/openapi/spec.patched.json @@ -16778,7 +16778,11 @@ ] }, "labels": { - "$ref": "#/components/schemas/networkLabels" + "type": "array", + "description": "Key/value labels attached to the network.", + "items": { + "$ref": "#/components/schemas/networkLabel" + } } }, "required": [ @@ -16854,9 +16858,6 @@ "tags": { "$ref": "#/components/schemas/networkTags" }, - "labels": { - "$ref": "#/components/schemas/networkLabels" - }, "router": { "$ref": "#/components/schemas/networkUuid" }, @@ -16921,6 +16922,13 @@ }, "main_account_id": { "$ref": "#/components/schemas/networkAccountId" + }, + "labels": { + "type": "array", + "description": "Key/value labels attached to the network.", + "items": { + "$ref": "#/components/schemas/networkLabel" + } } }, "required": [ @@ -17169,6 +17177,13 @@ }, "zone": { "$ref": "#/components/schemas/networkZone" + }, + "labels": { + "type": "array", + "description": "Key/value labels attached to the network.", + "items": { + "$ref": "#/components/schemas/networkLabel" + } } }, "required": [ diff --git a/generator/tests/test_openapi_overlay.py b/generator/tests/test_openapi_overlay.py index 239c156..7e1c00b 100644 --- a/generator/tests/test_openapi_overlay.py +++ b/generator/tests/test_openapi_overlay.py @@ -94,6 +94,21 @@ def database_example(version): } +def network_request_schema(): + """Return a network request whose labels use the wrapped networkLabels schema.""" + return { + "type": "object", + "properties": { + "network": { + "type": "object", + "properties": { + "labels": {"$ref": "#/components/schemas/networkLabels"}, + }, + }, + }, + } + + def defective_spec(): """Return a minimal spec with the defects the overlay fixes, plus unrelated data.""" spec = { @@ -166,6 +181,9 @@ def defective_spec(): }, "unrelated": {"title": "Keep", "type": "string"}, "storageLabelFilter": {"type": "string", "pattern": OLD_LABEL_FILTER_PATTERN}, + "createNetworkRequest": network_request_schema(), + "modifyNetworkRequest": network_request_schema(), + "networkDetails": {"type": "object", "properties": {"name": {"type": "string"}}}, "kubernetesPrefixedClaimOrExpression": { "type": "object", "properties": { @@ -460,6 +478,16 @@ def test_fixes_only_the_defects(self): responses = expected["paths"][CLUSTER_PATH]["post"]["responses"] responses["200"] = responses.pop("201") schemas["storageLabelFilter"]["pattern"] = NEW_LABEL_FILTER_PATTERN + network_labels = { + "type": "array", + "description": "Key/value labels attached to the network.", + "items": {"$ref": "#/components/schemas/networkLabel"}, + } + for name in ("createNetworkRequest", "modifyNetworkRequest"): + schemas[name]["properties"]["network"]["properties"]["labels"] = copy.deepcopy( + network_labels + ) + schemas["networkDetails"]["properties"]["labels"] = copy.deepcopy(network_labels) prefix = schemas["kubernetesPrefixedClaimOrExpression"]["properties"]["prefix"] prefix.pop("nullable") prefix["type"] = ["string", "null"] @@ -800,6 +828,26 @@ def test_contract_fixes_match_the_source_spec(self): self.assertEqual(output_clone["oneOf"], source_clone["oneOf"]) self.assertEqual(output_clone["properties"], source_clone["properties"]) + def test_network_labels_are_plain_arrays(self): + """Network requests and responses use labels as an array, not the networkLabels wrapper.""" + output = self.overlay_document(json.loads(SPEC.read_text(encoding="utf-8"))) + schemas = output["components"]["schemas"] + request_networks = [ + schemas[name]["properties"]["network"]["properties"] + for name in ("createNetworkRequest", "modifyNetworkRequest") + ] + for name, properties in zip( + ("createNetworkRequest", "modifyNetworkRequest", "networkDetails"), + [*request_networks, schemas["networkDetails"]["properties"]], + strict=True, + ): + with self.subTest(schema=name): + self.assertEqual(properties["labels"]["type"], "array") + self.assertEqual( + properties["labels"]["items"], + {"$ref": "#/components/schemas/networkLabel"}, + ) + def test_rewritten_patterns_preserve_intended_matching(self): import re diff --git a/upcloud_api/models/create_network_request_network.py b/upcloud_api/models/create_network_request_network.py index 433333c..063f0f5 100644 --- a/upcloud_api/models/create_network_request_network.py +++ b/upcloud_api/models/create_network_request_network.py @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ..models.create_network_request_network_ip_networks import CreateNetworkRequestNetworkIpNetworks - from ..models.network_labels import NetworkLabels + from ..models.network_label import NetworkLabel T = TypeVar("T", bound="CreateNetworkRequestNetwork") @@ -31,8 +31,7 @@ class CreateNetworkRequestNetwork: zone (str): Zone identifier ip_networks (CreateNetworkRequestNetworkIpNetworks): router (UUID | Unset): Universally unique identifier Example: 0414e0d7-4436-4037-9dd8-6eaf47dce599. - labels (NetworkLabels | Unset): Collection of key/value labels for a resource. Example: {'label': [{'key': - 'env', 'value': 'prod'}, {'key': 'team', 'value': 'network'}]}. + labels (list[NetworkLabel] | Unset): Key/value labels attached to the network. """ type_: NetworkType @@ -40,7 +39,7 @@ class CreateNetworkRequestNetwork: zone: str ip_networks: CreateNetworkRequestNetworkIpNetworks router: UUID | Unset = UNSET - labels: NetworkLabels | Unset = UNSET + labels: list[NetworkLabel] | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -56,9 +55,12 @@ def to_dict(self) -> dict[str, Any]: if not isinstance(self.router, Unset): router = str(self.router) - labels: dict[str, Any] | Unset = UNSET + labels: list[dict[str, Any]] | Unset = UNSET if not isinstance(self.labels, Unset): - labels = self.labels.to_dict() + labels = [] + for labels_item_data in self.labels: + labels_item = labels_item_data.to_dict() + labels.append(labels_item) field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) @@ -82,7 +84,7 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: from ..models.create_network_request_network_ip_networks import ( CreateNetworkRequestNetworkIpNetworks, # noqa: PLC0415 ) - from ..models.network_labels import NetworkLabels # noqa: PLC0415 + from ..models.network_label import NetworkLabel # noqa: PLC0415 d = dict(src_dict) type_ = NetworkType(d.pop("type")) @@ -101,11 +103,13 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: router = UUID(_router) _labels = d.pop("labels", UNSET) - labels: NetworkLabels | Unset - if isinstance(_labels, Unset): - labels = UNSET - else: - labels = NetworkLabels.from_dict(_labels) + labels: list[NetworkLabel] | Unset = UNSET + if _labels is not UNSET: + labels = [] + for labels_item_data in _labels: + labels_item = NetworkLabel.from_dict(labels_item_data) + + labels.append(labels_item) create_network_request_network = cls( type_=type_, diff --git a/upcloud_api/models/modify_network_request_network.py b/upcloud_api/models/modify_network_request_network.py index 28c530b..2342767 100644 --- a/upcloud_api/models/modify_network_request_network.py +++ b/upcloud_api/models/modify_network_request_network.py @@ -13,7 +13,7 @@ if TYPE_CHECKING: from ..models.modify_network_request_network_ip_networks import ModifyNetworkRequestNetworkIpNetworks - from ..models.network_labels import NetworkLabels + from ..models.network_label import NetworkLabel from ..models.network_tags import NetworkTags @@ -29,27 +29,26 @@ class ModifyNetworkRequestNetwork: zone (str): Zone identifier tags (NetworkTags): Container object for resource tags. Example: {'tags': {'tag': [{'name': 'PROD', 'description': 'Production servers', 'servers': {'server': ['0077fa3d-32db-4b09-9f5f-30d9e9afb565']}}]}}. - labels (NetworkLabels): Collection of key/value labels for a resource. Example: {'label': [{'key': 'env', - 'value': 'prod'}, {'key': 'team', 'value': 'network'}]}. router (UUID): Universally unique identifier Example: 0414e0d7-4436-4037-9dd8-6eaf47dce599. grt_export (NetworkBoolean01): Schema for boolean-like values encoded as 0 or 1. parent_network (str): ip_networks (ModifyNetworkRequestNetworkIpNetworks): network_features (NetworkFeatures): Features available for a network main_account_id (int): Unique numeric identifier of an account. + labels (list[NetworkLabel]): Key/value labels attached to the network. """ type_: NetworkType name: str zone: str tags: NetworkTags - labels: NetworkLabels router: UUID grt_export: NetworkBoolean01 parent_network: str ip_networks: ModifyNetworkRequestNetworkIpNetworks network_features: NetworkFeatures main_account_id: int + labels: list[NetworkLabel] additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -61,8 +60,6 @@ def to_dict(self) -> dict[str, Any]: tags = self.tags.to_dict() - labels = self.labels.to_dict() - router = str(self.router) grt_export = self.grt_export.value @@ -75,6 +72,11 @@ def to_dict(self) -> dict[str, Any]: main_account_id = self.main_account_id + labels = [] + for labels_item_data in self.labels: + labels_item = labels_item_data.to_dict() + labels.append(labels_item) + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -83,13 +85,13 @@ def to_dict(self) -> dict[str, Any]: "name": name, "zone": zone, "tags": tags, - "labels": labels, "router": router, "grt_export": grt_export, "parent_network": parent_network, "ip_networks": ip_networks, "network_features": network_features, "main_account_id": main_account_id, + "labels": labels, } ) @@ -100,7 +102,7 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: from ..models.modify_network_request_network_ip_networks import ( ModifyNetworkRequestNetworkIpNetworks, # noqa: PLC0415 ) - from ..models.network_labels import NetworkLabels # noqa: PLC0415 + from ..models.network_label import NetworkLabel # noqa: PLC0415 from ..models.network_tags import NetworkTags # noqa: PLC0415 d = dict(src_dict) @@ -112,8 +114,6 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: tags = NetworkTags.from_dict(d.pop("tags")) - labels = NetworkLabels.from_dict(d.pop("labels")) - router = UUID(d.pop("router")) grt_export = NetworkBoolean01(d.pop("grt_export")) @@ -126,18 +126,25 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: main_account_id = d.pop("main_account_id") + labels = [] + _labels = d.pop("labels") + for labels_item_data in _labels: + labels_item = NetworkLabel.from_dict(labels_item_data) + + labels.append(labels_item) + modify_network_request_network = cls( type_=type_, name=name, zone=zone, tags=tags, - labels=labels, router=router, grt_export=grt_export, parent_network=parent_network, ip_networks=ip_networks, network_features=network_features, main_account_id=main_account_id, + labels=labels, ) modify_network_request_network.additional_properties = d diff --git a/upcloud_api/models/network_details.py b/upcloud_api/models/network_details.py index 58c2cf1..cc7bf76 100644 --- a/upcloud_api/models/network_details.py +++ b/upcloud_api/models/network_details.py @@ -16,6 +16,7 @@ from ..models.network_details_peerings import NetworkDetailsPeerings from ..models.network_details_servers import NetworkDetailsServers from ..models.network_details_services import NetworkDetailsServices + from ..models.network_label import NetworkLabel T = TypeVar("T", bound="NetworkDetails") @@ -49,6 +50,7 @@ class NetworkDetails: tags (list[str] | Unset): type_ (NetworkType | Unset): Network access type Example: public. uuid (UUID | Unset): + labels (list[NetworkLabel] | Unset): Key/value labels attached to the network. """ name: str @@ -64,6 +66,7 @@ class NetworkDetails: tags: list[str] | Unset = UNSET type_: NetworkType | Unset = UNSET uuid: UUID | Unset = UNSET + labels: list[NetworkLabel] | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -115,6 +118,13 @@ def to_dict(self) -> dict[str, Any]: if not isinstance(self.uuid, Unset): uuid = str(self.uuid) + labels: list[dict[str, Any]] | Unset = UNSET + if not isinstance(self.labels, Unset): + labels = [] + for labels_item_data in self.labels: + labels_item = labels_item_data.to_dict() + labels.append(labels_item) + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -145,6 +155,8 @@ def to_dict(self) -> dict[str, Any]: field_dict["type"] = type_ if uuid is not UNSET: field_dict["uuid"] = uuid + if labels is not UNSET: + field_dict["labels"] = labels return field_dict @@ -154,6 +166,7 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: from ..models.network_details_peerings import NetworkDetailsPeerings # noqa: PLC0415 from ..models.network_details_servers import NetworkDetailsServers # noqa: PLC0415 from ..models.network_details_services import NetworkDetailsServices # noqa: PLC0415 + from ..models.network_label import NetworkLabel # noqa: PLC0415 d = dict(src_dict) name = d.pop("name") @@ -227,6 +240,15 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: else: uuid = UUID(_uuid) + _labels = d.pop("labels", UNSET) + labels: list[NetworkLabel] | Unset = UNSET + if _labels is not UNSET: + labels = [] + for labels_item_data in _labels: + labels_item = NetworkLabel.from_dict(labels_item_data) + + labels.append(labels_item) + network_details = cls( name=name, zone=zone, @@ -241,6 +263,7 @@ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T: tags=tags, type_=type_, uuid=uuid, + labels=labels, ) network_details.additional_properties = d