我正在尝试使用 assert 语句比较两个列表的结果,以使用 pytest 测试函数。每当我尝试使用 assert 语句进行比较时,我的预期结果都会自动转换为带双引号的字符串。这是到目前为止我所做的:
# read data from xlsx file
book = xlrd.open_workbook("nameEntityDataSet.xlsx")
first_sheet = book.sheet_by_index(0) # get first worksheet
# take second element(index starts from 0) from first row
se1 = first_sheet.row_values(1)[1]
print "se1 ", se1 #returns me list:
# take third element(index 2) from first row
se2 = first_sheet.row_values(1)[2]
expected_output = first_sheet.row_values(1)[3]
#expected output is printed as: [['UAE', 'United'], ['UAE', 'Arab'], ['UAE', 'Emirates']]
current_output = [['UAE', 'United'], ['UAE', 'Arab'], ['UAE', 'Emirates']]
#When I do assert to compare both outputs
assert current_output == expected_output
返回此错误:
assert [['UAE', 'United'], ['UAE', 'Arab'], ['UAE', 'Emirates']] == "[['UAE', 'United'], ['UAE', 'Arab'], ['UAE', 'Emirates']]" test_wordAligner.py:15: AssertionError
我不知道为什么它会在预期输出上添加双引号。由于这个原因,我收到了 AssertionError。我进行了很多搜索,但在我的案例中没有找到任何有用的答案。请注意,我希望在 pytest 中解决方案而不是 unittest
提前致谢
最佳答案
仅仅是因为 expected_output
是一个字符串,并且您针对一个列表进行断言。
expected_output = first_sheet.row_values(1)[3]
该行返回一个字符串。由于您访问了 row_values(1)
返回的列表中的一个特定项目。为了帮助您调试,请尝试:
print(type(expected_output))
这会告诉你 expected_output
目前是一个字符串。
现在,为了将其转换为列表,您可以尝试以下方法:
import ast #put this at the top of your file
expected_output = first_sheet.row_values(1)[3]
expected_output = ast.literal_eval(expected_output)
然后您可以比较这两个值。
关于python - 如何使用断言语句(添加双引号)比较pytest中的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46984656/