So I'm trying to test my parser using nose
. I have few arguments that are used for handling files using type=argparse.FileType()
.
When I print out my parser's parser_args()
function, my filename argument is of course specified, looks like this:
Namespace(command_name='edit', filename=[<open file 'filename.p', mode 'r' at 0x108d4e1e0>])
Now I want to test this using nose
testing framework, specifically checking if the correct filename was indeed opened but I don't know exactly how.
When I do this (test_sys_args
is modified sys.argv
list for testing purposes):
test_parser = test_parser_output(test_sys_args)
assert_equal(test_parser.filename, "[<open file 'filename.p', mode 'r' at 0x108d4e1e0>]")
It doesn't work. I know I'm not doing this right because the memory address might be different each time the test is run and I'm also not sure if I can pass the filename
object as a string like that.
Try:
assert_equal(test_parser.filename.name, 'filename.p')
assert_equal(test_parser.filename.mode, 'r')
Here's part of the section of the test_argparse.py
file (from a recent development download):
class RFile(object):
seen = {}
def __init__(self, name):
self.name = name
def __eq__(self, other):
if other in self.seen:
text = self.seen[other]
else:
text = self.seen[other] = other.read()
other.close()
if not isinstance(text, str):
text = text.decode('ascii')
return self.name == other.name == text
class TestFileTypeR(TempDirMixin, ParserTestCase):
"""Test the FileType option/argument type for reading files"""
def setUp(self):
super(TestFileTypeR, self).setUp()
for file_name in ['foo', 'bar']:
file = open(os.path.join(self.temp_dir, file_name), 'w')
file.write(file_name)
file.close()
self.create_readonly_file('readonly')
argument_signatures = [
Sig('-x', type=argparse.FileType()),
Sig('spam', type=argparse.FileType('r')),
]
failures = ['-x', '', 'non-existent-file.txt']
successes = [
('foo', NS(x=None, spam=RFile('foo'))),
('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
('-x - -', NS(x=sys.stdin, spam=sys.stdin)),
('readonly', NS(x=None, spam=RFile('readonly'))),
]
There's a lot of testing framework that I'm not showing, but you should get the idea. The full file is at https://hg.python.org/cpython/file/ba5d7041e2f5/Lib/test/test_argparse.py