单元测试使用subprocess.Popen的Python代码

cme*_*ren 7 python git unit-testing

我有一个Python项目,我在其中读取外部文件,处理它们,并将结果写入新文件.输入文件可以直接读取,也可以使用git存储库提取git show.调用git show和返回stdout 的函数如下所示:

def git_show(fname, rev):
    '''Runs git show and returns stdout'''
    process = subprocess.Popen(['git', 'show', '{}:{}'.format(rev, fname)],
                               stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()
    ret_code = process.wait()
    if ret_code:
        raise Exception(stderr)
    return stdout
Run Code Online (Sandbox Code Playgroud)

我有单元测试,它测试程序的整个处理部分,即除了读取和写入文件之外的所有内容.但是,我偶然发现(并修复了)有关返回字符串编码的问题git_show(),这取决于Python版本,很可能是操作系统和要读取的实际文件.

我想设置一个单元测试,git_show()这样我可以确保整个应用程序工作,从输入到输出.但是,据我所知,如果没有要测试的实际git存储库,这是不可能的.整个软件包是使用git进行版本管理的,我希望如果我在git存储库中有一个git存储库,可能会导致问题,而且我脑子里的一个声音告诉我,这可能不是最好的解决方案.

如何才能最好地实现从git show(通常是命令行/ Popen.communicate())输入的单元测试代码?

Jam*_*lls 5

所以我这样做的方法是使用pytest

示例:(做作

from subprocess import Popen, PIPE


def test():
    p = Popen(["echo", "Hello World!"], stdout=PIPE)
    stdout, _ = p.communicate()

    assert stdout == b"Hello World!\n"
Run Code Online (Sandbox Code Playgroud)

输出:

$ py.test -x -s test_subprocess.py 
======================================= test session starts ========================================
platform linux2 -- Python 2.7.9 -- py-1.4.28 -- pytest-2.7.1
rootdir: /home/prologic/work/circuits, inifile: 
plugins: cov
collected 1 items 

test_subprocess.py .

===================================== 1 passed in 0.01 seconds =====================================
Run Code Online (Sandbox Code Playgroud)

或者使用标准库unittest

例子:

#!/usr/bin/env python


from unittest import main, TestCase


from subprocess import Popen, PIPE


class TestProcess(TestCase):

    def test(self):
        p = Popen(["echo", "Hello World!"], stdout=PIPE)
        stdout, _ = p.communicate()

        self.assertEquals(stdout, b"Hello World!\n")


if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

输出:

$ python test_subprocess.py 
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Run Code Online (Sandbox Code Playgroud)


Dim*_*nek 5

也许您想要(组合之一)不同类型的测试

单元测试

在代码中测试一小部分代码。

  1. 模拟 subprocess.Popen
  2. 返回静态值 stdout, stderr
  3. 检查处理是否正确

示例代码非常小,您只能测试stdout真正返回的并且在非零时wait()引发异常。

介于两者之间

测试向量,即给定集合输入,应产生集合输出

  1. 模拟 git,而是使用cat vector1.txt以特定方式编码
  2. 测试结果

集成测试

测试您的代码如何连接到外部实体,在本例中git。此类测试可防止您意外更改内部系统的预期。那就是“冻结”API。

  1. 用一个小的 git 存储库创建一个 tarball
  2. 可选地将 git 二进制文件打包到同一个 tarball 中
  3. 解压 tarball
  4. 运行 git 命令
  5. 将输出与预期进行比较