OLD | NEW |
(Empty) | |
| 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 |
| 8 |
| 9 """Test utilities.""" |
| 10 |
| 11 |
| 12 import filecmp |
| 13 import os |
| 14 import uuid |
| 15 |
| 16 |
| 17 class FileWriter(object): |
| 18 """Write files into a given directory.""" |
| 19 def __init__(self, cwd): |
| 20 self._cwd = cwd |
| 21 if not os.path.exists(self._cwd): |
| 22 os.makedirs(self._cwd) |
| 23 |
| 24 def mkdir(self, dname, mode=0755): |
| 25 """Create the given directory with the given mode.""" |
| 26 dname = os.path.join(self._cwd, dname) |
| 27 os.mkdir(dname) |
| 28 os.chmod(dname, mode) |
| 29 |
| 30 def write(self, fname, mode=0640): |
| 31 """Write the file with the given mode and random contents.""" |
| 32 fname = os.path.join(self._cwd, fname) |
| 33 with open(fname, 'w') as f: |
| 34 f.write(str(uuid.uuid4())) |
| 35 os.chmod(fname, mode) |
| 36 |
| 37 def remove(self, fname): |
| 38 """Remove the file.""" |
| 39 fname = os.path.join(self._cwd, fname) |
| 40 if os.path.isfile(fname): |
| 41 os.remove(fname) |
| 42 else: |
| 43 os.rmdir(fname) |
| 44 |
| 45 |
| 46 def compare_trees(test, a, b): |
| 47 """Compare two directory trees, assert if any differences.""" |
| 48 def _cmp(prefix, dcmp): |
| 49 # Verify that the file and directory names are the same. |
| 50 test.assertEqual(len(dcmp.left_only), 0) |
| 51 test.assertEqual(len(dcmp.right_only), 0) |
| 52 test.assertEqual(len(dcmp.diff_files), 0) |
| 53 test.assertEqual(len(dcmp.funny_files), 0) |
| 54 |
| 55 # Verify that the files are identical. |
| 56 for f in dcmp.common_files: |
| 57 pathA = os.path.join(a, prefix, f) |
| 58 pathB = os.path.join(b, prefix, f) |
| 59 test.assertTrue(filecmp.cmp(pathA, pathB, shallow=False)) |
| 60 statA = os.stat(pathA) |
| 61 statB = os.stat(pathB) |
| 62 test.assertEqual(statA.st_mode, statB.st_mode) |
| 63 with open(pathA, 'rb') as f: |
| 64 contentsA = f.read() |
| 65 with open(pathB, 'rb') as f: |
| 66 contentsB = f.read() |
| 67 test.assertEqual(contentsA, contentsB) |
| 68 |
| 69 # Recurse on subdirectories. |
| 70 for prefix, obj in dcmp.subdirs.iteritems(): |
| 71 _cmp(prefix, obj) |
| 72 |
| 73 _cmp('', filecmp.dircmp(a, b)) |
OLD | NEW |