Python 单元测试 - 设置警告 : ResourceWarning

标签 python python-3.x unit-testing python-unittest

我正在准备测试,运行此脚本后出现一个警告:

class TestForm(unittest.TestCase):


    def setUp(self):
        with open('test_json.json') as f:
            self.hd = json.load(f)

        self.reader = csv.reader(open('test.csv'))
        self.result = {}
        for row in self.reader:
            key = row[0]
            self.result[key] = row[1:]

    def test_1(self):
        self.form = self.hd[0]['Customer'][0]['Information'][0]['Form']
        self.exp = self.result['Form1'][0]
        self.assertEqual(self.form, self.exp)

    def test_2(self):
        self.form = self.hd[1]['Customer'][0]['Information'][0]['Form']
        self.exp = self.result['Form2'][0]
        self.assertEqual(self.form, self.exp)

错误:

.C:\Program Files\Python\3.5.1\lib\unittest\suite.py:107: ResourceWarning: unclosed file <_io.TextIOWrapper name='test.csv' mode='r' encoding='cp1250'>
  for index, test in enumerate(self):

脚本已完成,但这个错误很奇怪。我观察到,只有当这部分位于 setUp 函数中时才会发生:

        with open('test_json.json') as f:
            self.hd = json.load(f)

        self.reader = csv.reader(open('test.csv'))
        self.result = {}
        for row in self.reader:
            key = row[0]
            self.result[key] = row[1:]

当我在TestForm之外使用它时,脚本中没有警告。我应该将其移回 class TestForm 之外,还是在不同的文件中进行?

最佳答案

此代码打开一个 CSV 文件并使其永远保持打开状态:

self.reader = csv.reader(open('test.csv'))

这是“正确”的方法:

with open('test.csv') as csv_file:
    self.reader = csv.reader(csv_file)
    # use the file

# the file is closed here, when the context is closed

另一种方法是“手动”打开和关闭:

csv_file = open('test.csv')
self.reader = csv.reader(csv_file)
# use the file

# when you are done, close the file:
csv_file.close()

看起来您在 setUp 之后从未使用过 self.reader,所以这似乎是您的情况的最佳解决方案:

def setUp(self):
    with open('test.csv') as csv_file:
        reader = csv.reader(csv_file)
        self.result = {}
        for row in reader:
            key = row[0]
            self.result[key] = row[1:]

    # csv_file closes here; reader is not any longer available either

关于Python 单元测试 - 设置警告 : ResourceWarning,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50336368/

相关文章:

python - 计算偏置隐藏层

python-3.x - ValueError : Expected IDs to be a non-empty list, 在 Chroma 中得到 []

ios - 测试时默认 undoManager 为 nil

python - 如何在 Python 中检测小写字母?

python - TF-IDF 和非 TF-IDF 功能的准确性

python,如何对不区分大小写的元组或列表进行排序?

python - 将构建输入从 Jenkins 传递给 python

postgresql - 如何将 pandas DataFrame 插入现有的 PostgreSQL 表?

java - 使用 hamcrest 的 Assert.fail 等效项

python - 从单元测试中的结果访问运行时