1

Python 3 unittest で奇妙な動作が見られます。次の Testcase テストは、testValue存在しないモジュールを機能させます。

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 は、次の出力を正しく提供します。

2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)]
E
======================================================================
ERROR: testValue (__main__.ModuleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\bin\WinPython-64bit-2.7.5.1\workspace\unknown_module_test.py", line 7, in testValue
    import unknown_module
ImportError: No module named unknown_module

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

しかし、Python 3 は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)

Python 2のように Python 3 をスローしないのはなぜImportErrorですか?

4

1 に答える 1