test_utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2016 Google Inc.
  4. #
  5. # Use of this source code is governed by a BSD-style license that can be
  6. # found in the LICENSE file.
  7. """Test utilities."""
  8. import filecmp
  9. import os
  10. import uuid
  11. class FileWriter(object):
  12. """Write files into a given directory."""
  13. def __init__(self, cwd):
  14. self._cwd = cwd
  15. if not os.path.exists(self._cwd):
  16. os.makedirs(self._cwd)
  17. def mkdir(self, dname, mode=0755):
  18. """Create the given directory with the given mode."""
  19. dname = os.path.join(self._cwd, dname)
  20. os.mkdir(dname)
  21. os.chmod(dname, mode)
  22. def write(self, fname, mode=0640):
  23. """Write the file with the given mode and random contents."""
  24. fname = os.path.join(self._cwd, fname)
  25. with open(fname, 'w') as f:
  26. f.write(str(uuid.uuid4()))
  27. os.chmod(fname, mode)
  28. def remove(self, fname):
  29. """Remove the file."""
  30. fname = os.path.join(self._cwd, fname)
  31. if os.path.isfile(fname):
  32. os.remove(fname)
  33. else:
  34. os.rmdir(fname)
  35. def compare_trees(test, a, b):
  36. """Compare two directory trees, assert if any differences."""
  37. def _cmp(prefix, dcmp):
  38. # Verify that the file and directory names are the same.
  39. test.assertEqual(len(dcmp.left_only), 0)
  40. test.assertEqual(len(dcmp.right_only), 0)
  41. test.assertEqual(len(dcmp.diff_files), 0)
  42. test.assertEqual(len(dcmp.funny_files), 0)
  43. # Verify that the files are identical.
  44. for f in dcmp.common_files:
  45. pathA = os.path.join(a, prefix, f)
  46. pathB = os.path.join(b, prefix, f)
  47. test.assertTrue(filecmp.cmp(pathA, pathB, shallow=False))
  48. statA = os.stat(pathA)
  49. statB = os.stat(pathB)
  50. test.assertEqual(statA.st_mode, statB.st_mode)
  51. with open(pathA, 'rb') as f:
  52. contentsA = f.read()
  53. with open(pathB, 'rb') as f:
  54. contentsB = f.read()
  55. test.assertEqual(contentsA, contentsB)
  56. # Recurse on subdirectories.
  57. for prefix, obj in dcmp.subdirs.iteritems():
  58. _cmp(prefix, obj)
  59. _cmp('', filecmp.dircmp(a, b))