Esempio n. 1
0
    def test_invalid_project(self):
        """If the project is invalid, redirect home."""
        LocaleFactory.create(code='fakelocale')

        response = self.client.get('/fakelocale/invalid-project/')
        assert_redirects(response, reverse('pontoon.home'))
        assert_equal(self.client.session['translate_error'], {'none': None})
Esempio n. 2
0
    def test_pull_multi_locale(self):
        """
        If the repo is multi-locale, pull all of the repos for the
        active locales.
        """
        locale1 = LocaleFactory.create(code='locale1')
        locale2 = LocaleFactory.create(code='locale2')
        repo = RepositoryFactory.create(
            type=Repository.GIT,
            url='https://example.com/{locale_code}/',
            project__locales=[locale1, locale2])

        repo.locale_url = lambda locale: 'https://example.com/' + locale.code
        repo.locale_checkout_path = lambda locale: '/media/' + locale.code

        with patch('pontoon.base.models.update_from_vcs') as update_from_vcs, \
             patch('pontoon.base.models.get_revision') as mock_get_revision:
            # Return path as the revision so different locales return
            # different values.
            mock_get_revision.side_effect = lambda type, path: path

            assert_equal(repo.pull(), {
                'locale1': '/media/locale1',
                'locale2': '/media/locale2'
            })
            update_from_vcs.assert_has_calls([
                call(Repository.GIT, 'https://example.com/locale1',
                     '/media/locale1'),
                call(Repository.GIT, 'https://example.com/locale2',
                     '/media/locale2')
            ])
Esempio n. 3
0
    def test_pull_multi_locale(self):
        """
        If the repo is multi-locale, pull all of the repos for the
        active locales.
        """
        locale1 = LocaleFactory.create(code="locale1")
        locale2 = LocaleFactory.create(code="locale2")
        repo = RepositoryFactory.create(
            type=Repository.GIT, url="https://example.com/{locale_code}/", project__locales=[locale1, locale2]
        )

        repo.locale_url = lambda locale: "https://example.com/" + locale.code
        repo.locale_checkout_path = lambda locale: "/media/" + locale.code

        with patch("pontoon.base.models.update_from_vcs") as update_from_vcs, patch(
            "pontoon.base.models.get_revision"
        ) as mock_get_revision:
            # Return path as the revision so different locales return
            # different values.
            mock_get_revision.side_effect = lambda type, path: path

            assert_equal(repo.pull(), {"locale1": "/media/locale1", "locale2": "/media/locale2"})
            update_from_vcs.assert_has_calls(
                [
                    call(Repository.GIT, "https://example.com/locale1", "/media/locale1"),
                    call(Repository.GIT, "https://example.com/locale2", "/media/locale2"),
                ]
            )
Esempio n. 4
0
    def test_invalid_project(self):
        """If the project is invalid, redirect home."""
        LocaleFactory.create(code='fakelocale')

        response = self.client.get('/fakelocale/invalid-project/')
        assert_redirects(response, reverse('pontoon.home'))
        assert_equal(self.client.session['translate_error'], {'none': None})
Esempio n. 5
0
    def test_invalid_project(self):
        """If the project is invalid, redirect home."""
        LocaleFactory.create(code="fakelocale")

        response = self.client.get("/fakelocale/invalid-project/")
        assert_redirects(response, reverse("pontoon.home"))
        assert_equal(self.client.session["translate_error"], {"none": None})
Esempio n. 6
0
    def test_pull_multi_locale(self):
        """
        If the repo is multi-locale, pull all of the repos for the
        active locales.
        """
        locale1 = LocaleFactory.create(code='locale1')
        locale2 = LocaleFactory.create(code='locale2')
        repo = RepositoryFactory.create(
            type=Repository.GIT,
            url='https://example.com/{locale_code}/',
            project__locales=[locale1, locale2]
        )

        repo.locale_url = lambda locale: 'https://example.com/' + locale.code
        repo.locale_checkout_path = lambda locale: '/media/' + locale.code

        with patch('pontoon.base.models.update_from_vcs') as update_from_vcs, \
             patch('pontoon.base.models.get_revision') as mock_get_revision:
            # Return path as the revision so different locales return
            # different values.
            mock_get_revision.side_effect = lambda type, path: path

            assert_equal(repo.pull(), {
                'locale1': '/media/locale1',
                'locale2': '/media/locale2'
            })
            update_from_vcs.assert_has_calls([
                call(Repository.GIT, 'https://example.com/locale1', '/media/locale1'),
                call(Repository.GIT, 'https://example.com/locale2', '/media/locale2')
            ])
Esempio n. 7
0
    def test_locale_top_contributors(self):
        """
        Tests if view returns top contributors specific for given locale.
        """
        first_locale = LocaleFactory.create()
        first_locale_contributor = TranslationFactory.create(
            locale=first_locale,
            entity__resource__project__locales=[first_locale]).user

        second_locale = LocaleFactory.create()
        second_locale_contributor = TranslationFactory.create(
            locale=second_locale,
            entity__resource__project__locales=[second_locale]).user

        with patch.object(views.LocaleContributorsView,
                          'render_to_response',
                          return_value=HttpResponse('')) as mock_render:
            self.client.get('/{}/contributors/'.format(first_locale.code))
            assert_equal(mock_render.call_args[0][0]['locale'], first_locale)
            assert_equal(list(mock_render.call_args[0][0]['contributors']),
                         [first_locale_contributor])

            self.client.get('/{}/contributors/'.format(second_locale.code))
            assert_equal(mock_render.call_args[0][0]['locale'], second_locale)
            assert_equal(list(mock_render.call_args[0][0]['contributors']),
                         [second_locale_contributor])
    def setUp(self):
        timezone_patch = patch.object(sync_projects, 'timezone')
        self.mock_timezone = timezone_patch.start()
        self.addCleanup(timezone_patch.stop)
        self.mock_timezone.now.return_value = aware_datetime(1970, 1, 1)

        self.translated_locale = LocaleFactory.create(code='translated-locale')
        self.inactive_locale = LocaleFactory.create(code='inactive-locale')
        self.repository = RepositoryFactory()

        self.db_project = ProjectFactory.create(
            name='db-project',
            locales=[self.translated_locale],
            repositories=[self.repository]
        )
        self.main_db_resource = ResourceFactory.create(
            project=self.db_project,
            path='main.lang',
            format='lang'
        )
        self.other_db_resource = ResourceFactory.create(
            project=self.db_project,
            path='other.lang',
            format='lang'
        )
        self.missing_db_resource = ResourceFactory.create(
            project=self.db_project,
            path='missing.lang',
            format='lang'
        )

        # Load paths from the fake locale directory.
        checkout_path_patch = patch.object(
            Project,
            'checkout_path',
            new_callable=PropertyMock,
            return_value=FAKE_CHECKOUT_PATH
        )
        checkout_path_patch.start()
        self.addCleanup(checkout_path_patch.stop)

        self.vcs_project = VCSProject(self.db_project)
        self.main_vcs_resource = self.vcs_project.resources[self.main_db_resource.path]
        self.other_vcs_resource = self.vcs_project.resources[self.other_db_resource.path]
        self.missing_vcs_resource = self.vcs_project.resources[self.missing_db_resource.path]
        self.main_vcs_entity = self.main_vcs_resource.entities['Source String']
        self.main_vcs_translation = self.main_vcs_entity.translations['translated-locale']

        # Mock VCSResource.save() for each resource to avoid altering
        # the filesystem.
        resource_save_patch = patch.object(VCSResource, 'save')
        resource_save_patch.start()
        self.addCleanup(resource_save_patch.stop)

        self.changeset = sync_projects.ChangeSet(
            self.db_project,
            self.vcs_project,
            aware_datetime(1970, 1, 1)
        )
    def setUp(self):
        timezone_patch = patch.object(sync_projects, 'timezone')
        self.mock_timezone = timezone_patch.start()
        self.addCleanup(timezone_patch.stop)
        self.mock_timezone.now.return_value = aware_datetime(1970, 1, 1)

        self.translated_locale = LocaleFactory.create(code='translated-locale')
        self.inactive_locale = LocaleFactory.create(code='inactive-locale')

        self.db_project = ProjectFactory.create(
            name='db-project',
            locales=[self.translated_locale],
            repository_type='git',
            repository_url='https://example.com/git'
        )
        self.main_db_resource = ResourceFactory.create(
            project=self.db_project,
            path='main.lang',
            format='lang'
        )
        self.other_db_resource = ResourceFactory.create(
            project=self.db_project,
            path='other.lang',
            format='lang'
        )
        self.missing_db_resource = ResourceFactory.create(
            project=self.db_project,
            path='missing.lang',
            format='lang'
        )

        # Load paths from the fake locale directory.
        checkout_path_patch = patch.object(
            Project,
            'checkout_path',
            new_callable=PropertyMock,
            return_value=FAKE_CHECKOUT_PATH
        )
        checkout_path_patch.start()
        self.addCleanup(checkout_path_patch.stop)

        self.vcs_project = VCSProject(self.db_project)
        self.main_vcs_resource = self.vcs_project.resources[self.main_db_resource.path]
        self.other_vcs_resource = self.vcs_project.resources[self.other_db_resource.path]
        self.missing_vcs_resource = self.vcs_project.resources[self.missing_db_resource.path]
        self.main_vcs_entity = self.main_vcs_resource.entities['Source String']
        self.main_vcs_translation = self.main_vcs_entity.translations['translated-locale']

        # Mock VCSResource.save() for each resource to avoid altering
        # the filesystem.
        for resource in self.vcs_project.resources.values():
            save_patch = patch.object(resource, 'save')
            save_patch.start()
            self.addCleanup(save_patch.stop)

        self.changeset = sync_projects.ChangeSet(self.db_project, self.vcs_project)
Esempio n. 10
0
    def test_locale_not_available(self):
        """
        If the requested locale is not available for this project,
        redirect home.
        """
        LocaleFactory.create(code='fakelocale')
        ProjectFactory.create(slug='valid-project')

        response = self.client.get('/fakelocale/valid-project/path/')
        assert_equal(response.status_code, 404)
Esempio n. 11
0
    def test_locale_not_available(self):
        """
        If the requested locale is not available for this project,
        redirect home.
        """
        LocaleFactory.create(code='fakelocale')
        ProjectFactory.create(slug='valid-project')

        response = self.client.get('/fakelocale/valid-project/path/')
        assert_equal(response.status_code, 404)
Esempio n. 12
0
    def test_locale_not_available(self):
        """
        If the requested locale is not available for this project,
        redirect home.
        """
        LocaleFactory.create(code='fakelocale')
        ProjectFactory.create(slug='valid-project')

        response = self.client.get('/fakelocale/valid-project/')
        assert_redirects(response, reverse('pontoon.home'))
        assert_equal(self.client.session['translate_error'], {'none': None})
Esempio n. 13
0
    def test_locale_not_available(self):
        """
        If the requested locale is not available for this project,
        redirect home.
        """
        LocaleFactory.create(code="fakelocale")
        ProjectFactory.create(slug="valid-project")

        response = self.client.get("/fakelocale/valid-project/")
        assert_redirects(response, reverse("pontoon.home"))
        assert_equal(self.client.session["translate_error"], {"none": None})
Esempio n. 14
0
    def test_locale_not_available(self):
        """
        If the requested locale is not available for this project,
        redirect home.
        """
        LocaleFactory.create(code='fakelocale')
        ProjectFactory.create(slug='valid-project')

        response = self.client.get('/fakelocale/valid-project/')
        assert_redirects(response, reverse('pontoon.home'))
        assert_equal(self.client.session['translate_error'], {'none': None})
Esempio n. 15
0
    def test_project_add_locale(self):
        locale_kl = LocaleFactory.create(code='kl', name='Klingon')
        locale_gs = LocaleFactory.create(code='gs', name='Geonosian')
        project = ProjectFactory.create(
            data_source='database',
            locales=[locale_kl],
            repositories=[],
        )
        _create_or_update_translated_resources(project, [locale_kl])

        url = reverse('pontoon.admin.project', args=(project.slug, ))

        # Boring data creation for FormSets. Django is painful with that,
        # or I don't know how to handle that more gracefully.
        form = ProjectForm(instance=project)
        form_data = dict(form.initial)
        del form_data['width']
        del form_data['deadline']
        del form_data['contact']
        form_data.update({
            'subpage_set-INITIAL_FORMS': '0',
            'subpage_set-TOTAL_FORMS': '1',
            'subpage_set-MIN_NUM_FORMS': '0',
            'subpage_set-MAX_NUM_FORMS': '1000',
            'externalresource_set-TOTAL_FORMS': '1',
            'externalresource_set-MAX_NUM_FORMS': '1000',
            'externalresource_set-MIN_NUM_FORMS': '0',
            'externalresource_set-INITIAL_FORMS': '0',
            'tag_set-TOTAL_FORMS': '1',
            'tag_set-INITIAL_FORMS': '0',
            'tag_set-MAX_NUM_FORMS': '1000',
            'tag_set-MIN_NUM_FORMS': '0',
            'repositories-INITIAL_FORMS': '0',
            'repositories-MIN_NUM_FORMS': '0',
            'repositories-MAX_NUM_FORMS': '1000',
            'repositories-TOTAL_FORMS': '0',
            # These are the values that actually matter.
            'pk': project.pk,
            'locales': [locale_kl.id, locale_gs.id],
        })

        response = self.client.post(url, form_data)
        assert_code(response, 200)
        assert_not_contains(response, '. Error.')

        # Verify we have the right ProjectLocale objects.
        pl = ProjectLocale.objects.filter(project=project)
        assert_equal(len(pl), 2)

        # Verify that TranslatedResource objects have been created.
        resource = Resource.objects.get(project=project, path='database')
        tr = TranslatedResource.objects.filter(resource=resource)
        assert_equal(len(tr), 2)
Esempio n. 16
0
    def test_manage_project_strings_translated_resource(self):
        """Test that adding new strings to a project enables translation of that
        project on all enabled locales.
        """
        locales = [
            LocaleFactory.create(code='kl', name='Klingon'),
            LocaleFactory.create(code='gs', name='Geonosian'),
        ]
        project = ProjectFactory.create(data_source='database',
                                        locales=locales,
                                        repositories=[])
        locales_count = len(locales)
        _create_or_update_translated_resources(project, locales)

        url = reverse('pontoon.admin.project.strings', args=(project.slug, ))

        new_strings = """
            Morty, do you know what "Wubba lubba dub dub" means?
            Oh that's just Rick's stupid non-sense catch phrase.
            It's not.
            In my people's tongue, it means "I am in great pain, please help me".
        """
        strings_count = 4
        response = self.client.post(url, {'new_strings': new_strings})
        assert_code(response, 200)

        # Verify no strings have been created as entities.
        entities = list(Entity.objects.filter(resource__project=project))
        assert_equal(len(entities), strings_count)

        # Verify the resource has the right stats.
        resources = Resource.objects.filter(project=project)
        assert_equal(len(resources), 1)
        resource = resources[0]
        assert_equal(resource.total_strings, strings_count)

        # Verify the correct TranslatedResource objects have been created.
        translated_resources = TranslatedResource.objects.filter(
            resource__project=project)
        assert_equal(len(translated_resources), locales_count)

        # Verify stats have been correctly updated on locale, project and resource.
        for tr in translated_resources:
            assert_equal(tr.total_strings, strings_count)

        project = Project.objects.get(id=project.id)
        assert_equal(project.total_strings, strings_count * locales_count)

        for l in locales:
            locale = Locale.objects.get(id=l.id)
            assert_equal(locale.total_strings, strings_count)
Esempio n. 17
0
    def test_latest_activity(self):
        """Ensure that the latest_activity field is added to parts."""
        locale = LocaleFactory.create(code='test')
        project = ProjectFactory.create(locales=[locale], slug='test-project')
        resource = ResourceFactory.create(project=project, path='has/stats.po')
        translation = TranslationFactory.create(entity__resource=resource,
                                                locale=locale)
        StatsFactory.create(resource=resource,
                            locale=locale,
                            latest_translation=translation)

        with patch.object(Project, 'locales_parts_stats') as mock_locales_parts_stats, \
                patch('pontoon.base.views.render') as mock_render:
            mock_locales_parts_stats.return_value = [{
                'resource__path':
                'has/stats.po'
            }, {
                'resource__path':
                'no/stats.po'
            }]

            views.locale_project(self.factory.get('/'),
                                 locale='test',
                                 slug='test-project')
            ctx = mock_render.call_args[0][2]
            assert_equal(ctx['parts'], [{
                'resource__path': 'has/stats.po',
                'latest_activity': translation
            }, {
                'resource__path': 'no/stats.po',
                'latest_activity': None
            }])
Esempio n. 18
0
    def test_translation_counts(self):
        """
        Translation memory should aggregate identical translations strings
        from the different entities and count up their occurrences.
        """
        new_locale = LocaleFactory.create()
        memory_entry = TranslationMemoryFactory.create(source="aaaa", target="ccc", locale=new_locale)
        TranslationMemoryFactory.create(source="abaa", target="ccc", locale=new_locale)
        TranslationMemoryFactory.create(source="aaab", target="ccc", locale=new_locale)
        TranslationMemoryFactory.create(source="aaab", target="ccc", locale=new_locale)

        response = self.client.get('/translation-memory/', {
            'text': 'aaaa',
            'pk': memory_entry.entity.pk,
            'locale': memory_entry.locale.code
        })

        result = response.json()
        src_string = result[0].pop('source')

        assert_true(src_string in ('abaa', 'aaab', 'aaab'))
        assert_equal(
            result,
            [{
                u'count': 3,
                u'quality': 75.0,
                u'target': u'ccc',
            }]
        )
Esempio n. 19
0
    def test_best_quality_entry(self):
        """
        Translation memory should return results entries aggregated by
        translation string.
        """
        new_locale = LocaleFactory.create()
        memory_entry = TranslationMemoryFactory.create(source="aaa",
                                                       target="ccc",
                                                       locale=new_locale)
        TranslationMemoryFactory.create(source="aaa",
                                        target="ddd",
                                        locale=new_locale)
        TranslationMemoryFactory.create(source="bbb",
                                        target="ccc",
                                        locale=new_locale)

        response = self.client.get('/translation-memory/', {
            'text': 'aaa',
            'pk': memory_entry.entity.pk,
            'locale': new_locale.code
        })
        assert_json(response, [{
            "count": 1,
            "source": "aaa",
            "quality": 100.0,
            "target": "ddd"
        }])
Esempio n. 20
0
    def test_locale_checkout_path(self):
        """Append the locale code the the project's checkout_path."""
        repo = RepositoryFactory.create(url="https://example.com/path/{locale_code}/", project__slug="test-project")
        locale = LocaleFactory.create(code="test-locale")

        with self.settings(MEDIA_ROOT="/media/root"):
            assert_equal(repo.locale_checkout_path(locale), "/media/root/projects/test-project/path/test-locale")
Esempio n. 21
0
    def test_query_args_filtering(self):
        """
        Tests if query args are honored properly and contributors are filtered.
        """
        locale_first, locale_second = LocaleFactory.create_batch(2)

        first_contributor = self.create_contributor_with_translation_counts(
            approved=12, unapproved=1, needs_work=2, locale=locale_first)
        second_contributor = self.create_contributor_with_translation_counts(
            approved=11, unapproved=1, needs_work=2, locale=locale_second)
        third_contributor = self.create_contributor_with_translation_counts(
            approved=10, unapproved=12, needs_work=2, locale=locale_first)

        # Testing filtering for the first locale
        top_contributors = User.translators.with_translation_counts(aware_datetime(2015, 1, 1), Q(translation__locale=locale_first))
        assert_equal(top_contributors.count(), 2)
        assert_equal(top_contributors[0], third_contributor)
        assert_attributes_equal(top_contributors[0], translations_count=24,
            translations_approved_count=10, translations_unapproved_count=12,
            translations_needs_work_count=2)

        assert_equal(top_contributors[1], first_contributor)
        assert_attributes_equal(top_contributors[1], translations_count=15,
            translations_approved_count=12, translations_unapproved_count=1,
            translations_needs_work_count=2)

        # Testing filtering for the second locale
        top_contributors = User.translators.with_translation_counts(aware_datetime(2015, 1, 1), Q(translation__locale=locale_second))

        assert_equal(top_contributors.count(), 1)
        assert_equal(top_contributors[0], second_contributor)
        assert_attributes_equal(top_contributors[0], translations_count=14,
            translations_approved_count=11, translations_unapproved_count=1,
            translations_needs_work_count=2)
Esempio n. 22
0
 def setUp(self):
     self.resource = ResourceFactory.create()
     self.locale = LocaleFactory.create()
     ProjectLocale.objects.create(project=self.resource.project, locale=self.locale)
     TranslatedResource.objects.create(resource=self.resource, locale=self.locale)
     self.entities = EntityFactory.create_batch(3, resource=self.resource)
     self.entities_pks = [e.pk for e in self.entities]
Esempio n. 23
0
    def test_url_for_path(self):
        """
        Return the first locale_checkout_path for locales active for the
        repo's project that matches the given path.
        """
        matching_locale = LocaleFactory.create(code="match")
        non_matching_locale = LocaleFactory.create(code="nomatch")
        repo = RepositoryFactory.create(
            project__locales=[matching_locale, non_matching_locale],
            project__slug="test-project",
            url="https://example.com/path/to/{locale_code}/",
        )

        with self.settings(MEDIA_ROOT="/media/root"):
            test_path = "/media/root/projects/test-project/path/to/match/foo/bar.po"
            assert_equal(repo.url_for_path(test_path), "https://example.com/path/to/match/")
Esempio n. 24
0
 def test_get_latest_activity_without_latest(self):
     """
     If the locale doesn't have a latest_translation and no project
     is given, return None.
     """
     locale = LocaleFactory.create(latest_translation=None)
     assert_is_none(locale.get_latest_activity())
Esempio n. 25
0
 def setUp(self):
     self.locale = LocaleFactory.create(cldr_plurals="0,1")
     self.project = ProjectFactory.create(locales=[self.locale])
     self.main_resource = ResourceFactory.create(project=self.project, path="main.lang")
     self.other_resource = ResourceFactory.create(project=self.project, path="other.lang")
     self.main_entity = EntityFactory.create(
         resource=self.main_resource,
         string="Source String",
         string_plural="Plural Source String",
         key="Source String",
     )
     self.other_entity = EntityFactory.create(
         resource=self.other_resource,
         string="Other Source String",
         key="Key" + KEY_SEPARATOR + "Other Source String",
     )
     self.main_translation = TranslationFactory.create(
         entity=self.main_entity, locale=self.locale, plural_form=0, string="Translated String"
     )
     self.main_translation_plural = TranslationFactory.create(
         entity=self.main_entity, locale=self.locale, plural_form=1, string="Translated Plural String"
     )
     self.other_translation = TranslationFactory.create(
         entity=self.other_entity, locale=self.locale, string="Other Translated String"
     )
     self.subpage = SubpageFactory.create(project=self.project, name="Subpage", resources=[self.main_resource])
Esempio n. 26
0
 def test_get_latest_activity_without_latest(self):
     """
     If the locale doesn't have a latest_translation and no project
     is given, return None.
     """
     locale = LocaleFactory.create(latest_translation=None)
     assert_is_none(locale.get_latest_activity())
Esempio n. 27
0
    def test_managers_group(self):
        """
        Tests if user has permission to manage and translate locales after assigment.
        """
        user = UserFactory.create()
        [first_locale, second_locale] = LocaleFactory.create_batch(2)

        assert_equal(user.has_perm("base.can_translate_locale"), False)
        assert_equal(user.has_perm("base.can_translate_locale", first_locale), False)
        assert_equal(user.has_perm("base.can_translate_locale", second_locale), False)
        assert_equal(user.has_perm("base.can_manage_locale"), False)
        assert_equal(user.has_perm("base.can_manage_locale", first_locale), False)
        assert_equal(user.has_perm("base.can_manage_locale", second_locale), False)

        user.groups.add(second_locale.managers_group)

        assert_equal(user.has_perm("base.can_translate_locale"), False)
        assert_equal(user.has_perm("base.can_translate_locale", first_locale), False)
        assert_equal(user.has_perm("base.can_translate_locale", second_locale), True)
        assert_equal(user.has_perm("base.can_manage_locale"), False)
        assert_equal(user.has_perm("base.can_manage_locale", first_locale), False)
        assert_equal(user.has_perm("base.can_manage_locale", second_locale), True)

        user.groups.add(first_locale.managers_group)

        assert_equal(user.has_perm("base.can_translate_locale"), False)
        assert_equal(user.has_perm("base.can_translate_locale", first_locale), True)
        assert_equal(user.has_perm("base.can_translate_locale", second_locale), True)
        assert_equal(user.has_perm("base.can_manage_locale"), False)
        assert_equal(user.has_perm("base.can_manage_locale", first_locale), True)
        assert_equal(user.has_perm("base.can_manage_locale", second_locale), True)
Esempio n. 28
0
 def setUp(self):
     self.locale = LocaleFactory.create(cldr_plurals="0,1")
     self.project = ProjectFactory.create(locales=[self.locale])
     self.main_resource = ResourceFactory.create(project=self.project,
                                                 path='main.lang')
     self.other_resource = ResourceFactory.create(project=self.project,
                                                  path='other.lang')
     self.main_entity = EntityFactory.create(
         resource=self.main_resource,
         string='Source String',
         string_plural='Plural Source String',
         key='Source String')
     self.other_entity = EntityFactory.create(resource=self.other_resource,
                                              string='Other Source String',
                                              key='Key' + KEY_SEPARATOR +
                                              'Other Source String')
     self.main_translation = TranslationFactory.create(
         entity=self.main_entity,
         locale=self.locale,
         plural_form=0,
         string='Translated String')
     self.main_translation_plural = TranslationFactory.create(
         entity=self.main_entity,
         locale=self.locale,
         plural_form=1,
         string='Translated Plural String')
     self.other_translation = TranslationFactory.create(
         entity=self.other_entity,
         locale=self.locale,
         string='Other Translated String')
     self.subpage = SubpageFactory.create(project=self.project,
                                          name='Subpage',
                                          resources=[self.main_resource])
Esempio n. 29
0
    def test_translators_group(self):
        """
        Tests if user has permission to translate locales after assigment.
        """
        user = UserFactory.create()
        [first_locale, second_locale] = LocaleFactory.create_batch(2)

        assert_equal(user.has_perm('base.can_translate_locale'), False)
        assert_equal(user.has_perm('base.can_translate_locale', first_locale),
                     False)
        assert_equal(user.has_perm('base.can_translate_locale', second_locale),
                     False)

        user.groups.add(second_locale.translators_group)

        assert_equal(user.has_perm('base.can_translate_locale'), False)
        assert_equal(user.has_perm('base.can_translate_locale', first_locale),
                     False)
        assert_equal(user.has_perm('base.can_translate_locale', second_locale),
                     True)

        user.groups.add(first_locale.translators_group)

        assert_equal(user.has_perm('base.can_translate_locale'), False)
        assert_equal(user.has_perm('base.can_translate_locale', first_locale),
                     True)
        assert_equal(user.has_perm('base.can_translate_locale', second_locale),
                     True)
Esempio n. 30
0
    def test_translation_counts(self):
        """
        Translation memory should aggregate identical translations strings
        from the different entities and count up their occurrences.
        """
        new_locale = LocaleFactory.create()
        memory_entry = TranslationMemoryFactory.create(source="aaaa",
                                                       target="ccc",
                                                       locale=new_locale)
        TranslationMemoryFactory.create(source="abaa",
                                        target="ccc",
                                        locale=new_locale)
        TranslationMemoryFactory.create(source="aaab",
                                        target="ccc",
                                        locale=new_locale)
        TranslationMemoryFactory.create(source="aaab",
                                        target="ccc",
                                        locale=new_locale)

        response = self.client.get(
            '/translation-memory/', {
                'text': 'aaaa',
                'pk': memory_entry.entity.pk,
                'locale': memory_entry.locale.code
            })

        result = response.json()
        src_string = result[0].pop('source')

        assert_true(src_string in ('abaa', 'aaab', 'aaab'))
        assert_equal(result, [{
            u'count': 3,
            u'quality': 75.0,
            u'target': u'ccc',
        }])
Esempio n. 31
0
    def test_save_latest_translation_update(self):
        """
        When a translation is saved, update the latest_translation
        attribute on the related project, locale, stats, and
        project_locale objects.
        """
        locale = LocaleFactory.create(latest_translation=None)
        project = ProjectFactory.create(locales=[locale], latest_translation=None)
        resource = ResourceFactory.create(project=project)
        stats = StatsFactory.create(locale=locale, resource=resource, latest_translation=None)
        project_locale = ProjectLocale.objects.get(locale=locale, project=project)

        assert_is_none(locale.latest_translation)
        assert_is_none(project.latest_translation)
        assert_is_none(stats.latest_translation)
        assert_is_none(project_locale.latest_translation)

        translation = TranslationFactory.create(
            locale=locale,
            entity__resource=resource,
            date=aware_datetime(1970, 1, 1)
        )
        self.assert_latest_translation(locale, translation)
        self.assert_latest_translation(project, translation)
        self.assert_latest_translation(stats, translation)
        self.assert_latest_translation(project_locale, translation)

        # Ensure translation is replaced for newer translations
        newer_translation = TranslationFactory.create(
            locale=locale,
            entity__resource=resource,
            date=aware_datetime(1970, 2, 1)
        )
        self.assert_latest_translation(locale, newer_translation)
        self.assert_latest_translation(project, newer_translation)
        self.assert_latest_translation(stats, newer_translation)
        self.assert_latest_translation(project_locale, newer_translation)

        # Ensure translation isn't replaced for older translations.
        TranslationFactory.create(
            locale=locale,
            entity__resource=resource,
            date=aware_datetime(1970, 1, 5)
        )
        self.assert_latest_translation(locale, newer_translation)
        self.assert_latest_translation(project, newer_translation)
        self.assert_latest_translation(stats, newer_translation)
        self.assert_latest_translation(project_locale, newer_translation)

        # Ensure approved_date is taken into consideration as well.
        newer_approved_translation = TranslationFactory.create(
            locale=locale,
            entity__resource=resource,
            approved_date=aware_datetime(1970, 3, 1)
        )
        self.assert_latest_translation(locale, newer_approved_translation)
        self.assert_latest_translation(project, newer_approved_translation)
        self.assert_latest_translation(stats, newer_approved_translation)
        self.assert_latest_translation(project_locale, newer_approved_translation)
Esempio n. 32
0
    def test_save_latest_translation_update(self):
        """
        When a translation is saved, update the latest_translation
        attribute on the related project, locale, stats, and
        project_locale objects.
        """
        locale = LocaleFactory.create(latest_translation=None)
        project = ProjectFactory.create(locales=[locale],
                                        latest_translation=None)
        resource = ResourceFactory.create(project=project)
        stats = StatsFactory.create(locale=locale,
                                    resource=resource,
                                    latest_translation=None)
        project_locale = ProjectLocale.objects.get(locale=locale,
                                                   project=project)

        assert_is_none(locale.latest_translation)
        assert_is_none(project.latest_translation)
        assert_is_none(stats.latest_translation)
        assert_is_none(project_locale.latest_translation)

        translation = TranslationFactory.create(locale=locale,
                                                entity__resource=resource,
                                                date=aware_datetime(
                                                    1970, 1, 1))
        self.assert_latest_translation(locale, translation)
        self.assert_latest_translation(project, translation)
        self.assert_latest_translation(stats, translation)
        self.assert_latest_translation(project_locale, translation)

        # Ensure translation is replaced for newer translations
        newer_translation = TranslationFactory.create(
            locale=locale,
            entity__resource=resource,
            date=aware_datetime(1970, 2, 1))
        self.assert_latest_translation(locale, newer_translation)
        self.assert_latest_translation(project, newer_translation)
        self.assert_latest_translation(stats, newer_translation)
        self.assert_latest_translation(project_locale, newer_translation)

        # Ensure translation isn't replaced for older translations.
        TranslationFactory.create(locale=locale,
                                  entity__resource=resource,
                                  date=aware_datetime(1970, 1, 5))
        self.assert_latest_translation(locale, newer_translation)
        self.assert_latest_translation(project, newer_translation)
        self.assert_latest_translation(stats, newer_translation)
        self.assert_latest_translation(project_locale, newer_translation)

        # Ensure approved_date is taken into consideration as well.
        newer_approved_translation = TranslationFactory.create(
            locale=locale,
            entity__resource=resource,
            approved_date=aware_datetime(1970, 3, 1))
        self.assert_latest_translation(locale, newer_approved_translation)
        self.assert_latest_translation(project, newer_approved_translation)
        self.assert_latest_translation(stats, newer_approved_translation)
        self.assert_latest_translation(project_locale,
                                       newer_approved_translation)
Esempio n. 33
0
 def setUp(self):
     super(FormatTestsMixin, self).setUp()
     self.locale = LocaleFactory.create(
         code='test-locale',
         name='Test Locale',
         plural_rule='(n != 1)',
         cldr_plurals='1,5',
     )
Esempio n. 34
0
 def setUp(self):
     super().setUp()
     self.locale = LocaleFactory.create(
         code="test-locale",
         name="Test Locale",
         plural_rule="(n != 1)",
         cldr_plurals="1,5",
     )
Esempio n. 35
0
    def test_locale_url(self):
        """Fill in the {locale_code} variable in the URL."""
        repo = RepositoryFactory.create(
            url='https://example.com/path/to/{locale_code}/',
        )
        locale = LocaleFactory.create(code='test-locale')

        assert_equal(repo.locale_url(locale), 'https://example.com/path/to/test-locale/')
Esempio n. 36
0
    def test_url_for_path(self):
        """
        Return the first locale_checkout_path for locales active for the
        repo's project that matches the given path.
        """
        matching_locale = LocaleFactory.create(code='match')
        non_matching_locale = LocaleFactory.create(code='nomatch')
        repo = RepositoryFactory.create(
            project__locales=[matching_locale, non_matching_locale],
            project__slug='test-project',
            url='https://example.com/path/to/{locale_code}/',
            multi_locale=True
        )

        with self.settings(MEDIA_ROOT='/media/root'):
            test_path = '/media/root/projects/test-project/path/to/match/foo/bar.po'
            assert_equal(repo.url_for_path(test_path), 'https://example.com/path/to/match/')
Esempio n. 37
0
 def setUp(self):
     self.locale, self.locale_other = LocaleFactory.create_batch(2)
     self.project = ProjectFactory.create(
         locales=[self.locale, self.locale_other])
     self.resource = ResourceFactory.create(project=self.project,
                                            path='/main/path.po')
     EntityFactory.create(resource=self.resource)
     StatsFactory.create(resource=self.resource, locale=self.locale)
Esempio n. 38
0
    def test_locale_url(self):
        """Fill in the {locale_code} variable in the URL."""
        repo = RepositoryFactory.create(
            url='https://example.com/path/to/{locale_code}/', )
        locale = LocaleFactory.create(code='test-locale')

        assert_equal(repo.locale_url(locale),
                     'https://example.com/path/to/test-locale/')
Esempio n. 39
0
    def test_url_for_path(self):
        """
        Return the first locale_checkout_path for locales active for the
        repo's project that matches the given path.
        """
        matching_locale = LocaleFactory.create(code='match')
        non_matching_locale = LocaleFactory.create(code='nomatch')
        repo = RepositoryFactory.create(
            project__locales=[matching_locale, non_matching_locale],
            project__slug='test-project',
            url='https://example.com/path/to/{locale_code}/',
        )

        with self.settings(MEDIA_ROOT='/media/root'):
            test_path = '/media/root/projects/test-project/path/to/match/foo/bar.po'
            assert_equal(repo.url_for_path(test_path),
                         'https://example.com/path/to/match/')
Esempio n. 40
0
    def test_get_latest_activity_with_latest(self):
        """
        If the locale has a latest_translation and no project is given,
        return it.
        """
        translation = TranslationFactory.create()
        locale = LocaleFactory.create(latest_translation=translation)

        assert_equal(locale.get_latest_activity(), translation.latest_activity)
Esempio n. 41
0
    def test_get_latest_activity_with_latest(self):
        """
        If the locale has a latest_translation and no project is given,
        return it.
        """
        translation = TranslationFactory.create()
        locale = LocaleFactory.create(latest_translation=translation)

        assert_equal(locale.get_latest_activity(), translation.latest_activity)
Esempio n. 42
0
def test_profileform_user_locales_order(member, settings_url):
    locale1, locale2, locale3 = LocaleFactory.create_batch(3)
    response = member.client.get(settings_url)
    assert response.status_code == 200

    response = member.client.post(
        "/settings/",
        {
            "first_name": "contributor",
            "email": member.user.email,
            "locales_order": commajoin(
                locale2.pk,
                locale1.pk,
                locale3.pk,
            ),
        },
    )

    assert response.status_code == 200
    assert list(
        User.objects.get(pk=member.user.pk).profile.sorted_locales) == [
            locale2,
            locale1,
            locale3,
        ]
    # Test if you can clear all locales
    response = member.client.post(
        "/settings/",
        {
            "first_name": "contributor",
            "email": member.user.email,
            "locales_order": ""
        },
    )
    assert response.status_code == 200
    assert list(
        User.objects.get(pk=member.user.pk).profile.sorted_locales) == []

    # Test if form handles duplicated locales
    response = member.client.post(
        "/settings/",
        {
            "first_name": "contributor",
            "email": member.user.email,
            "locales_order": commajoin(
                locale1.pk,
                locale2.pk,
                locale2.pk,
            ),
        },
    )
    assert response.status_code, 200
    assert list(
        User.objects.get(pk=member.user.pk).profile.sorted_locales) == [
            locale1,
            locale2,
        ]
Esempio n. 43
0
    def test_user_locales_order(self):
        locale1, locale2, locale3 = LocaleFactory.create_batch(3)
        response = self.client.get(self.url)
        assert_equal(response.status_code, 200)

        response = self.client.post(
            "/settings/",
            {
                "first_name": "contributor",
                "email": self.user.email,
                "locales_order": commajoin(
                    locale2.pk,
                    locale1.pk,
                    locale3.pk,
                ),
            },
        )

        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales),
            [locale2, locale1, locale3],
        )
        # Test if you can clear all locales
        response = self.client.post(
            "/settings/",
            {
                "first_name": "contributor",
                "email": self.user.email,
                "locales_order": "",
            },
        )
        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales), [])

        # Test if form handles duplicated locales
        response = self.client.post(
            "/settings/",
            {
                "first_name": "contributor",
                "email": self.user.email,
                "locales_order": commajoin(
                    locale1.pk,
                    locale2.pk,
                    locale2.pk,
                ),
            },
        )
        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales),
            [locale1, locale2],
        )
Esempio n. 44
0
    def test_locale_top_contributors(self):
        """
        Tests if view returns top contributors specific for given locale.
        """
        first_locale = LocaleFactory.create()
        first_locale_contributor = TranslationFactory.create(locale=first_locale,
            entity__resource__project__locales=[first_locale]).user

        second_locale = LocaleFactory.create()
        second_locale_contributor = TranslationFactory.create(locale=second_locale,
            entity__resource__project__locales=[second_locale]).user

        with patch.object(views.LocaleContributorsView, 'render_to_response', return_value=HttpResponse('')) as mock_render:
            self.client.get('/{}/contributors/'.format(first_locale.code))
            assert_equal(mock_render.call_args[0][0]['locale'], first_locale)
            assert_equal(list(mock_render.call_args[0][0]['contributors']), [first_locale_contributor])

            self.client.get('/{}/contributors/'.format(second_locale.code))
            assert_equal(mock_render.call_args[0][0]['locale'], second_locale)
            assert_equal(list(mock_render.call_args[0][0]['contributors']), [second_locale_contributor])
Esempio n. 45
0
 def setUp(self):
     self.locale, self.locale_other = LocaleFactory.create_batch(2)
     self.project = ProjectFactory.create(
         locales=[self.locale, self.locale_other]
     )
     self.resource = ResourceFactory.create(
         project=self.project,
         path='/main/path.po'
     )
     EntityFactory.create(resource=self.resource)
     StatsFactory.create(resource=self.resource, locale=self.locale)
Esempio n. 46
0
    def test_locale_checkout_path(self):
        """Append the locale code the the project's checkout_path."""
        repo = RepositoryFactory.create(
            url='https://example.com/path/{locale_code}/',
            project__slug='test-project',
        )
        locale = LocaleFactory.create(code='test-locale')

        with self.settings(MEDIA_ROOT='/media/root'):
            assert_equal(repo.locale_checkout_path(locale),
                         '/media/root/projects/test-project/path/test-locale')
Esempio n. 47
0
    def test_get_latest_activity_with_locale(self):
        """
        If a locale is given, defer to
        ProjectLocale.get_latest_activity.
        """
        locale = LocaleFactory.create()
        project = ProjectFactory.create(locales=[locale])

        with patch.object(ProjectLocale, "get_latest_activity") as mock_get_latest_activity:
            mock_get_latest_activity.return_value = "latest"
            assert_equal(locale.get_latest_activity(project=project), "latest")
            mock_get_latest_activity.assert_called_with(project, locale)
    def test_save_create_dirs(self):
        """
        If the directories in a resource's path don't exist, create them
        on save.
        """
        path = os.path.join(tempfile.mkdtemp(), 'does', 'not', 'exist.dtd')
        translated_resource = self.create_nonexistant_resource(path)

        translated_resource.translations[0].strings = {None: 'New Translated String'}
        translated_resource.save(LocaleFactory.create())

        assert_true(os.path.exists(path))
Esempio n. 49
0
    def test_project_locale_added(self):
        """
        When a locale is added to a project, has_changed should be set
        to True.
        """
        project = ProjectFactory.create(locales=[], has_changed=False)
        assert_false(project.has_changed)

        locale = LocaleFactory.create()
        ProjectLocaleFactory.create(project=project, locale=locale)
        project.refresh_from_db()
        assert_true(project.has_changed)
Esempio n. 50
0
    def test_get_latest_activity_with_project(self):
        """
        If a locale is given, defer to
        ProjectLocale.get_latest_activity.
        """
        locale = LocaleFactory.create()
        project = ProjectFactory.create(locales=[locale])

        with patch.object(ProjectLocale, 'get_latest_activity') as mock_get_latest_activity:
            mock_get_latest_activity.return_value = 'latest'
            assert_equal(locale.get_latest_activity(project=project), 'latest')
            mock_get_latest_activity.assert_called_with(locale, project)
Esempio n. 51
0
    def test_save_create_dirs(self):
        """
        If the directories in a resource's path don't exist, create them
        on save.
        """
        path = os.path.join(tempfile.mkdtemp(), 'does', 'not', 'exist.dtd')
        translated_resource = self.create_nonexistant_resource(path)

        translated_resource.translations[0].strings = {None: 'New Translated String'}
        translated_resource.save(LocaleFactory.create())

        assert_true(os.path.exists(path))
Esempio n. 52
0
    def test_project_locale_added(self):
        """
        When a locale is added to a project, has_changed should be set
        to True.
        """
        project = ProjectFactory.create(locales=[], has_changed=False)
        assert_false(project.has_changed)

        locale = LocaleFactory.create()
        ProjectLocaleFactory.create(project=project, locale=locale)
        project.refresh_from_db()
        assert_true(project.has_changed)
Esempio n. 53
0
    def setUp(self):
        super(TranslationActionsTests, self).setUp()
        project = ProjectFactory.create()
        locale = LocaleFactory.create()

        ProjectLocale.objects.create(project=project, locale=locale)

        translation = TranslationFactory.create(locale=locale, entity__resource__project=project)
        translation.approved = True
        translation.save()

        self.translation = translation
Esempio n. 54
0
    def test_user_locales_order(self):
        locale1, locale2, locale3 = LocaleFactory.create_batch(3)
        response = self.client.get(self.url)
        assert_equal(response.status_code, 200)

        response = self.client.post('/settings/', {
            'first_name': 'contributor',
            'email': self.user.email,
            'locales_order': commajoin(
                locale2.pk,
                locale1.pk,
                locale3.pk,
            ),
        })

        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales),
            [
                locale2,
                locale1,
                locale3,
            ]
        )
        # Test if you can clear all locales
        response = self.client.post('/settings/', {
            'first_name': 'contributor',
            'email': self.user.email,
            'locales_order': '',
        })
        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales),
            []
        )

        # Test if form handles duplicated locales
        response = self.client.post('/settings/', {
            'first_name': 'contributor',
            'email': self.user.email,
            'locales_order': commajoin(
                locale1.pk,
                locale2.pk,
                locale2.pk,
            )
        })
        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales), [
                locale1,
                locale2,
            ]
        )
Esempio n. 55
0
    def test_locale_view(self):
        """
        Checks if locale page is returned properly.
        """
        locale = LocaleFactory.create()

        # Locale requires valid project with resources
        ResourceFactory.create(project__locales=[locale])

        with patch('pontoon.base.views.render', wraps=render) as mock_render:
            self.client.get('/{}/'.format(locale.code))
            assert_equal(mock_render.call_args[0][2]['locale'], locale)
Esempio n. 56
0
    def test_user_locales_order(self):
        locale1, locale2, locale3 = LocaleFactory.create_batch(3)
        response = self.client.get(self.url)
        assert_equal(response.status_code, 200)

        response = self.client.post('/settings/', {
            'first_name': 'contributor',
            'email': self.user.email,
            'locales_order': commajoin(
                locale2.pk,
                locale1.pk,
                locale3.pk,
            ),
        })

        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales),
            [
                locale2,
                locale1,
                locale3,
            ]
        )
        # Test if you can clear all locales
        response = self.client.post('/settings/', {
            'first_name': 'contributor',
            'email': self.user.email,
            'locales_order': '',
        })
        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales),
            []
        )

        # Test if form handles duplicated locales
        response = self.client.post('/settings/', {
            'first_name': 'contributor',
            'email': self.user.email,
            'locales_order': commajoin(
                locale1.pk,
                locale2.pk,
                locale2.pk,
            )
        })
        assert_equal(response.status_code, 200)
        assert_equal(
            list(User.objects.get(pk=self.user.pk).profile.sorted_locales), [
                locale1,
                locale2,
            ]
        )
Esempio n. 57
0
    def test_locale_view(self):
        """
        Checks if locale page is returned properly.
        """
        locale = LocaleFactory.create()

        # Locale requires valid project with resources
        ResourceFactory.create(project__locales=[locale])

        with patch('pontoon.base.views.render', wraps=render) as mock_render:
            self.client.get('/{}/'.format(locale.code))
            assert_equal(mock_render.call_args[0][2]['locale'], locale)