简体   繁体   English

单元测试输入验证(python)

[英]unit test input validation (python)

I do the following input validation check:我执行以下输入验证检查:

self.path = kwargs.get('path', default_path) 
if not os.path.isdir(self.path): 
    raise ValueError(msg1)
if not os.access(self.path, os.W_OK):
        raise ValueError(msg2)

What would be the best way to test it (in unit test)?测试它的最佳方法是什么(在单元测试中)?

clarification: I want to check the following:澄清:我想检查以下内容:

  • function should raise a ValueError if path is not a directory如果路径不是目录,function 应该引发 ValueError
  • function should raise a ValueError if path is a directory that is not writable如果路径是不可写的目录,function 应该引发 ValueError

The easiest way to test this functionality is to mock the respective os functions.测试此功能的最简单方法是模拟相应的os功能。 Assuming your function looks like this:假设您的 function 如下所示:

class MyClass:
    def __init__(self):
        self.path = None

    def get_path(self, *args, **kwargs):
        self.path = kwargs.get('path', 'default_path')
        if not os.path.isdir(self.path):
            raise ValueError('message 1')
        if not os.access(self.path, os.W_OK):
            raise ValueError('message 2')

If using unittest , your tests can then look like this:如果使用unittest ,您的测试可以如下所示:

class TestPath(unittest.TestCase):

    @mock.patch('os.path.isdir', return_value=False)
    def test_path_is_not_dir(self, mocked_isdir):
        with self.assertRaises(ValueError, msg="message 1"):
            inst = MyClass()
            inst.get_path(path="foo")

    @mock.patch('os.path.isdir', return_value=True)
    @mock.patch('os.access', return_value=False)
    def test_path_not_accessible(self, mocked_access, mocked_isdir):
        with self.assertRaises(ValueError, msg="msg2"):
            inst = MyClass()
            inst.get_path(path="foo")

    @mock.patch('os.path.isdir', return_value=True)
    @mock.patch('os.access', return_value=True)
    def test_valid_path(self, mocked_access, mocked_isdir):
        inst = MyClass()
        inst.get_path(path="foo")
        self.assertEqual("foo", inst.path)

This way you can test the functionality without the need to provide any real files.这样您就可以测试功能而无需提供任何真实文件。

Apart from that, it would make sense to separate the argument parsing functionality from the tested functionality in your tested code.除此之外,将参数解析功能与测试代码中的测试功能分开是有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM