代码之家  ›  专栏  ›  技术社区  ›  Alex Harvey

无法在unittest中导入类

  •  0
  • Alex Harvey  · 技术社区  · 8 年前

    这可能是一个初级问题,但我真的很紧张。

    #!/usr/bin/env python
    
    class Foo():
      def __init__(self):
        self.do_something()
    
      def do_something(self):
        print "foo"
    
    def main():
      Foo()
    
    if __name__ == '__main__':
      main()
    

    脚本运行良好:

    $ python foo.py 
    foo
    

    我想在unittest中测试函数“do\u something”,我有以下代码:

    #!/usr/bin/env python
    
    import unittest
    import foo
    from foo import *
    
    class TestFoo(unittest.TestCase):
      def test_foo(self):
        Foo()
    
    def main():
      unittest.main()
    
    if __name__ == "__main__":
      main()
    

    $ python pyunit/foo.py
    E
    ======================================================================
    ERROR: test_foo (__main__.TestFoo)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "pyunit/foo.py", line 9, in test_foo
        Foo()
    NameError: global name 'Foo' is not defined
    
    ----------------------------------------------------------------------
    Ran 1 test in 0.000s
    
    FAILED (errors=1)
    

    我的项目结构:

    $ tree 
    .
    ├── foo.py
    └── pyunit
        └── foo.py
    

    inspect dir() ,Python调试器等等,但我什么都做不到。

    虽然 import foo from foo import * main 从该文件导入,类本身 Foo

    最终,我的目标是为类中的函数编写单元测试 .

    我做错了什么?

    2 回复  |  直到 8 年前
        1
  •  3
  •   Chen A.    8 年前

    您不应该在模块中使用相同的文件名(foo.py)。将测试模块改为test\u foo。 显式优于隐式。

    从父目录导入模块时,需要使用 from <parent_dir> import <module_name> from <parent_dir> import foo

    您遇到 ImportError: No module named foo 错误,因为您的模块不是 sys.path .

    import sys
    sys.path.append('.')
    

    在其他导入语句之前。这将把项目目录附加到路径。如果有多个同名的类,最好使用 sys.path.insert(0, '.') 将路径推到第一个位置

        2
  •  1
  •   Ridge Kimani    8 年前

    Python测试可能会令人不安,尤其是相对导入。

    首先,我建议您安装 pytest公司 解析sys中的名称。测试模块包含的路径。。通过运行安装 pip install pytest .

    from ..foo import Foo
    

    import foo

    pytest pytest test_foo.py (如果您在pyunit文件夹中)