From 96f0e5246d8751c4cdc8fd76cd43b98432ddb23f Mon Sep 17 00:00:00 2001 From: Anmol Sharma Date: Sun, 15 Nov 2026 23:10:15 -0500 Subject: [PATCH 1/5] TPT-4130: add support for valkey as a new managed database type in linode python sdk --- linode_api4/groups/database.py | 155 ++++++++- linode_api4/objects/database.py | 187 ++++++++++- test/fixtures/databases_engines.json | 7 +- test/fixtures/databases_instances.json | 15 +- test/fixtures/databases_types.json | 9 + test/fixtures/databases_valkey_config.json | 58 ++++ test/fixtures/databases_valkey_instances.json | 51 +++ ...ases_valkey_instances_123_credentials.json | 4 + ...alkey_instances_123_credentials_reset.json | 1 + .../databases_valkey_instances_123_patch.json | 1 + ...databases_valkey_instances_123_resume.json | 1 + .../databases_valkey_instances_123_ssl.json | 3 + ...atabases_valkey_instances_123_suspend.json | 1 + .../models/database/test_database.py | 2 +- .../models/database/test_valkey.py | 182 ++++++++++ test/unit/groups/database_test.py | 4 +- test/unit/groups/valkey_test.py | 316 ++++++++++++++++++ test/unit/objects/valkey_test.py | 217 ++++++++++++ 18 files changed, 1205 insertions(+), 9 deletions(-) create mode 100644 test/fixtures/databases_valkey_config.json create mode 100644 test/fixtures/databases_valkey_instances.json create mode 100644 test/fixtures/databases_valkey_instances_123_credentials.json create mode 100644 test/fixtures/databases_valkey_instances_123_credentials_reset.json create mode 100644 test/fixtures/databases_valkey_instances_123_patch.json create mode 100644 test/fixtures/databases_valkey_instances_123_resume.json create mode 100644 test/fixtures/databases_valkey_instances_123_ssl.json create mode 100644 test/fixtures/databases_valkey_instances_123_suspend.json create mode 100644 test/integration/models/database/test_valkey.py create mode 100644 test/unit/groups/valkey_test.py create mode 100644 test/unit/objects/valkey_test.py diff --git a/linode_api4/groups/database.py b/linode_api4/groups/database.py index 9546100a8..25a686581 100644 --- a/linode_api4/groups/database.py +++ b/linode_api4/groups/database.py @@ -1,18 +1,22 @@ -from typing import Any, Dict, Union +from datetime import datetime, timezone +from typing import Any, Dict, Optional, Union from linode_api4 import ( MySQLDatabaseConfigOptions, PostgreSQLDatabaseConfigOptions, + ValkeyDatabaseConfigOptions, ) from linode_api4.errors import UnexpectedResponseError from linode_api4.groups import Group from linode_api4.objects import ( + DATE_FORMAT, Database, DatabaseEngine, DatabasePrivateNetwork, DatabaseType, MySQLDatabase, PostgreSQLDatabase, + ValkeyDatabase, drop_null_keys, ) from linode_api4.objects.base import _flatten_request_body_recursive @@ -384,3 +388,152 @@ def postgresql_fork(self, source, restore_time, **kwargs): d = PostgreSQLDatabase(self.client, result["id"], result) return d + + def valkey_config_options(self): + """ + Return the advanced-parameter catalog for Valkey (limited availability). + + Metadata is returned unchanged, including scalar or array ``type`` + values, enums, examples, and defaults. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-databases-valkey-config + + :returns: Configuration option metadata. + :rtype: dict + """ + return self.client.get("/databases/valkey/config", model=self) + + def valkey_instances(self, *filters): + """ + List Valkey Managed Databases on this account (limited availability). + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-databases-valkey-instances + + :param filters: Filters to apply to the collection. + :returns: The matching clusters. + :rtype: PaginatedList of ValkeyDatabase + """ + return self.client._get_and_filter(ValkeyDatabase, *filters) + + def valkey_create( + self, + label, + region, + engine, + ltype, + engine_config: Optional[ + Union[ValkeyDatabaseConfigOptions, Dict[str, Any]] + ] = None, + private_network: Optional[ + Union[DatabasePrivateNetwork, Dict[str, Any]] + ] = None, + **kwargs, + ): + """ + Create a Valkey Managed Database (limited availability). + + Discover available engine versions and plans using :any:`engines` + and :any:`types`. Advanced options use flat keys, for example:: + + db = client.database.valkey_create( + "example-valkey", region, engine, node_type, + engine_config=ValkeyDatabaseConfigOptions( + valkey_persistence="rdb", frequent_snapshots=True + ), + ) + + API Documentation: https://techdocs.akamai.com/linode-api/reference/post-databases-valkey-instances + + :param label: Cluster label. + :type label: str + :param region: Deployment region. + :type region: str or Region + :param engine: Versioned engine ID. + :type engine: str or DatabaseEngine + :param ltype: Database node type. + :type ltype: str or DatabaseType + :param engine_config: Flat advanced configuration. + :type engine_config: ValkeyDatabaseConfigOptions or dict + :param private_network: VPC configuration. + :type private_network: DatabasePrivateNetwork or dict + :param kwargs: Additional API create options, such as ``cluster_size`` + and ``allow_list``. ``ssl_connection`` must be true. + :returns: The created cluster. + :rtype: ValkeyDatabase + :raises UnexpectedResponseError: If the response lacks an ID. + """ + params = { + "label": label, + "region": region, + "engine": engine, + "type": ltype, + "engine_config": engine_config, + "private_network": private_network, + } + params.update(kwargs) + result = self.client.post( + "/databases/valkey/instances", + data=_flatten_request_body_recursive(drop_null_keys(params)), + ) + if "id" not in result: + raise UnexpectedResponseError( + "Unexpected response when creating Valkey Database", json=result + ) + return ValkeyDatabase(self.client, result["id"], result) + + def valkey_fork( + self, + source: int, + restore_time: Optional[Union[str, datetime]] = None, + **kwargs, + ): + """ + Restore a Valkey snapshot into a new cluster (limited availability). + + Use a string from the source cluster's ``available_restore_times``, + or omit ``restore_time`` to use the latest snapshot. Unlike SQL + engines, Valkey does not support arbitrary point-in-time recovery. + Persistence must be enabled on the source cluster. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/post-databases-valkey-instances + + :param source: Source cluster ID. + :type source: int + :param restore_time: Exact snapshot timestamp. Strings are sent + unchanged; naive datetimes are UTC and aware + datetimes are converted to UTC. + :type restore_time: str or datetime or None + :param kwargs: Optional create overrides such as ``label``, ``region``, + ``engine``, ``ltype``, and ``engine_config``. + :returns: The new cluster. + :rtype: ValkeyDatabase + :raises TypeError: If restore_time is not a string, datetime, or None. + :raises ValueError: If both ltype and type, or a fork override, are given. + :raises UnexpectedResponseError: If the response lacks an ID. + """ + if "ltype" in kwargs and "type" in kwargs: + raise ValueError("Specify only one of ltype and type") + if "fork" in kwargs: + raise ValueError("Use source and restore_time to specify the fork") + if isinstance(restore_time, datetime): + if restore_time.tzinfo is not None: + restore_time = restore_time.astimezone(timezone.utc) + restore_time = restore_time.strftime(DATE_FORMAT) + elif restore_time is not None and not isinstance(restore_time, str): + raise TypeError("restore_time must be a string, datetime, or None") + + if "ltype" in kwargs: + kwargs["type"] = kwargs.pop("ltype") + params = { + **kwargs, + "fork": {"source": source, "restore_time": restore_time}, + } + result = self.client.post( + "/databases/valkey/instances", + data=_flatten_request_body_recursive(drop_null_keys(params)), + ) + if "id" not in result: + raise UnexpectedResponseError( + "Unexpected response when forking Valkey Database", json=result + ) + return ValkeyDatabase(self.client, result["id"], result) diff --git a/linode_api4/objects/database.py b/linode_api4/objects/database.py index a3a918bbe..1d8569c82 100644 --- a/linode_api4/objects/database.py +++ b/linode_api4/objects/database.py @@ -1,7 +1,13 @@ from dataclasses import dataclass, field -from typing import Optional +from typing import Optional, Union -from linode_api4.objects import Base, JSONObject, MappedObject, Property +from linode_api4.objects import ( + Base, + ExplicitNullValue, + JSONObject, + MappedObject, + Property, +) class DatabaseType(Base): @@ -42,6 +48,7 @@ class DatabaseEngine(Base): - MySQL - PostgreSQL + - Valkey API Documentation: https://techdocs.akamai.com/linode-api/reference/get-databases-engine """ @@ -212,6 +219,36 @@ class PostgreSQLDatabaseConfigOptions(JSONObject): work_mem: Optional[int] = None +@dataclass +class ValkeyDatabaseConfigOptions(JSONObject): + """ + Advanced configuration for a Valkey Managed Database. + + All fields are flat keys within ``engine_config``. Unset (``None``) + options are omitted. Use an ``ExplicitNullValue`` instance to send + JSON null for a nullable option. Zero and false values are preserved. + + Disabling ``valkey_persistence`` (``"off"``) disables snapshots and + restoring the cluster, and causes data loss on service restarts. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-databases-valkey-config + """ + + backup_hour: Optional[Union[int, ExplicitNullValue]] = None + backup_minute: Optional[Union[int, ExplicitNullValue]] = None + frequent_snapshots: Optional[bool] = None + valkey_acl_channels_default: Optional[str] = None + valkey_active_expire_effort: Optional[int] = None + valkey_activedefrag: Optional[bool] = None + valkey_lfu_decay_time: Optional[int] = None + valkey_lfu_log_factor: Optional[int] = None + valkey_maxmemory_policy: Optional[Union[str, ExplicitNullValue]] = None + valkey_number_of_databases: Optional[int] = None + valkey_persistence: Optional[str] = None + valkey_pubsub_client_output_buffer_limit: Optional[int] = None + valkey_timeout: Optional[int] = None + + class MySQLDatabase(Base): """ An accessible Managed MySQL Database. @@ -501,9 +538,152 @@ def resume(self): return self.invalidate() +class ValkeyDatabase(Base): + """ + A Valkey Managed Database (limited availability). + + ``available_restore_times`` contains API-format UTC timestamp strings for + discrete snapshots, not a continuous point-in-time recovery window. Pass + one to :any:`DatabaseGroup.valkey_fork`, or omit the restore time to use + the latest snapshot. Use ``client.load(ValkeyDatabase, id)`` to fetch an + existing cluster, and ``db.save()`` / ``db.delete()`` to update or delete it. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-databases-valkey-instance + """ + + api_endpoint = "/databases/valkey/instances/{id}" + + properties = { + "id": Property(identifier=True), + "label": Property(mutable=True), + "allow_list": Property(mutable=True, unordered=True), + "cluster_size": Property(mutable=True), + "created": Property(is_datetime=True), + "encrypted": Property(), + "engine": Property(), + "hosts": Property(), + "port": Property(), + "region": Property(mutable=True), + "ssl_connection": Property(), + "status": Property(volatile=True), + "type": Property(mutable=True), + "fork": Property(), + "available_restore_times": Property(), + "updated": Property(volatile=True, is_datetime=True), + "updates": Property(mutable=True), + "version": Property(mutable=True), + "members": Property(), + "used_disk_size_gb": Property(), + "total_disk_size_gb": Property(), + "engine_config": Property( + mutable=True, json_object=ValkeyDatabaseConfigOptions + ), + "private_network": Property( + mutable=True, json_object=DatabasePrivateNetwork, nullable=True + ), + } + + @property + def credentials(self): + """ + Return cached root credentials for an active Valkey Managed Database. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-databases-valkey-instance-credentials + + :returns: The root username and password. + :rtype: MappedObject + """ + if not hasattr(self, "_credentials"): + resp = self._client.get( + "{}/credentials".format(ValkeyDatabase.api_endpoint), + model=self, + ) + self._set("_credentials", MappedObject(**resp)) + + return self._credentials + + @property + def ssl(self): + """ + Return the cached base64-encoded SSL CA certificate. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-databases-valkey-instance-ssl + + :returns: An object containing ``ca_certificate``. + :rtype: MappedObject + """ + if not hasattr(self, "_ssl"): + resp = self._client.get( + "{}/ssl".format(ValkeyDatabase.api_endpoint), model=self + ) + self._set("_ssl", MappedObject(**resp)) + + return self._ssl + + def credentials_reset(self): + """ + Reset the root password and invalidate cached cluster data. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/post-databases-valkey-instance-credentials-reset + + :returns: The API response. + :rtype: dict + """ + self.invalidate() + return self._client.post( + "{}/credentials/reset".format(ValkeyDatabase.api_endpoint), + model=self, + ) + + def patch(self): + """ + Apply operating system security patches and updates. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/post-databases-valkey-instance-patch + + :returns: The API response. + :rtype: dict + """ + self.invalidate() + return self._client.post( + "{}/patch".format(ValkeyDatabase.api_endpoint), model=self + ) + + def suspend(self): + """ + Suspend the cluster, releasing idle resources while retaining data. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/suspend-databases-valkey-instance + """ + self._client.post( + "{}/suspend".format(ValkeyDatabase.api_endpoint), model=self + ) + return self.invalidate() + + def resume(self): + """ + Resume a suspended cluster. Resume before attempting updates. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/resume-databases-valkey-instance + """ + self._client.post( + "{}/resume".format(ValkeyDatabase.api_endpoint), model=self + ) + return self.invalidate() + + def invalidate(self): + """Clear cached properties, credentials, and SSL certificate.""" + for attr in ["_ssl", "_credentials"]: + if hasattr(self, attr): + delattr(self, attr) + + Base.invalidate(self) + + ENGINE_TYPE_TRANSLATION = { "mysql": MySQLDatabase, "postgresql": PostgreSQLDatabase, + "valkey": ValkeyDatabase, } @@ -512,7 +692,7 @@ class Database(Base): A generic Database instance. Note: This class does not have a corresponding GET endpoint. For detailed information - about the database, use the .instance() property method instead. + about the database, use the ``.instance`` property instead. """ api_endpoint = "/databases/instances/{id}" @@ -531,6 +711,7 @@ class Database(Base): "status": Property(), "type": Property(), "fork": Property(), + "available_restore_times": Property(), "updated": Property(), "updates": Property(), "version": Property(), diff --git a/test/fixtures/databases_engines.json b/test/fixtures/databases_engines.json index 6418f93ab..861a9edb0 100644 --- a/test/fixtures/databases_engines.json +++ b/test/fixtures/databases_engines.json @@ -9,9 +9,14 @@ "engine": "postgresql", "id": "postgresql/10.14", "version": "10.14" + }, + { + "engine": "valkey", + "id": "valkey/8.1", + "version": "8.1" } ], "page": 1, "pages": 1, - "results": 2 + "results": 3 } \ No newline at end of file diff --git a/test/fixtures/databases_instances.json b/test/fixtures/databases_instances.json index d2e6f0cf9..5b9a416fc 100644 --- a/test/fixtures/databases_instances.json +++ b/test/fixtures/databases_instances.json @@ -9,6 +9,7 @@ "created": "2022-01-01T00:01:01", "encrypted": false, "engine": "mysql", + "available_restore_times": null, "hosts": { "primary": "lin-123-456-mysql-mysql-primary.servers.linodedb.net", "standby": "lin-123-456-mysql-primary-private.servers.linodedb.net" @@ -33,9 +34,21 @@ "subnet_id": 5678, "public_access": true } + }, + { + "id": 123, + "label": "example-valkey", + "engine": "valkey", + "instance_uri": "/v4/databases/valkey/instances/123", + "available_restore_times": ["2026-01-01T01:00:00"], + "region": "us-east", + "status": "active", + "type": "g7-dedicated-4-2", + "version": "8.1", + "private_network": null } ], "page": 1, "pages": 1, - "results": 1 + "results": 2 } \ No newline at end of file diff --git a/test/fixtures/databases_types.json b/test/fixtures/databases_types.json index d85232764..d82908b87 100644 --- a/test/fixtures/databases_types.json +++ b/test/fixtures/databases_types.json @@ -14,6 +14,15 @@ "quantity": 1 } ], + "valkey": [ + { + "price": { + "hourly": 0.03, + "monthly": 20 + }, + "quantity": 1 + } + ], "postgresql": [ { "price": { diff --git a/test/fixtures/databases_valkey_config.json b/test/fixtures/databases_valkey_config.json new file mode 100644 index 000000000..293f1f584 --- /dev/null +++ b/test/fixtures/databases_valkey_config.json @@ -0,0 +1,58 @@ +{ + "backup_hour": { + "description": "UTC hour to start a backup.", + "example": 3, "minimum": 0, "maximum": 23, "requires_restart": false, + "type": ["integer", "null"] + }, + "backup_minute": { + "description": "Minute to start a backup.", + "example": 30, "minimum": 0, "maximum": 59, "requires_restart": false, + "type": ["integer", "null"] + }, + "frequent_snapshots": { + "description": "Enable frequent RDB snapshots.", + "default": true, "requires_restart": false, "type": "boolean" + }, + "valkey_acl_channels_default": { + "description": "Default ACL for pub/sub channels.", + "enum": ["allchannels", "resetchannels"], "requires_restart": false, "type": "string" + }, + "valkey_active_expire_effort": { + "description": "Effort used to reclaim expired keys.", + "default": 1, "minimum": 1, "maximum": 10, "requires_restart": false, "type": "integer" + }, + "valkey_activedefrag": { + "description": "Enable active memory defragmentation.", + "default": false, "example": false, "requires_restart": false, "type": "boolean" + }, + "valkey_lfu_decay_time": { + "description": "LFU counter decay time in minutes.", + "default": 1, "minimum": 1, "maximum": 120, "requires_restart": false, "type": "integer" + }, + "valkey_lfu_log_factor": { + "description": "LFU counter logarithm factor.", + "default": 10, "minimum": 0, "maximum": 100, "requires_restart": false, "type": "integer" + }, + "valkey_maxmemory_policy": { + "description": "Policy used when memory is full.", + "default": "noeviction", + "enum": ["noeviction", "allkeys-lru", "volatile-lru", "allkeys-random", "volatile-random", "volatile-ttl", "volatile-lfu", "allkeys-lfu"], + "requires_restart": false, "type": ["string", "null"] + }, + "valkey_number_of_databases": { + "description": "Number of logical Valkey databases.", + "example": 16, "minimum": 1, "maximum": 128, "requires_restart": true, "type": "integer" + }, + "valkey_persistence": { + "description": "RDB persistence mode; off disables backups and forking.", + "enum": ["off", "rdb"], "requires_restart": true, "type": "string" + }, + "valkey_pubsub_client_output_buffer_limit": { + "description": "Pub/sub client output buffer limit in MB.", + "example": 64, "minimum": 32, "maximum": 262144, "requires_restart": false, "type": "integer" + }, + "valkey_timeout": { + "description": "Idle connection timeout in seconds.", + "default": 300, "minimum": 0, "maximum": 2073600, "requires_restart": false, "type": "integer" + } +} diff --git a/test/fixtures/databases_valkey_instances.json b/test/fixtures/databases_valkey_instances.json new file mode 100644 index 000000000..c34ac23ea --- /dev/null +++ b/test/fixtures/databases_valkey_instances.json @@ -0,0 +1,51 @@ +{ + "data": [ + { + "id": 123, + "label": "example-valkey", + "allow_list": ["192.0.2.0/24"], + "cluster_size": 1, + "created": "2026-01-01T00:00:00", + "encrypted": true, + "engine": "valkey", + "hosts": { + "primary": "valkey.example.com", + "endpoints": [ + {"address": "valkey.example.com", "port": 6379, "public_access": true, "role": "primary"} + ] + }, + "port": 6379, + "region": "us-east", + "ssl_connection": true, + "status": "active", + "type": "g7-dedicated-4-2", + "fork": {"source": 455, "restore_time": "2026-01-01T01:00:00"}, + "available_restore_times": ["2026-01-01T01:00:00", "2026-01-01T01:10:00"], + "updated": "2026-01-01T00:10:00", + "updates": {"day_of_week": 1, "duration": 4, "frequency": "weekly", "hour_of_day": 0, "pending": []}, + "version": "8.1", + "members": {"192.0.2.1": "primary"}, + "used_disk_size_gb": null, + "total_disk_size_gb": 15, + "engine_config": { + "backup_hour": 0, + "backup_minute": 30, + "frequent_snapshots": false, + "valkey_acl_channels_default": "resetchannels", + "valkey_active_expire_effort": 1, + "valkey_activedefrag": false, + "valkey_lfu_decay_time": 1, + "valkey_lfu_log_factor": 0, + "valkey_maxmemory_policy": "noeviction", + "valkey_number_of_databases": 16, + "valkey_persistence": "rdb", + "valkey_pubsub_client_output_buffer_limit": 64, + "valkey_timeout": 0 + }, + "private_network": {"vpc_id": 1234, "subnet_id": 5678, "public_access": false} + } + ], + "page": 1, + "pages": 1, + "results": 1 +} diff --git a/test/fixtures/databases_valkey_instances_123_credentials.json b/test/fixtures/databases_valkey_instances_123_credentials.json new file mode 100644 index 000000000..91016b6cf --- /dev/null +++ b/test/fixtures/databases_valkey_instances_123_credentials.json @@ -0,0 +1,4 @@ +{ + "username": "example-admin", + "password": "example-test-password" +} diff --git a/test/fixtures/databases_valkey_instances_123_credentials_reset.json b/test/fixtures/databases_valkey_instances_123_credentials_reset.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/test/fixtures/databases_valkey_instances_123_credentials_reset.json @@ -0,0 +1 @@ +{} diff --git a/test/fixtures/databases_valkey_instances_123_patch.json b/test/fixtures/databases_valkey_instances_123_patch.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/test/fixtures/databases_valkey_instances_123_patch.json @@ -0,0 +1 @@ +{} diff --git a/test/fixtures/databases_valkey_instances_123_resume.json b/test/fixtures/databases_valkey_instances_123_resume.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/test/fixtures/databases_valkey_instances_123_resume.json @@ -0,0 +1 @@ +{} diff --git a/test/fixtures/databases_valkey_instances_123_ssl.json b/test/fixtures/databases_valkey_instances_123_ssl.json new file mode 100644 index 000000000..e6ca26e17 --- /dev/null +++ b/test/fixtures/databases_valkey_instances_123_ssl.json @@ -0,0 +1,3 @@ +{ + "ca_certificate": "ZXhhbXBsZS10ZXN0LWNlcnRpZmljYXRl" +} diff --git a/test/fixtures/databases_valkey_instances_123_suspend.json b/test/fixtures/databases_valkey_instances_123_suspend.json new file mode 100644 index 000000000..0967ef424 --- /dev/null +++ b/test/fixtures/databases_valkey_instances_123_suspend.json @@ -0,0 +1 @@ +{} diff --git a/test/integration/models/database/test_database.py b/test/integration/models/database/test_database.py index 7092eca06..f8eeab0ce 100644 --- a/test/integration/models/database/test_database.py +++ b/test/integration/models/database/test_database.py @@ -133,7 +133,7 @@ def test_get_engines(test_linode_client): engines = client.database.engines() for e in engines: - assert e.engine in ["mysql", "postgresql"] + assert e.engine in ["mysql", "postgresql", "valkey"] # assert re.search("[0-9]+.[0-9]+", e.version) assert e.id == e.engine + "/" + e.version diff --git a/test/integration/models/database/test_valkey.py b/test/integration/models/database/test_valkey.py new file mode 100644 index 000000000..fc1c4c48c --- /dev/null +++ b/test/integration/models/database/test_valkey.py @@ -0,0 +1,182 @@ +import os +from dataclasses import fields +from test.integration.helpers import ( + get_test_label, + send_request_when_resource_available, + wait_for_condition, +) + +import pytest + +from linode_api4 import ( + DatabaseEngine, + DatabasePrivateNetwork, + ExplicitNullValue, + ValkeyDatabase, + ValkeyDatabaseConfigOptions, +) + +pytestmark = pytest.mark.skipif( + os.getenv("RUN_VALKEY_DB_TESTS", "").strip().lower() not in {"yes", "true"}, + reason="RUN_VALKEY_DB_TESTS must be 'yes' or 'true'; creates real databases", +) + + +def wait_for_valkey_status(client, database, status): + wait_for_condition( + 30, + 1200, + lambda: client.load(ValkeyDatabase, database.id).status == status, + ) + database.invalidate() + + +@pytest.fixture +def create_valkey_database(test_linode_client, request): + client = test_linode_client + engines = list(client.database.engines(DatabaseEngine.engine == "valkey")) + assert engines, "No Valkey database engine is available to this account" + types = [ + node_type + for node_type in client.database.types() + if not node_type.deprecated and getattr(node_type.engines, "valkey", []) + ] + assert types, "No Valkey-capable database type is available to this account" + node_type = min(types, key=lambda candidate: candidate.memory) + + def create(**kwargs): + params = { + "label": get_test_label() + "-valkey", + "region": os.getenv("LINODE_TEST_REGION_OVERRIDE", "us-ord"), + "engine": engines[0].id, + "ltype": node_type.id, + "cluster_size": 1, + "engine_config": ValkeyDatabaseConfigOptions( + valkey_persistence="rdb", + frequent_snapshots=True, + valkey_timeout=300, + ), + } + params.update(kwargs) + database = client.database.valkey_create(**params) + request.addfinalizer( + lambda: send_request_when_resource_available(600, database.delete) + ) + wait_for_valkey_status(client, database, "active") + return database + + return create + + +def test_valkey_config_catalog(test_linode_client): + catalog = test_linode_client.database.valkey_config_options() + assert {field.name for field in fields(ValkeyDatabaseConfigOptions)} <= set( + catalog + ) + assert catalog["backup_hour"]["type"] == ["integer", "null"] + assert catalog["backup_minute"]["type"] == ["integer", "null"] + assert catalog["valkey_acl_channels_default"]["enum"] == [ + "allchannels", + "resetchannels", + ] + assert catalog["valkey_number_of_databases"]["requires_restart"] + + +def test_valkey_lifecycle(test_linode_client, create_valkey_database): + client = test_linode_client + database = create_valkey_database() + assert database.engine == "valkey" + assert database.engine_config.valkey_persistence == "rdb" + assert any( + db.id == database.id for db in client.database.valkey_instances() + ) + generic = next( + db for db in client.database.instances() if db.id == database.id + ) + assert isinstance(generic.instance, ValkeyDatabase) + assert generic.instance.id == database.id + assert database.ssl.ca_certificate + assert database.credentials.username + password = database.credentials.password + assert password + + database.engine_config = ValkeyDatabaseConfigOptions(valkey_timeout=301) + database.allow_list = ["192.0.2.0/24"] + assert send_request_when_resource_available(300, database.save) + + def updated(): + db = client.load(ValkeyDatabase, database.id) + return ( + db.status == "active" + and db.engine_config.valkey_timeout == 301 + and db.allow_list == ["192.0.2.0/24"] + ) + + wait_for_condition(30, 1200, updated) + send_request_when_resource_available(300, database.credentials_reset) + + def password_changed(): + database.invalidate() + return database.credentials.password != password + + wait_for_condition(10, 300, password_changed) + send_request_when_resource_available(300, database.patch) + wait_for_valkey_status(client, database, "active") + send_request_when_resource_available(300, database.suspend) + wait_for_valkey_status(client, database, "suspended") + database.resume() + wait_for_valkey_status(client, database, "active") + + +@pytest.mark.skipif( + os.getenv("RUN_VALKEY_DB_FORK_TESTS", "").strip().lower() + not in {"yes", "true"}, + reason="RUN_VALKEY_DB_FORK_TESTS must be 'yes' or 'true'; creates forked databases", +) +@pytest.mark.parametrize("latest", [False, True]) +def test_valkey_fork( + test_linode_client, create_valkey_database, request, latest +): + client = test_linode_client + source = create_valkey_database() + snapshots = wait_for_condition( + 30, + 1800, + lambda: client.load(ValkeyDatabase, source.id).available_restore_times, + ) + fork = client.database.valkey_fork( + source.id, + None if latest else snapshots[-1], + label=get_test_label() + "-valkey-fork", + ) + request.addfinalizer( + lambda: send_request_when_resource_available(600, fork.delete) + ) + wait_for_valkey_status(client, fork, "active") + assert fork.fork.source == source.id + if not latest: + assert fork.fork.restore_time == snapshots[-1] + + +def test_valkey_private_network( + test_linode_client, create_valkey_database, create_vpc_with_subnet +): + client = test_linode_client + vpc, subnet = create_vpc_with_subnet + database = create_valkey_database( + region=vpc.region, + private_network=DatabasePrivateNetwork( + vpc_id=vpc.id, subnet_id=subnet.id, public_access=False + ), + ) + assert database.private_network.vpc_id == vpc.id + assert database.private_network.subnet_id == subnet.id + assert database.private_network.public_access is False + database.private_network = ExplicitNullValue() + assert send_request_when_resource_available(300, database.save) + wait_for_condition( + 30, + 1200, + lambda: client.load(ValkeyDatabase, database.id).private_network + is None, + ) diff --git a/test/unit/groups/database_test.py b/test/unit/groups/database_test.py index 8038e8c6b..5436cdedf 100644 --- a/test/unit/groups/database_test.py +++ b/test/unit/groups/database_test.py @@ -28,7 +28,7 @@ def test_get_engines(self): """ engines = self.client.database.engines() - self.assertEqual(len(engines), 2) + self.assertEqual(len(engines), 3) self.assertEqual(engines[0].engine, "mysql") self.assertEqual(engines[0].id, "mysql/8.0.26") @@ -44,7 +44,7 @@ def test_get_databases(self): """ dbs = self.client.database.instances() - self.assertEqual(len(dbs), 1) + self.assertEqual(len(dbs), 2) self.assertEqual(dbs[0].allow_list[1], "192.0.1.0/24") self.assertEqual(dbs[0].cluster_size, 3) self.assertEqual(dbs[0].encrypted, False) diff --git a/test/unit/groups/valkey_test.py b/test/unit/groups/valkey_test.py new file mode 100644 index 000000000..a2f4519c4 --- /dev/null +++ b/test/unit/groups/valkey_test.py @@ -0,0 +1,316 @@ +import json +from dataclasses import fields +from datetime import datetime, timedelta, timezone +from test.unit.base import ClientBaseCase, load_json + +from mock import patch + +from linode_api4 import ( + ApiError, + Database, + DatabaseEngine, + DatabasePrivateNetwork, + DatabaseType, + ExplicitNullValue, + MySQLDatabase, + PaginatedList, + PostgreSQLDatabase, + Region, + UnexpectedResponseError, + ValkeyDatabase, + ValkeyDatabaseConfigOptions, +) + + +class ValkeyGroupTest(ClientBaseCase): + def setUp(self): + super().setUp() + self.response = load_json("/databases/valkey/instances/123") + + def test_list_and_filter(self): + with self.mock_get("/databases/valkey/instances") as mock: + databases = self.client.database.valkey_instances( + ValkeyDatabase.label == "example-valkey" + ) + self.assertIsInstance(databases, PaginatedList) + self.assertEqual(len(databases), 1) + self.assertIsInstance(databases[0], ValkeyDatabase) + self.assertEqual(databases[0].id, 123) + self.assertEqual(mock.call_url, "/databases/valkey/instances") + self.assertEqual( + json.loads(mock.call_headers["X-Filter"]), + {"label": "example-valkey"}, + ) + + def test_pagination(self): + page = { + "data": [self.response], + "page": 1, + "pages": 2, + "results": 2, + } + with self.mock_get(page): + databases = self.client.database.valkey_instances() + page["page"] = 2 + page["data"] = [{**self.response, "id": 124}] + with self.mock_get(page) as mock: + self.assertEqual(databases[1].id, 124) + self.assertIn("/databases/valkey/instances?page=2", mock.call_url) + + def test_config_catalog(self): + with self.mock_get("/databases/valkey/config") as mock: + config = self.client.database.valkey_config_options() + self.assertEqual(mock.call_url, "/databases/valkey/config") + self.assertEqual(config, load_json("/databases/valkey/config")) + self.assertEqual( + set(config), + {field.name for field in fields(ValkeyDatabaseConfigOptions)}, + ) + self.assertEqual(config["backup_hour"]["type"], ["integer", "null"]) + self.assertEqual(config["backup_minute"]["maximum"], 59) + self.assertEqual(config["valkey_timeout"]["type"], "integer") + self.assertEqual( + config["valkey_acl_channels_default"]["enum"], + ["allchannels", "resetchannels"], + ) + self.assertIs(config["valkey_activedefrag"]["example"], False) + self.assertIs(config["frequent_snapshots"]["default"], True) + self.assertEqual( + config["valkey_maxmemory_policy"]["default"], "noeviction" + ) + self.assertNotIn("default", config["valkey_persistence"]) + + def test_create(self): + config = ValkeyDatabaseConfigOptions.from_json( + self.response["engine_config"] + ) + network = DatabasePrivateNetwork( + vpc_id=1234, subnet_id=5678, public_access=False + ) + with self.mock_post(self.response) as mock: + db = self.client.database.valkey_create( + "example-valkey", + Region(self.client, "us-east"), + DatabaseEngine(self.client, "valkey/8.1"), + DatabaseType(self.client, "g7-dedicated-4-2"), + engine_config=config, + private_network=network, + cluster_size=1, + allow_list=[], + ssl_connection=True, + ) + self.assertEqual(mock.call_url, "/databases/valkey/instances") + self.assertEqual( + mock.call_data, + { + "label": "example-valkey", + "region": "us-east", + "engine": "valkey/8.1", + "type": "g7-dedicated-4-2", + "engine_config": self.response["engine_config"], + "private_network": self.response["private_network"], + "cluster_size": 1, + "allow_list": [], + "ssl_connection": True, + }, + ) + self.assertIsInstance(db, ValkeyDatabase) + self.assertEqual(db.id, 123) + self.assertEqual(db.engine_config, config) + + def test_create_optional_configuration(self): + for config in (None, {}, ValkeyDatabaseConfigOptions()): + with ( + self.subTest(config=config), + self.mock_post(self.response) as mock, + ): + self.client.database.valkey_create( + "example-valkey", + "us-east", + "valkey/8.1", + "g7-dedicated-4-2", + engine_config=config, + ) + if config is None: + self.assertNotIn("engine_config", mock.call_data) + else: + self.assertEqual(mock.call_data["engine_config"], {}) + self.assertNotIn("private_network", mock.call_data) + + def test_create_null_zero_false_and_dictionary_options(self): + expected = { + "backup_hour": None, + "backup_minute": None, + "valkey_maxmemory_policy": None, + "frequent_snapshots": False, + "valkey_timeout": 0, + } + configs = [ + ValkeyDatabaseConfigOptions( + backup_hour=ExplicitNullValue(), + backup_minute=ExplicitNullValue(), + valkey_maxmemory_policy=ExplicitNullValue(), + frequent_snapshots=False, + valkey_timeout=0, + ), + { + **expected, + "backup_hour": ExplicitNullValue(), + "backup_minute": ExplicitNullValue(), + "valkey_maxmemory_policy": ExplicitNullValue(), + }, + ] + for config in configs: + with ( + self.subTest(config=config), + self.mock_post(self.response) as mock, + ): + self.client.database.valkey_create( + "example-valkey", + "us-east", + "valkey/8.1", + "g7-dedicated-4-2", + engine_config=config, + ) + self.assertEqual(mock.call_data["engine_config"], expected) + + def test_missing_create_or_fork_id(self): + for operation, args in ( + ( + self.client.database.valkey_create, + ("example-valkey", "us-east", "valkey/8.1", "g7-dedicated-4-2"), + ), + (self.client.database.valkey_fork, (123,)), + ): + with self.subTest(operation=operation), self.mock_post({}): + with self.assertRaises(UnexpectedResponseError): + operation(*args) + + def test_api_errors_propagate(self): + error = ApiError("Valkey access is not enabled", status=403) + with patch.object(self.client, "get", side_effect=error): + for operation in ( + self.client.database.valkey_instances, + self.client.database.valkey_config_options, + ): + with self.subTest(operation=operation): + with self.assertRaises(ApiError) as raised: + operation() + self.assertIs(raised.exception, error) + with patch.object(self.client, "post", side_effect=error): + with self.assertRaises(ApiError): + self.client.database.valkey_create( + "example-valkey", + "us-east", + "valkey/8.1", + "g7-dedicated-4-2", + ) + with self.assertRaises(ApiError): + self.client.database.valkey_fork(123) + + def test_fork_restore_times(self): + for restore_time, expected in ( + (None, {"source": 123}), + ( + "2026-01-01T01:00:00", + {"source": 123, "restore_time": "2026-01-01T01:00:00"}, + ), + ( + datetime(2026, 1, 1, 1), + {"source": 123, "restore_time": "2026-01-01T01:00:00"}, + ), + ( + datetime(2026, 1, 1, 3, tzinfo=timezone(timedelta(hours=2))), + {"source": 123, "restore_time": "2026-01-01T01:00:00"}, + ), + ): + with ( + self.subTest(restore_time=restore_time), + self.mock_post(self.response) as mock, + ): + db = self.client.database.valkey_fork(123, restore_time) + self.assertEqual(mock.call_url, "/databases/valkey/instances") + self.assertEqual(mock.call_data, {"fork": expected}) + self.assertIsInstance(db, ValkeyDatabase) + + def test_fork_overrides(self): + with self.mock_post(self.response) as mock: + self.client.database.valkey_fork( + 123, + label="forked", + ltype=DatabaseType(self.client, "g7-dedicated-4-2"), + region=Region(self.client, "us-east"), + engine_config=ValkeyDatabaseConfigOptions(valkey_timeout=0), + private_network=DatabasePrivateNetwork(vpc_id=1234), + ) + self.assertEqual( + mock.call_data, + { + "fork": {"source": 123}, + "label": "forked", + "type": "g7-dedicated-4-2", + "region": "us-east", + "engine_config": {"valkey_timeout": 0}, + "private_network": {"vpc_id": 1234}, + }, + ) + with self.mock_post(self.response) as mock: + self.client.database.valkey_fork(123, type="g7-dedicated-4-2") + self.assertEqual(mock.call_data["type"], "g7-dedicated-4-2") + + def test_invalid_fork_inputs_do_not_send_requests(self): + with self.mock_post(self.response) as mock: + for value in (0, False, [], {}): + with self.subTest(value=value), self.assertRaises(TypeError): + self.client.database.valkey_fork(123, value) + for options in ( + {"ltype": "one", "type": "two"}, + {"fork": {"source": 1}}, + ): + with ( + self.subTest(options=options), + self.assertRaises(ValueError), + ): + self.client.database.valkey_fork(123, **options) + self.assertFalse(mock.called) + + def test_discovery_and_generic_database_translation(self): + engines = self.client.database.engines() + self.assertEqual(engines[2].engine, "valkey") + self.assertEqual(engines[2].id, "valkey/8.1") + self.assertEqual( + self.client.database.types()[0].engines.valkey[0].quantity, 1 + ) + databases = self.client.database.instances() + self.assertIsNone(databases[0].available_restore_times) + self.assertIsInstance(databases[1].instance, ValkeyDatabase) + self.assertIs(databases[1].instance, databases[1].instance) + self.assertEqual(databases[1].instance.id, 123) + self.assertEqual(databases[1].instance.label, "example-valkey") + for engine, model in ( + ("mysql", MySQLDatabase), + ("postgresql", PostgreSQLDatabase), + ): + self.assertIsInstance( + Database(self.client, 123, {"engine": engine}).instance, model + ) + self.assertIsNone( + Database(self.client, 123, {"engine": "unknown"}).instance + ) + + def test_restore_list_shapes_and_round_trip(self): + for model in (Database, ValkeyDatabase): + for times in (None, [], ["2026-01-01T01:00:00"]): + with self.subTest(model=model, times=times): + db = model( + self.client, 123, {"available_restore_times": times} + ) + self.assertEqual(db.available_restore_times, times) + db = model(self.client, 123, {"engine": "valkey"}) + self.assertIsNone(db.available_restore_times) + snapshot = self.client.load( + ValkeyDatabase, 123 + ).available_restore_times[0] + with self.mock_post(self.response) as mock: + self.client.database.valkey_fork(123, snapshot) + self.assertEqual(mock.call_data["fork"]["restore_time"], snapshot) diff --git a/test/unit/objects/valkey_test.py b/test/unit/objects/valkey_test.py new file mode 100644 index 000000000..380b426fb --- /dev/null +++ b/test/unit/objects/valkey_test.py @@ -0,0 +1,217 @@ +import json +from datetime import datetime, timedelta +from test.unit.base import ClientBaseCase, load_json + +from mock import patch + +from linode_api4 import ( + ApiError, + DatabasePrivateNetwork, + ExplicitNullValue, + ValkeyDatabase, + ValkeyDatabaseConfigOptions, +) + + +class ValkeyDatabaseTest(ClientBaseCase): + def test_load_and_lazy_load(self): + with self.mock_get("/databases/valkey/instances/123") as mock: + db = ValkeyDatabase(self.client, 123) + self.assertFalse(mock.called) + self.assertEqual(db.id, 123) + self.assertEqual(db.label, "example-valkey") + self.assertEqual(mock.call_count, 1) + self.assertEqual(mock.call_url, "/databases/valkey/instances/123") + self.assertEqual(db.created, datetime(2026, 1, 1)) + self.assertEqual(db.updated, datetime(2026, 1, 1, 0, 10)) + self.assertEqual(db.hosts.endpoints[0].role, "primary") + self.assertEqual(db.members.dict, {"192.0.2.1": "primary"}) + self.assertIsNone(db.used_disk_size_gb) + self.assertEqual(db.total_disk_size_gb, 15) + self.assertEqual(db.port, 6379) + self.assertIsInstance(db.engine_config, ValkeyDatabaseConfigOptions) + self.assertEqual( + db.engine_config.dict, + load_json("/databases/valkey/instances/123")["engine_config"], + ) + self.assertEqual(self.client.load(ValkeyDatabase, 123).id, 123) + + def test_update(self): + db = self.client.load(ValkeyDatabase, 123) + db.label = "updated-valkey" + db.allow_list = [] + db.cluster_size = 3 + db.region = "us-east" + db.type = "g7-dedicated-8-4" + db.version = "8.1" + db.updates.day_of_week = 2 + db.engine_config = ValkeyDatabaseConfigOptions( + valkey_timeout=0, + frequent_snapshots=False, + backup_hour=ExplicitNullValue(), + backup_minute=ExplicitNullValue(), + valkey_maxmemory_policy=ExplicitNullValue(), + ) + db.private_network = DatabasePrivateNetwork( + vpc_id=1234, subnet_id=5678, public_access=False + ) + with self.mock_put({}) as mock: + self.assertTrue(db.save()) + self.assertEqual(mock.call_url, "/databases/valkey/instances/123") + data = mock.call_data + self.assertEqual( + set(data), + { + "label", + "allow_list", + "cluster_size", + "region", + "type", + "version", + "updates", + "engine_config", + "private_network", + }, + ) + self.assertEqual(data["label"], "updated-valkey") + self.assertEqual(data["allow_list"], []) + self.assertEqual(data["cluster_size"], 3) + self.assertEqual(data["updates"]["day_of_week"], 2) + self.assertEqual( + data["engine_config"], + { + "backup_hour": None, + "backup_minute": None, + "valkey_maxmemory_policy": None, + "valkey_timeout": 0, + "frequent_snapshots": False, + }, + ) + self.assertIs(data["private_network"]["public_access"], False) + + def test_update_configuration_round_trip(self): + db = self.client.load(ValkeyDatabase, 123) + expected = db.engine_config.dict + with self.mock_put({}) as mock: + db.save() + self.assertEqual(mock.call_data["engine_config"], expected) + db.engine_config = {"valkey_timeout": 0, "frequent_snapshots": False} + with self.mock_put({}) as mock: + db.save() + self.assertEqual(mock.call_data["engine_config"], db.engine_config) + + def test_nullable_fields(self): + response = { + **load_json("/databases/valkey/instances/123"), + "private_network": None, + "engine_config": None, + } + with self.mock_get(response): + db = self.client.load(ValkeyDatabase, 123) + self.assertIsNone(db.private_network) + self.assertIsNone(db.engine_config) + db.private_network = ExplicitNullValue() + with self.mock_put({}) as mock: + db.save() + self.assertIsNone(json.loads(mock.call_data_raw)["private_network"]) + config = ValkeyDatabaseConfigOptions.from_json( + { + "backup_hour": None, + "backup_minute": None, + "valkey_maxmemory_policy": None, + } + ) + self.assertEqual(config.dict, {}) + + def test_read_only_properties(self): + db = self.client.load(ValkeyDatabase, 123) + for key in ( + "engine", + "available_restore_times", + "status", + "members", + "port", + "fork", + "created", + "updated", + "total_disk_size_gb", + ): + with self.subTest(key=key), self.assertRaises(AttributeError): + setattr(db, key, None) + + def test_volatile_status_refresh(self): + db = self.client.load(ValkeyDatabase, 123) + db._last_updated = datetime.now() - timedelta(seconds=30) + response = { + **load_json("/databases/valkey/instances/123"), + "status": "suspended", + } + with self.mock_get(response) as mock: + self.assertEqual(db.status, "suspended") + self.assertEqual(mock.call_count, 1) + + def test_action_errors_propagate(self): + for action in ("credentials_reset", "patch", "suspend", "resume"): + with self.subTest(action=action): + db = ValkeyDatabase(self.client, 123) + error = ApiError("Cluster is not available", status=400) + with patch.object(self.client, "post", side_effect=error): + with self.assertRaises(ApiError) as raised: + getattr(db, action)() + self.assertIs(raised.exception, error) + + def test_credentials_and_ssl_are_cached(self): + db = ValkeyDatabase(self.client, 123) + for name, response in ( + ( + "credentials", + { + "username": "example-admin", + "password": "example-test-password", + }, + ), + ("ssl", {"ca_certificate": "ZXhhbXBsZS10ZXN0LWNlcnRpZmljYXRl"}), + ): + with self.subTest(name=name), self.mock_get(response) as mock: + value = getattr(db, name) + self.assertEqual(value.dict, response) + self.assertIs(value, getattr(db, name)) + self.assertEqual(mock.call_count, 1) + self.assertEqual( + mock.call_url, f"/databases/valkey/instances/123/{name}" + ) + + def test_actions_invalidate_caches(self): + for action, path, expected in ( + ("credentials_reset", "credentials/reset", {}), + ("patch", "patch", {}), + ("suspend", "suspend", None), + ("resume", "resume", None), + ): + with self.subTest(action=action): + db = self.client.load(ValkeyDatabase, 123) + credentials, ssl = db.credentials, db.ssl + with self.mock_post( + f"/databases/valkey/instances/123/{path}" + ) as mock: + self.assertEqual(getattr(db, action)(), expected) + self.assertEqual( + mock.call_url, f"/databases/valkey/instances/123/{path}" + ) + self.assertFalse(db._populated) + self.assertNotIn("_credentials", vars(db)) + self.assertNotIn("_ssl", vars(db)) + self.assertEqual(db.id, 123) + self.assertIsNot(db.credentials, credentials) + self.assertIsNot(db.ssl, ssl) + + def test_delete(self): + db = self.client.load(ValkeyDatabase, 123) + db.credentials + db.ssl + with self.mock_delete() as mock: + self.assertTrue(db.delete()) + self.assertEqual(mock.call_url, "/databases/valkey/instances/123") + self.assertFalse(db._populated) + self.assertNotIn("_credentials", vars(db)) + self.assertNotIn("_ssl", vars(db)) From 30323ec8fe941149aee3d7ecd93ac596cf95e934 Mon Sep 17 00:00:00 2001 From: Anmol Sharma Date: Sun, 15 Nov 2026 23:58:12 -0500 Subject: [PATCH 2/5] TPT-4130: address test race condition for test_valkey.py identified on live test --- .../models/database/test_valkey.py | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/test/integration/models/database/test_valkey.py b/test/integration/models/database/test_valkey.py index fc1c4c48c..f6cd47109 100644 --- a/test/integration/models/database/test_valkey.py +++ b/test/integration/models/database/test_valkey.py @@ -1,5 +1,6 @@ import os from dataclasses import fields +from test.integration.conftest import get_region from test.integration.helpers import ( get_test_label, send_request_when_resource_available, @@ -9,6 +10,7 @@ import pytest from linode_api4 import ( + Capability, DatabaseEngine, DatabasePrivateNetwork, ExplicitNullValue, @@ -159,12 +161,27 @@ def test_valkey_fork( def test_valkey_private_network( - test_linode_client, create_valkey_database, create_vpc_with_subnet + test_linode_client, create_valkey_database, request ): client = test_linode_client - vpc, subnet = create_vpc_with_subnet + region = get_region(client, {Capability.vpcs, Capability.linodes}) + vpc = client.vpcs.create( + label=get_test_label(), + region=region, + description="Valkey private-network integration test", + ) + request.addfinalizer( + lambda: send_request_when_resource_available(600, vpc.delete) + ) + subnet = vpc.subnet_create( + label=get_test_label(), + ipv4="10.0.0.0/24", + ) + request.addfinalizer( + lambda: send_request_when_resource_available(600, subnet.delete) + ) database = create_valkey_database( - region=vpc.region, + region=region, private_network=DatabasePrivateNetwork( vpc_id=vpc.id, subnet_id=subnet.id, public_access=False ), From bc46ce0ea3bbad61038237d7c270394e687fe1d5 Mon Sep 17 00:00:00 2001 From: anmsharm1 Date: Mon, 23 Nov 2026 14:46:12 -0500 Subject: [PATCH 3/5] Potential fix for pull request finding 'Run database cleanup before network teardown to prevent leaked resources' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adjusted text logic to account for the test scenario where If the private-network test fails before detaching the database, the fixture’s cleanup runs after the test’s subnet/VPC finalizers, so network deletion can fail while the database is still attached. The change is to register database cleanup on request.node so it runs before subnet and VPC cleanup. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- test/integration/models/database/test_valkey.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/models/database/test_valkey.py b/test/integration/models/database/test_valkey.py index f6cd47109..92d43354e 100644 --- a/test/integration/models/database/test_valkey.py +++ b/test/integration/models/database/test_valkey.py @@ -61,7 +61,7 @@ def create(**kwargs): } params.update(kwargs) database = client.database.valkey_create(**params) - request.addfinalizer( + request.node.addfinalizer( lambda: send_request_when_resource_available(600, database.delete) ) wait_for_valkey_status(client, database, "active") From d34fbdd7fcae86eff22bb64a41371ada5fc8ddc2 Mon Sep 17 00:00:00 2001 From: Zhiwei Liang <121905282+zliang-akamai@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:15:23 -0500 Subject: [PATCH 4/5] TPT-4765: Raise minimum supported Python to 3.11 (#757) * TPT-4765: Require Python 3.11 * TPT-4765: Default E2E workflow to Python 3.11 --- .github/workflows/ci.yml | 2 +- .github/workflows/e2e-test.yml | 13 ++----------- .github/workflows/release-cross-repo-test.yml | 2 +- AGENTS.md | 2 +- linode_api4/groups/linode.py | 1 - linode_api4/login_client.py | 8 +------- linode_api4/objects/account.py | 1 - linode_api4/objects/linode.py | 10 ++-------- linode_api4/objects/serializable.py | 3 --- pyproject.toml | 8 ++++---- 10 files changed, 12 insertions(+), 38 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fecd97885..b83380aec 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -59,7 +59,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ['3.10', '3.11', '3.12', '3.13', '3.14'] + python-version: ['3.11', '3.12', '3.13', '3.14', '3.15'] steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index 46742cbae..8d16f9979 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -41,14 +41,6 @@ on: python-version: description: 'Specify the Python version to use for running tests. Leave empty to use the default Python version configured in the environment' required: false - run-eol-python-version: - description: 'Indicates whether to run tests using an End-of-Life (EOL) Python version. Defaults to "false". Choose "true" to include tests for deprecated Python versions' - required: false - default: 'false' - type: choice - options: - - 'true' - - 'false' test_report_upload: description: 'Indicates whether to upload the test report to object storage. Defaults to "false"' type: choice @@ -63,8 +55,7 @@ on: - dev env: - DEFAULT_PYTHON_VERSION: "3.13" - EOL_PYTHON_VERSION: "3.10" + DEFAULT_PYTHON_VERSION: "3.11" EXIT_STATUS: 0 jobs: @@ -89,7 +80,7 @@ jobs: - name: Setup Python uses: actions/setup-python@v7 with: - python-version: ${{ inputs.run-eol-python-version == 'true' && env.EOL_PYTHON_VERSION || inputs.python-version || env.DEFAULT_PYTHON_VERSION }} + python-version: ${{ inputs.python-version || env.DEFAULT_PYTHON_VERSION }} - name: Install Python deps run: pip install -U setuptools wheel boto3 certifi diff --git a/.github/workflows/release-cross-repo-test.yml b/.github/workflows/release-cross-repo-test.yml index be2eaba68..8a57205bb 100644 --- a/.github/workflows/release-cross-repo-test.yml +++ b/.github/workflows/release-cross-repo-test.yml @@ -27,7 +27,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v7 with: - python-version: '3.10' + python-version: '3.13' - name: Checkout ansible repo uses: actions/checkout@v7 diff --git a/AGENTS.md b/AGENTS.md index 20f924d80..e9192dc6e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -3,7 +3,7 @@ ## Source of Truth - This is the official synchronous Python SDK for the Linode API. Supported - Python versions come from [pyproject.toml](pyproject.toml) (`>=3.10`). + Python versions come from [pyproject.toml](pyproject.toml) (`>=3.11`). - Make changes only in canonical source trees such as `linode_api4/`, `test/`, `docs/`, `examples/`, and `.github/`. Do not edit generated copies or output in `build/`, `dist/`, `docs/build/`, `docs/_build/`, or `linode_api4.egg-info/`. diff --git a/linode_api4/groups/linode.py b/linode_api4/groups/linode.py index 07254fb3d..1b4060931 100644 --- a/linode_api4/groups/linode.py +++ b/linode_api4/groups/linode.py @@ -97,7 +97,6 @@ def stackscripts(self, *filters, **kwargs): :returns: A list of StackScripts matching the query. :rtype: PaginatedList of StackScript """ - # python2 can't handle *args and a single keyword argument, so this is a workaround if "mine_only" in kwargs: if kwargs["mine_only"]: new_filter = Filter({"mine": True}) diff --git a/linode_api4/login_client.py b/linode_api4/login_client.py index 8b8fe69c3..b671d1724 100644 --- a/linode_api4/login_client.py +++ b/linode_api4/login_client.py @@ -1,18 +1,12 @@ import re from datetime import datetime, timedelta from enum import Enum +from urllib.parse import urlencode, urlparse, urlunparse import requests from linode_api4.errors import ApiError -try: - from urllib.parse import urlencode, urlparse, urlunparse -except ImportError: - from urllib import urlencode - - from urlparse import urlparse, urlunparse - class AllWrapper: def __repr__(self): diff --git a/linode_api4/objects/account.py b/linode_api4/objects/account.py index a4aca1848..9b61b448b 100644 --- a/linode_api4/objects/account.py +++ b/linode_api4/objects/account.py @@ -494,7 +494,6 @@ def set_thumbnail(self, thumbnail): "Content-type": "image/png", } - # TODO this check needs to be smarter - python2 doesn't do it right if not isinstance(thumbnail, bytes): with open(thumbnail, "rb") as f: thumbnail = f.read() diff --git a/linode_api4/objects/linode.py b/linode_api4/objects/linode.py index 78bc0710a..f2249213e 100644 --- a/linode_api4/objects/linode.py +++ b/linode_api4/objects/linode.py @@ -2,7 +2,6 @@ import copy import string -import sys import warnings from dataclasses import dataclass, field from datetime import datetime @@ -1292,15 +1291,10 @@ def resize( @staticmethod def generate_root_password(): - def _func(value): - if sys.version_info[0] < 3: - value = int(value.encode("hex"), 16) - return value - password = "".join( [ - PASSWORD_CHARS[_func(c) % len(PASSWORD_CHARS)] - for c in urandom(randint(50, 110)) + PASSWORD_CHARS[value % len(PASSWORD_CHARS)] + for value in urandom(randint(50, 110)) ] ) diff --git a/linode_api4/objects/serializable.py b/linode_api4/objects/serializable.py index c1f59f6d4..55a2d6fba 100644 --- a/linode_api4/objects/serializable.py +++ b/linode_api4/objects/serializable.py @@ -272,9 +272,6 @@ class StrEnum(str, Enum): """ Used for enums that are of type string, which is necessary for implicit JSON serialization. - - NOTE: Replace this with StrEnum once Python 3.10 has been EOL'd. - See: https://docs.python.org/3/library/enum.html#enum.StrEnum """ def __new__(cls, *values): diff --git a/pyproject.toml b/pyproject.toml index e4e641aa7..a7008fea0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,7 +8,7 @@ name = "linode_api4" authors = [{ name = "Linode", email = "devs@linode.com" }] description = "The official Python SDK for Linode API v4" readme = "README.rst" -requires-python = ">=3.10" +requires-python = ">=3.11" keywords = [ "akamai", "Akamai Connected Cloud", @@ -25,11 +25,11 @@ classifiers = [ "License :: OSI Approved :: BSD License", "Programming Language :: Python", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", ] dependencies = ["requests", "polling", "deprecated"] dynamic = ["version"] @@ -49,7 +49,7 @@ int-test = [ "cryptography", ] lint = [ - "black>=23.1.0", + "black>=26.10.1", "isort>=5.12.0", "autoflake>=2.0.1", "pylint", @@ -85,7 +85,7 @@ line_length = 80 [tool.black] line-length = 80 -target-version = ["py310", "py311", "py312", "py313", "py314"] +target-version = ["py311", "py312", "py313", "py314", "py315"] [tool.autoflake] expand-star-imports = true From 3f58e517186227cf9cf5ea76840b3e6cb4feeb7b Mon Sep 17 00:00:00 2001 From: Erik Zilber Date: Mon, 30 Nov 2026 10:12:53 -0500 Subject: [PATCH 5/5] TPT-4596: NAT Service for VPC (#762) * TPT-4602: Added support for NAT Service #1033 (#738) * Added support for NAT Gateway * Fix lint * Address CoPilot suggestions * Added doc links * Address CoPilot fixes * Address more CoPilot suggestions * TPT-4602: Support NAT service int tests (#743) * Add int tests for networking NAT Gateway endpoints * Add int tests for VPC subnet with NAT Gateway * Remove condition for NAT gateway deletion * Refactor NAT Gateway integration tests * Clean up * Add fixture for Reserved IP created in the NAT Gateway region * Add test for NAT Gateway and Reserved IP in diff regions * Activate test skipped due to VPC-6253 (#749) * Removed VPC IP Changes * Updated NATGatewayType to include region_prices and transfer * Fix lint * Copilot fixes --------- Co-authored-by: Maciej Wilk --- linode_api4/groups/networking.py | 122 ++++++- linode_api4/groups/vpc.py | 28 +- linode_api4/objects/linode_interfaces.py | 33 ++ linode_api4/objects/networking.py | 245 +++++++++++++ linode_api4/objects/vpc.py | 76 +++- .../linode_instances_124_interfaces.json | 16 +- .../linode_instances_124_interfaces_456.json | 16 +- ...node_instances_124_upgrade-interfaces.json | 16 +- test/fixtures/networking_natgateways.json | 30 ++ .../networking_natgateways_42_addresses.json | 16 + ...natgateways_42_addresses_203.0.113.42.json | 8 + ..._42_addresses_203.0.113.42_interfaces.json | 23 ++ .../networking_natgateways_42_interfaces.json | 40 +++ .../networking_natgateways_settings.json | 6 + .../networking_natgateways_types.json | 29 ++ test/fixtures/vpcs_123456_subnets.json | 18 + test/fixtures/vpcs_123456_subnets_789.json | 18 + test/fixtures/vpcs_123456_subnets_790.json | 11 + test/integration/conftest.py | 47 +++ .../models/networking/test_networking.py | 328 +++++++++++++++--- test/integration/models/vpc/test_vpc.py | 21 +- test/unit/groups/networking_test.py | 93 ++++- test/unit/groups/vpc_test.py | 77 +++- test/unit/objects/linode_interface_test.py | 11 + test/unit/objects/networking_test.py | 178 ++++++++++ test/unit/objects/vpc_test.py | 111 +++++- 26 files changed, 1560 insertions(+), 57 deletions(-) create mode 100644 test/fixtures/networking_natgateways.json create mode 100644 test/fixtures/networking_natgateways_42_addresses.json create mode 100644 test/fixtures/networking_natgateways_42_addresses_203.0.113.42.json create mode 100644 test/fixtures/networking_natgateways_42_addresses_203.0.113.42_interfaces.json create mode 100644 test/fixtures/networking_natgateways_42_interfaces.json create mode 100644 test/fixtures/networking_natgateways_settings.json create mode 100644 test/fixtures/networking_natgateways_types.json create mode 100644 test/fixtures/vpcs_123456_subnets_790.json diff --git a/linode_api4/groups/networking.py b/linode_api4/groups/networking.py index bdcb5b7cb..721580da2 100644 --- a/linode_api4/groups/networking.py +++ b/linode_api4/groups/networking.py @@ -13,11 +13,18 @@ IPAddress, IPv6Pool, IPv6Range, + NATGateway, + NATGatewayAddress, NetworkTransferPrice, Region, ) from linode_api4.objects.base import _flatten_request_body_recursive -from linode_api4.objects.networking import ReservedIPAddress, ReservedIPType +from linode_api4.objects.networking import ( + NATGatewaySettings, + NATGatewayType, + ReservedIPAddress, + ReservedIPType, +) from linode_api4.paginated_list import PaginatedList from linode_api4.util import drop_null_keys @@ -622,3 +629,116 @@ def reserved_ip_types(self, *filters) -> PaginatedList: return self.client._get_and_filter( ReservedIPType, *filters, endpoint="/networking/reserved/ips/types" ) + + def natgateways(self, *filters): + """ + Retrieves the NAT Gateways your user has access to. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateways + + :param filters: Any number of filters to apply to this query. + See :doc:`Filtering Collections` + for more details on filtering. + + :returns: A list of NAT Gateways the acting user can access. + :rtype: PaginatedList of NATGateway + """ + return self.client._get_and_filter(NATGateway, *filters) + + def natgateway_create( + self, + region: Union[Region, str], + label: str, + addresses: Optional[ + List[Union[NATGatewayAddress, Dict[str, Any]]] + ] = None, + default_ports_per_interface: Optional[int] = None, + use_autoscaling: Optional[bool] = None, + vpc_subnet_id: Optional[int] = None, + **kwargs, + ) -> NATGateway: + """ + Create a NAT Gateway in the given region. + + NOTE: NAT Gateways may not currently be available to all users. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/post-natgateways + + :param region: The region in which to create the NAT Gateway. + :type region: str or Region + :param label: The label of the NAT Gateway. + :type label: str + :param addresses: The reserved IP addresses to assign to this NAT Gateway. + :type addresses: list of NATGatewayAddress or list of dict + :param default_ports_per_interface: The default ports per interface to use. + Defaults to 4096 on the API side. + :type default_ports_per_interface: int + :param use_autoscaling: Whether the NAT Gateway should autoscale its address pool. + :type use_autoscaling: bool + :param vpc_subnet_id: The ID of the VPC subnet this NAT Gateway should attach to. + :type vpc_subnet_id: int + + :returns: The new NAT Gateway. + :rtype: NATGateway + """ + params = { + "region": region.id if isinstance(region, Region) else region, + "label": label, + "addresses": addresses, + "default_ports_per_interface": default_ports_per_interface, + "use_autoscaling": use_autoscaling, + "vpc_subnet_id": vpc_subnet_id, + } + params.update(kwargs) + + result = self.client.post( + "/networking/natgateways", + data=drop_null_keys(_flatten_request_body_recursive(params)), + ) + + if "id" not in result: + raise UnexpectedResponseError( + "Unexpected response when creating NAT Gateway!", json=result + ) + + return NATGateway(self.client, result["id"], result) + + def natgateway_types(self, *filters) -> PaginatedList: + """ + Returns a list of NAT Gateway types with pricing information. + + NOTE: NAT Gateways may not currently be available to all users. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway-types + + :param filters: Any number of filters to apply to this query. + See :doc:`Filtering Collections` + for more details on filtering. + + :returns: A list of NAT Gateway types. + :rtype: PaginatedList of NATGatewayType + """ + return self.client._get_and_filter( + NATGatewayType, *filters, endpoint="/networking/natgateways/types" + ) + + def natgateway_settings(self) -> NATGatewaySettings: + """ + Returns the account-wide NAT Gateway settings and limits for the current user. + + NOTE: NAT Gateways may not currently be available to all users. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway-settings + + :returns: The NAT Gateway settings for the current user. + :rtype: NATGatewaySettings + """ + result = self.client.get("/networking/natgateways/settings") + + if "allowed_ports_per_interface" not in result: + raise UnexpectedResponseError( + "Unexpected response when getting NAT Gateway settings!", + json=result, + ) + + return NATGatewaySettings.from_json(result) diff --git a/linode_api4/groups/vpc.py b/linode_api4/groups/vpc.py index 947c6ff6f..167ca4487 100644 --- a/linode_api4/groups/vpc.py +++ b/linode_api4/groups/vpc.py @@ -93,10 +93,30 @@ def create( params.update(kwargs) - result = self.client.post( - "/vpcs", - data=drop_null_keys(_flatten_request_body_recursive(params)), - ) + data = drop_null_keys(_flatten_request_body_recursive(params)) + + # Recursively clean each subnet while preserving the ``{"id": null}`` + # detach signal on any explicitly-supplied ``natgateway`` object. + if subnets is not None: + cleaned_subnets = [] + for subnet in subnets: + flattened = _flatten_request_body_recursive(subnet) + cleaned = drop_null_keys(flattened) + + # If the caller explicitly supplied a ``natgateway`` field, + # re-inject its flattened (but not null-stripped) form so + # the detach signal survives. + if ( + isinstance(flattened, dict) + and "natgateway" in flattened + and flattened["natgateway"] is not None + ): + cleaned["natgateway"] = flattened["natgateway"] + + cleaned_subnets.append(cleaned) + data["subnets"] = cleaned_subnets + + result = self.client.post("/vpcs", data=data) if not "id" in result: raise UnexpectedResponseError( diff --git a/linode_api4/objects/linode_interfaces.py b/linode_api4/objects/linode_interfaces.py index 43c4192c4..742d49b3c 100644 --- a/linode_api4/objects/linode_interfaces.py +++ b/linode_api4/objects/linode_interfaces.py @@ -287,6 +287,38 @@ class LinodeInterfaceVPCIPv4Range(JSONObject): range: str = "" +@dataclass +class LinodeInterfaceVPCIPv4NATGatewayPortsetPort(JSONObject): + start: int = 0 + end: int = 0 + + +@dataclass +class LinodeInterfaceVPCIPv4NATGatewayPortset(JSONObject): + address: str = "" + ports: List[LinodeInterfaceVPCIPv4NATGatewayPortsetPort] = field( + default_factory=list + ) + + +@dataclass +class LinodeInterfaceVPCIPv4NATGateway(JSONObject): + """ + A NAT gateway under the IPv4 configuration of a VPC Linode Interface. + """ + + id: int = 0 + label: str = "" + type: str = "" + url: str = "" + addresses: List[str] = field(default_factory=list) + portset_assignments: int = 0 + portset_capacity: int = 0 + portsets: List[LinodeInterfaceVPCIPv4NATGatewayPortset] = field( + default_factory=list + ) # NOTE: This field may not be available to all users. + + @dataclass class LinodeInterfaceVPCIPv4(JSONObject): """ @@ -297,6 +329,7 @@ class LinodeInterfaceVPCIPv4(JSONObject): addresses: List[LinodeInterfaceVPCIPv4Address] = field(default_factory=list) ranges: List[LinodeInterfaceVPCIPv4Range] = field(default_factory=list) + natgateway: Optional[LinodeInterfaceVPCIPv4NATGateway] = None @dataclass diff --git a/linode_api4/objects/networking.py b/linode_api4/objects/networking.py index 7693953d5..e1d5e4285 100644 --- a/linode_api4/objects/networking.py +++ b/linode_api4/objects/networking.py @@ -7,6 +7,7 @@ from linode_api4.objects.dbase import DerivedBase from linode_api4.objects.region import Region from linode_api4.objects.serializable import JSONObject +from linode_api4.paginated_list import PaginatedList class IPv6Pool(Base): @@ -490,3 +491,247 @@ class ReservedIPType(Base): "price": Property(json_object=Price), "region_prices": Property(json_object=RegionPrice), } + + +@dataclass +class NATGatewayAddress(JSONObject): + address: str = "" + + +@dataclass +class NATGatewayVPCSubnet(JSONObject): + id: int = 0 + type: str = "" + label: str = "" + url: str = "" + vpc_id: int = 0 + vpc_label: str = "" + + +@dataclass +class NATGatewayAddressAssignment(JSONObject): + address: str = "" + in_use: bool = False + interface_count: int = 0 + interface_url: str = "" + portset_assignments: int = 0 + portset_capacity: int = 0 + + +@dataclass +class NATGatewayInterfaceLinode(JSONObject): + id: int = 0 + label: str = "" + type: str = "" + url: str = "" + + +@dataclass +class NATGatewayInterfacePortsetPort(JSONObject): + start: int = 0 + end: int = 0 + + +@dataclass +class NATGatewayInterfacePortset(JSONObject): + address: str = "" + ports: List[NATGatewayInterfacePortsetPort] = field(default_factory=list) + + +@dataclass +class NATGatewayInterface(JSONObject): + id: int = 0 + linode: Optional[NATGatewayInterfaceLinode] = None + addresses: List[str] = field(default_factory=list) + portsets: List[NATGatewayInterfacePortset] = field( + default_factory=list + ) # NOTE: This field may not be available to all users. + + +class NATGatewayType(Base): + """ + Represents a NAT Gateway type with pricing information. + + NOTE: NAT Gateways may not currently be available to all users. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway-types + """ + + properties = { + "id": Property(identifier=True), + "label": Property(), + "price": Property(json_object=Price), + "region_prices": Property(json_object=RegionPrice), + "transfer": Property(), + } + + +@dataclass +class NATGatewaySettings(JSONObject): + allowed_ports_per_interface: List[int] = field(default_factory=list) + maximum_autoscaling_addresses_per_natgateway: int = 0 + maximum_reserved_addresses_per_natgateway: int = 0 + + +class NATGateway(Base): + """ + Represents a single Linode NAT Gateway. + + API documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway + + NOTE: This feature may not currently be available to all users. + """ + + api_endpoint = "/networking/natgateways/{id}" + + id_attribute = "id" + + properties = { + "id": Property(identifier=True), + "region": Property(slug_relationship=Region), + "addresses": Property(json_object=NATGatewayAddress), + "address_autoscale_max": Property(), + "default_ports_per_interface": Property(), + "label": Property(mutable=True), + "portset_assignments": Property(), + "portset_capacity": Property(), + "vpc_subnet": Property(json_object=NATGatewayVPCSubnet), + "created": Property(is_datetime=True), + "updated": Property(is_datetime=True), + } + + def address_assignments(self, *filters) -> PaginatedList: + """ + Retrieves the reserved IP address assignments for this NAT Gateway. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway-addresses + + :param filters: Any number of filters to apply to this query. + See :doc:`Filtering Collections` + for more details on filtering. + + :returns: A paginated list of address assignments for this NAT Gateway. + :rtype: PaginatedList of NATGatewayAddressAssignment + """ + return self._client._get_and_filter( + NATGatewayAddressAssignment, + *filters, + endpoint="{}/addresses".format(NATGateway.api_endpoint).format( + id=self.id + ), + ) + + def address_assignment_view( + self, address: str + ) -> NATGatewayAddressAssignment: + """ + Retrieves a single reserved IP address assignment for this NAT Gateway. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway-address + + :param address: The reserved IPv4 address to look up. + :type address: str + + :returns: The requested address assignment. + :rtype: NATGatewayAddressAssignment + """ + result = self._client.get( + "{}/addresses/{}".format(NATGateway.api_endpoint, address), + model=self, + ) + return NATGatewayAddressAssignment.from_json(result) + + def address_assignment_create( + self, address: str + ) -> NATGatewayAddressAssignment: + """ + Assigns a reserved IP address to this NAT Gateway. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/post-natgateway-address + + :param address: The reserved IPv4 address to assign to this NAT Gateway. + :type address: str + + :returns: The new address assignment. + :rtype: NATGatewayAddressAssignment + """ + result = self._client.post( + "{}/addresses".format(NATGateway.api_endpoint), + model=self, + data={"address": address}, + ) + self.invalidate() + + if "address" not in result: + raise UnexpectedResponseError( + "Unexpected response when assigning address to NAT Gateway!", + json=result, + ) + + return NATGatewayAddressAssignment.from_json(result) + + def address_assignment_delete(self, address: str) -> bool: + """ + Removes a reserved IP address assignment from this NAT Gateway. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/delete-natgateway-address + + :param address: The reserved IPv4 address to remove from this NAT Gateway. + :type address: str + + :returns: True if the delete request succeeded. + :rtype: bool + """ + resp = self._client.delete( + "{}/addresses/{}".format(NATGateway.api_endpoint, address), + model=self, + ) + self.invalidate() + + if "error" in resp: + return False + return True + + def interfaces(self, *filters) -> PaginatedList: + """ + Retrieves the Linode Interfaces attached to this NAT Gateway. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway-interfaces + + :param filters: Any number of filters to apply to this query. + See :doc:`Filtering Collections` + for more details on filtering. + + :returns: A paginated list of interfaces attached to this NAT Gateway. + :rtype: PaginatedList of NATGatewayInterface + """ + return self._client._get_and_filter( + NATGatewayInterface, + *filters, + endpoint="{}/interfaces".format(NATGateway.api_endpoint).format( + id=self.id + ), + ) + + def address_interfaces(self, address: str, *filters) -> PaginatedList: + """ + Retrieves the Linode Interfaces using the given reserved IP address on this NAT Gateway. + + API Documentation: https://techdocs.akamai.com/linode-api/reference/get-natgateway-address-interfaces + + :param address: The reserved IPv4 address to look up interfaces for. + :type address: str + :param filters: Any number of filters to apply to this query. + See :doc:`Filtering Collections` + for more details on filtering. + + :returns: A paginated list of interfaces using the given address. + :rtype: PaginatedList of NATGatewayInterface + """ + return self._client._get_and_filter( + NATGatewayInterface, + *filters, + endpoint="{}/addresses/{}/interfaces".format( + NATGateway.api_endpoint, address + ).format(id=self.id), + ) diff --git a/linode_api4/objects/vpc.py b/linode_api4/objects/vpc.py index 4a4df9e35..2e4edfda4 100644 --- a/linode_api4/objects/vpc.py +++ b/linode_api4/objects/vpc.py @@ -1,4 +1,4 @@ -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Union from linode_api4.errors import UnexpectedResponseError @@ -110,6 +110,58 @@ class VPCSubnetDatabase(JSONObject): ipv6_ranges: Optional[List[str]] = None +@dataclass +class VPCSubnetNATGatewayOptions(JSONObject): + """ + VPCSubnetNATGatewayOptions is used to specify a NAT Gateway when creating or updating a VPC subnet. + + To attach or change the NAT Gateway on a subnet, set ``id`` to the ID of the target NAT Gateway:: + + subnet.natgateway = VPCSubnetNATGatewayOptions(id=42) + subnet.save() + + To disconnect the NAT Gateway from a subnet, set ``id`` to ``None`` (or :any:`ExplicitNullValue`):: + + subnet.natgateway = VPCSubnetNATGatewayOptions(id=None) + subnet.save() + + To update other fields without touching the NAT Gateway, simply do not modify the ``natgateway`` + attribute before calling ``save()``. + """ + + # Ensure ``id`` is always included in the serialized payload so that + # ``VPCSubnetNATGatewayOptions(id=None)`` produces ``{"id": null}`` which + # signals the API to disconnect the NAT Gateway from the subnet. + always_include = {"id"} + + id: Optional[int] = None + + +@dataclass +class VPCSubnetNATGatewayPortsetPort(JSONObject): + start: int = 0 + end: int = 0 + + +@dataclass +class VPCSubnetNATGatewayPortset(JSONObject): + address: str = "" + ports: List[VPCSubnetNATGatewayPortsetPort] = field(default_factory=list) + + +@dataclass +class VPCSubnetNATGateway(JSONObject): + put_class = VPCSubnetNATGatewayOptions + + id: int = 0 + label: str = "" + addresses: List[str] = field(default_factory=list) + portset_assignments: int = 0 + portset_capacity: int = 0 + # NOTE: This field may not be available to all users. + portsets: List[VPCSubnetNATGatewayPortset] = field(default_factory=list) + + class VPCSubnet(DerivedBase): """ An instance of a VPC subnet. @@ -129,6 +181,7 @@ class VPCSubnet(DerivedBase): "linodes": Property(json_object=VPCSubnetLinode, unordered=True), "databases": Property(json_object=VPCSubnetDatabase, unordered=True), "vpc_type": Property(), + "natgateway": Property(json_object=VPCSubnetNATGateway, mutable=True), "created": Property(is_datetime=True), "updated": Property(is_datetime=True), } @@ -166,6 +219,9 @@ def subnet_create( ipv6: Optional[ List[Union[VPCSubnetIPv6RangeOptions, Dict[str, Any]]] ] = None, + natgateway: Optional[ + Union[VPCSubnetNATGatewayOptions, Dict[str, Any]] + ] = None, **kwargs, ) -> VPCSubnet: """ @@ -179,15 +235,29 @@ def subnet_create( :type ipv4: str :param ipv6: The IPv6 range of this subnet in CIDR format. :type ipv6: List[Union[VPCSubnetIPv6RangeOptions, Dict[str, Any]]] + :param natgateway: The NAT gateway options for this subnet. NOTE: May not be available for all users. + :type natgateway: VPCSubnetNATGatewayOptions """ - params = {"label": label, "ipv4": ipv4, "ipv6": ipv6} + params = { + "label": label, + "ipv4": ipv4, + "ipv6": ipv6, + } params.update(kwargs) + data = drop_null_keys(_flatten_request_body_recursive(params)) + + # Preserve the ``{"id": null}`` detach signal separately: ``drop_null_keys`` + # is recursive and would otherwise strip an explicit ``id: None`` inside + # ``natgateway``, collapsing the detach payload to ``{}``. + if natgateway is not None: + data["natgateway"] = _flatten_request_body_recursive(natgateway) + result = self._client.post( "{}/subnets".format(VPC.api_endpoint), model=self, - data=drop_null_keys(_flatten_request_body_recursive(params)), + data=data, ) self.invalidate() diff --git a/test/fixtures/linode_instances_124_interfaces.json b/test/fixtures/linode_instances_124_interfaces.json index dbb6f79fb..5f74fc53a 100644 --- a/test/fixtures/linode_instances_124_interfaces.json +++ b/test/fixtures/linode_instances_124_interfaces.json @@ -79,7 +79,21 @@ { "range": "192.168.22.32/28" } - ] + ], + "natgateway": { + "id": 42, + "label": "the-natgateway", + "type": "natgateway", + "url": "/v4/networking/natgateways/42", + "addresses": [ "203.0.113.42" ], + "portset_capacity": 30, + "portsets": [ + { + "address": "203.0.113.42", + "ports": [{"start": 2048, "end": 3071}] + } + ] + } }, "ipv6": { "is_public": true, diff --git a/test/fixtures/linode_instances_124_interfaces_456.json b/test/fixtures/linode_instances_124_interfaces_456.json index 8ec4abd3d..524a49c96 100644 --- a/test/fixtures/linode_instances_124_interfaces_456.json +++ b/test/fixtures/linode_instances_124_interfaces_456.json @@ -20,7 +20,21 @@ "ranges": [ { "range": "192.168.22.16/28"}, { "range": "192.168.22.32/28"} - ] + ], + "natgateway": { + "id": 42, + "label": "the-natgateway", + "type": "natgateway", + "url": "/v4/networking/natgateways/42", + "addresses": [ "203.0.113.42" ], + "portset_capacity": 30, + "portsets": [ + { + "address": "203.0.113.42", + "ports": [{"start": 2048, "end": 3071}] + } + ] + } }, "ipv6": { "is_public": true, diff --git a/test/fixtures/linode_instances_124_upgrade-interfaces.json b/test/fixtures/linode_instances_124_upgrade-interfaces.json index fa1015029..a82045ab9 100644 --- a/test/fixtures/linode_instances_124_upgrade-interfaces.json +++ b/test/fixtures/linode_instances_124_upgrade-interfaces.json @@ -81,7 +81,21 @@ { "range": "192.168.22.32/28" } - ] + ], + "natgateway": { + "id": 42, + "label": "the-natgateway", + "type": "natgateway", + "url": "/v4/networking/natgateways/42", + "addresses": [ "203.0.113.42" ], + "portset_capacity": 30, + "portsets": [ + { + "address": "203.0.113.42", + "ports": [{"start": 2048, "end": 3071}] + } + ] + } }, "ipv6": { "is_public": true, diff --git a/test/fixtures/networking_natgateways.json b/test/fixtures/networking_natgateways.json new file mode 100644 index 000000000..b4b74891f --- /dev/null +++ b/test/fixtures/networking_natgateways.json @@ -0,0 +1,30 @@ +{ + "data": [ + { + "id": 42, + "label": "the-natgateway", + "region": "us-east", + "addresses": [ + {"address": "203.0.113.42"} + ], + "address_autoscale_max": 4, + "default_ports_per_interface": 4096, + "portset_assignments": 15, + "portset_capacity": 30, + "vpc_subnet": { + "id": 789, + "type": "subnet", + "label": "my-subnet", + "url": "/v4/vpcs/123456/subnets/789", + "vpc_id": 123456, + "vpc_label": "my-vpc" + }, + "created": "2018-01-01T00:01:01", + "updated": "2018-01-01T00:01:01" + } + ], + "page": 1, + "pages": 1, + "results": 1 +} + diff --git a/test/fixtures/networking_natgateways_42_addresses.json b/test/fixtures/networking_natgateways_42_addresses.json new file mode 100644 index 000000000..1c44b27f7 --- /dev/null +++ b/test/fixtures/networking_natgateways_42_addresses.json @@ -0,0 +1,16 @@ +{ + "data": [ + { + "address": "203.0.113.42", + "in_use": true, + "interface_count": 1, + "interface_url": "/v4/networking/natgateways/42/addresses/203.0.113.42/interfaces", + "portset_assignments": 15, + "portset_capacity": 30 + } + ], + "page": 1, + "pages": 1, + "results": 1 +} + diff --git a/test/fixtures/networking_natgateways_42_addresses_203.0.113.42.json b/test/fixtures/networking_natgateways_42_addresses_203.0.113.42.json new file mode 100644 index 000000000..313810cfe --- /dev/null +++ b/test/fixtures/networking_natgateways_42_addresses_203.0.113.42.json @@ -0,0 +1,8 @@ +{ + "address": "203.0.113.42", + "in_use": true, + "interface_count": 1, + "interface_url": "/v4/networking/natgateways/42/addresses/203.0.113.42/interfaces", + "portset_assignments": 15, + "portset_capacity": 30 +} diff --git a/test/fixtures/networking_natgateways_42_addresses_203.0.113.42_interfaces.json b/test/fixtures/networking_natgateways_42_addresses_203.0.113.42_interfaces.json new file mode 100644 index 000000000..15b94a8b1 --- /dev/null +++ b/test/fixtures/networking_natgateways_42_addresses_203.0.113.42_interfaces.json @@ -0,0 +1,23 @@ +{ + "data": [ + { + "id": 142, + "linode": { + "id": 1001, + "label": "linode1001", + "type": "linode", + "url": "/v4/linode/instances/1001" + }, + "addresses": ["203.0.113.42"], + "portsets": [ + { + "address": "203.0.113.42", + "ports": [{"start": 2048, "end": 3071}] + } + ] + } + ], + "page": 1, + "pages": 1, + "results": 1 +} diff --git a/test/fixtures/networking_natgateways_42_interfaces.json b/test/fixtures/networking_natgateways_42_interfaces.json new file mode 100644 index 000000000..8d85d9c6d --- /dev/null +++ b/test/fixtures/networking_natgateways_42_interfaces.json @@ -0,0 +1,40 @@ +{ + "data": [ + { + "id": 142, + "linode": { + "id": 1001, + "label": "linode1001", + "type": "linode", + "url": "/v4/linode/instances/1001" + }, + "addresses": ["203.0.113.42"], + "portsets": [ + { + "address": "203.0.113.42", + "ports": [{"start": 2048, "end": 3071}] + } + ] + }, + { + "id": 143, + "linode": { + "id": 1002, + "label": "linode1002", + "type": "linode", + "url": "/v4/linode/instances/1002" + }, + "addresses": ["203.0.113.43"], + "portsets": [ + { + "address": "203.0.113.43", + "ports": [{"start": 3072, "end": 4095}] + } + ] + } + ], + "page": 1, + "pages": 1, + "results": 2 +} + diff --git a/test/fixtures/networking_natgateways_settings.json b/test/fixtures/networking_natgateways_settings.json new file mode 100644 index 000000000..6faa25ee0 --- /dev/null +++ b/test/fixtures/networking_natgateways_settings.json @@ -0,0 +1,6 @@ +{ + "allowed_ports_per_interface": [4096, 8192, 16384], + "maximum_autoscaling_addresses_per_natgateway": 100, + "maximum_reserved_addresses_per_natgateway": 100 +} + diff --git a/test/fixtures/networking_natgateways_types.json b/test/fixtures/networking_natgateways_types.json new file mode 100644 index 000000000..d1ac54e68 --- /dev/null +++ b/test/fixtures/networking_natgateways_types.json @@ -0,0 +1,29 @@ +{ + "data": [ + { + "id": "g1-natgateway", + "label": "NAT Gateway", + "price": { + "hourly": 0.035, + "monthly": 25 + }, + "region_prices": [ + { + "id": "us-east", + "hourly": 0.036, + "monthly": 26 + }, + { + "id": "br-gru", + "hourly": 0.041, + "monthly": 30 + } + ], + "transfer": 1000 + } + ], + "page": 1, + "pages": 1, + "results": 1 +} + diff --git a/test/fixtures/vpcs_123456_subnets.json b/test/fixtures/vpcs_123456_subnets.json index e387e0215..b98cacf58 100644 --- a/test/fixtures/vpcs_123456_subnets.json +++ b/test/fixtures/vpcs_123456_subnets.json @@ -36,6 +36,24 @@ } ], "vpc_type": "regular", + "natgateway": { + "id": 42, + "label": "my-nat-gateway", + "addresses": [ "203.0.113.42" ], + "portset_assignments": 15, + "portset_capacity": 30, + "portsets": [ + { + "address": "203.0.113.42", + "ports": [ + { + "start": 2048, + "end": 3071 + } + ] + } + ] + }, "created": "2018-01-01T00:01:01", "updated": "2018-01-01T00:01:01" } diff --git a/test/fixtures/vpcs_123456_subnets_789.json b/test/fixtures/vpcs_123456_subnets_789.json index b58c382db..8b0db7069 100644 --- a/test/fixtures/vpcs_123456_subnets_789.json +++ b/test/fixtures/vpcs_123456_subnets_789.json @@ -34,6 +34,24 @@ ] } ], + "natgateway": { + "id": 42, + "label": "my-nat-gateway", + "addresses": [ "203.0.113.42" ], + "portset_assignments": 15, + "portset_capacity": 30, + "portsets": [ + { + "address": "203.0.113.42", + "ports": [ + { + "start": 2048, + "end": 3071 + } + ] + } + ] + }, "created": "2018-01-01T00:01:01", "updated": "2018-01-01T00:01:01" } \ No newline at end of file diff --git a/test/fixtures/vpcs_123456_subnets_790.json b/test/fixtures/vpcs_123456_subnets_790.json new file mode 100644 index 000000000..ccfc9d085 --- /dev/null +++ b/test/fixtures/vpcs_123456_subnets_790.json @@ -0,0 +1,11 @@ +{ + "id": 790, + "label": "no-gateway-subnet", + "ipv4": "10.0.1.0/24", + "ipv6": [], + "linodes": [], + "databases": [], + "created": "2018-01-01T00:01:01", + "updated": "2018-01-01T00:01:01" +} + diff --git a/test/integration/conftest.py b/test/integration/conftest.py index 9c845f117..c002dcf31 100644 --- a/test/integration/conftest.py +++ b/test/integration/conftest.py @@ -18,6 +18,7 @@ from requests.exceptions import ConnectionError, RequestException from linode_api4 import ( + Capability, Instance, InterfaceGeneration, IPAddress, @@ -963,3 +964,49 @@ def create_reserved_ip_assigned(test_linode_client, create_linode): IPAddress.address == reserved_ip.address ): address[0].delete() + + +@pytest.fixture +def create_nat_gateway(request, test_linode_client): + client = test_linode_client + label = "nat-gateway-" + get_test_label(length=8) + autoscaling = getattr(request, "param", True) + region = get_region( + client, + { + Capability.firewall, + Capability.linodes, + Capability.linode_interfaces, + Capability.natgateway, + Capability.vpcs, + Capability.vpc_dual_stack, + Capability.vpc_ipv6_stack, + }, + ) + + gateway = client.networking.natgateway_create( + label=label, + region=region, + use_autoscaling=autoscaling, + ) + + yield gateway + + gateway.delete() + + +@pytest.fixture +def create_nat_vpc(test_linode_client, create_nat_gateway): + client = test_linode_client + gateway = create_nat_gateway + label = get_test_label(length=10) + + vpc = client.vpcs.create( + label=label, + region=gateway.region, + description="test NAT Gateway VPC", + ipv6=[{"range": "auto"}], + ) + yield vpc + + vpc.delete() diff --git a/test/integration/models/networking/test_networking.py b/test/integration/models/networking/test_networking.py index de5b53f4c..37e823f6f 100644 --- a/test/integration/models/networking/test_networking.py +++ b/test/integration/models/networking/test_networking.py @@ -15,14 +15,27 @@ import pytest import requests -from linode_api4 import ApiError, Instance, LinodeClient +from linode_api4 import ( + ApiError, + Capability, + Instance, + InterfaceGeneration, + LinodeClient, +) from linode_api4.objects import ( Capability, Config, ConfigInterfaceIPv4, Firewall, IPAddress, + LinodeInterfaceDefaultRouteOptions, + LinodeInterfaceVPCIPv4AddressOptions, + LinodeInterfaceVPCIPv4Options, + LinodeInterfaceVPCIPv4RangeOptions, + LinodeInterfaceVPCOptions, + NATGateway, ReservedIPAddress, + VPCSubnetNATGatewayOptions, ) from linode_api4.objects.networking import ( FirewallCreateDevicesOptions, @@ -75,18 +88,6 @@ def create_linode_to_be_shared_with_ips(test_linode_client): linode.delete() -@pytest.mark.smoke -def test_get_networking_rules(test_linode_client, test_firewall): - firewall = test_linode_client.load(Firewall, test_firewall.id) - - rules = firewall.get_rules() - - assert "inbound" in str(rules) - assert "inbound_policy" in str(rules) - assert "outbound" in str(rules) - assert "outbound_policy" in str(rules) - - @pytest.fixture def create_linode_without_firewall(test_linode_client): """ @@ -128,6 +129,120 @@ def create_firewall_with_device(create_linode_without_firewall): firewall.delete() +@pytest.fixture +def create_nat_reserved_ip(test_linode_client, create_nat_gateway): + client = test_linode_client + gateway = create_nat_gateway + + reserved_ip = client.networking.reserved_ip_create(region=gateway.region) + + yield reserved_ip + + reserved_ip.delete() + + +@pytest.fixture +def create_nat_vpc_with_subnet(test_linode_client, create_nat_vpc): + subnet = create_nat_vpc.subnet_create( + label="test-nat-subnet", + ipv4="10.0.0.0/24", + ipv6=[{"range": "auto"}], + ) + + yield create_nat_vpc, subnet + + subnet.delete() + + +@pytest.fixture +def create_nat_vpc_with_subnet_and_linode( + test_linode_client, create_nat_vpc_with_subnet, e2e_test_firewall +): + vpc, subnet = create_nat_vpc_with_subnet + + instance = test_linode_client.linode.instance_create( + "g6-standard-1", + vpc.region, + label=get_test_label(length=8), + firewall=e2e_test_firewall, + interface_generation=InterfaceGeneration.LINODE, + booted=False, + ) + + yield vpc, subnet, instance + + instance.delete() + + +def verify_reserved_ip(reserved_ip): + assert isinstance( + ipaddress.ip_address(reserved_ip.address), ipaddress.IPv4Address + ) + assert reserved_ip.type == "ipv4" + assert reserved_ip.public == True + assert reserved_ip.reserved == True + assert reserved_ip.linode_id is None + assert reserved_ip.assigned_entity is None + + +def verify_reserved_ip_assigned(reserved_ip, resource): + assert isinstance( + ipaddress.ip_address(reserved_ip.address), ipaddress.IPv4Address + ) + assert reserved_ip.type == "ipv4" + assert reserved_ip.public == True + assert reserved_ip.reserved == True + assert reserved_ip.linode_id == resource.id + assert reserved_ip.region.id == resource.region.id + assert reserved_ip.assigned_entity.id == resource.id + assert reserved_ip.assigned_entity.type == "linode" + assert reserved_ip.assigned_entity.label == resource.label + assert ( + reserved_ip.assigned_entity.url == f"/v4/linode/instances/{resource.id}" + ) + + +def verify_nat_gateway(nat_gateway, nat_gateway_read): + assert nat_gateway_read.id == nat_gateway.id + assert nat_gateway_read.region.id == nat_gateway.region.id + assert nat_gateway_read.label == nat_gateway.label + assert len(nat_gateway_read.addresses) == 0 + assert nat_gateway_read.address_autoscale_max > 0 + assert nat_gateway_read.default_ports_per_interface == 4096 + assert nat_gateway_read.portset_assignments == 0 + assert nat_gateway_read.portset_capacity > 0 + + +def verify_nat_gateway_address(nat_address, reserved_ip_address): + assert nat_address.address == reserved_ip_address + assert nat_address.in_use == False + assert nat_address.interface_count == 0 + assert nat_address.interface_url.endswith( + f"/{reserved_ip_address}/interfaces" + ) + assert nat_address.portset_assignments == 0 + assert nat_address.portset_capacity > 0 + + +def verify_nat_gateway_interface(interface, linode, reserved_ip): + assert interface.id == linode.linode_interfaces[0].id + assert interface.linode.id == linode.id + assert interface.addresses[0] == reserved_ip.address + assert interface.portsets[0].address == reserved_ip.address + + +@pytest.mark.smoke +def test_get_networking_rules(test_linode_client, test_firewall): + firewall = test_linode_client.load(Firewall, test_firewall.id) + + rules = firewall.get_rules() + + assert "inbound" in str(rules) + assert "inbound_policy" in str(rules) + assert "outbound" in str(rules) + assert "outbound_policy" in str(rules) + + def test_get_networking_rule_versions(test_linode_client, test_firewall): firewall = test_linode_client.load(Firewall, test_firewall.id) @@ -363,34 +478,6 @@ def test_ip_info(test_linode_client, create_linode): assert ip_info.vpc_nat_1_1 is None -def verify_reserved_ip(reserved_ip): - assert isinstance( - ipaddress.ip_address(reserved_ip.address), ipaddress.IPv4Address - ) - assert reserved_ip.type == "ipv4" - assert reserved_ip.public == True - assert reserved_ip.reserved == True - assert reserved_ip.linode_id is None - assert reserved_ip.assigned_entity is None - - -def verify_reserved_ip_assigned(reserved_ip, resource): - assert isinstance( - ipaddress.ip_address(reserved_ip.address), ipaddress.IPv4Address - ) - assert reserved_ip.type == "ipv4" - assert reserved_ip.public == True - assert reserved_ip.reserved == True - assert reserved_ip.linode_id == resource.id - assert reserved_ip.region.id == resource.region.id - assert reserved_ip.assigned_entity.id == resource.id - assert reserved_ip.assigned_entity.type == "linode" - assert reserved_ip.assigned_entity.label == resource.label - assert ( - reserved_ip.assigned_entity.url == f"/v4/linode/instances/{resource.id}" - ) - - @pytest.mark.smoke @pytest.mark.parametrize( "region, tags, expected", @@ -556,3 +643,162 @@ def test_convert_unassigned_reserved_ip_to_ephemeral( ReservedIPAddress.address == reserved_ip.address ) assert len(reserved_ips_list) == 0 + + +@pytest.mark.smoke +def test_create_nat_gateway(test_linode_client, create_nat_gateway): + client = test_linode_client + + gateway = client.load(NATGateway, create_nat_gateway.id) + verify_nat_gateway(create_nat_gateway, gateway) + + gateways = client.networking.natgateways( + NATGateway.label == create_nat_gateway.label + ) + assert len(gateways) == 1 + verify_nat_gateway(create_nat_gateway, gateways[0]) + + +def test_update_nat_gateway(test_linode_client, create_nat_gateway): + client = test_linode_client + gateway = create_nat_gateway + + new_label = f"{gateway.label}-updated" + gateway.label = new_label + gateway.save() + + gateway_updated = client.load(NATGateway, gateway.id) + assert gateway_updated.label == new_label + + +@pytest.mark.parametrize("create_nat_gateway", [False], indirect=True) +def test_assign_nat_gateway_ip_address( + test_linode_client, create_nat_gateway, create_nat_reserved_ip +): + gateway = create_nat_gateway + reserved_ip = create_nat_reserved_ip + + gateway.address_assignment_create(reserved_ip.address) + + addresses = gateway.address_assignments() + assert len(addresses) == 1 + verify_nat_gateway_address(addresses[0], reserved_ip.address) + + address = gateway.address_assignment_view(reserved_ip.address) + verify_nat_gateway_address(address, reserved_ip.address) + + gateway.address_assignment_delete(reserved_ip.address) + addresses = gateway.address_assignments() + assert len(addresses) == 0 + + +@pytest.mark.parametrize("create_nat_gateway", [False], indirect=True) +def test_get_nat_gateway_linode_ifaces( + test_linode_client, + e2e_test_firewall, + create_nat_gateway, + create_nat_vpc_with_subnet_and_linode, + create_nat_reserved_ip, +): + client = test_linode_client + gateway = create_nat_gateway + vpc, subnet, linode = create_nat_vpc_with_subnet_and_linode + reserved_ip = create_nat_reserved_ip + + gateway.address_assignment_create(reserved_ip.address) + # Link the NAT Gateway to the VPC Subnet + subnet.natgateway = VPCSubnetNATGatewayOptions(id=gateway.id) + subnet.save() + + linode.interface_create( + firewall_id=e2e_test_firewall, + default_route=LinodeInterfaceDefaultRouteOptions( + ipv4=True, + ), + vpc=LinodeInterfaceVPCOptions( + subnet_id=subnet.id, + ipv4=LinodeInterfaceVPCIPv4Options( + addresses=[ + LinodeInterfaceVPCIPv4AddressOptions( + address="auto", + primary=True, + nat_1_1_address=None, + ) + ], + ranges=[ + LinodeInterfaceVPCIPv4RangeOptions( + range="/32", + ) + ], + ), + ), + ) + linode = client.load(Instance, linode.id) + + gateway_ifaces = gateway.interfaces() + assert len(gateway_ifaces) == 1 + verify_nat_gateway_interface(gateway_ifaces[0], linode, reserved_ip) + + gateway_ifaces = gateway.address_interfaces(reserved_ip.address) + verify_nat_gateway_interface(gateway_ifaces[0], linode, reserved_ip) + + address = gateway.address_assignment_view(reserved_ip.address) + assert address.in_use == True + assert address.interface_count == 1 + assert address.portset_assignments == 1 + + +def test_get_nat_gateway_types(test_linode_client): + client = test_linode_client + + gateway_types = client.networking.natgateway_types() + assert len(gateway_types) > 0 + assert gateway_types[0].id == "g1-natgateway" + assert gateway_types[0].label == "NAT Gateway" + assert ( + gateway_types[0].price.hourly >= 0 + or gateway_types[0].price.monthly >= 0 + ) + assert isinstance(gateway_types[0].region_prices, list) + assert isinstance(gateway_types[0].transfer, int) + + +def test_get_nat_gateway_settings(test_linode_client): + client = test_linode_client + + gateway_settings = client.networking.natgateway_settings() + assert all( + port in [4096, 8192, 16384] + for port in gateway_settings.allowed_ports_per_interface + ) + assert gateway_settings.maximum_autoscaling_addresses_per_natgateway > 0 + assert gateway_settings.maximum_reserved_addresses_per_natgateway > 0 + + +@pytest.mark.parametrize("create_nat_gateway", [False], indirect=True) +def test_assign_nat_gateway_ip_address_in_diff_region_fail( + test_linode_client, create_nat_gateway +): + client = test_linode_client + gateway = create_nat_gateway + region = get_region( + client, {Capability.linodes, Capability.firewall}, site_type="core" + ) + + while region.id == gateway.region.id: + region = get_region( + client, {Capability.linodes, Capability.firewall}, site_type="core" + ) + + reserved_ip = client.networking.reserved_ip_create(region=region) + + try: + with pytest.raises(ApiError) as err: + gateway.address_assignment_create(reserved_ip.address) + assert "[400] address: The provided IP was not found" in str(err.value) + + addresses = gateway.address_assignments() + assert len(addresses) == 0 + + finally: + reserved_ip.delete() diff --git a/test/integration/models/vpc/test_vpc.py b/test/integration/models/vpc/test_vpc.py index 5d9473b53..2a983a44b 100644 --- a/test/integration/models/vpc/test_vpc.py +++ b/test/integration/models/vpc/test_vpc.py @@ -3,7 +3,7 @@ import pytest from linode_api4 import VPC, ApiError, VPCIPv4DefaultRange, VPCSubnet -from linode_api4.objects import Capability +from linode_api4.objects import Capability, VPCSubnetNATGatewayOptions @pytest.mark.smoke @@ -201,3 +201,22 @@ def test_vpc_with_ipv4(test_linode_client, create_vpc_with_ipv4): updated_vpc = client.load(VPC, vpc.id) assert updated_vpc.ipv4[0].range == "192.168.0.0/17" + + +def test_vpc_subnet_with_nat_gateway( + request, test_linode_client, create_nat_gateway, create_nat_vpc +): + client = test_linode_client + gateway = create_nat_gateway + vpc = create_nat_vpc + + subnet = vpc.subnet_create( + label="test-nat-subnet", + ipv4="10.0.0.0/24", + ipv6=[{"range": "auto"}], + natgateway=VPCSubnetNATGatewayOptions(id=gateway.id), + ) + request.addfinalizer(subnet.delete) + + subnet = client.load(VPCSubnet, subnet.id, vpc.id) + assert subnet.natgateway.id == gateway.id diff --git a/test/unit/groups/networking_test.py b/test/unit/groups/networking_test.py index 6503b426f..4dd9c5e81 100644 --- a/test/unit/groups/networking_test.py +++ b/test/unit/groups/networking_test.py @@ -1,7 +1,13 @@ from test.unit.base import ClientBaseCase, MethodMock from test.unit.objects.firewall_test import FirewallTemplatesTest +from test.unit.objects.networking_test import NATGatewayTest -from linode_api4.objects.networking import ReservedIPAddress +from linode_api4.objects import NATGateway, NATGatewayAddress +from linode_api4.objects.networking import ( + NATGatewaySettings, + NATGatewayType, + ReservedIPAddress, +) class NetworkingGroupTest(ClientBaseCase): @@ -238,3 +244,88 @@ def test_ip_allocate_rejects_region_when_not_reserved(self): "region is only valid when reserved is True." ) assert m.called is False + + def test_list_natgateways(self): + """ + Tests that NAT Gateways can be listed via GET /networking/natgateways. + """ + natgateways = self.client.networking.natgateways() + + assert len(natgateways) == 1 + NATGatewayTest.assert_natgateway_42(natgateways[0]) + + def test_natgateway_create(self): + """ + Tests that natgateway_create sends the correct POST body and returns a NATGateway. + """ + with self.mock_post("/networking/natgateways/42") as m: + result = self.client.networking.natgateway_create( + region="us-east", + label="the-natgateway", + addresses=[NATGatewayAddress(address="203.0.113.42")], + default_ports_per_interface=4096, + use_autoscaling=True, + vpc_subnet_id=789, + ) + + assert m.call_url == "/networking/natgateways" + assert m.call_data == { + "region": "us-east", + "label": "the-natgateway", + "addresses": [{"address": "203.0.113.42"}], + "default_ports_per_interface": 4096, + "use_autoscaling": True, + "vpc_subnet_id": 789, + } + + assert isinstance(result, NATGateway) + NATGatewayTest.assert_natgateway_42(result) + + def test_natgateway_create_minimal(self): + """ + Tests that natgateway_create with only required fields omits optional fields + and accepts raw dict form for addresses. + """ + with self.mock_post("/networking/natgateways/42") as m: + self.client.networking.natgateway_create( + region="us-east", + label="the-natgateway", + addresses=[{"address": "203.0.113.42"}], + ) + + assert m.call_data == { + "region": "us-east", + "label": "the-natgateway", + "addresses": [{"address": "203.0.113.42"}], + } + + def test_natgateway_types(self): + """ + Tests GET /networking/natgateways/types. + """ + types = self.client.networking.natgateway_types() + + assert len(types) == 1 + + t = types[0] + assert isinstance(t, NATGatewayType) + assert t.id == "g1-natgateway" + assert t.label == "NAT Gateway" + assert t.price.hourly == 0.035 + assert t.price.monthly == 25 + assert len(t.region_prices) == 2 + assert t.region_prices[0].id == "us-east" + assert t.region_prices[0].hourly == 0.036 + assert t.region_prices[0].monthly == 26 + assert t.transfer == 1000 + + def test_natgateway_settings(self): + """ + Tests GET /networking/natgateways/settings. + """ + settings = self.client.networking.natgateway_settings() + + assert isinstance(settings, NATGatewaySettings) + assert settings.allowed_ports_per_interface == [4096, 8192, 16384] + assert settings.maximum_autoscaling_addresses_per_natgateway == 100 + assert settings.maximum_reserved_addresses_per_natgateway == 100 diff --git a/test/unit/groups/vpc_test.py b/test/unit/groups/vpc_test.py index fbeda5f3a..2d93a1998 100644 --- a/test/unit/groups/vpc_test.py +++ b/test/unit/groups/vpc_test.py @@ -1,7 +1,13 @@ import datetime from test.unit.base import ClientBaseCase -from linode_api4 import DATE_FORMAT, VPC, VPCIPv4DefaultRange, VPCSubnet +from linode_api4 import ( + DATE_FORMAT, + VPC, + VPCIPv4DefaultRange, + VPCSubnet, + VPCSubnetNATGatewayOptions, +) class VPCTest(ClientBaseCase): @@ -58,6 +64,75 @@ def test_create_vpc_with_subnet(self): self.assertEqual(vpc._populated, True) self.validate_vpc_123456(vpc) + def test_create_vpc_with_subnet_natgateway(self): + """ + Tests that a subnet's natgateway is correctly serialized. + """ + + with self.mock_post("/vpcs/123456") as m: + vpc = self.client.vpcs.create( + "test-vpc", + "us-southeast", + subnets=[ + { + "label": "test-subnet", + "ipv4": "10.0.0.0/24", + "natgateway": VPCSubnetNATGatewayOptions(id=42), + }, + ], + ) + + self.assertEqual(m.call_url, "/vpcs") + + self.assertEqual( + m.call_data, + { + "label": "test-vpc", + "region": "us-southeast", + "subnets": [ + { + "label": "test-subnet", + "ipv4": "10.0.0.0/24", + "natgateway": {"id": 42}, + }, + ], + }, + ) + + self.assertEqual(vpc._populated, True) + self.validate_vpc_123456(vpc) + + def test_create_vpc_with_subnet_natgateway_detach_signal(self): + """ + Tests that a subnet's ``natgateway`` set to + ``VPCSubnetNATGatewayOptions(id=None)`` on VPC create is preserved + as ``{"natgateway": {"id": null}}`` through ``drop_null_keys``. + """ + + with self.mock_post("/vpcs/123456") as m: + self.client.vpcs.create( + "test-vpc", + "us-southeast", + subnets=[ + { + "label": "test-subnet", + "ipv4": "10.0.0.0/24", + "natgateway": VPCSubnetNATGatewayOptions(id=None), + }, + ], + ) + + self.assertEqual( + m.call_data.get("subnets"), + [ + { + "label": "test-subnet", + "ipv4": "10.0.0.0/24", + "natgateway": {"id": None}, + }, + ], + ) + def test_list_ips(self): """ Validates that all VPC IPs can be listed. diff --git a/test/unit/objects/linode_interface_test.py b/test/unit/objects/linode_interface_test.py index 7e8139186..460282942 100644 --- a/test/unit/objects/linode_interface_test.py +++ b/test/unit/objects/linode_interface_test.py @@ -169,6 +169,17 @@ def assert_linode_124_interface_456(iface: LinodeInterface): assert iface.vpc.ipv4.ranges[0].range == "192.168.22.16/28" assert iface.vpc.ipv4.ranges[1].range == "192.168.22.32/28" + # natgateway assertions + assert iface.vpc.ipv4.natgateway.id == 42 + assert iface.vpc.ipv4.natgateway.label == "the-natgateway" + assert iface.vpc.ipv4.natgateway.type == "natgateway" + assert iface.vpc.ipv4.natgateway.url == "/v4/networking/natgateways/42" + assert iface.vpc.ipv4.natgateway.addresses == ["203.0.113.42"] + assert iface.vpc.ipv4.natgateway.portset_capacity == 30 + assert iface.vpc.ipv4.natgateway.portsets[0].address == "203.0.113.42" + assert iface.vpc.ipv4.natgateway.portsets[0].ports[0].start == 2048 + assert iface.vpc.ipv4.natgateway.portsets[0].ports[0].end == 3071 + assert iface.vpc.ipv6.is_public assert iface.vpc.ipv6.slaac[0].range == "1234::/64" diff --git a/test/unit/objects/networking_test.py b/test/unit/objects/networking_test.py index 245767214..a54479fc0 100644 --- a/test/unit/objects/networking_test.py +++ b/test/unit/objects/networking_test.py @@ -3,6 +3,9 @@ from linode_api4 import VLAN, ExplicitNullValue, Instance, Region from linode_api4.objects import Firewall, IPAddress, IPv6Range from linode_api4.objects.networking import ( + NATGateway, + NATGatewayAddressAssignment, + NATGatewayInterface, ReservedIPAddress, ReservedIPAssignedEntity, ) @@ -455,3 +458,178 @@ def test_instance_ip_allocate_without_address(self): assert m.call_url == "/linode/instances/123/ips" assert "address" not in m.call_data + + +class NATGatewayTest(ClientBaseCase): + """ + Tests methods of the NATGateway class. + """ + + @staticmethod + def assert_natgateway_42(natgateway: NATGateway): + assert natgateway.id == 42 + assert natgateway.label == "the-natgateway" + assert natgateway.region.id == "us-east" + assert natgateway.address_autoscale_max == 4 + assert natgateway.default_ports_per_interface == 4096 + assert natgateway.portset_assignments == 15 + assert natgateway.portset_capacity == 30 + assert natgateway.addresses[0].address == "203.0.113.42" + assert natgateway.vpc_subnet.id == 789 + assert natgateway.vpc_subnet.type == "subnet" + assert natgateway.vpc_subnet.label == "my-subnet" + assert natgateway.vpc_subnet.url == "/v4/vpcs/123456/subnets/789" + assert natgateway.vpc_subnet.vpc_id == 123456 + assert natgateway.vpc_subnet.vpc_label == "my-vpc" + + def test_get_natgateway(self): + """ + Tests that a NAT Gateway is loaded correctly via GET /networking/natgateways/{id}. + """ + natgateway = NATGateway(self.client, 42) + self.assertEqual(natgateway._populated, False) + + self.assert_natgateway_42(natgateway) + self.assertEqual(natgateway._populated, True) + + def test_update_natgateway(self): + """ + Tests that only the mutable ``label`` field is sent via PUT /networking/natgateways/{id}. + """ + with self.mock_put("/networking/natgateways/42") as m: + natgateway = NATGateway(self.client, 42) + # Force a lazy load so the object is fully populated. + _ = natgateway.label + + natgateway.label = "renamed-natgateway" + natgateway.save() + + self.assertEqual(m.call_url, "/networking/natgateways/42") + self.assertEqual(m.call_data, {"label": "renamed-natgateway"}) + + def test_delete_natgateway(self): + """ + Tests that DELETE /networking/natgateways/{id} is issued. + """ + with self.mock_delete() as m: + natgateway = NATGateway(self.client, 42) + natgateway.delete() + + self.assertEqual(m.call_url, "/networking/natgateways/42") + + @staticmethod + def assert_address_assignment(assignment: NATGatewayAddressAssignment): + assert assignment.address == "203.0.113.42" + assert assignment.in_use is True + assert assignment.interface_count == 1 + assert ( + assignment.interface_url + == "/v4/networking/natgateways/42/addresses/203.0.113.42/interfaces" + ) + assert assignment.portset_assignments == 15 + assert assignment.portset_capacity == 30 + + def test_list_address_assignments(self): + """ + Tests GET /networking/natgateways/{id}/addresses. + """ + natgateway = NATGateway(self.client, 42) + assignments = natgateway.address_assignments() + + assert len(assignments) == 1 + NATGatewayTest.assert_address_assignment(assignments[0]) + + def test_view_address_assignment(self): + """ + Tests GET /networking/natgateways/{id}/addresses/{address}. + """ + natgateway = NATGateway(self.client, 42) + assignment = natgateway.address_assignment_view("203.0.113.42") + + assert isinstance(assignment, NATGatewayAddressAssignment) + NATGatewayTest.assert_address_assignment(assignment) + + def test_create_address_assignment(self): + """ + Tests POST /networking/natgateways/{id}/addresses. + """ + with self.mock_post( + "/networking/natgateways/42/addresses/203.0.113.42" + ) as m: + natgateway = NATGateway(self.client, 42) + assignment = natgateway.address_assignment_create("203.0.113.42") + + self.assertEqual(m.call_url, "/networking/natgateways/42/addresses") + self.assertEqual(m.call_data, {"address": "203.0.113.42"}) + + assert isinstance(assignment, NATGatewayAddressAssignment) + NATGatewayTest.assert_address_assignment(assignment) + + def test_delete_address_assignment(self): + """ + Tests DELETE /networking/natgateways/{id}/addresses/{address}. + """ + with self.mock_delete() as m: + natgateway = NATGateway(self.client, 42) + result = natgateway.address_assignment_delete("203.0.113.42") + + self.assertEqual( + m.call_url, + "/networking/natgateways/42/addresses/203.0.113.42", + ) + assert result is True + + @staticmethod + def assert_interfaces(interfaces): + assert len(interfaces) == 2 + + first = interfaces[0] + assert isinstance(first, NATGatewayInterface) + assert first.id == 142 + assert first.linode.id == 1001 + assert first.linode.label == "linode1001" + assert first.linode.type == "linode" + assert first.linode.url == "/v4/linode/instances/1001" + assert first.addresses == ["203.0.113.42"] + assert first.portsets[0].address == "203.0.113.42" + assert first.portsets[0].ports[0].start == 2048 + assert first.portsets[0].ports[0].end == 3071 + + second = interfaces[1] + assert second.id == 143 + assert second.linode.id == 1002 + assert second.linode.label == "linode1002" + assert second.addresses == ["203.0.113.43"] + assert second.portsets[0].address == "203.0.113.43" + + def test_list_interfaces(self): + """ + Tests GET /networking/natgateways/{id}/interfaces. + """ + natgateway = NATGateway(self.client, 42) + interfaces = natgateway.interfaces() + NATGatewayTest.assert_interfaces(interfaces) + + def test_list_address_interfaces(self): + """ + Tests GET /networking/natgateways/{id}/addresses/{address}/interfaces. + + The per-address endpoint returns only the interfaces using that + specific address. In the fixture, only interface 142 uses + 203.0.113.42; interface 143 uses 203.0.113.43. + """ + natgateway = NATGateway(self.client, 42) + interfaces = natgateway.address_interfaces("203.0.113.42") + + assert len(interfaces) == 1 + iface = interfaces[0] + assert isinstance(iface, NATGatewayInterface) + assert iface.id == 142 + assert iface.linode.id == 1001 + assert iface.linode.label == "linode1001" + assert iface.linode.type == "linode" + assert iface.linode.url == "/v4/linode/instances/1001" + assert iface.addresses == ["203.0.113.42"] + assert iface.portsets[0].address == "203.0.113.42" + assert iface.portsets[0].ports[0].start == 2048 + assert iface.portsets[0].ports[0].end == 3071 diff --git a/test/unit/objects/vpc_test.py b/test/unit/objects/vpc_test.py index fc44722a4..9d95246f0 100644 --- a/test/unit/objects/vpc_test.py +++ b/test/unit/objects/vpc_test.py @@ -1,7 +1,7 @@ import datetime from test.unit.base import ClientBaseCase -from linode_api4 import DATE_FORMAT, VPC, VPCSubnet +from linode_api4 import DATE_FORMAT, VPC, VPCSubnet, VPCSubnetNATGatewayOptions from linode_api4.objects.vpc import VPCType @@ -63,7 +63,11 @@ def test_create_subnet(self): with self.mock_post("/vpcs/123456/subnets/789") as m: vpc = VPC(self.client, 123456) - subnet = vpc.subnet_create("test-subnet", "10.0.0.0/24") + subnet = vpc.subnet_create( + "test-subnet", + "10.0.0.0/24", + natgateway=VPCSubnetNATGatewayOptions(id=42), + ) self.assertEqual(m.call_url, "/vpcs/123456/subnets") @@ -72,11 +76,114 @@ def test_create_subnet(self): { "label": "test-subnet", "ipv4": "10.0.0.0/24", + "natgateway": {"id": 42}, }, ) self.validate_vpc_subnet_789(subnet) + def test_update_subnet_attach_natgateway(self): + """ + Tests that saving a subnet with a new NAT Gateway sends + {"label": ..., "natgateway": {"id": 42}}. + """ + + with self.mock_put("/vpcs/123456/subnets/789") as m: + subnet = VPCSubnet(self.client, 789, 123456) + # Force a lazy load so the object is fully populated. + _ = subnet.label + + subnet.label = "cool-vpc-subnet" + subnet.natgateway = VPCSubnetNATGatewayOptions(id=42) + subnet.save() + + self.assertEqual(m.call_url, "/vpcs/123456/subnets/789") + + self.assertEqual(m.call_data.get("label"), "cool-vpc-subnet") + self.assertEqual(m.call_data.get("natgateway"), {"id": 42}) + + def test_update_subnet_label_only(self): + """ + Tests that saving a subnet without touching natgateway either + omits the field or serializes the current attached NAT Gateway + as a no-op {"id": }. + """ + + with self.mock_put("/vpcs/123456/subnets/789") as m: + subnet = VPCSubnet(self.client, 789, 123456) + # Force a lazy load so the object is fully populated. + _ = subnet.label + + subnet.label = "cool-vpc-subnet" + subnet.save() + + self.assertEqual(m.call_url, "/vpcs/123456/subnets/789") + self.assertEqual(m.call_data.get("label"), "cool-vpc-subnet") + + # The fixture has a NAT Gateway already attached, so the + # unchanged put_class serialization is a no-op. + self.assertEqual(m.call_data.get("natgateway"), {"id": 42}) + + def test_update_subnet_disconnect_natgateway(self): + """ + Tests that saving a subnet after setting natgateway to + VPCSubnetNATGatewayOptions(id=None) sends {"natgateway": {"id": null}}. + """ + + with self.mock_put("/vpcs/123456/subnets/789") as m: + subnet = VPCSubnet(self.client, 789, 123456) + # Force a lazy load so the object is fully populated. + _ = subnet.label + + subnet.natgateway = VPCSubnetNATGatewayOptions(id=None) + subnet.save() + + self.assertEqual(m.call_url, "/vpcs/123456/subnets/789") + self.assertEqual(m.call_data.get("natgateway"), {"id": None}) + + def test_update_subnet_label_only_no_gateway(self): + """ + Tests that saving a subnet with no NAT Gateway attached omits the + ``natgateway`` key from the PUT body entirely (rather than sending + a spurious ``null`` or empty object). This is the safe path for + accounts without the NAT Gateway feature. + """ + + with self.mock_put("/vpcs/123456/subnets/790") as m: + subnet = VPCSubnet(self.client, 790, 123456) + _ = subnet.label + + subnet.label = "renamed-subnet" + subnet.save() + + self.assertEqual(m.call_url, "/vpcs/123456/subnets/790") + self.assertEqual(m.call_data.get("label"), "renamed-subnet") + self.assertNotIn("natgateway", m.call_data) + + def test_create_subnet_disconnect_natgateway_signal(self): + """ + Tests that ``VPCSubnetNATGatewayOptions(id=None)`` on POST is + preserved as ``{"natgateway": {"id": null}}`` through + ``drop_null_keys`` (rather than collapsing to ``{}``). + """ + + with self.mock_post("/vpcs/123456/subnets/789") as m: + vpc = VPC(self.client, 123456) + vpc.subnet_create( + "test-subnet", + "10.0.0.0/24", + natgateway=VPCSubnetNATGatewayOptions(id=None), + ) + + self.assertEqual( + m.call_data, + { + "label": "test-subnet", + "ipv4": "10.0.0.0/24", + "natgateway": {"id": None}, + }, + ) + def test_list_ips(self): """ Validates that all VPC IPs can be listed.