簡體   English   中英

使用 python 單元測試的相對導入錯誤

[英]Relative import error using python unittest

我正在使用內置的 python 單元測試模塊。 我的目錄結構如下:

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'

我錯過了test/__init__.py文件。 有了這個改變,我什至不需要相對的..game導入。但我想知道為什么 python 只需要這個來導入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM