[Python-Dev] Adding test.support.safe_rmpath()

Giampaolo Rodola' g.rodola at gmail.com
Wed Feb 13 07:24:53 EST 2019


Hello,
after discovering os.makedirs() has no unit-tests (
https://bugs.python.org/issue35982) I was thinking about working on a PR to
increase the test coverage of fs-related os.* functions. In order to do so
I think it would be useful to add a convenience function to "just delete
something if it exists", regardless if it's a file, directory, directory
tree, etc., and include it into test.support module. Basically it would be
very similar to "rm -rf". I use something like this into psutil:
https://github.com/giampaolo/psutil/blob/3ea94c1b8589891a8d1a5781f0445cb5080b7c3e/psutil/tests/__init__.py#L696
I find this paradigm especially useful when testing functions involving two
files ("src" and "dst"). E.g. in case of os.renames() unit-tests I would
write something like this:


class RenamesTest(unittest.TestCase):
    srcname = support.TESTFN
    dstname = support.TESTFN + '2'

    def setUp(self):
        test.support.rmpath(self.srcname)
        test.support.rmpath(self.dstname)
    tearDown = setUp

    def test_rename_file(self):
        ...
    def test_rename_dir(self):
        ...
    def test_rename_failure(self):
        # both src and dst will not exist
        ...

With the current utilities included in test.support the setUp function
above would be written as such:

    def setUp(self):
        for path in (self.srcname, self.dstname):
            if os.path.isdir(path):
                test.support.rmtree(path)
            elif os.path.exists(path):
                test.support.unlink(path)

Extra: one may argue whether this utility could be included into shutil
module instead. The extra advantage of test.support.rmtree and
test.support.unlink though, is that on Windows they use a timeout, catching
"file is currently in use" exceptions for some time before giving up. That
IMO would probably make this utility function not palatable for inclusion
into shutil module, so test.support would probably be a better landing
place.

Thoughts?

-- 
Giampaolo - http://grodola.blogspot.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20190213/9051fcaa/attachment.html>


More information about the Python-Dev mailing list