Python 3 单元测试在目录级别 运行 时失败

Python 3 unit test fails when running at directory level

我在一个文件夹中有两个 python 单元测试文件

test/folder1/test_file1.py
test/folder2/test_file2.py

当我 运行 测试单独通过时,但是当我 运行 在目录级别时,第一个测试文件通过但第二个测试文件失败。为什么会这样?两个测试文件都导入了一些相同的模块。一个文件使用 MagicMock,另一个不使用

Pass commands
python3 -m pytest test/folder1/test_file1.py
python3 -m pytest test/folder1/test_file2.py

Fail command
python3 -m pytest test/folder1/

在 test_file1

中导入命令
import os
import shutil
import tempfile
import xlrd
from unittest import TestCase

from example.folder1 import module1
from example.folder4 import module4

在 test_file2

中导入命令
import xlrd
from unittest import TestCase
from unittest.mock import MagicMock

from example.folder1 import module1 (same as test_file1)
from example.folder2 import module2
from example.folder3 import module3
import pkg_resources

找到问题。

我们使用的是本地 CACHE 变量。第一个测试是设置缓存,第二个测试最终使用第一个测试的缓存。

在 运行 第二次测试解决问题之前清除 setupClass() 中的缓存