如何使用python unittest对写入文件的函数进行单元测试 [英] How to do unit testing of functions writing files using python unittest

查看:222
本文介绍了如何使用python unittest对写入文件的函数进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python函数,可将输出文件写入磁盘.

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

我想使用Python unittest模块为其编写单元测试.

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

我应如何断言文件的相等性?如果文件内容与预期的一个+差异列表不同,我想得到一个错误.与unix diff命令的输出中一样.

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?

推荐答案

最简单的方法是写入输出文件,然后读取其内容,读取gold(预期)文件的内容,然后将它们与简单的字符串相等性进行比较.如果它们相同,请删除输出文件.如果它们不同,则提出一个断言.

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.

这样,当测试完成时,每个失败的测试都会用一个输出文件表示,并且您可以使用第3方工具将它们与黄金文件进行比较(超越比较"很不错).

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).

如果您真的想提供自己的diff输出,请记住Python stdlib具有difflib模块. Python 3.1中新的单元测试支持包括一个assertMultiLineEqual方法,使用该方法显示差异,类似于:

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)

这篇关于如何使用python unittest对写入文件的函数进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆