我在我的一个大学项目中使用pycharm,我想将它与unittest
模块集成,但我在构建项目时遇到问题
这个项目的一部分涉及生成抽象语法树,所以我创建了AST
目录并将__init__.py
放在那里,然后我创建了expression
模块。我想把我的测试放在test/
子目录中,所以它看起来像这样:
AST/
__init__.py
expression.py
test/
some_test.py
utils.py
现在我的AST
中还有一个名为symbol_table
的模块和名为utils
的模块,示例测试类看起来像
import unittest
from ...AST import expression
from ...AST import utils
class ConstantExpressionTest(unittest.TestCase):
def testConstantExpressionCheck(self):
constantExpression = expression.ConstantExpression(17, 5, utils.TYPES.INT)
self.assertTrue(constantExpression.check())
当我右键单击此文件并选择Run Unittest in ...
我收到错误时:
/usr/bin/python2.7 /home/xubuntu/Downloads/pycharm-2.7.2/helpers/pycharm/utrunner.py /home/xubuntu/Przedmioty/VI/kompilatory/tk-projekt/src/AST/test/test_constant_expression.py true
Testing started at 12:06 PM ...
Traceback (most recent call last):
File "/home/xubuntu/Downloads/pycharm-2.7.2/helpers/pycharm/utrunner.py", line 110, in <module>
modules = [loadSource(a[0])]
File "/home/xubuntu/Downloads/pycharm-2.7.2/helpers/pycharm/utrunner.py", line 34, in loadSource
module = imp.load_source(moduleName, fileName)
File "/home/xubuntu/Przedmioty/VI/kompilatory/tk-projekt/src/AST/test/test_constant_expression.py", line 2, in <module>
from ...AST import utils
ValueError: Attempted relative import in non-package
Process finished with exit code 1
我已经阅读过有关此问题的内容,如果我理解这一点,则此文件会被视为顶层包中的文件,因此我无法使用任何相对导入。
但如果是这样的话,我如何从pycharm运行单元测试并保持我当前的项目结构呢?
如果我没有弄错的话,将测试放在子包中非常受欢迎(http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html)所以必须有某种解决方案
答案 0 :(得分:2)
嗯,这有点傻,我发现pycharm将项目的根添加到路径中,所以我可以使用项目根目录中的正常导入。
例如,我可以写
我的from AST import expression
文件中的 some_test