Debian Codegraph @

translation-canary/translation_canary/translated/__init__.py

raw
1 # Framework for testing translations
2 #
3 # Copyright (C) 2015 Red Hat, Inc.
4 #
5 # This copyrighted material is made available to anyone wishing to use,
6 # modify, copy, or redistribute it subject to the terms and conditions of
7 # the GNU Lesser General Public License v.2, or (at your option) any later
8 # version. This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY expressed or implied, including the implied
10 # warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
11 # the GNU Lesser General Public License for more details. You should have
12 # received a copy of the GNU Lesser General Public License along with this
13 # program; if not, write to the Free Software Foundation, Inc., 51 Franklin
14 # Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks
15 # that are incorporated in the source code or documentation are not subject
16 # to the GNU Lesser General Public License and may only be used or
17 # replicated with the express permission of Red Hat, Inc.
18 #
19 # Red Hat Author(s): David Shea <[email protected]>
20
21 """
22 Framework for running tests against translations.
23
24 Tests are loaded from modules in this directory. A test is any callable object
25 within the module with a name that starts with 'test_'.
26
27 Each test is called with the name of .po file to test as an argument. A test
28 passes if it returns without raising an exception.
29 """
30
31 import os, warnings
32
33 _tests = []
34
35 # Gather tests from this directory
36 import pkgutil
37 import importlib
38
39 for finder, mod_name, _ispkg in pkgutil.iter_modules(__path__):
40 # Skip __main__
41 if mod_name == "__main__":
42 continue
43
44 # Load the module
45 full_name = "{}.{}".format(__name__, mod_name)
46 module = importlib.import_module(full_name)
47
48 # Look for attributes that start with 'test_' and add them to the test list
49 for attrname, attr in module.__dict__.items():
50 if attrname.startswith('test_') and callable(attr):
51 _tests.append(attr)
52
53 def _remove_lingua(linguas, language):
54 # Read in the LINGUAS file
55 with open(linguas, "rt") as f:
56 lingua_lines = f.readlines()
57
58 output_lines = []
59 for line in lingua_lines:
60 # Leave comments alone
61 if line.startswith('#'):
62 output_lines.append(line)
63 continue
64
65 # Split the line into a list of languages, remove the one we don't
66 # want, and put it back together
67 lingua_list = line.split()
68 lingua_list.remove(language)
69 output_lines.append(" ".join(lingua_list))
70
71 # Write LINGUAS back out
72 with open(linguas, "wt") as f:
73 f.writelines(output_lines)
74
75 def testFile(pofile, prefix=None, releaseMode=False, modifyLinguas=True):
76 """Run all registered tests against the given .mo file.
77
78 If run in release mode, this function will always return true, and if
79 the mofile does not pass the tests the langauge will be removed.
80
81 :param str mofile: The .mo file name to check
82 :param str prefix: An optional directory prefix to strip from error messages
83 :param bool releaseMode: whether to run in release mode
84 :param bool modifyLinguas: whether to remove translations from LINGUAS in release mode
85 :return: whether the checks succeeded or not
86 :rtype: bool
87 """
88 success = True
89 for test in _tests:
90 # Don't print the tmpdir path in error messages
91 if prefix is not None and pofile.startswith(prefix):
92 poerror = pofile[len(prefix):]
93 else:
94 poerror = pofile
95
96 try:
97 with warnings.catch_warnings(record=True) as w:
98 test(pofile)
99
100 # Print any warnings collected
101 for warn in w:
102 print("%s warned on %s: %s" % (test.__name__, poerror, warn.message))
103 except Exception as e: # pylint: disable=broad-except
104 print("%s failed on %s: %s" % (test.__name__, poerror, str(e)))
105 if releaseMode:
106 # Remove the po file and the .mo file built from it
107 print("Removing %s" % pofile)
108 os.remove(pofile)
109
110 # Check for both .mo and .gmo
111 mofile = os.path.splitext(pofile)[0] + '.mo'
112 if os.path.exists(mofile):
113 print("Removing %s" % mofile)
114 os.remove(mofile)
115
116 gmofile = os.path.splitext(pofile)[0] + '.gmo'
117 if os.path.exists(gmofile):
118 print("Removing %s" % gmofile)
119 os.remove(gmofile)
120
121 if modifyLinguas:
122 # If there is a LINGUAS file in the po directory, remove the
123 # language from it
124 linguas = os.path.join(os.path.dirname(mofile), 'LINGUAS')
125 if os.path.exists(linguas):
126 language = os.path.splitext(os.path.basename(pofile))[0]
127 print("Removing %s from LINGUAS" % language)
128 _remove_lingua(linguas, language)
129
130 # No need to run the rest of the tests since we just killed the file
131 break
132 else:
133 success = False
134
135 return success
136
137 def testSourceTree(srcdir, releaseMode=False, modifyLinguas=True):
138 """Runs all registered tests against all .po files in the given directory.
139
140 If run in release mode, this function will always return True and the
141 languages that do not pass the tests will be removed.
142
143 :param str srcdir: The path to the source directory to check
144 :param bool releaseMode: whether to run in release mode
145 :param bool modifyLinguas: whether to remove translations from LINGUAS in release mode
146 :return: whether the checks succeeded or not
147 :rtype: bool
148 """
149 success = True
150 srcdir = os.path.normpath(srcdir)
151
152 for dirpath, _dirnames, paths in os.walk(srcdir):
153 for pofile in (os.path.join(dirpath, path) for path in paths if path.endswith('.po')):
154 if not testFile(pofile, prefix=srcdir + "/", releaseMode=releaseMode, modifyLinguas=modifyLinguas):
155 success = False
156
157 return success