From 894c9609d2cb4c6c7a37b52225805e13cbd6dc19 Mon Sep 17 00:00:00 2001 From: Anmol Sharma Date: Sun, 15 Nov 2026 23:10:15 -0500 Subject: [PATCH 1/3] 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 6127f34ea6a77647ba979c5f182567739120f95a Mon Sep 17 00:00:00 2001 From: Anmol Sharma Date: Sun, 15 Nov 2026 23:58:12 -0500 Subject: [PATCH 2/3] 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 7e899be945b0c89a983412df060cdfc544106d44 Mon Sep 17 00:00:00 2001 From: anmsharm1 Date: Mon, 23 Nov 2026 14:46:12 -0500 Subject: [PATCH 3/3] 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")