I am using Python 2.7 for a coding project. I'd love to switch to Python 3, but unfortunately I'm writing scripts for a program that only has a python package in 2.7 and even if it had one in 3 our codebase would be impractical to switch over, so it's not possible.
My code involves checking if a path it is given in string form exists, then because I don't know if os.path.exists does this itself, if it does not, it runs .strip() on the file name and tries again.
I am trying to unit test this. I've run a test on it not existing at all by patching os.path.exists to return False. But I can't figure out how to unit test the case where it returns False before .strip(), and True after.
Here is the relevant portion of the function being tested (the if/elif/else is relevant for the unit tests):
import os
class Runner:
def __init__(self, fname):
self.fname = fname
def input_check(self):
if not os.path.exists(self.fname):
self.fname = self.fname.strip()
if not os.path.exists(self.fname):
raise ValueError('input is not a valid path')
if os.path.isfile(self.fname):
self.ftype = 'file'
elif os.path.isdir(self.fname):
self.ftype = 'folder'
else:
raise ValueError('how is your input neither a file nor a folder??')
And two examples of what I have tried for unit testing: Example 1
import unittest
from mock import patch
class TestRunner(unittest.TestCase):
@patch('.strip')
@patch('os.path.exists')
def test_input_check_exists_after_strip(self, patchexist, patchstrip):
runner = Runner('test ')
patchstrip.return_value = 'test'
patchexist.return_value = False if runner.fname[-1] == ' ' else True
with self.assertRaisesRegexp(ValueError, 'how is your input neither a file nor a folder??'):
runner.input_check()
This one, seems I can't figure out how to get it to actually patch .strip, and the answers I have found through Google seem to say that there is no way to patch certain builtin functions (I also tried builtins.strip, didn't work either.) It says empty module name or no module named builtins.
Example 2
import unittest
from mock import patch
class TestRunner(unittest.TestCase):
@patch('os.path.exists')
def test_input_check_exists_after_strip(self, patchexist):
runner = Runner('test')
patchexist.return_value = patchexist.called
with self.assertRaisesRegexp(ValueError, 'how is your input neither a file nor a folder??'):
runner.input_check()
This one returns with the 'input is not a valid path' ValueError. I am guessing that the patch's return value is simply not updated during the running of input_check(), which makes sense even if it's inconvenient for me.
Is there a way to test this? Is this even necessary, or does os.path.exists() deal with there being extraneous whitespace already? I am pretty new to unit testing and even newer to the concept of mocking, so I would appreciate any help.
str.strip
. Mockos.path.exists()
so it return False whenever the name begins or ends with a space.