test_dircache.py 2.4 KB

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