<分区> 分区>
我正在尝试运行 unittest,但我的 test_fruit.py 找不到名为 whatis.py 的主脚本。所有__init__.py文件都是空的,这个示例项目的完整路径是/home/user/unittest_test。
我总是收到此错误:ModuleNotFoundError: No module named 'x'。如果我使用相对导入,我总是会收到此消息:ValueError: attempted relative import beyond top-level package。
# python tests/test_fruit.py
Traceback (most recent call last):
File "tests/test_fruit.py", line 2, in <module>
from app.whatis import whatis
ModuleNotFoundError: No module named 'app'
# python tests/test_fruit.py
Traceback (most recent call last):
File "tests/test_fruit.py", line 2, in <module>
from ..app.whatis import whatis
ValueError: attempted relative import beyond top-level package
#
目录结构如下:
unittest_test
├── app
│ ├── __init__.py
│ └── whatis.py
├── env
│ ├── bin
│ ├── include
│ ├── lib
│ └── pip-selfcheck.json
└── tests
├── __init__.py
└── test_fruit.py
6 directories, 5 files
这是 unittest_test/app/whatis.py 中的代码:
import sys
def whatis(fruit):
if fruit == 'apple':
print('APPLE!')
return 'apple'
else:
print('Sorry, I only return "apple".')
sys.exit(1)
if __name__ == "__main__":
try:
fruit = sys.argv[1].lower()
except IndexError:
print('Please provide a name of fruit.')
sys.exit(1)
else:
whatis(fruit)
这是 unittest_test/tests/test_fruit.py 中的代码:
import unittest
from app.whatis import whatis
class FruitTest(unittest.TestCase):
def test_fruit(self):
self.assertEqual(whatis('apple'), 'apple')
if __name__ == '__main__':
unittest.main()
