Pytest无法运行测试,其中脚本A在与A相同的文件夹级别导入另一个脚本B,并给我ModuleNotFoundError



我试图在这个项目中使用pytest运行单元测试,这里main_0.py正在导入s3文件。

我得到ModuleNotFoundError: no module named 's3'

项目文件夹结构

some_project
└───src
├───main
│   └───lambda_function
│       └───some
│               main_0.py
│               s3.py
│
└───test
└───unittest
└───lambda_function
└───some
test_main_0.py
test_s3.py

main_0.py

from s3 import PrintS3
def lambda_handler():
obj = PrintS3()
res = obj.print_txt()
return res

s3.py

class PrintS3:
def __init__(self) -> None:
self.txt = "Hello"
def print_txt(self):
print(self.txt)
return self.txt

test_main_0.py

import unittest
class TestSomeMain(unittest.TestCase):
def test_main_0(self):
from src.main.lambda_function.some.main_0 import lambda_handler
res = lambda_handler()
assert res == "Hello"

testrong3.py为空

我还尝试在两个目录中添加一个空的__init__.py文件,但仍然出现相同的错误添加__init__.py文件后的项目文件夹结构

some_project
└───src
├───main
│   └───lambda_function
│       └───some
│               main_0.py
│               s3.py
│               __init__.py
│
└───test
└───unittest
└───lambda_function
└───some
test_main_0.py
test_s3.py
__init__.py

用来运行pytest的命令:

python -m pytest ./src/test

,我在some_project文件夹内,也使用main_0.py而不是main.py,因为不要与主文件夹

混淆编辑2:

我要通过在test_main_0.py文件中添加sys.path来成功运行测试用例,但它在代码编辑器(vscode)中破坏了检测和提示它没有破坏检测和提示,两个import语句都有效,但是有更好的方法吗?

新test_main_0.py:

import unittest
import os
import sys
sys.path.append(os.path.abspath("./src/main/lambda_function/some/"))
class TestSomeMain(unittest.TestCase):
def test_main_0(self):
from src.main.lambda_function.some.main_0 import lambda_handler # this works
from main_0 import lambda_handler # this also works but break linting and hinting in the code editor
res = lambda_handler()
assert res == "Hello"

你可以试试吗


import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from some.s3 import PrintS3
def lambda_handler():
obj = PrintS3()
res = obj.print_txt()
return res

我找到了一个可行的解决方案。

在类中增加setUp()tearDown()方法用于sys.path中路径的插入和删除

sys. pathPath是main_0.py和s3.py所在目录的位置

import unittest
import os
import sys
class TestSomeMain(unittest.TestCase):
def setUp(self) -> None:
sys.path.insert(0, os.path.abspath("./src/main/lambda_function/some/"))

def tearDown(self) -> None:
sys.path.remove(os.path.abspath("./src/main/lambda_function/some/"))
def test_main_0(self):
from src.main.lambda_function.some.main_0 import lambda_handler
res = lambda_handler()
assert res == "Hello"

还更新终端中的test命令:

python -m pytest ./src/test/unittest/lambda_function/some --cov ./src/main/lambda_function/some --cov-report html

相关内容

最新更新