使用Moto mock AWS Textract时遇NotImplementedError问题求助
使用Moto Mock AWS Textract时遭遇
NotImplementedError 相关代码
Lambda函数代码
from textractcaller.t_call import call_textract, Textract_Features def lambda_function(event,context): s3InputDocPath = "s3://test" jsonObject = call_textract( input_document = s3InputDocPath, features = [Textract_Features.FORMS, Textract_Features.Tables], job_done_polling_interval=5, )
textract.py中的Fixture代码
@pytest.fixtures def callTextract(): textract = boto3.client("textract", region_name="usThis-east-1") bucket = "inputBucket" textract.analyze_document( Document = {"S3Object":{"Bucket":bucket, "Name" = "test_doc.pdf"}}, FeatureTypes=["TABLES", "FORMS"] )
测试文件test_lambda_function.py代码
@mock_textract @mock_s3 def test_lambda_function(event, callTextract, s3_object): callTextract() s3_object() result = lambda_function(event, None)
错误信息
NotImplementedError: The analyze_document hasConstruct not been Implemented
解决方法
- 升级Moto到最新版本:旧版Moto可能未实现
analyze_document方法,执行升级命令:pip install --upgrade moto - 修复代码语法错误:
- Fixture装饰器应为
@pytest.fixture(原代码多了个s) - 修正region名称为合法值,比如
us-east-1(原usThis-east-1无效) analyze_document参数中Name = "test_doc.pdf"改为Name: "test_doc.pdf"(Python字典用冒号而非等号)
- Fixture装饰器应为
- 确保Mock作用域覆盖所有客户端:
textractcaller的call_textract可能会创建独立的Textract客户端,需确保该客户端处于Moto的Mock环境中。可以在测试前配置boto3使用Mock的客户端,或者在fixture中统一创建客户端供测试和业务代码复用 - 自定义Mock方法(可选):如果升级后仍未实现该方法,可手动扩展Moto的TextractBackend:
from moto.textract.models import TextractBackend def mock_analyze_document(self, **kwargs): return { "DocumentMetadata": {"Pages": 1}, "Blocks": [] } TextractBackend.analyze_document = mock_analyze_document
内容的提问来源于stack exchange,提问作者User2603
相关产品推荐
相关产品推荐

