Left: | ||
Right: |
OLD | NEW |
---|---|
(Empty) | |
1 # This file is part of the Adblock Plus web scripts, | |
2 # Copyright (C) 2006-present eyeo GmbH | |
3 # | |
4 # Adblock Plus is free software: you can redistribute it and/or modify | |
5 # it under the terms of the GNU General Public License version 3 as | |
6 # published by the Free Software Foundation. | |
7 # | |
8 # Adblock Plus is distributed in the hope that it will be useful, | |
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
11 # GNU General Public License for more details. | |
12 # | |
13 # You should have received a copy of the GNU General Public License | |
14 # along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>. | |
15 from __future__ import unicode_literals | |
Vasily Kuznetsov
2018/09/26 15:45:26
Nit: you know
Tudor Avram
2018/10/04 06:48:14
Done.
| |
16 | |
17 import pytest | |
Vasily Kuznetsov
2018/09/26 15:45:26
Nit: pytest should be after all of that stdlib stu
Tudor Avram
2018/10/04 06:48:13
Done.
| |
18 | |
19 import os | |
20 from ConfigParser import SafeConfigParser | |
21 import io | |
22 import sys | |
23 import json | |
24 | |
25 from cms.bin.xtm_translations import constants as const | |
26 from cms.bin.xtm_translations.projects_handler import ( | |
27 main as main_project_handler, | |
28 create_project, upload_files, download_files, | |
29 ) | |
30 from cms.bin.xtm_translations.translate_xtm_cloud import generate_token | |
31 | |
32 _CMD_START = ['python', '-m', 'cms.bin.xtm_translations'] | |
33 | |
34 _ENV_NO_TOKEN = dict(os.environ) | |
35 _ENV_NO_TOKEN.pop(const.Token.ENV_VAR, None) | |
36 | |
37 _ENV_TOKEN_VALID = dict(os.environ) | |
38 _ENV_TOKEN_VALID[const.Token.ENV_VAR] = 'TheXTM-APIToken-VALID' | |
39 | |
40 _ENV_TOKEN_INVALID = dict(os.environ) | |
41 _ENV_TOKEN_INVALID[const.Token.ENV_VAR] = 'TheXTM-APIToken-INVALID' | |
42 | |
43 | |
44 class _CreationArgsNamespace: | |
45 def __init__(self): | |
46 pass | |
47 | |
48 name = 'bar' | |
49 desc = 'foo' | |
50 client_id = 10 | |
51 ref_id = 'faz' | |
52 workflow_id = 20 | |
53 save_id = False | |
54 source_dir = None | |
55 projects_func = staticmethod(create_project) | |
56 source_lang = 'en_US' | |
57 | |
58 | |
59 class _UploadArgsNamespace: | |
60 def __init__(self): | |
61 pass | |
62 | |
63 source_dir = None | |
64 projects_func = staticmethod(upload_files) | |
65 no_overwrite = False | |
66 | |
67 | |
68 class _DownloadArgsNamespace: | |
69 def __init__(self): | |
70 pass | |
71 | |
72 source_dir = None | |
73 projects_func = staticmethod(download_files) | |
74 | |
75 | |
76 _CREATION_ARGS_DEFAULT = ['--name', 'bar', '--desc', 'foo', '--client-id', | |
77 '10', '--ref-id', 'faz', '--workflow-id', '20'] | |
78 _CREATION_ARGS_INVALID_TYPE_1 = ['--name', 'bar', '--desc', 'foo', | |
79 '--client-id', 'foo', '--ref-id', 'faz', | |
80 '--workflow-id', '3'] | |
81 _CREATION_ARGS_INVALID_TYPE_2 = ['--name', 'bar', '--desc', 'foo', | |
82 '--client-id', '23', '--ref-id', 'faz', | |
83 '--workflow-id', 'foo'] | |
84 | |
85 | |
86 @pytest.fixture | |
87 def env_valid_token(): | |
88 old_env = os.environ | |
89 os.environ = _ENV_TOKEN_VALID | |
90 yield True | |
91 os.environ = old_env | |
92 | |
93 | |
94 @pytest.mark.script_launch_mode('subprocess') | |
95 @pytest.mark.parametrize('args,exp_msg', [ | |
96 (['-h'], 'usage: __main__.py [-h] [-v] {login,create,upload,download} ' | |
97 '...'), | |
98 (['create', '-h'], 'usage: __main__.py create [-h] --name NAME --desc ' | |
99 'DESC --client-id CLIENT_ID --ref-id REF_ID ' | |
100 '--workflow-id WORKFLOW_ID [--source-lang SOURCE_LANG] ' | |
101 '[--save-id] [source_dir]'), | |
102 (['upload', '-h'], 'usage: __main__.py upload [-h] [--no-overwrite] ' | |
103 '[source_dir]'), | |
104 (['download', '-h'], 'usage: __main__.py download [-h] [source_dir]'), | |
105 ]) | |
106 def test_usage_messages(args, exp_msg, script_runner): | |
107 """Test if appropriate usage messages are displayed.""" | |
108 cmd = list(_CMD_START) | |
109 cmd.extend(args) | |
110 ret = script_runner.run(*cmd) | |
111 | |
112 usg_msg = ret.stdout.replace('\n', '').replace(' ', '') | |
113 | |
114 assert exp_msg.replace(' ', '') in usg_msg | |
115 | |
116 | |
117 @pytest.mark.script_launch_mode('subprocess') | |
118 @pytest.mark.parametrize('args', [ | |
119 ['create', '--name', 'bar', '--desc', 'foo', '--client-id', '1', | |
120 '--ref-id', 'faz', '--workflow-id', '3'], | |
121 ['upload'], | |
122 ['download'], | |
123 ]) | |
124 def test_default_source_directory(args, script_runner): | |
125 """Test if the source directory if set to default if not provided.""" | |
126 exp = const.ErrorMessages.NO_TOKEN_PROVIDED.split('\n')[0] | |
127 cmd = list(_CMD_START) | |
128 cmd.extend(args) | |
129 | |
130 ret = script_runner.run(*cmd) | |
131 | |
132 assert not ret.success | |
133 assert exp in ret.stderr | |
134 | |
135 | |
136 @pytest.mark.script_launch_mode('subprocess') | |
137 @pytest.mark.parametrize('source_dir,args,env,exp_msg', [ | |
138 ('str(temp_site)', _CREATION_ARGS_INVALID_TYPE_1, _ENV_NO_TOKEN, | |
139 "--client-id: invalid int value: 'foo'"), | |
140 ('str(temp_site)', _CREATION_ARGS_INVALID_TYPE_2, _ENV_NO_TOKEN, | |
141 "--workflow-id: invalid int value: 'foo'"), | |
142 ('str(temp_site)', _CREATION_ARGS_DEFAULT, _ENV_NO_TOKEN, | |
143 const.ErrorMessages.NO_TOKEN_PROVIDED.split('\n')[0]), | |
144 ('str(temp_site_valid_project)', _CREATION_ARGS_DEFAULT, _ENV_TOKEN_VALID, | |
145 const.ErrorMessages.PROJECT_EXISTS.format(1234)), | |
146 ('str(temp_site)', _CREATION_ARGS_DEFAULT, _ENV_TOKEN_INVALID, | |
147 'Authentication failed'), | |
148 ]) | |
149 def test_creation_error_messages(temp_site, intercept, script_runner, args, | |
150 source_dir, temp_site_valid_project, env, | |
151 exp_msg): | |
152 """Test if error cases are treated correctly when creating a project.""" | |
153 cmd = list(_CMD_START) | |
154 cmd.extend(['create', eval(source_dir)]) | |
155 cmd.extend(args) | |
156 | |
157 ret = script_runner.run(*cmd, env=env) | |
158 | |
159 assert not ret.success | |
160 assert exp_msg in ret.stderr | |
161 | |
162 | |
163 def test_creation_correct(temp_site, intercept, env_valid_token): | |
164 """Test if a project is created correctly, given the appropriate args.""" | |
165 namespace = _CreationArgsNamespace() | |
166 namespace.source_dir = str(temp_site) | |
167 main_project_handler(namespace) | |
168 | |
169 | |
170 def test_creation_save_id(temp_site, intercept, env_valid_token): | |
171 """Test the project id is saved after successfully creating a project.""" | |
172 namespace = _CreationArgsNamespace() | |
173 namespace.source_dir = str(temp_site) | |
174 namespace.save_id = True | |
175 main_project_handler(namespace) | |
176 cnf = SafeConfigParser() | |
177 try: | |
178 with io.open(os.path.join(temp_site, 'settings.ini'), | |
179 encoding='utf-8') as f: | |
180 cnf_data = f.read() | |
181 cnf.readfp(io.StringIO(cnf_data)) | |
182 project_id = cnf.get(const.Config.XTM_SECTION, | |
183 const.Config.PROJECT_OPTION) | |
184 | |
185 assert int(project_id) == 1234 | |
186 finally: | |
187 cnf.remove_option(const.Config.XTM_SECTION, | |
188 const.Config.PROJECT_OPTION) | |
189 cnf.write(open(os.path.join(temp_site, 'settings.ini'), 'w')) | |
190 | |
191 | |
192 def test_login(intercept, monkeypatch, capsys): | |
193 """Test if the login functionality works as expected.""" | |
194 exp_output = const.Token.SAVE_COMMAND.format(const.Token.ENV_VAR, | |
195 'TheXTM-APIToken-VALID') | |
196 monkeypatch.setattr( | |
197 'cms.bin.xtm_translations.translate_xtm_cloud.input_fn', | |
198 lambda inp: 'admin' if 'username' in inp.lower() else '20', | |
199 ) | |
200 monkeypatch.setattr('getpass.getpass', lambda prompt: 'pass') | |
201 | |
202 generate_token(None) | |
203 out, err = capsys.readouterr() | |
204 | |
205 assert err == '' | |
206 assert exp_output in out | |
207 | |
208 | |
209 def test_login_wrong_credentials(intercept, monkeypatch, capsys): | |
210 """Test exception handling when generating the tokens.""" | |
211 monkeypatch.setattr( | |
212 'cms.bin.xtm_translations.translate_xtm_cloud.input_fn', | |
213 lambda inp: 'foo' if 'username' in inp.lower() else '50', | |
214 ) | |
215 monkeypatch.setattr('getpass.getpass', lambda prompt: 'pass') | |
216 monkeypatch.setattr('sys.exit', lambda x: sys.stderr.write(str(x))) | |
217 | |
218 generate_token(None) | |
219 out, err = capsys.readouterr() | |
220 | |
221 assert 'Invalid credentials' in err | |
222 assert out == '' | |
223 | |
224 | |
225 @pytest.mark.script_launch_mode('subprocess') | |
226 @pytest.mark.parametrize('args,env,exp_msg', [ | |
227 (['str(temp_site)'], _ENV_NO_TOKEN, | |
228 const.ErrorMessages.NO_TOKEN_PROVIDED.split('\n')[0]), | |
229 (['str(temp_site)'], _ENV_TOKEN_VALID, 'No project configured'), | |
230 ]) | |
231 def test_upload_error_messages_as_script(temp_site, script_runner, args, env, | |
232 exp_msg): | |
233 cmd = list(_CMD_START) | |
234 cmd.append('upload') | |
235 | |
236 cmd.extend(list(map(eval, args))) | |
237 | |
238 ret = script_runner.run(*cmd, env=env) | |
239 | |
240 assert not ret.success | |
241 assert exp_msg in ret.stderr | |
242 | |
243 | |
244 def test_upload_too_many_languages(intercept_too_many_targets, | |
245 env_valid_token, temp_site_valid_project): | |
246 namespace = _UploadArgsNamespace() | |
247 namespace.source_dir = str(temp_site_valid_project) | |
248 | |
249 with pytest.raises(Exception) as err: | |
250 main_project_handler(namespace) | |
251 | |
252 assert 'languages are enabled in the API, but not listed in locales' in \ | |
253 str(err.value) | |
254 | |
255 | |
256 def test_upload_successful(intercept, env_valid_token, | |
257 temp_site_valid_project, monkeypatch, capsys): | |
258 namespace = _UploadArgsNamespace() | |
259 namespace.source_dir = str(temp_site_valid_project) | |
260 monkeypatch.setattr('logging.info', lambda x: sys.stderr.write(x)) | |
261 | |
262 main_project_handler(namespace) | |
263 _, err = capsys.readouterr() | |
264 | |
265 assert const.InfoMessages.FILES_UPLOADED in err | |
266 assert 'Created job 1' in err | |
267 | |
268 | |
269 @pytest.mark.script_launch_mode('subprocess') | |
270 @pytest.mark.parametrize('env,exp_msg', [ | |
271 (_ENV_NO_TOKEN, const.ErrorMessages.NO_TOKEN_PROVIDED.split('\n')[0]), | |
272 (_ENV_TOKEN_VALID, 'No project configured'), | |
273 ]) | |
274 def test_download_error_messages_as_script(temp_site, script_runner, env, | |
275 exp_msg): | |
276 cmd = list(_CMD_START) | |
277 cmd.extend(['download', str(temp_site)]) | |
278 | |
279 ret = script_runner.run(*cmd, env=env) | |
280 | |
281 assert not ret.success | |
282 assert exp_msg in ret.stderr | |
283 | |
284 | |
285 def test_download_no_target_files(temp_site_no_target_files, env_valid_token, | |
286 intercept, monkeypatch, capsys): | |
287 namespace = _DownloadArgsNamespace() | |
288 namespace.source_dir = str(temp_site_no_target_files) | |
289 monkeypatch.setattr('sys.exit', lambda x: sys.stderr.write(x)) | |
290 | |
291 main_project_handler(namespace) | |
292 out, err = capsys.readouterr() | |
293 | |
294 assert const.ErrorMessages.NO_TARGET_FILES_FOUND in err | |
295 | |
296 | |
297 def test_download_saves_to_disk(temp_site_valid_project, env_valid_token, | |
298 intercept_populated): | |
299 namespace = _DownloadArgsNamespace() | |
300 namespace.source_dir = str(temp_site_valid_project) | |
301 | |
302 main_project_handler(namespace) | |
303 | |
304 with open(os.path.join(temp_site_valid_project, 'locales', 'de', | |
305 'file.json')) as f: | |
306 assert json.dumps({'foo': 'bar', 'faz': 'baz'}) == f.read() | |
307 | |
308 with open(os.path.join(temp_site_valid_project, 'locales', 'de', 'foo', | |
309 'file-utf8.json'), 'rb') as f: | |
310 assert json.loads(f.read()) == {'foo': '\u1234'} | |
OLD | NEW |