0

我想创建一个模拟 ECS 集群,但它似乎无法正常工作。尽管有些东西被嘲笑(我没有收到凭据错误),但似乎没有“保存”集群。

如何使用 moto 创建模拟集群?

MVCE

foo.py

import boto3


def print_clusters():
    client = boto3.client("ecs")
    print(client.list_clusters())
    return client.list_clusters()["clusterArns"]

test_foo.py

import boto3
import pytest
from moto import mock_ecs

import foo

@pytest.fixture
def ecs_cluster():
    with mock_ecs():
        client = boto3.client("ecs", region_name="us-east-1")
        response = client.create_cluster(clusterName="test_ecs_cluster")
        yield client


def test_foo(ecs_cluster):
    assert foo.print_clusters() == ["test_ecs_cluster"]

怎么了

$ pytest test_foo.py
Test session starts (platform: linux, Python 3.8.1, pytest 5.3.5, pytest-sugar 0.9.2)
rootdir: /home/math/GitHub
plugins: black-0.3.8, mock-2.0.0, cov-2.8.1, mccabe-1.0, flake8-1.0.4, env-0.6.2, sugar-0.9.2, mypy-0.5.0
collecting ... 

―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― test_foo ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――

ecs_cluster = <botocore.client.ECS object at 0x7fe9b0c73580>

    def test_foo(ecs_cluster):
>       assert foo.print_clusters() == ["test_ecs_cluster"]
E       AssertionError: assert [] == ['test_ecs_cluster']
E         Right contains one more item: 'test_ecs_cluster'
E         Use -v to get the full diff

test_foo.py:19: AssertionError
---------------------------------------------------------------------------------------------------------------------------------- Captured stdout call ----------------------------------------------------------------------------------------------------------------------------------
{'clusterArns': [], 'ResponseMetadata': {'HTTPStatusCode': 200, 'HTTPHeaders': {'server': 'amazon.com'}, 'RetryAttempts': 0}}

 test_foo.py ⨯

我所期望的

我希望集群 ARN 列表具有一个元素(不是断言语句中的元素,而是一个 ARN)。但是列表是空的。

4

1 回答 1

0

创建集群时,您使用的是模拟 ECS 客户端。
列出集群时,您正在创建一个超出 moto 范围的新 ECS 客户端。

换句话说,您正在内存中创建一个集群 - 但随后向 AWS 本身询问集群列表。

您可以重写 foo 方法以使用模拟的 ECS 客户端:

def print_clusters(client):
    print(client.list_clusters())
    return client.list_clusters()["clusterArns"]


def test_foo(ecs_cluster):
    assert foo.print_clusters(ecs_cluster) == ["test_ecs_cluster"]
于 2020-04-07T07:06:48.260 回答