Python导入语句。ModuleNotFoundError:运行测试并引用父文件夹中的模块时

巴诺纳

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

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

我运行以下命令:

用于运行测试的命令

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!"
巴诺纳

感谢从父文件夹和@woofless(如上所述)导入模块,这是我解决该问题的方法(问题声明实际上是我在父目录中引用一个模块。AWSToolkit for Visual Studio with SAM的脚手架没有提供适当的代码以充分引用其他父模块)!

请注意下面sys.path.insert另外,按照@woofless,我简化了我的命名空间引用,以便它不引用根文件夹“ health_check”。瞧!

。\ cluster_health \ tests \ unit \ test_handler.py

import sys, os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
parentdir = "%s\\health_check"%os.path.dirname(parentdir)
sys.path.insert(0,parentdir)
print(parentdir)

import json

import pytest
import health_check
import app
import my_elastic_search

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章