【问题标题】:Test AWS s3 PUT and Download in Pytest在 Pytest 中测试 AWS s3 PUT 和下载
【发布时间】:2019-01-29 18:11:28
【问题描述】:

我有以下功能。

def test_download(test_args):
    mock = mock_s3()
    mock.start()
    conn = boto3.resource('s3', region_name='us-west-2')
    conn.create_bucket(Bucket=test_args.source_bucket)
    s3.Object(test_args.source_bucket, 'testing.txt').put(
        Body=open("testing.txt", 'rb'))
    handler_client = HandlerClient(test_args)
    handler_client.get_s3_file()

使用from moto import mock_s3

我去测试时遇到错误。

    def add_auth(self, request):
        if self.credentials is None:
>           raise NoCredentialsError
E           botocore.exceptions.NoCredentialsError: Unable to locate credentials at line
>       `conn.create_bucket(Bucket=test_args.source_bucket)`

我尝试过使用装饰器 还有

with moto.mock_s3():

都得到相同的错误。我该如何解决这个问题,以创建一个假的桶,在里面放一个项目。

【问题讨论】:

    标签: python amazon-web-services boto3 moto


    【解决方案1】:

    moto 不幸的是没有模拟boto3 的授权部分。因此,您需要设置 AWS 授权链的某些部分,例如导出AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY。我们通常会在每次测试前设置一个fixture来更新环境:

    @pytest.fixture(scope='function')
    def context():
        context = attrdict.AttrMap()
        orig_env = os.environ.copy()
        os.environ['AWS_ACCESS_KEY_ID'] = 'foo'
        os.environ['AWS_SECRET_ACCESS_KEY'] = 'bar'
        context.os = {'environ': os.environ}
        yield context
        os.environ = orig_env
    

    导入部分是设置AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEY,然后设置yielding,然后将os.environ 恢复到原始状态。您不必使用context = attrdict.AttrMap 部分,我们喜欢这样,因此使用此夹具的测试函数可以访问测试os.environ(和其他测试)属性。

    【讨论】:

    • 这通常在任何测试中都很有用。使用伪造的凭据将捕获您忘记模拟服务或以其他方式阻止实时请求的情况。
    • 好点@JordonPhillips!我们肯定已经看到测试修改了真实的 AWS 资源。我发誓即使使用正确的 moto 模拟,这种情况也发生过一次。
    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2021-05-15
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多