导入App Engine应用的父目录进行单元测试
我相信这个问题很简单就能解决,但我盯着它看了太久,反而看不到解决办法了。任何提示、建议或者解决方案都非常感谢!
我正在尝试为我的应用程序添加一些单元测试。我使用的是来自 http://code.google.com/appengine/docs/python/tools/localunittesting.html 的 testrunner.py 示例(页面底部)。如果我把单元测试文件(命名为 'test_lib.py')放在应用程序的根目录(myapp)下,这个方法是可以正常工作的,但我想把测试移动到应用程序内的一个单独子目录(命名为 'tests')。现在我需要从应用程序中导入一些模块,但由于单元测试文件的工作目录现在深了一层,它无法看到我应用程序中的实际模块。
我尝试在 tests 目录下添加一个 __init__.py 文件,并在里面添加了以下代码:
import os
import sys
sys.path.append(os.path.dirname(os.getcwd()))
我希望这能找到当前的工作目录,然后向上一级添加到 sys.path,这样我就可以在单元测试文件('test_lib.py')中导入 'util.lib'。然而,当我运行 testrunner.py 时,仍然出现错误 "ImportError: No module named util.lib" -> 我在这里尝试导入一个名为 lib 的模块,它位于根目录 'myapp' 下的一个子目录 util 中。我的目录结构如下:
testrunner.py
|- myapp
|- __init__.py
|- util
|- __init__.py
|- lib.py
|- tests
|- __init__.py ## this file has the import mentioned above.
|- test_lib.py
我还尝试将应用程序根目录的导入添加到 testrunner,但这也返回了相同的错误。
def main(sdk_path, test_path):
sys.path.append(os.path.dirname(test_path)) ## This line I added to the testrunner.
sys.path.insert(0, sdk_path)
import dev_appserver
dev_appserver.fix_sys_path()
suite = unittest2.loader.TestLoader().discover(test_path)
unittest2.TextTestRunner(verbosity=2).run(suite)
我用以下命令调用测试:
./testrunner.py ~/sdk/google_appengine/ myapp/tests/
有什么建议是我遗漏的地方吗?
1 个回答
2
你试过用绝对路径吗?
sys.path.append(os.path.abspath(os.path.dirname(test_path)))