字典输出的Pytest错误

2024-05-16 02:10:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个apache日志解析脚本,它返回这个输出

'remote_host': '192.168.0.1', 'apache_status': '403', 'data_transfer': '3985'

现在为了测试这个脚本,我使用pytest编写unittest

^{pr2}$

运行此脚本时,由于以下错误而失败

test_logparsing_apache.py:4: 
logparsing_apache.py:25: in final_report
line_dict = apache_output(line)
line = '1'
def apache_output(line):
    split_line = line.split()
    return {'remote_host': split_line[0],
          'apache_status': split_line[8],
            'data_transfer': split_line[9],
    }
E       IndexError: list index out of range
 logparsing_apache.py:18: IndexError

 1 failed,  in 0.03 seconds 

当我的脚本返回dictionary时,如何使用assert验证它的输出?在

脚本:

import sys

def apache_output(line):
    split_line = line.split()
    return {'remote_host': split_line[0],
            'apache_status': split_line[8],
            'data_transfer': split_line[9],
    }


def final_report(logfile):
    for line in logfile:
        line_dict = apache_output(line)
        print(line_dict)


if __name__ == "__main__":
    if not len(sys.argv) > 1:
        print (__doc__)
        sys.exit(1)
    infile_name = sys.argv[1]
    try:
        infile = open(infile_name, 'r')
    except IOError:
        print ("You must specify a valid file to parse")
        print (__doc__)
        sys.exit(1)
    log_report = final_report(infile)
    print (log_report)
    infile.close()

Tags: report脚本hostoutputdataremoteapachestatus
1条回答
网友
1楼 · 发布于 2024-05-16 02:10:46

错误的原因是因为您的final_report函数需要一个file对象,而不是字符串。因此,final_report函数最终迭代字符串中的每个字符。最后传递给apache_output的是字符串“1”。在

您可以通过在测试中传递列表而不是字符串来修复当前异常:

output = logparsing_apache.final_report(['192.168.0.1 - - [23/Apr/2017:05:54:36 -0400] "GET / HTTP/1.1" 403 3985 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"'])

如果愿意,也可以使用mock库来创建类似文件的对象。在

为了进行比较,您可以断言dictionary is equal,但实际上需要使其成为dictionary而不是string:

^{pr2}$

相关问题 更多 >