用python3测试unittest中的未知模块

2024-06-26 15:02:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我观察到python3unittest有一个奇怪的行为。在函数testValue中的Testcase测试之后,一个不存在的模块。在

import sys
import unittest

class ModuleTest(unittest.TestCase):

    def testValue(self):
        import unknown_module
        result = unknown_module.value

        self.assertEqual(0.0, result)


if __name__ == "__main__":
    print(sys.version)
    unittest.main()

Python2正确地给出以下输出:

^{pr2}$

但是python3在引用unknown_module.value时声明了AttributeError。在

3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:55:48) [MSC v.1600 32 bit (Intel)]
E
======================================================================
ERROR: testValue (__main__.ModuleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "unknown_module_test.py", line 8, in testValue
    result = unknown_module.value
AttributeError: 'module' object has no attribute 'value'

----------------------------------------------------------------------
Ran 1 test in 0.016s

FAILED (errors=1)

为什么python3不像python2那样抛出ImportError?在


Tags: intestimportselfvaluemainsysunittest
1条回答
网友
1楼 · 发布于 2024-06-26 15:02:49

您正在导入一个隐式命名空间包。引用Python 3.3 What's New page

Native support for package directories that don’t require __init__.py marker files and can automatically span multiple path segments (inspired by various third party approaches to namespace packages, as described in PEP 420)

PEP 420 Implicit Namespace Packages

If the scan completes without returning a module or package, and at least one directory was recorded, then a namespace package is created. The new namespace package:

  • Has a __path__ attribute set to an iterable of the path strings that were found and recorded during the scan.
  • Does not have a __file__ attribute.

以及

Namespace packages and regular packages are very similar. The differences are:

  • Portions of namespace packages need not all come from the same directory structure, or even from the same loader. Regular packages are self-contained: all parts live in the same directory hierarchy.
  • Namespace packages have no __file__ attribute.
  • Namespace packages' __path__ attribute is a read-only iterable of strings, which is automatically updated when the parent path is modified.
  • Namespace packages have no __init__.py module.
  • Namespace packages have a different type of object for their __loader__ attribute.

从您的sys.path中删除unknown_module目录,您的测试将像在早期的Python版本中那样失败。在

相关问题 更多 >