简体   繁体   English

欺骗导入的脚本,以便它可以导入不存在的模块

[英]fooling imported script so it can import module which does not exist

I'm writing foobaz python app which uses plugins (in rules/plugins/ directory) and tests to these plugins (in rules/tests/ ) from project foobar . 我正在编写foob​​az python应用程序,该应用程序使用插件(在rules/plugins/目录中)并从foob​​ar项目对这些插件进行测试(在rules/tests/ )。 I do not control these (both plugins and their tests). 我不控制这些(插件及其测试)。

Because of import statements in the tests, I can not figure out how to run these. 由于测试中有import语句,因此我无法弄清楚如何运行这些语句。 Test looks like this: 测试看起来像这样:

$ cat rules/tests/test_something.py
import unittest

from foobar.rules.plugins import something

class TestSomething(unittest.TestCase):
    def test_something_equals(self):
        self.assertEqual(1, something.equals(1))

Plugin itself can look like this: 插件本身可以如下所示:

$ cat rules/plugins/something.py
def equals(i):
  return i

And script I'm using to run all the tests look like this: 我用来运行所有测试的脚本如下所示:

$ cat tests.py 
#!/usr/bin/env python

import sys
import unittest

sys.path.append('rules/tests/')
from test_something import TestSomething

if __name__ == '__main__':
    unittest.main()

When I want to execute the tests, I (no surprise) get: 当我想执行测试时,我(不足为奇)得到:

$ ./tests.py 
Traceback (most recent call last):
  File "./tests.py", line 8, in <module>
    from test_something import TestSomething
  File "rules/tests/test_something.py", line 6, in <module>
    from foobar.rules.plugins import something
ImportError: No module named foobar.rules.plugins

Is there some way I can get this running given I can not edit plugin or test? 如果我无法编辑插件或测试,是否可以通过某种方式使其运行?

If I could edit test, I would do: 如果可以编辑测试,则可以执行以下操作:

- from foobar.rules.plugins import something
+ import sys
+ sys.path.append('rules/plugins/')
+ import something

and it would work (tested). 并且可以正常工作(经过测试)。

OK, after a discussion with a colleagues, there is a really simple way how to resolve this: 好,与同事讨论后,有一种非常简单的方法来解决此问题:

$ mkdir foobar
$ mv rules/ foobar/
$ touch foobar/__init__.py
$ touch foobar/rules/__init__.py
$ touch foobar/rules/plugins/__init__.py

This way test will be able to find what it needs. 这样一来,测试就能找到需要的东西。 I did not realized this obvious thing before. 我以前没有意识到这一明显的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM