gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:26:40 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com