Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Side by Side Diff: tests/test_xtm_translations_utils.py

Issue 29886648: Issue #6942 - Add XTM integration in CMS (Closed)
Patch Set: Created Sept. 20, 2018, 4:24 p.m.
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View unified diff | Download patch
OLDNEW
(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 import pytest
16 import json
17 import os
18
19 from cms.bin.xtm_translations import utils
20 import cms.bin.xtm_translations.constants as cnts
21 from cms.sources import FileSource
22 from cms.bin.xtm_translations.xtm_api import XTMCloudAPI
23
24 from tests.utils import exception_test
25
26 _API_TOKEN = 'TheXTM-APIToken-VALID'
27 _PROJECT_ID = 1234
28
29
30 @pytest.fixture
31 def toydir(tmpdir):
32 """"""
33 toydir = tmpdir.mkdir('toydir')
34
35 en_dir = toydir.mkdir('en')
36 en_dir.join('file.json').write(json.dumps({'a': 'b'}))
37
38 de_dir = toydir.mkdir('de')
39 de_dir.join('file.json').write(json.dumps({'a': 'b'}))
40 de_dir.join('file.txt').write('test')
41
42 return toydir
43
44
45 def test_get_files_to_upload():
46 """Generation of correct datatype for the XTMCloudAPI class."""
47 files = [('local.json', 'remote.json')]
48 data = {'a': 'b', 'c': 12}
49 file_strings = {'local': data}
50 expected_output = [('remote.json', json.dumps(data))]
51
52 assert expected_output == utils.get_files_to_upload(files, file_strings)
53
54
55 def test_read_token_invalid():
56 """Test if appropriate exception is raised when no token is found."""
57 exp_msg = cnts.ErrorMessages.NO_TOKEN_PROVIDED.format(
58 cnts.TOKEN['creation_cmd'],
59 )
60 with pytest.raises(Exception) as err:
61 utils.read_token()
62 assert exp_msg in str(err.value)
63
64
65 def test_read_token_valid():
66 """Test if the token is read correctly when the env is setup."""
67 env_var = cnts.TOKEN['env_var']
68 token = 'test_token'
69 os.environ[env_var] = token
70
71 try:
72 assert token == utils.read_token()
73 finally:
74 del os.environ[env_var]
75
76
77 def test_resolve_naming_conflicts_characters():
78 """Test if invalid name characters are replaced as expected."""
79 test_in = '{0}{1}{0}'.format(
80 'test', ''.join(cnts.PROJECT_NAME['invalid_chars']),
81 )
82 exp_out = '{0}{1}{0}'.format(
83 'test',
84 cnts.PROJECT_NAME['name_wildcard'] *
85 len(cnts.PROJECT_NAME['invalid_chars']),
86 )
87
88 assert exp_out == utils.resolve_naming_conflicts(test_in)
89
90
91 def test_resolve_naming_conflicts_length():
92 """Test if names that are too long are truncated as expected."""
93 test_in = 'a' * (cnts.PROJECT_NAME['max_length'] + 10)
94 exp_out = 'a' * cnts.PROJECT_NAME['max_length']
95
96 assert exp_out == utils.resolve_naming_conflicts(test_in)
97
98
99 def test_map_locales(temp_site):
100 """Test if a local website's languages are mapped to XTM's format."""
101 test_source = FileSource(str(temp_site))
102 exp_out = {'de_DE'}
103
104 assert exp_out == utils.map_locales(test_source)
105
106
107 def test_resolve_remote_filename_good(temp_site):
108 """Test if a remote filename is resolved to a valid OS path."""
109 test_in = '___foo___bar___faz___test.json'
110 exp_out = os.path.join(str(temp_site), *['foo', 'bar', 'faz', 'test.json'])
111
112 assert exp_out == utils.resolve_remote_filename(test_in, str(temp_site),
113 locales=['foo'])
114
115
116 def test_resolve_remote_filename_exception(temp_site):
117 test_in = '___foo___bar___faz___test.json'
118 exp_msg = cnts.ErrorMessages.CANT_RESOLVE_REMOTE_LANG.format('foo')
119
120 exception_test(utils.resolve_remote_filename, Exception, exp_msg,
121 test_in, str(temp_site), locales=['bar'])
122
123
124 def test_run_and_wait_no_err():
125 exp_out = 'test'
126
127 def func():
128 return exp_out
129
130 assert exp_out == utils.run_and_wait(func, Exception, '')
131
132
133 def test_run_and_wait_with_params():
134 test_in = 'test'
135
136 def func(a):
137 return a
138
139 assert test_in == utils.run_and_wait(func, Exception, '', a=test_in)
140
141
142 @pytest.mark.slow_test
143 def test_run_and_wait_infinite():
144 exp_msg = 'ERROR'
145
146 def func():
147 raise Exception(exp_msg)
148
149 with pytest.raises(Exception) as err:
150 utils.run_and_wait(func, Exception, exp_msg, max_tries=1)
151
152 assert exp_msg == str(err.value)
153
154
155 def test_resolve_locales(intercept_populated, temp_site):
156 """Test if locales are resolved correctly.
157
158 In this environment, no languages have to be added.
159 """
160 api = XTMCloudAPI(_API_TOKEN)
161 source = FileSource(str(temp_site))
162 source.write_to_config('XTM', 'project_id', str(_PROJECT_ID))
163
164 utils.resolve_locales(api, source)
165
166
167 def test_resolve_locales_adds_langs(intercept, temp_site):
168 """Test if locales are resolved correctly.
169
170 In this environment, new target languages are added.
171 """
172 api = XTMCloudAPI(_API_TOKEN)
173 source = FileSource(str(temp_site))
174 source.write_to_config('XTM', 'project_id', str(_PROJECT_ID))
175 exp_targets = {'de_DE'}
176
177 utils.resolve_locales(api, source)
178
179 assert exp_targets == api.get_target_languages(_PROJECT_ID)
180
181
182 def test_resolve_locales_raise_exception(intercept_populated, temp_site):
183 """Test if locales are resolved correctly.
184
185 In this environment, the API has more target languages configured than are
186 available online. We except an exception to be raised.
187 """
188 api = XTMCloudAPI(_API_TOKEN)
189 api.add_target_languages(_PROJECT_ID, ['ro_RO'])
190 source = FileSource(str(temp_site))
191 source.write_to_config('XTM', 'project_id', str(_PROJECT_ID))
192 exp_msg = ('The following languages are enabled in the API, but not '
193 "listed in locales: set(['ro_RO'])! Please remove them manually"
194 ' from project number 1234 and then re-run the script!')
195
196 exception_test(utils.resolve_locales, Exception, exp_msg, api, source)
197
198
199 def test_list_locales(toydir):
200 """Test if the the locales are listed correctly."""
201 assert utils.get_locales(str(toydir), 'en') == ['de']
202
203
204 def test_clear_files(toydir):
205 """Test if local translation files are deleted, as expected."""
206 required_locales = ['de']
207
208 utils.clear_files(str(toydir), required_locales)
209
210 assert os.path.exists(str(toydir.join('en/file.json')))
211 assert os.path.isfile(str(toydir.join('de/file.txt')))
212 assert not os.path.exists(str(toydir.join('de/file.json')))
213
214
215 @pytest.mark.parametrize('path', ['de/test.json', 'de/dir1/dir2/test.json'])
216 def test_write_data(toydir, path):
217 """Test if writing data to files works as expected."""
218 data = bytes(json.dumps({'a': 'b'}))
219
220 utils.write_to_file(data, str(toydir.join(path)))
221
222 assert toydir.join(path).read('rb') == data
OLDNEW

Powered by Google App Engine
This is Rietveld