【问题标题】:importing app engine app parent directory for unittest为单元测试导入应用引擎应用父目录
【发布时间】:2011-09-16 08:08:15
【问题描述】:

我确信这很容易解决,但我已经盯着它看了很长时间,以至于我一直盯着解决方案。任何提示/提示/建议/解决方案表示赞赏!

我正在尝试向我的应用引擎应用添加一些单元测试。我正在使用来自http://code.google.com/appengine/docs/python/tools/localunittesting.html(页面底部)的 testrunner.py 示例。如果我将 unittest 文件(名为“test_lib.py”)放在应用程序(myapp)的根目录中,这可以正常工作,但是我想将测试移动到应用程序内的单独子目录(名为“tests”)。现在我需要从应用程序中导入一些模块,但是由于 unittest 文件的工作目录现在更深一层,它看不到我的应用程序引擎应用程序中的实际模块。

我尝试在测试中添加 __ init__.py 并在其中添加以下代码:

    import os
    import sys

    sys.path.append(os.path.dirname(os.getcwd()))

我希望这会找到当前的工作目录并上一层并将其添加到 sys.path 中,然后我将能够在 unittest 文件('test_lib.py')中导入'util.lib' .但是,当我运行 testrunner.py 时,我仍然收到错误“ImportError:没有名为 util.lib 的模块”-> 我在这里尝试在根“myapp”中名为 util 的子目录中导入名为 lib 的模块。我的目录结构如下:

    testrunner.py
    |- myapp
            |- __init__.py
            |- util
                    |- __init__.py
                    |- lib.py
            |- tests
                    |- __init__.py  ## this file has the import mentioned above.
                    |- test_lib.py

我还尝试将应用程序根目录的导入添加到测试运行程序,但这会返回相同的错误。

    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/

有什么我在这里遗漏的建议吗?

【问题讨论】:

  • 将此添加到 testrunner.py 主函数有效:sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(test_path))))
  • 您最初的尝试没有成功,因为os.getcwd() 是您运行它的目录——myapp 的父目录。您可以使用 os.path.dirname(__file__) 避免将路径编码到您的应用程序中。

标签: python unit-testing google-app-engine


【解决方案1】:

您是否尝试过使用绝对路径?

sys.path.append(os.path.abspath(os.path.dirname(test_path)))

【讨论】:

  • 不幸的是,这也不起作用,但您为 testrunner.py 行提出了一个很好的观点。不过感谢您的思考:)
  • 但是,将其添加到 testrunner.py 代码有效! sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(test_path)))) 谢谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-27
相关资源
最近更新 更多