Pytest Lambda处理程序传递事件和上下文 [英] Pytest lambda handler passing event and context

查看:85
本文介绍了Pytest Lambda处理程序传递事件和上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pytest为我的lambda函数编写一个单元测试.我不知道如何将事件参数传递给函数调用.我了解到可以使用@ pytest.fixture来实现.我对Python和pytest非常陌生.相信我以错误的方式使用固定装置.请帮助我!

I am writing a unit test for my lambda function using pytest. I cannot figure out how should I pass my event parameters to the function call. I learnt that it can be achieved using @pytest.fixture. I am very very new to Python and pytest. Believe I am using fixures in the wrong way. Please help me!!

下面是我的lambda处理程序:

Below is my lambda handler:

lambda_service.py

lambda_service.py

def lambda_handler(event, context):   
    logger.info('Event received: ' + json.dumps(event))
    try:
        sort = (event['sort'])
        size = int(event['size'])
        page = int(event['page'])

        list_response = MyService().get_people_list(sort, size, page)
        logger.info(list_response)

    except Exception as e:
        logger.error("Unable to fetch details")
        logger.exception(e)

    return list_response

这是我的测试课-

class TestServiceHandler:
    @pytest.fixture
    def event(self):
        return {
            "sort": "asc",
            "size": 5,
            "page": 0
        }
    @pytest.fixture
    def context(self):
        return None

    def test_lambda_handler(self):
        result = lambda_service.lambda_handler(self.event, self.context)
        assert_valid_schema(result, 'vendor_list.json')

运行此测试时,我遇到错误了

And I am getting below error when running this test

line 17, in lambda_handler
sort = (event['sort'])\nTypeError: 'method' object is not subscriptable"

尽管我在固定装置中传递事件和上下文,但它仍然引用 lambda_handler 中的 event [sort] .

Though I am passing event and context in fixtures, it is still referring to event[sort] inside lambda_handler.

推荐答案

您已经正确定义了灯具,但是使用它们的方式是错误的.要解决此问题,请将参数完全添加到 test_lambda_handler 方法中.在运行测试时, pytest 将分析每个参数,并在可以找到具有该名称的灯具的情况下插入灯具的返回值.示例:

You've defined the fixtures correctly, but using them wrong. To fix, add arguments to the test_lambda_handler method named exactly as the fixtures. When running tests, pytest will analyze each argument and insert the fixture return value if it can find a fixture with that name. Example:

class TestServiceHandler:
    @pytest.fixture
    def event(self):
        ...
    @pytest.fixture
    def context(self):
        ...

    def test_lambda_handler(self, event, context):
        result = lambda_service.lambda_handler(event, context)
        assert ...

这篇关于Pytest Lambda处理程序传递事件和上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆