pytest结果不匹配-数据以某种方式损坏?



我有以下python代码:

class CSVFile:
def __init__(self, filename):
self.filename = filename
def write_csv_line(self, row, mode):
for value in row:
if value == "None":
value = ""
writer = csv.writer(open(self.filename, mode))
writer.writerow(row)
def read_file(self):
data = []
with open(self.filename, mode="r") as csvfile:
csv_data = csv.reader(csvfile, delimiter=",")
for row in csv_data:
data.append(row)
return data
def file_exists(self):
return os.path.exists(self.filename)
def delete(self):
if os.path.exists(self.filename):
os.remove(self.filename)
return True
else:
return False

我正在尝试对代码进行参数化测试,如下所示:

@pytest.fixture(scope="function")
def csv_file():
csv_file = CSVFile("test")
yield csv_file
csv_file.delete()

# Test if file is writable and correct data written
# @pytest.mark.skip("WIP")
@pytest.mark.parametrize(
"file, row, expected",
[
(lazy_fixture("csv_file"), [["a", "b", "c"]], [["a", "b", "c"]]),
],
)
def test_CSVLineWritable(file, row, expected):
file.write_csv_line(row, "w")
data_read = file.read_file()
assert file.file_exists() is True
assert data_read == expected

当我运行pytest,我得到:


file = <process_resources.CSVFile object at 0x108a64af0>, row = [['a', 'b', 'c']], expected = [['a', 'b', 'c']]
@pytest.mark.parametrize(
"file, row, expected",
[
(lazy_fixture("csv_file"), [["a", "b", "c"]], [["a", "b", "c"]]),
# (lazy_fixture("csv_file"), [["None", "b", "c"]], [["", "b", "c"]]),
# (lazy_fixture("csv_file"), [[None, "b", "c"]], [["", "b", "c"]]),
],
)
def test_CSVLineWritable(file, row, expected):
file.write_csv_line(row, "w")
data_read = file.read_file()
assert file.file_exists() is True
>       assert data_read == expected
E       assert [["['a', 'b', 'c']"]] == [['a', 'b', 'c']]
E         At index 0 diff: ["['a', 'b', 'c']"] != ['a', 'b', 'c']
E         Full diff:
E         - [['a', 'b', 'c']]
E         + [["['a', 'b', 'c']"]]
E         ?  ++               + +
tests/test_process_resources.py:117: AssertionError

具体来说,似乎数据正在损坏,因为读进来的内容与写进来的内容不一样。换句话说,data_read的内容与预期的不一样。我已经审查了read_file方法,对我来说似乎很好。你知道为什么它不起作用吗?

我修复了这个问题,也修复了一些bug。我意识到问题是写文件,即文件得到损坏的数据在那一点。所以我专注于这个功能。

def write_csv_line(self, row, mode):
i = 0
for value in row:
print(row)
if value == "None" or value is None:
row[i] = ""
print("changed - " + str(row))
i = i + 1
with open(self.filename, "w", newline="") as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerow(row)

我还更新了测试用例以使其正确:

@pytest.mark.parametrize(
"file, row, expected",
[
(lazy_fixture("csv_file"), ["a", "b", "c"], [["a", "b", "c"]]),
(lazy_fixture("csv_file"), ["None", "b", "c"], [["", "b", "c"]]),
(lazy_fixture("csv_file"), [None, "b", "c"], [["", "b", "c"]]),
],
)
def test_CSVLineWritable(file, row, expected):
file.write_csv_line(row, "w")
data_read = file.read_file()
assert file.file_exists() is True
assert data_read == expected

相关内容

  • 没有找到相关文章

最新更新