From 2f14b48e79bc5d4cf4fc62eb55c3835c218881a7 Mon Sep 17 00:00:00 2001 From: sanderegg <35365065+sanderegg@users.noreply.github.com> Date: Mon, 21 Nov 2022 16:11:28 +0100 Subject: [PATCH] fix moto server not reset between tests --- services/autoscaling/tests/unit/conftest.py | 30 +++++++++++++++++++ .../autoscaling/tests/unit/test_utils_aws.py | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/services/autoscaling/tests/unit/conftest.py b/services/autoscaling/tests/unit/conftest.py index a3e888acbb56..139f9df3452f 100644 --- a/services/autoscaling/tests/unit/conftest.py +++ b/services/autoscaling/tests/unit/conftest.py @@ -22,6 +22,7 @@ import httpx import psutil import pytest +import requests import simcore_service_autoscaling from aiohttp.test_utils import unused_port from asgi_lifespan import LifespanManager @@ -299,10 +300,22 @@ def mocked_aws_server() -> Iterator[ThreadedMotoServer]: print(f"<-- stopped mock AWS server on {server._ip_address}:{server._port}") +@pytest.fixture +def reset_aws_server_state(mocked_aws_server: ThreadedMotoServer) -> Iterator[None]: + # NOTE: reset_aws_server_state [http://docs.getmoto.org/en/latest/docs/server_mode.html#reset-api] + yield + # pylint: disable=protected-access + requests.post( + f"http://{mocked_aws_server._ip_address}:{mocked_aws_server._port}/moto-api/reset", + timeout=10, + ) + + @pytest.fixture def mocked_aws_server_envs( app_environment: EnvVarsDict, mocked_aws_server: ThreadedMotoServer, + reset_aws_server_state: None, monkeypatch: pytest.MonkeyPatch, ) -> Iterator[EnvVarsDict]: changed_envs = { @@ -364,8 +377,25 @@ def aws_subnet_id( monkeypatch.setenv("AWS_SUBNET_ID", subnet_id) yield subnet_id + + # all the instances in the subnet must be terminated before that works + instances_in_subnet = ec2_client.describe_instances( + Filters=[{"Name": "subnet-id", "Values": [subnet_id]}] + ) + if instances_in_subnet["Reservations"]: + print(f"--> terminating {len(instances_in_subnet)} instances in subnet") + ec2_client.terminate_instances( + InstanceIds=[ + instance["Instances"][0]["InstanceId"] # type: ignore + for instance in instances_in_subnet["Reservations"] + ] + ) + print(f"<-- terminated {len(instances_in_subnet)} instances in subnet") + ec2_client.delete_subnet(SubnetId=subnet_id) + subnets = ec2_client.describe_subnets() print(f"<-- Deleted Subnet in AWS with {subnet_id=}") + print(f"current {subnets=}") @pytest.fixture diff --git a/services/autoscaling/tests/unit/test_utils_aws.py b/services/autoscaling/tests/unit/test_utils_aws.py index 2864c5df6b5b..07504b68f4bc 100644 --- a/services/autoscaling/tests/unit/test_utils_aws.py +++ b/services/autoscaling/tests/unit/test_utils_aws.py @@ -141,7 +141,7 @@ def test_compose_user_data(aws_settings: AwsSettings): assert f"ubuntu@{aws_settings.AWS_DNS}" in line -def test_start_instance_aws( +def test_start_aws_instance( faker: Faker, mocked_ec2_server_with_client: EC2Client, aws_settings: AwsSettings,