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