|
| 1 | +""" |
| 2 | + Test cases for the dircache module |
| 3 | + Nick Mathewson |
| 4 | +""" |
| 5 | + |
| 6 | +import unittest |
| 7 | +from test.test_support import run_unittest # , import_module |
| 8 | +# dircache = import_module('dircache', deprecated=True) |
| 9 | +import dircache |
| 10 | +import os, time, sys, tempfile |
| 11 | + |
| 12 | + |
| 13 | +class DircacheTests(unittest.TestCase): |
| 14 | + def setUp(self): |
| 15 | + self.tempdir = tempfile.mkdtemp() |
| 16 | + |
| 17 | + def tearDown(self): |
| 18 | + for fname in os.listdir(self.tempdir): |
| 19 | + self.delTemp(fname) |
| 20 | + os.rmdir(self.tempdir) |
| 21 | + |
| 22 | + def writeTemp(self, fname): |
| 23 | + f = open(os.path.join(self.tempdir, fname), 'w') |
| 24 | + f.close() |
| 25 | + |
| 26 | + def mkdirTemp(self, fname): |
| 27 | + os.mkdir(os.path.join(self.tempdir, fname)) |
| 28 | + |
| 29 | + def delTemp(self, fname): |
| 30 | + fname = os.path.join(self.tempdir, fname) |
| 31 | + if os.path.isdir(fname): |
| 32 | + os.rmdir(fname) |
| 33 | + else: |
| 34 | + os.unlink(fname) |
| 35 | + |
| 36 | + def test_listdir(self): |
| 37 | + ## SUCCESSFUL CASES |
| 38 | + entries = dircache.listdir(self.tempdir) |
| 39 | + self.assertEqual(entries, []) |
| 40 | + |
| 41 | + # Check that cache is actually caching, not just passing through. |
| 42 | + self.assertTrue(dircache.listdir(self.tempdir) is entries) |
| 43 | + |
| 44 | + # Directories aren't "files" on Windows, and directory mtime has |
| 45 | + # nothing to do with when files under a directory get created. |
| 46 | + # That is, this test can't possibly work under Windows -- dircache |
| 47 | + # is only good for capturing a one-shot snapshot there. |
| 48 | + |
| 49 | + if sys.platform[:3] not in ('win', 'os2'): |
| 50 | + # Sadly, dircache has the same granularity as stat.mtime, and so |
| 51 | + # can't notice any changes that occurred within 1 sec of the last |
| 52 | + # time it examined a directory. |
| 53 | + time.sleep(1) |
| 54 | + self.writeTemp("test1") |
| 55 | + entries = dircache.listdir(self.tempdir) |
| 56 | + self.assertEqual(entries, ['test1']) |
| 57 | + self.assertTrue(dircache.listdir(self.tempdir) is entries) |
| 58 | + |
| 59 | + ## UNSUCCESSFUL CASES |
| 60 | + self.assertRaises(OSError, dircache.listdir, self.tempdir+"_nonexistent") |
| 61 | + |
| 62 | + def test_annotate(self): |
| 63 | + self.writeTemp("test2") |
| 64 | + self.mkdirTemp("A") |
| 65 | + lst = ['A', 'test2', 'test_nonexistent'] |
| 66 | + dircache.annotate(self.tempdir, lst) |
| 67 | + self.assertEqual(lst, ['A/', 'test2', 'test_nonexistent']) |
| 68 | + |
| 69 | + |
| 70 | +def test_main(): |
| 71 | + try: |
| 72 | + run_unittest(DircacheTests) |
| 73 | + finally: |
| 74 | + dircache.reset() |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == "__main__": |
| 78 | + test_main() |
0 commit comments