python - 如何使用 Nose 测试 argparse 中打开的文件

标签 python testing argparse nose

所以我正在尝试使用 nose 测试我的解析器.我有几个用于使用 type=argparse.FileType() 处理文件的参数.

当我打印出解析器的 parser_args() 时函数,我的文件名参数当然是指定的,看起来像这样:

Namespace(command_name='edit', filename=[<open file 'filename.p', mode 'r' at 0x108d4e1e0>])

现在我想使用 nose 来测试它测试框架,专门检查是否确实打开了正确的文件名,但我不知 Prop 体是如何打开的。

当我这样做时(test_sys_args 已修改 sys.argv 列表用于测试目的):

test_parser = test_parser_output(test_sys_args) assert_equal(test_parser.filename, "[<open file 'filename.p', mode 'r' at 0x108d4e1e0>]")

这是行不通的。我知道我这样做不对,因为每次运行测试时内存地址可能不同,而且我也不确定我是否可以通过 filename像这样的字符串对象。

最佳答案

尝试:

assert_equal(test_parser.filename.name, 'filename.p')
assert_equal(test_parser.filename.mode, 'r')

这是 test_argparse.py 文件部分的一部分(来自最近的开发下载):

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'))),
    ]

有很多测试框架我没有展示,但你应该明白了。完整文件位于 https://hg.python.org/cpython/file/ba5d7041e2f5/Lib/test/test_argparse.py

关于python - 如何使用 Nose 测试 argparse 中打开的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30135715/

相关文章:

python - Plotly 循环中的一些子图

spring - 如何防止 Spring JmsTemplate 单元测试在读取 ActiveMQ 队列时阻塞?

java - 我应该在测试方法中模拟本地方法调用吗?

testing - cabal 测试不打印可执行输出

python - argparse:将无法识别的选项视为位置?

python - 使用 argparse 调用不同的函数

python - 从子类中的属性中删除属性(getter/setter)

python - 在 pyInstaller 生成的 Python EXE 中确定应用程序路径

python - 将列表与元组列表进行比较以获得另一个列表

python - 逗号分隔列表的 argparse 操作或类型