提交 9b7def22 编写于 作者: C Cleber Rosa

avocado.utils.path: introduce check_readable()

It's a common use case to want to make sure a file can be read, or if
not fail as early as possible with a relevant error message.

The avocado.utils.iso9600 is doing that itself, but for the sake of
being useful to a wider audience, let's make that a utility itself.

As always, the benefits are also increased test coverage and
documentation.
Signed-off-by: NCleber Rosa <crosa@redhat.com>
上级 b06b87ec
......@@ -34,6 +34,7 @@ import sys
import tempfile
from . import process
from . import path as utils_path
try:
......@@ -129,25 +130,8 @@ class BaseIso9660(object):
"""
def __init__(self, path):
utils_path.check_readable(path)
self.path = path
self._verify_path(path)
@staticmethod
def _verify_path(path):
"""
Verify that the current set path is accessible
:param path: the path for test
:type path: str
:raise OSError: path does not exist or path could not be read
:rtype: None
"""
if not os.path.exists(path):
raise OSError('File or device path does not exist: %s' %
path)
if not os.access(path, os.R_OK):
raise OSError('File or device path could not be read: %s' %
path)
def read(self, path):
"""
......
......@@ -190,3 +190,22 @@ def usable_ro_dir(directory):
pass
return False
def check_readable(path):
"""
Verify that the given path exists and is readable
This should be used where an assertion makes sense, and is useful
because it can provide a better message in the exception it
raises.
:param path: the path to test
:type path: str
:raise OSError: path does not exist or path could not be read
:rtype: None
"""
if not os.path.exists(path):
raise OSError('File "%s" does not exist' % path)
if not os.access(path, os.R_OK):
raise OSError('File "%s" can not be read' % path)
import os
import unittest
try:
from unittest import mock
except ImportError:
import mock
from avocado.utils import path
class Path(unittest.TestCase):
def test_check_readable_exists(self):
with mock.patch('avocado.utils.path.os.path.exists',
return_value=False) as mocked_exists:
with self.assertRaises(OSError) as cm:
path.check_readable(os.devnull)
self.assertEqual('File "%s" does not exist' % os.devnull,
cm.exception.args[0])
mocked_exists.assert_called_with(os.devnull)
def test_check_readable_access(self):
with mock.patch('avocado.utils.path.os.access',
return_value=False) as mocked_access:
with self.assertRaises(OSError) as cm:
path.check_readable(os.devnull)
self.assertEqual('File "%s" can not be read' % os.devnull,
cm.exception.args[0])
mocked_access.assert_called_with(os.devnull, os.R_OK)
if __name__ == '__main__':
unittest.main()
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册