Search code examples
pythonunit-testingcode-coverage

Increasing coverage with try-except-finally and a context-manager


This is the flow that I have in my program

277: try:
278:    with open(r"c:\afile.txt", "w") as aFile:
...:        pass # write data, other exceptions/errors can occur here that have to be handled by the caller
329: except IOError as ex:
...:    print ex
332: finally:
333:    if os.path.exists(r"c:\afile.txt"):
334:        shutil.copy(r"c:\afile.txt", r"c:\dest.txt")

I've got all paths covered except for from line 278 to line 333

  • I got a normal happy-flow.
  • I stubbed __builtin__.open to raise IOError when the open is called with said file name

But how do I go from 278 to 333. Is this even possible?


Additional information: - using coverage.py 3.4 (we can't upgrade to 3.5)


Solution

  • One usually handles the flow in the following way

    try:
        with open(r"C:\file.txt", "w") as aFile:
            a.File.write("!")
        if os.path.exists(r"C:\file.txt"):
            shutil.copy(r"C:\file.txt", r"C:\dest.txt")
    except IOError as ex:
        print ex