【问题标题】:Relative import error using python unittest使用python unittest的相对导入错误
【发布时间】:2021-05-14 23:50:58
【问题描述】:

我正在使用内置的 python unittest 模块。我的目录结构如下:

game.py
test/test_game.py

test_game.py的内容:

import unittest
from ..game import *

class TestGame(unittest.TestCase):
    def test_pawn(self):
        game = Game()
        game.make_move("e2e3")

        self.assertEqual(game.board[6][5].piece_type, "P")

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

这就是问题所在。当我运行python -m unittest test/test_game.py 时出现错误:

ImportError: Failed to import test module: test_game
Traceback (most recent call last):
  File "/usr/local/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/loader.py", line 154, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'test.test_game'

【问题讨论】:

    标签: python unit-testing import module


    【解决方案1】:

    我错过了test/__init__.py 文件。有了这个改变,我什至不需要相对的..game import.. 但我想知道为什么 python 只需要这个来导入

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-24
      • 2018-12-24
      • 2016-06-13
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      • 2016-03-04
      • 2016-03-07
      相关资源
      最近更新 更多