File: test_project.py

package info (click to toggle)
transifex-client 0.8-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 332 kB
  • sloc: python: 2,437; makefile: 6
file content (538 lines) | stat: -rw-r--r-- 21,256 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# -*- coding: utf-8 -*-

from __future__ import with_statement
import unittest
import contextlib
import itertools
try:
    import json
except ImportError:
    import simplejson as json
from mock import Mock, patch

from txclib.project import Project
from txclib.config import Flipdict


class TestProject(unittest.TestCase):

    def test_extract_fields(self):
        """Test the functions that extract a field from a stats object."""
        stats = {
            'completed': '80%',
            'last_update': '00:00',
            'foo': 'bar',
        }
        self.assertEqual(
            stats['completed'], '%s%%' % Project._extract_completed(stats)
        )
        self.assertEqual(stats['last_update'], Project._extract_updated(stats))

    def test_specifying_resources(self):
        """Test the various ways to specify resources in a project."""
        p = Project(init=False)
        resources = [
            'proj1.res1',
            'proj2.res2',
            'transifex.txn',
            'transifex.txo',
        ]
        with patch.object(p, 'get_resource_list') as mock:
            mock.return_value = resources
            cmd_args = [
                'proj1.res1', '*1*', 'transifex*', '*r*',
                '*o', 'transifex.tx?', 'transifex.txn',
            ]
            results = [
                ['proj1.res1', ],
                ['proj1.res1', ],
                ['transifex.txn', 'transifex.txo', ],
                ['proj1.res1', 'proj2.res2', 'transifex.txn', 'transifex.txo', ],
                ['transifex.txo', ],
                ['transifex.txn', 'transifex.txo', ],
                ['transifex.txn', ],
                [],
            ]

            for i, arg in enumerate(cmd_args):
                resources = [arg]
                self.assertEqual(p.get_chosen_resources(resources), results[i])

            # wrong argument
            resources = ['*trasnifex*', ]
            self.assertRaises(Exception, p.get_chosen_resources, resources)


class TestProjectMinimumPercent(unittest.TestCase):
    """Test the minimum-perc option."""

    def setUp(self):
        super(TestProjectMinimumPercent, self).setUp()
        self.p = Project(init=False)
        self.p.minimum_perc = None
        self.p.resource = "resource"

    def test_cmd_option(self):
        """Test command-line option."""
        self.p.minimum_perc = 20
        results = itertools.cycle([80, 90 ])
        def side_effect(*args):
            return results.next()

        with patch.object(self.p, "get_resource_option") as mock:
            mock.side_effect = side_effect
            self.assertFalse(self.p._satisfies_min_translated({'completed': '12%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '20%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '30%'}))

    def test_global_only(self):
        """Test only global option."""
        results = itertools.cycle([80, None ])
        def side_effect(*args):
            return results.next()

        with patch.object(self.p, "get_resource_option") as mock:
            mock.side_effect = side_effect
            self.assertFalse(self.p._satisfies_min_translated({'completed': '70%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '80%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '90%'}))

    def test_local_lower_than_global(self):
        """Test the case where the local option is lower than the global."""
        results = itertools.cycle([80, 70 ])
        def side_effect(*args):
            return results.next()

        with patch.object(self.p, "get_resource_option") as mock:
            mock.side_effect = side_effect
            self.assertFalse(self.p._satisfies_min_translated({'completed': '60%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '70%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '80%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '90%'}))

    def test_local_higher_than_global(self):
        """Test the case where the local option is lower than the global."""
        results = itertools.cycle([60, 70 ])
        def side_effect(*args):
            return results.next()

        with patch.object(self.p, "get_resource_option") as mock:
            mock.side_effect = side_effect
            self.assertFalse(self.p._satisfies_min_translated({'completed': '60%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '70%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '80%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '90%'}))

    def test_local_only(self):
        """Test the case where the local option is lower than the global."""
        results = itertools.cycle([None, 70 ])
        def side_effect(*args):
            return results.next()

        with patch.object(self.p, "get_resource_option") as mock:
            mock.side_effect = side_effect
            self.assertFalse(self.p._satisfies_min_translated({'completed': '60%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '70%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '80%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '90%'}))

    def test_no_option(self):
        """"Test the case there is nothing defined."""
        results = itertools.cycle([None, None ])
        def side_effect(*args):
            return results.next()

        with patch.object(self.p, "get_resource_option") as mock:
            mock.side_effect = side_effect
            self.assertTrue(self.p._satisfies_min_translated({'completed': '0%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '10%'}))
            self.assertTrue(self.p._satisfies_min_translated({'completed': '90%'}))


class TestProjectFilters(unittest.TestCase):
    """Test filters used to decide whether to push/pull a translation or not."""

    def setUp(self):
        super(TestProjectFilters, self).setUp()
        self.p = Project(init=False)
        self.p.minimum_perc = None
        self.p.resource = "resource"
        self.stats = {
            'en': {
                'completed': '100%', 'last_update': '2011-11-01 15:00:00',
            }, 'el': {
                'completed': '60%', 'last_update': '2011-11-01 15:00:00',
            }, 'pt': {
                'completed': '70%', 'last_update': '2011-11-01 15:00:00',
            },
        }
        self.langs = self.stats.keys()

    def test_add_translation(self):
        """Test filters for adding translations.

        We do not test here for minimum percentages.
        """
        with patch.object(self.p, "get_resource_option") as mock:
            mock.return_value = None
            should_add = self.p._should_add_translation
            for force in [True, False]:
                for lang in self.langs:
                    self.assertTrue(should_add(lang, self.stats, force))

            # unknown language
            self.assertFalse(should_add('es', self.stats))

    def test_update_translation(self):
        """Test filters for updating a translation.

        We do not test here for minimum percentages.
        """
        with patch.object(self.p, "get_resource_option") as mock:
            mock.return_value = None

            should_update = self.p._should_update_translation
            force = True
            for lang in self.langs:
                self.assertTrue(should_update(lang, self.stats, 'foo', force))

            force = False       # reminder
            local_file = 'foo'

            # unknown language
            self.assertFalse(should_update('es', self.stats, local_file))

            # no local file
            with patch.object(self.p, "_get_time_of_local_file") as time_mock:
                time_mock.return_value = None
                with patch.object(self.p, "get_full_path") as path_mock:
                    path_mock.return_value = "foo"
                    for lang in self.langs:
                        self.assertTrue(
                            should_update(lang, self.stats, local_file)
                        )

            # older local files
            local_times = [self.p._generate_timestamp('2011-11-01 14:00:59')]
            results = itertools.cycle(local_times)
            def side_effect(*args):
                return results.next()

            with patch.object(self.p, "_get_time_of_local_file") as time_mock:
                time_mock.side_effect = side_effect
                with patch.object(self.p, "get_full_path") as path_mock:
                    path_mock.return_value = "foo"
                    for lang in self.langs:
                        self.assertTrue(
                            should_update(lang, self.stats, local_file)
                        )

            # newer local files
            local_times = [self.p._generate_timestamp('2011-11-01 15:01:59')]
            results = itertools.cycle(local_times)
            def side_effect(*args):
                return results.next()

            with patch.object(self.p, "_get_time_of_local_file") as time_mock:
                time_mock.side_effect = side_effect
                with patch.object(self.p, "get_full_path") as path_mock:
                    path_mock.return_value = "foo"
                    for lang in self.langs:
                        self.assertFalse(
                            should_update(lang, self.stats, local_file)
                        )

    def test_push_translation(self):
        """Test filters for pushing a translation file."""
        with patch.object(self.p, "get_resource_option") as mock:
            mock.return_value = None

            local_file = 'foo'
            should_push = self.p._should_push_translation
            force = True
            for lang in self.langs:
                self.assertTrue(should_push(lang, self.stats, local_file, force))

            force = False       # reminder

            # unknown language
            self.assertTrue(should_push('es', self.stats, local_file))

            # older local files
            local_times = [self.p._generate_timestamp('2011-11-01 14:00:59')]
            results = itertools.cycle(local_times)
            def side_effect(*args):
                return results.next()

            with patch.object(self.p, "_get_time_of_local_file") as time_mock:
                time_mock.side_effect = side_effect
                with patch.object(self.p, "get_full_path") as path_mock:
                    path_mock.return_value = "foo"
                    for lang in self.langs:
                        self.assertFalse(
                            should_push(lang, self.stats, local_file)
                        )

            # newer local files
            local_times = [self.p._generate_timestamp('2011-11-01 15:01:59')]
            results = itertools.cycle(local_times)
            def side_effect(*args):
                return results.next()

            with patch.object(self.p, "_get_time_of_local_file") as time_mock:
                time_mock.side_effect = side_effect
                with patch.object(self.p, "get_full_path") as path_mock:
                    path_mock.return_value = "foo"
                    for lang in self.langs:
                        self.assertTrue(
                            should_push(lang, self.stats, local_file)
                        )


class TestProjectPull(unittest.TestCase):
    """Test bits & pieces of the pull method."""

    def setUp(self):
        super(TestProjectPull, self).setUp()
        self.p = Project(init=False)
        self.p.minimum_perc = None
        self.p.resource = "resource"
        self.p.host = 'foo'
        self.p.project_slug = 'foo'
        self.p.resource_slug = 'foo'
        self.stats = {
            'en': {
                'completed': '100%', 'last_update': '2011-11-01 15:00:00',
            }, 'el': {
                'completed': '60%', 'last_update': '2011-11-01 15:00:00',
            }, 'pt': {
                'completed': '70%', 'last_update': '2011-11-01 15:00:00',
            },
        }
        self.langs = self.stats.keys()
        self.files = dict(zip(self.langs, itertools.repeat(None)))
        self.details = {'available_languages': []}
        for lang in self.langs:
            self.details['available_languages'].append({'code': lang})
        self.slang = 'en'
        self.lang_map = Flipdict()

    def test_new_translations(self):
        """Test finding new transaltions to add."""
        with patch.object(self.p, 'do_url_request') as resource_mock:
            resource_mock.return_value = json.dumps(self.details)
            files_keys = self.langs
            new_trans = self.p._new_translations_to_add
            for force in [True, False]:
                res = new_trans(
                    self.files, self.slang, self.lang_map, self.stats, force
                )
                self.assertEquals(res, set([]))

            with patch.object(self.p, '_should_add_translation') as filter_mock:
                filter_mock.return_value = True
                for force in [True, False]:
                    res = new_trans(
                        {'el': None}, self.slang, self.lang_map, self.stats, force
                    )
                    self.assertEquals(res, set(['pt']))
                for force in [True, False]:
                    res = new_trans(
                        {}, self.slang, self.lang_map, self.stats, force
                    )
                    self.assertEquals(res, set(['el', 'pt']))

                files = {}
                files['pt_PT'] = None
                lang_map = {'pt': 'pt_PT'}
                for force in [True, False]:
                    res = new_trans(
                        files, self.slang, lang_map, self.stats, force
                    )
                    self.assertEquals(res, set(['el']))

    def test_languages_to_pull_empty_initial_list(self):
        """Test determining the languages to pull, when the initial
        list is empty.
        """
        languages = []
        force = False

        res = self.p._languages_to_pull(
            languages, self.files, self.lang_map, self.stats, force
        )
        existing = res[0]
        new = res[1]
        self.assertEquals(existing, set(['el', 'en', 'pt']))
        self.assertFalse(new)

        del self.files['el']
        self.files['el-gr'] = None
        self.lang_map['el'] = 'el-gr'
        res = self.p._languages_to_pull(
            languages, self.files, self.lang_map, self.stats, force
        )
        existing = res[0]
        new = res[1]
        self.assertEquals(existing, set(['el', 'en', 'pt']))
        self.assertFalse(new)

    def test_languages_to_pull_with_initial_list(self):
        """Test determining the languages to pull, then there is a
        language selection from the user.
        """
        languages = ['el', 'en']
        self.lang_map['el'] = 'el-gr'
        del self.files['el']
        self.files['el-gr'] = None
        force = False

        with patch.object(self.p, '_should_add_translation') as mock:
            mock.return_value = True
            res = self.p._languages_to_pull(
                languages, self.files, self.lang_map, self.stats, force
            )
            existing = res[0]
            new = res[1]
            self.assertEquals(existing, set(['en', 'el-gr', ]))
            self.assertFalse(new)

            mock.return_value = False
            res = self.p._languages_to_pull(
                languages, self.files, self.lang_map, self.stats, force
            )
            existing = res[0]
            new = res[1]
            self.assertEquals(existing, set(['en', 'el-gr', ]))
            self.assertFalse(new)

            del self.files['el-gr']
            mock.return_value = True
            res = self.p._languages_to_pull(
                languages, self.files, self.lang_map, self.stats, force
            )
            existing = res[0]
            new = res[1]
            self.assertEquals(existing, set(['en', ]))
            self.assertEquals(new, set(['el', ]))

            mock.return_value = False
            res = self.p._languages_to_pull(
                languages, self.files, self.lang_map, self.stats, force
            )
            existing = res[0]
            new = res[1]
            self.assertEquals(existing, set(['en', ]))
            self.assertEquals(new, set([]))

    def test_in_combination_with_force_option(self):
        """Test the minumum-perc option along with -f."""
        with patch.object(self.p, 'get_resource_option') as mock:
            mock.return_value = 70

            res = self.p._should_download('de', self.stats, None, False)
            self.assertEquals(res, False)
            res = self.p._should_download('el', self.stats, None, False)
            self.assertEquals(res, False)
            res = self.p._should_download('el', self.stats, None, True)
            self.assertEquals(res, False)
            res = self.p._should_download('en', self.stats, None, False)
            self.assertEquals(res, True)
            res = self.p._should_download('en', self.stats, None, True)
            self.assertEquals(res, True)

            with patch.object(self.p, '_remote_is_newer') as local_file_mock:
                local_file_mock = False
                res = self.p._should_download('pt', self.stats, None, False)
                self.assertEquals(res, True)
                res = self.p._should_download('pt', self.stats, None, True)
                self.assertEquals(res, True)


class TestFormats(unittest.TestCase):
    """Tests for the supported formats."""

    def setUp(self):
        self.p = Project(init=False)

    def test_extensions(self):
        """Test returning the correct extension for a format."""
        sample_formats = {
            'PO': {'file-extensions': '.po, .pot'},
            'QT': {'file-extensions': '.ts'},
        }
        extensions = ['.po', '.ts', '', ]
        with patch.object(self.p, "do_url_request") as mock:
            mock.return_value = json.dumps(sample_formats)
            for (type_, ext) in zip(['PO', 'QT', 'NONE', ], extensions):
                extension = self.p._extension_for(type_)
                self.assertEquals(extension, ext)


class TestOptions(unittest.TestCase):
    """Test the methods related to parsing the configuration file."""

    def assertIs(self, expr1, expr2, msg=None):
        """Just like self.assertTrue(a is b), but with a nicer default message."""
        if expr1 is not expr2:
            standardMsg = '%s is not %s' % (safe_repr(expr1),
                                             safe_repr(expr2))
            self.fail(self._formatMessage(msg, standardMsg))

    def setUp(self):
        self.p = Project(init=False)

    def test_get_option(self):
        """Test _get_option method."""
        with contextlib.nested(
            patch.object(self.p, 'get_resource_option'),
            patch.object(self.p, 'config', create=True)
        ) as (rmock, cmock):
            rmock.return_value = 'resource'
            cmock.has_option.return_value = 'main'
            cmock.get.return_value = 'main'
            self.assertEqual(self.p._get_option(None, None), 'resource')
            rmock.return_value = None
            cmock.has_option.return_value = 'main'
            cmock.get.return_value = 'main'
            self.assertEqual(self.p._get_option(None, None), 'main')
            cmock.has_option.return_value = None
            self.assertIs(self.p._get_option(None, None), None)


class TestConfigurationOptions(unittest.TestCase):
    """Test the various configuration options."""

    def test_i18n_type(self):
        p = Project(init=False)
        type_string = 'type'
        i18n_type = 'PO'
        with patch.object(p, 'config', create=True) as config_mock:
            p.set_i18n_type([], i18n_type)
            calls = config_mock.method_calls
            self.assertEquals('set', calls[0][0])
            self.assertEquals('main', calls[0][1][0])
            p.set_i18n_type(['transifex.txo'], 'PO')
            calls = config_mock.method_calls
            self.assertEquals('set', calls[0][0])
            p.set_i18n_type(['transifex.txo', 'transifex.txn'], 'PO')
            calls = config_mock.method_calls
            self.assertEquals('set', calls[0][0])
            self.assertEquals('set', calls[1][0])


class TestStats(unittest.TestCase):
    """Test the access to the stats objects."""

    def setUp(self):
        self.stats = Mock()
        self.stats.__getitem__ = Mock()
        self.stats.__getitem__.return_value = '12%'

    def test_field_used_per_mode(self):
        """Test the fields used for each mode."""
        Project._extract_completed(self.stats, 'translate')
        self.stats.__getitem__.assert_called_with('completed')
        Project._extract_completed(self.stats, 'reviewed')
        self.stats.__getitem__.assert_called_with('reviewed_percentage')