Debian Codegraph @

testenv/conf/expected_files.py

raw
1 from difflib import unified_diff
2 import os
3 import sys
4 from conf import hook
5 from exc.test_failed import TestFailed
6
7
8 """ Post-Test Hook: ExpectedFiles
9 This is a Post-Test hook that checks the test directory for the files it
10 contains. A dictionary object is passed to it, which contains a mapping of
11 filenames and contents of all the files that the directory is expected to
12 contain.
13 Raises a TestFailed exception if the expected files are not found or if extra
14 files are found, else returns gracefully.
15 """
16
17
18 @hook()
19 class ExpectedFiles:
20 def __init__(self, expected_fs):
21 self.expected_fs = expected_fs
22
23 @staticmethod
24 def gen_local_fs_snapshot():
25 snapshot = {}
26 for parent, dirs, files in os.walk("."):
27 for name in files:
28 # pubring.gpg, pubring.kbx, common.conf, dirmngr.conf, gpg.conf will be created by libgpgme
29 # if $HOME doesn't contain the .gnupg directory.
30 # setting $HOME to CWD (in base_test.py) breaks two Metalink tests, so we skip this file here.
31 if name in [
32 "pubring.gpg",
33 "pubring.kbx",
34 "common.conf",
35 "dirmngr.conf",
36 "gpg.conf",
37 ]:
38 continue
39
40 f = {"content": ""}
41 file_path = os.path.join(parent, name)
42 with open(file_path) as fp:
43 f["content"] = fp.read()
44 snapshot[file_path[2:]] = f
45
46 return snapshot
47
48 def __call__(self, test_obj):
49 local_fs = self.gen_local_fs_snapshot()
50 for file in self.expected_fs:
51 if file.name in local_fs:
52 local_file = local_fs.pop(file.name)
53 formatted_content = test_obj._replace_substring(file.content)
54 if formatted_content != local_file["content"]:
55 diff = "".join(
56 unified_diff(
57 local_file["content"].splitlines(1),
58 formatted_content.splitlines(1),
59 fromfile="Actual",
60 tofile="Expected",
61 )
62 )
63 print(diff, file=sys.stderr)
64 raise TestFailed("Contents of %s do not match" % file.name)
65 else:
66 raise TestFailed("Expected file %s not found." % file.name)
67 if local_fs:
68 print(local_fs)
69 raise TestFailed("Extra files downloaded.")