Python unittest - setUp警告:ResourceWarning

时间:2018-05-14 17:57:51

标签: 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之外,还是在不同的档案中进行?

1 个答案:

答案 0 :(得分:1)

此代码打开一个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()

您似乎永远不会在self.reader之后使用setUp,所以这似乎是您案例中的最佳解决方案:

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