如何使用assert语句(添加双引号)比较pytest中的列表?

时间:2017-10-27 23:16:12

标签: python python-2.7 testing pytest

我试图使用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

返回此错误:

  断言[[' UAE',' United'],[' UAE',' Arab'],['阿联酋','阿联酋']] ==" [['阿联酋'联合'],['阿联酋' ;,'阿拉伯'],['阿联酋','阿联酋']]"       test_wordAligner.py:15:AssertionError

我不知道为什么它会在预期输出上添加双引号。由于这个原因,我得到了AssertionError。我搜索了很多,但在我的案例中找不到任何有用的答案。请注意,我想要 pytest 中的解决方案而不是 unittest

提前致谢

1 个答案:

答案 0 :(得分:1)

只是因为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)

然后你可以比较两个值。