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

标签 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

返回此错误:

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/

相关文章:

python - 用/openmp编译的模块无法导入?

DjangoRestFramework 类序列化程序缺少 "Meta"属性?

python - 使用子进程的 pip freeze 调用 - 没有这样的文件或目录

Python:遍历嵌套列表列表中的每个项目并替换特定项目

java - 如何在负载测试期间测量 CPU 和内存

java - 使用 JPATest 和 MongoDB Test 为 Polyglot Springboot 编写测试

python - 用于忽略字符串中括号的正则表达式

python - 从字典列表中返回最大的字典和

testing - 关于新迭代的 TFS 测试计划的管理

python - 使用 REGEX 读取财务报表