简体   繁体   中英

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 should raise a ValueError if path is a directory that is not writable

The easiest way to test this functionality is to mock the respective os functions. Assuming your function looks like this:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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