路径 : ImportError raised in mako template 中的 Python 模块

标签 python unit-testing mako importerror

有一个 ImportError 有可能让我发疯。情况如下:

tests/
    testWebsite.py
website/
    __init__.py
    __main__.py
    _webtools/
        __init__.py
        templatedefs.py
        ...
    _templates/
        base.mako
        article.mako
        ...

代码(没有测试目录,在问题解决之前我犹豫是否要提交)在线:https://github.com/Boldewyn/website/ .

当我调用python -m website.__main__ build时,主例程使用website/_templates下的模板从一些输入静态HTML文件创建。这在任何给定目录中都可以正常工作。

但是,在 tests/testWebsite.py 中我有一个单元测试,它也应该运行相同的东西。但 Mako 模板会引发文件导入错误,而在其他情况下导入正常。

$ head -n 5 website/_templates/article.mako
# -*- coding: utf-8 -*-
<%!
from website._webtools.templatedefs import strip_tags
%>
<%inherit file="base.mako" />

运行测试会产生:

$ python -m unittest tests.testWebsite
...
ERROR: test_initial_build (tests.testWebsite.BuildTestCase)
Check, if building directly after bootstrap works
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tests/testWebsite.py", line 99, in test_initial_build
  File "website/_webtools/build.py", line 89, in build
    article.save(articles=articles)
  File "website/_webtools/articles.py", line 514, in save
    template_engine.render_article(self, **ctx)
  File "website/_webtools/templates.py", line 52, in render_article
    r.render_article(article, **ctx)
  File "website/_webtools/templates.py", line 277, in render_article
    tpl = self.lookup.get_template(filename)
  File "/usr/lib/python2.7/dist-packages/mako/lookup.py", line 217, in get_template
    return self._load(srcfile, uri)
  File "/usr/lib/python2.7/dist-packages/mako/lookup.py", line 277, in _load
    **self.template_args)
  File "/usr/lib/python2.7/dist-packages/mako/template.py", line 205, in __init__
    module = self._compile_from_file(path, filename)
  File "/usr/lib/python2.7/dist-packages/mako/template.py", line 249, in _compile_from_file
    filename)
  File "/usr/lib/python2.7/dist-packages/mako/template.py", line 470, in _compile_text
    exec code in module.__dict__, module.__dict__
  File "_templates_article_mako", line 16, in <module>
ImportError: No module named templatedefs

现在,有趣的是,我可以直接从模板打印 sys.path:

<%!
import sys
print sys.path
from website._webtools.templatedefs import strip_tags
%>

我可以确认,网站位于路径中。此外,导入确实在所有其他部署场景中都能很好地工作。

导入websitewebsite._webtools 也可以很好地工作。只有 website._webtools.templatedefs 部分出了问题。

有谁知道我可以在哪里寻找可能出错的迹象吗?

测试代码非常简单:

class BuildTestCase(unittest.TestCase):

    def setUp(self):
        self.tmpdir = tempfile.mkdtemp()
        self.cwd = os.getcwd()
        os.chdir(self.tmpdir)
        bootstrap(self.tmpdir, { # this initiates a new project
          "URL": "localhost",
          "TITLE": "Example",
          "DEFAULTS": {
              "AUTHOR": "John Doe",
          }
        })

    def test_initial_build(self):
        """Check, if building directly after bootstrap works"""
        build()

    def tearDown(self):
        os.chdir(self.cwd)
        shutil.rmtree(self.tmpdir)

编辑:另一个诊断:我让 mako 编译模板并独立执行生成的 Python 文件。奇迹般有效。我还将 templatedefs.py 减少到最低限度(仅 defs 返回空字符串),这样我也可以排除该文件中的 ImportErrors(或其他奇怪的情况)。

系统信息:Ubuntu 11.04、Python 2.7、Mako 0.3.6。

最佳答案

这确实让人抓狂。不过,这里有一些事情:

  1. ./nosetests: 这有效并且所有 9 项测试都通过了

  2. 当您添加 'from website import _webtools' 时,
  3. 'templatedefs''_webtools.__dict__' 中唯一缺少的键> 到您的 mako 模板,并将 'nosetests''python -m unittesttests.testWebsite' 进行比较:其他部分已在之前导入

  4. sys.path'python -m unittesttests.testWebsite' 案例中包含 ''(相对路径) ,但不是在 'nosetests' 情况下,其中 sys.path 仅包含绝对路径。这会导致 'website._webtools.__file__' 的值不同:一个是相对 ['website/_webtools'],另一个是绝对 ['/home/用户名/tmp/网站/_webtools']。由于您创建了 os.chdir,相对路径不再起作用。

SO:如果您想使用纯单元测试,您可以在测试文件的开头添加 'import website._webtools.templatedefs' 。这可以确保您在运行 os.chdir 时导入了 templatedef。我建议使用 Nose 。希望有帮助。

关于路径 : ImportError raised in mako template 中的 Python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6821572/

相关文章:

python - 访问子模板中声明的变量或 Controller 范围的变量

python - 如何获取wget下载的文件的文件名

python - Django AllAuth 自定义模板不被识别

c++ - Gmock调用函数两次

python - 如何为 mako 模板配置 vim 语法突出显示?

python - 在 Mako 模板中使用字典

python - 基于 Sublime Text 2 语法的特定 font_face

python - 使用 datastax Python Cassandra 驱动程序从文件执行 CQL 查询

ios - 在 ViewController 中观察到的单元测试 RxSwift

带有用户输入的 Python 3 单元测试