python-3.x - Python导入语句。模块未找到错误: when running tests and referencing a module in a parent folder

标签 python-3.x aws-lambda aws-sam-cli aws-sam aws-toolkit

问题:如何修复测试文件中的导入语句?

================================================== =

我运行以下命令:

运行测试的命令

cd cluster_health
python -m pytest tests/ -v -s

然后我收到以下错误!

    ImportError while importing test module '<full path>...\cluster_health\tests\unit\test_handler.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests\unit\test_handler.py:5: in <module>
    from health_check import app
health_check\app.py:3: in <module>
    import my_elastic_search
E   ModuleNotFoundError: No module named 'my_elastic_search'

.\cluster_health\tests\unit\test_handler.py

import json
import sys
import pytest
import health_check
from health_check import app
from health_check import my_elastic_search
# from unittest.mock import patch
import mock
from mock import Mock

def test_lambda_handler(apigw_event, monkeypatch):
    CONN = Mock(return_value="banana")
    monkeypatch.setattr('health_check.my_elastic_search.connect', CONN)
    ret = app.lambda_handler(apigw_event, "")    
    # etc...

.\cluster_health\health_check\app.py

import json
import sys
import my_elastic_search

def lambda_handler(event, context):
    print(my_elastic_search.connect("myhost", "myuser", "mypass"))
    # etc

.\cluster_health\health_check\my_elastic_search.py​​

def connect(the_host, the_user, the_pass):
    return "You are connected!"

最佳答案

health_check 是文件夹的名称。在 Python 中导入时,您无需命名文件夹。您只需使用import my_elastic_search即可。但是,这可能会导致找不到模块。您可以使用名为“sys”的模块来定义程序应在何处搜索要导入的模块,或者您可以将代码放在与模块相同的目录中。 从文件或文件中导入特定函数或类时,您可以使用 from

关于python-3.x - Python导入语句。模块未找到错误: when running tests and referencing a module in a parent folder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55933630/

相关文章:

Python:导入 Slycot,未找到符号:_dgesv_

node.js - 如何调试 aws lambda 函数?

java - 如何将AWS Lambda函数的结果返回到Android应用程序?

amazon-web-services - sam 打包并部署,无需打包参数文件

amazon-web-services - 模板的输出 block 中 Unresolved 资源依赖性 [BasicAWSApiGateway]

amazon-web-services - AWS SAM 模板 - 设置集成响应映射模板

python - 异常处理程序可以在异常引发时访问全局变量和局部变量吗?

python-3.x - Pandas :转换和复制 Pandas 中的某些行

python-3.x - 为什么 `xml.etree.ElementTree.Element` 的实例没有 `__dict__` ?

scala - 在 Scala 中如何从 AWS API Gateway 调用 AWS Lambda?