从导入模块的 运行 代码中停止单元测试

Stop unittest from running code from import module

有 2 个文件:

new_project
├── Main.py
└── testing.py

我运行:

$ cd new_project
$ python -m unittest testing.py

我的整个测试文件是:

import unittest
from Main import Square


class TestSquare(unittest.TestCase):

    def test_init(self):
        self.assertEqual(Square(0,0).center, Point(50,50))
        print("test")

Square 是我 Main.py 文件中的第一个 class。 Main.py 组成如下:

import sys
import math
import random


def d_print(message):
    print(message, file=sys.stderr)


class Square:
    # on découpe le terrain en square et on les marque avec top right corner of square
    def __init__(self, x, y):
        self.xtr = x
        self.ytr = y
        self.size = 100
        self.explored = False
        self.center = Point(x+50, y+50)

while True:
    # do stuff every turn
    x, y, value = [int(j) for j in input().split()]

while 循环内的代码将由游戏模拟器每回合调用。模拟器提供输入。

当我 运行 unittest 命令行时,它实际上在等待输入

如果我删除 Square 上的 import Main 和 TestFixture,则单元测试通过。我尝试了几种配置,但在没有启动 while 循环的情况下,我无法设法导入 Square 进行测试。

所以当我只从 Main.py 导入一个 class 时,它仍然 运行 是 class 之外的代码。这让我很困惑。这是 link 导入机制,我不明白为什么它是 运行 代码以及如何防止它 https://docs.python.org/3/reference/import.html

由于游戏模拟不在我的控制范围内,我无法对Main.py的编写方式做太多更改。我唯一的想法是将循环和 classes 分成两个文件用于开发和测试;提交时,我必须将文件连接回一个。

所以(感谢到目前为止的阅读;):

为避免运行循环,当文件作为模块导入时,这样写:

if __name__ == "__main__":
    while True:
        # do stuff every turn
        x, y, value = [int(j) for j in input().split()]

答案很简单,当您导入模块时,将执行该文件中的代码,这将导致循环到 运行 并在 input() 上阻塞执行。有关其工作原理的更多详细信息,请 read this answer with a detailed explanation