vendredi 29 mai 2015

Unittesting Python code which uses subprocess.Popen

I have a Python project in which I read external files, process them, and write the results to a new file. The input files can either be read directly, or extracted from a git repository using git show. The function to call git show and return stdout looks like this:

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

I have unittests which test the whole processing part of the program, i.e., everything apart from reading and writing the files. However, I have stumbled upon (and fixed) issues regarding the encoding of the returned string from git_show(), depending Python version, and quite possibly OS and the actual file to read.

I would like to set up a unittest for git_show() so I can make sure the whole application works, from input to output. However, as far as I know, this is not possible without having an actual git repository to test on. The whole package is version managed with git, and I expect that if I have a git repository inside a git repository that might lead to problems on its own, and a voice in my head tells me that might not be the best solution anyway.

How can one best achieve unittesting code which gets input from git show (and in general, the command line / Popen.communicate())?

Aucun commentaire:

Enregistrer un commentaire