python测试函数怎么写,如何使用python unittest对写入文件的函数进行单元测试

I have a Python function that writes an output file to disk.

I want to write a unit test for it using Python unittest module.

How should I assert equality of files? I would like to get an error if the file content differs from the expected one + list of differences. As in the output of unix diff command.

Is there any official/recommended way of doing that?

解决方案

The simplest thing is to write the output file, then read its contents, read the contents of the gold (expected) file, and compare them with simple string equality. If they are the same, delete the output file. If they are different, raise an assertion.

This way, when the tests are done, every failed test will be represented with an output file, and you can use a 3rd-party tool to diff them against the gold files (Beyond Compare is wonderful for this).

If you really want to provide your own diff output, remember that the Python stdlib has the difflib module. The new unittest support in Python 3.1 includes an assertMultiLineEqual method that uses it to show diffs, similar to this:

def assertMultiLineEqual(self, first, second, msg=None):

"""Assert that two multi-line strings are equal.

If they aren't, show a nice diff.

"""

self.assertTrue(isinstance(first, str),

'First argument is not a string')

self.assertTrue(isinstance(second, str),

'Second argument is not a string')

if first != second:

message = ''.join(difflib.ndiff(first.splitlines(True),

second.splitlines(True)))

if msg:

message += " : " + msg

self.fail("Multi-line strings are unequal:\n" + message)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值