summaryrefslogtreecommitdiff
path: root/src/zope/i18n/tests/test_translationdomain.py
blob: 5d551564e43643b410e6a1d13304b0b747af6f7b (plain)
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
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2001-2008 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""This module tests the regular persistent Translation Domain.
"""
import unittest
import os
from zope.i18n.translationdomain import TranslationDomain
from zope.i18n.gettextmessagecatalog import GettextMessageCatalog
from zope.i18n.tests.test_itranslationdomain import \
    TestITranslationDomain, Environment
from zope.i18nmessageid import MessageFactory
from zope.i18n.interfaces import ITranslationDomain

import zope.component

testdir = os.path.dirname(__file__)

en_file = os.path.join(testdir, 'en-default.mo')
de_file = os.path.join(testdir, 'de-default.mo')


class TestGlobalTranslationDomain(TestITranslationDomain, unittest.TestCase):

    def _getTranslationDomain(self):
        domain = TranslationDomain('default')
        en_catalog = GettextMessageCatalog('en', 'default',
                                           en_file)
        de_catalog = GettextMessageCatalog('de', 'default',
                                           de_file)
        domain.addCatalog(en_catalog)
        domain.addCatalog(de_catalog)
        return domain

    def testNoTargetLanguage(self):
        # Having a fallback would interfere with this test
        self._domain.setLanguageFallbacks([])
        TestITranslationDomain.testNoTargetLanguage(self)

    def testSimpleNoTranslate(self):
        translate = self._domain.translate
        eq = self.assertEqual
        # Unset fallback translation languages
        self._domain.setLanguageFallbacks([])

        # Test that a translation in an unsupported language returns the
        # default, if there is no fallback language
        eq(translate('short_greeting', target_language='es'), 'short_greeting')
        eq(translate('short_greeting', target_language='es',
                     default='short_greeting'), 'short_greeting')

        # Same test, but use the context argument instead of target_language
        context = Environment()
        eq(translate('short_greeting', context=context), 'short_greeting')
        eq(translate('short_greeting', context=context,
                     default='short_greeting'), 'short_greeting')

    def testEmptyStringTranslate(self):
        translate = self._domain.translate
        self.assertEqual(translate(u"", target_language='en'), u"")
        self.assertEqual(translate(u"", target_language='foo'), u"")

    def testStringTranslate(self):
        self.assertEqual(
            self._domain.translate(u"short_greeting", target_language='en'),
            u"Hello!")

    def testMessageIDTranslate(self):
        factory = MessageFactory('default')
        translate = self._domain.translate
        msgid = factory(u"short_greeting", 'default')
        self.assertEqual(translate(msgid, target_language='en'), u"Hello!")
        # MessageID attributes override arguments
        msgid = factory('43-not-there', 'this ${that} the other',
                        mapping={'that': 'THAT'})
        self.assertEqual(
            translate(msgid, target_language='en', default="default",
                      mapping={"that": "that"}), "this THAT the other")

    def testMessageIDRecursiveTranslate(self):
        factory = MessageFactory('default')
        translate = self._domain.translate
        msgid_sub1 = factory(u"44-not-there", '${blue}',
                             mapping={'blue': 'BLUE'})
        msgid_sub2 = factory(u"45-not-there", '${yellow}',
                             mapping={'yellow': 'YELLOW'})
        mapping = {'color1': msgid_sub1,
                   'color2': msgid_sub2}
        msgid = factory(u"46-not-there", 'Color: ${color1}/${color2}',
                        mapping=mapping)
        self.assertEqual(
            translate(msgid, target_language='en', default="default"),
            "Color: BLUE/YELLOW")
        # The recursive translation must not change the mappings
        self.assertEqual(msgid.mapping, {'color1': msgid_sub1,
                                         'color2': msgid_sub2})
        # A circular reference should not lead to crashes
        msgid1 = factory(u"47-not-there", 'Message 1 and $msg2',
                         mapping={})
        msgid2 = factory(u"48-not-there", 'Message 2 and $msg1',
                         mapping={})
        msgid1.mapping['msg2'] = msgid2
        msgid2.mapping['msg1'] = msgid1
        self.assertRaises(ValueError,
                          translate, msgid1, None, None, 'en', "default")
        # Recursive translations also work if the original message id wasn't a
        # message id but a Unicode with a directly passed mapping
        self.assertEqual(
            "Color: BLUE/YELLOW",
            translate(u"Color: ${color1}/${color2}", mapping=mapping,
                      target_language='en'))

        # If we have mapping with a message id from a different
        # domain, make sure we use that domain, not ours. If the
        # message domain is not registered yet, we should return a
        # default translation.
        alt_factory = MessageFactory('alt')
        msgid_sub = alt_factory(u"special", default=u"oohhh")
        mapping = {'message': msgid_sub}
        msgid = factory(u"46-not-there", 'Message: ${message}',
                        mapping=mapping)
        # test we get a default with no domain registered
        self.assertEqual(
            translate(msgid, target_language='en', default="default"),
            "Message: oohhh")
        # provide the domain
        domain = TranslationDomain('alt')
        path = testdir
        en_catalog = GettextMessageCatalog('en', 'alt',
                                           os.path.join(path, 'en-alt.mo'))
        domain.addCatalog(en_catalog)
        # test that we get the right translation
        zope.component.provideUtility(domain, ITranslationDomain, 'alt')
        self.assertEqual(
            translate(msgid, target_language='en', default="default"),
            "Message: Wow")

    def testMessageIDTranslateForDifferentDomain(self):
        domain = TranslationDomain('alt')
        path = testdir
        en_catalog = GettextMessageCatalog('en', 'alt',
                                           os.path.join(path, 'en-alt.mo'))
        domain.addCatalog(en_catalog)

        zope.component.provideUtility(domain, ITranslationDomain, 'alt')

        factory = MessageFactory('alt')
        msgid = factory(u"special", 'default')
        self.assertEqual(
            self._domain.translate(msgid, target_language='en'), u"Wow")

    def testSimpleFallbackTranslation(self):
        translate = self._domain.translate
        eq = self.assertEqual
        # Test that a translation in an unsupported language returns a
        # translation in the fallback language (by default, English)
        eq(translate('short_greeting', target_language='es'),
           u"Hello!")
        # Same test, but use the context argument instead of target_language
        context = Environment()
        eq(translate('short_greeting', context=context),
           u"Hello!")

    def testInterpolationWithoutTranslation(self):
        translate = self._domain.translate
        self.assertEqual(
            translate('42-not-there', target_language="en",
                      default="this ${that} the other",
                      mapping={"that": "THAT"}),
            "this THAT the other")

    def test_getCatalogInfos(self):
        cats = self._domain.getCatalogsInfo()
        self.assertEqual(
            cats,
            {'en': [en_file],
             'de': [de_file]})

    def test_releoadCatalogs(self):
        # It uses the keys we pass
        # so this does nothing
        self._domain.reloadCatalogs(())

        # The catalogNames, somewhat confusingly, are
        # the paths to the files.
        self._domain.reloadCatalogs((en_file, de_file))

        with self.assertRaises(KeyError):
            self._domain.reloadCatalogs(('dne',))

    def test_character_sets(self):
        """Test two character sets for the same language.

        Serbian can be written in Latin or Cyrillic,
        where Latin is currently most used.
        Interestingly, every Latin character can actually be mapped to
        one Cyrillic character, and the other way around,
        so you could write a script to turn one po-file into the other.

        But most practical is to have two locales with names
        sr@Latn and sr@Cyrl.  These are then two character sets
        for the same language.  So they should end up together
        under the same language in a translation domain.

        The best way for an integrator to choose which one to use,
        is to add an environment variable 'zope_i18n_allowed_languages'
        and let this contain either sr@Latn or sr@Cyrl.

        See https://github.com/collective/plone.app.locales/issues/326
        """
        standard_file = os.path.join(testdir, 'sr-default.mo')
        latin_file = os.path.join(testdir, 'sr@Latn-default.mo')
        cyrillic_file = os.path.join(testdir, 'sr@Cyrl-default.mo')
        standard_catalog = GettextMessageCatalog('sr', 'char', standard_file)
        latin_catalog = GettextMessageCatalog('sr@Latn', 'char', latin_file)
        cyrillic_catalog = GettextMessageCatalog(
            'sr@Cyrl', 'char', cyrillic_file
        )

        # Test the standard file.
        domain = TranslationDomain('char')
        domain.addCatalog(standard_catalog)
        self.assertEqual(
            domain.translate('short_greeting', target_language='sr'),
            u"Hello in Serbian Standard!",
        )

        # Test the Latin file.
        domain = TranslationDomain('char')
        domain.addCatalog(latin_catalog)
        self.assertEqual(
            domain.translate('short_greeting', target_language='sr'),
            u"Hello in Serbian Latin!",
        )
        # Note that sr@Latn is not recognizes as language id.
        self.assertEqual(
            domain.translate('short_greeting', target_language='sr@Latn'),
            u"short_greeting",
        )

        # Test the Cyrillic file.
        domain = TranslationDomain('char')
        domain.addCatalog(cyrillic_catalog)
        self.assertEqual(
            domain.translate('short_greeting', target_language='sr'),
            u"Hello in српски!",
        )

        # When I have all three locales, this is the order that
        # os.listdir gives them in:
        domain = TranslationDomain('char')
        domain.addCatalog(latin_catalog)
        domain.addCatalog(cyrillic_catalog)
        domain.addCatalog(standard_catalog)
        # The Latin one is first, so it wins.
        self.assertEqual(
            domain.translate('short_greeting', target_language='sr'),
            u"Hello in Serbian Latin!",
        )