def test_match_client(self):
     params = {}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locales=['en-us'])
     SnippetFactory.create(on_release=False, on_startpage_4=True,
                           locales=['en-us'])
     self._assert_client_matches_snippets(params, [snippet])
 def test_match_client_match_locale(self):
     params = {}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locale_set=[SnippetLocale(locale='en-US')])
     SnippetFactory.create(on_release=True, on_startpage_4=True,
                           locale_set=[SnippetLocale(locale='fr')])
     self._assert_client_matches_snippets(params, [snippet])
 def test_render_unicode(self):
     variable = SnippetTemplateVariableFactory(name='data')
     template = SnippetTemplateFactory.create(code='{{ data }}',
                                              variable_set=[variable])
     snippet = SnippetFactory(template=template, data='{"data": "φοο"}')
     output = snippet.render()
     self.assertEqual(pq(output)[0].text, '\u03c6\u03bf\u03bf')
Beispiel #4
0
 def test_match_client(self):
     params = {}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locales=['en-US'])
     SnippetFactory.create(on_release=False, on_startpage_4=True,
                           locales=['en-US'])
     self._assert_client_matches_snippets(params, [snippet])
 def test_match_client_match_locale(self):
     params = {}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locale_set=[SnippetLocale(locale='en-US')])
     SnippetFactory.create(on_release=True, on_startpage_4=True,
                           locale_set=[SnippetLocale(locale='fr')])
     self._assert_client_matches_snippets(params, [snippet])
 def test_snippets(self):
     instance = UploadedFileFactory.build()
     instance.file = MagicMock()
     instance.file.url = '/media/foo.png'
     snippets = SnippetFactory.create_batch(2, data='lalala {0} foobar'.format(instance.url))
     template = SnippetTemplateFactory.create(code='<foo>{0}</foo>'.format(instance.url))
     more_snippets = SnippetFactory.create_batch(3, template=template)
     self.assertEqual(set(instance.snippets), set(list(snippets) + list(more_snippets)))
 def test_render_unicode(self):
     variable = SnippetTemplateVariableFactory(name='data')
     template = SnippetTemplateFactory.create(code='{{ data }}',
                                              variable_set=[variable])
     snippet = SnippetFactory(template=template,
                              data='{"data": "\u03c6\u03bf\u03bf"}')
     output = snippet.render()
     eq_(pq(output)[0].text, u'\u03c6\u03bf\u03bf')
Beispiel #8
0
 def test_snippets(self):
     instance = UploadedFileFactory.build()
     instance.file = MagicMock()
     instance.file.url = '/media/foo.png'
     snippets = SnippetFactory.create_batch(2, data='lalala {0} foobar'.format(instance.url))
     template = SnippetTemplateFactory.create(code='<foo>{0}</foo>'.format(instance.url))
     more_snippets = SnippetFactory.create_batch(3, template=template)
     eq_(set(instance.snippets), set(list(snippets) + list(more_snippets)))
 def test_match_client_invalid_locale(self):
     """
     If client sends invalid locale return snippets with no locales
     specified.
     """
     params = {'locale': 'foo'}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True, locales=[])
     SnippetFactory.create(on_release=True, on_startpage_4=True, locales=['en-us'])
     self._assert_client_matches_snippets(params, [snippet])
Beispiel #10
0
 def test_match_client_multiple_locales(self):
     """
     If there are multiple locales that should match the client's
     locale, include all of them.
     """
     params = {'locale': 'es-mx'}
     snippet_1 = SnippetFactory.create(on_release=True, on_startpage_4=True, locales=['es'])
     snippet_2 = SnippetFactory.create(on_release=True, on_startpage_4=True, locales=['es-mx'])
     self._assert_client_matches_snippets(params, [snippet_1, snippet_2])
 def test_match_client_multiple_locales(self):
     """
     If there are multiple locales that should match the client's
     locale, include all of them.
     """
     params = {'locale': 'es-mx'}
     snippet_1 = SnippetFactory.create(on_release=True, on_startpage_4=True, locales=['es'])
     snippet_2 = SnippetFactory.create(on_release=True, on_startpage_4=True, locales=['es-mx'])
     self._assert_client_matches_snippets(params, [snippet_1, snippet_2])
Beispiel #12
0
 def test_match_client_invalid_locale(self):
     """
     If client sends invalid locale return snippets with no locales
     specified.
     """
     params = {'locale': 'foo'}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True, locales=[])
     SnippetFactory.create(on_release=True, on_startpage_4=True, locales=['en-us'])
     self._assert_client_matches_snippets(params, [snippet])
Beispiel #13
0
    def test_snippet(self):
        nightly_snippets = SnippetFactory.create_batch(
            2, on_release=False, on_nightly=True)
        SnippetFactory.create_batch(2, on_release=False, on_beta=True)

        filtr = ChannelFilter(None, {'channel': 'on_nightly'}, Snippet, SnippetAdmin)
        result = filtr.queryset(None, Snippet.objects.all())

        self.assertTrue(result.count(), 2)
        self.assertEqual(set(result.all()), set(nightly_snippets))
    def test_snippet(self):
        nightly_snippets = SnippetFactory.create_batch(
            2, on_release=False, on_nightly=True)
        SnippetFactory.create_batch(2, on_release=False, on_beta=True)

        filtr = ChannelFilter(None, {'channel': 'on_nightly'}, Snippet, SnippetAdmin)
        result = filtr.queryset(None, Snippet.objects.all())

        self.assertTrue(result.count(), 2)
        self.assertEqual(set(result.all()), set(nightly_snippets))
Beispiel #15
0
    def test_match_client_base(self):
        client_match_rule_pass_1 = ClientMatchRuleFactory(channel='nightly')
        client_match_rule_pass_2 = ClientMatchRuleFactory(
            channel='/(beta|nightly)/')
        client_match_rule_fail = ClientMatchRuleFactory(channel='release')

        # Matching snippets.
        snippet_1 = SnippetFactory.create(
            on_nightly=True, client_match_rules=[client_match_rule_pass_1])
        snippet_2 = SnippetFactory.create(
            on_beta=True,
            on_nightly=True,
            client_match_rules=[client_match_rule_pass_2])
        snippet_3 = SnippetFactory.create(on_nightly=True)

        # Not matching snippets.
        SnippetFactory.create(on_beta=True)
        SnippetFactory.create(on_nightly=True,
                              client_match_rules=[client_match_rule_fail])
        SnippetFactory.create(on_nightly=True,
                              client_match_rules=[
                                  client_match_rule_fail,
                                  client_match_rule_pass_2
                              ])
        client = self._build_client(channel='nightly')
        snippets = Snippet.objects.match_client(client)
        self.assertEqual(set(snippets), set([snippet_1, snippet_2, snippet_3]))
    def test_base(self):
        snippet_without_end_date = SnippetFactory(published=True, publish_end=None)
        snippet_that_has_ended = SnippetFactory(published=True, publish_end=datetime.utcnow())
        snippet_ending_in_the_future = SnippetFactory(
            published=True, publish_end=datetime.utcnow() + timedelta(days=1))

        call_command('disable_snippets_past_publish_date', stdout=Mock())

        snippet_without_end_date.refresh_from_db()
        snippet_that_has_ended.refresh_from_db()
        snippet_ending_in_the_future.refresh_from_db()

        self.assertFalse(snippet_that_has_ended.published)
        self.assertTrue(snippet_without_end_date.published)
        self.assertTrue(snippet_ending_in_the_future.published)

        asrsnippet_without_end_date = ASRSnippetFactory(
            status=STATUS_CHOICES['Published'],
            publish_end=None)
        asrsnippet_that_has_ended = ASRSnippetFactory(
            status=STATUS_CHOICES['Published'],
            publish_end=datetime.utcnow())
        asrsnippet_ending_in_the_future = ASRSnippetFactory(
            status=STATUS_CHOICES['Published'],
            publish_end=datetime.utcnow() + timedelta(days=1))

        call_command('disable_snippets_past_publish_date', stdout=Mock())

        asrsnippet_without_end_date.refresh_from_db()
        asrsnippet_that_has_ended.refresh_from_db()
        asrsnippet_ending_in_the_future.refresh_from_db()

        self.assertEqual(asrsnippet_that_has_ended.status, STATUS_CHOICES['Approved'])
        self.assertEqual(asrsnippet_without_end_date.status, STATUS_CHOICES['Published'])
        self.assertEqual(asrsnippet_ending_in_the_future.status, STATUS_CHOICES['Published'])
 def test_match_client_match_channel_partially(self):
     """
     Client channels like "release-cck-mozilla14" should match
     "release".
     """
     params = {'channel': 'release-cck-mozilla14'}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locale_set=[SnippetLocale(locale='en-US')])
     SnippetFactory.create(on_release=False, on_startpage_4=True,
                           locale_set=[SnippetLocale(locale='en-US')])
     self._assert_client_matches_snippets(params, [snippet])
 def test_base(self):
     snippets = SnippetFactory.create_batch(2)
     jsonsnippets = JSONSnippetFactory.create_batch(2)
     SnippetFactory.create(disabled=True)
     JSONSnippetFactory.create(disabled=True)
     response = views.ActiveSnippetsView.as_view()(self.request)
     eq_(response.get('content-type'), 'application/json')
     data = json.loads(response.content)
     eq_(set([snippets[0].id, snippets[1].id,
              jsonsnippets[0].id, jsonsnippets[1].id]),
         set([x['id'] for x in data]))
 def test_match_client_match_channel_partially(self):
     """
     Client channels like "release-cck-mozilla14" should match
     "release".
     """
     params = {'channel': 'release-cck-mozilla14'}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locale_set=[SnippetLocale(locale='en-US')])
     SnippetFactory.create(on_release=False, on_startpage_4=True,
                           locale_set=[SnippetLocale(locale='en-US')])
     self._assert_client_matches_snippets(params, [snippet])
Beispiel #20
0
 def test_base(self):
     snippets = SnippetFactory.create_batch(2)
     jsonsnippets = JSONSnippetFactory.create_batch(2)
     SnippetFactory.create(disabled=True)
     JSONSnippetFactory.create(disabled=True)
     response = views.ActiveSnippetsView.as_view()(self.request)
     eq_(response.get('content-type'), 'application/json')
     data = json.loads(response.content)
     eq_(
         set([
             snippets[0].id, snippets[1].id, jsonsnippets[0].id,
             jsonsnippets[1].id
         ]), set([x['id'] for x in data]))
Beispiel #21
0
 def test_valid_disabled_snippet_authenticated(self):
     """Test disabled snippet returns 200 to authenticated users."""
     snippet = SnippetFactory.create(published=False)
     User.objects.create_superuser('admin', '*****@*****.**', 'asdf')
     self.client.login(username='******', password='******')
     response = self.client.get(reverse('base.show', kwargs={'snippet_id': snippet.id}))
     self.assertEqual(response.status_code, 200)
Beispiel #22
0
 def test_encode_snippet(self):
     encoder = ActiveSnippetsEncoder()
     now = datetime.now()
     data = {
         'id': 99,
         'publish_start': now,
         'name': 'Foo bar',
         'countries': ['us', 'gr']
     }
     snippet = SnippetFactory.create(**data)
     result = encoder.default(snippet)
     eq_(
         result, {
             'id': 99,
             'name': 'Foo bar',
             'type': 'Desktop Snippet',
             'template': snippet.template.name,
             'publish_start': now,
             'publish_end': None,
             'on_release': True,
             'on_beta': False,
             'on_aurora': False,
             'on_nightly': False,
             'locales': ['en-us'],
             'countries': ['gr', 'us'],
             'weight': 100
         })
    def test_base(self):
        # Matching snippets.
        snippet_1 = SnippetFactory.create(on_nightly=True)

        # Matching but disabled snippet.
        SnippetFactory.create(on_nightly=True, disabled=True)

        # Snippet that doesn't match.
        SnippetFactory.create(on_nightly=False),

        params = self.client_params
        response = self.client.get('/{0}/'.format('/'.join(params)))

        snippets_json = json.dumps([snippet_1.to_dict()])
        eq_(snippets_json, response.context['snippets_json'])
        eq_(response.context['locale'], 'en-US')
 def test_render_snippet_id(self):
     """Include the snippet ID in the template context when rendering."""
     snippet = SnippetFactory.create(
         template__code='<p>{{ snippet_id }}</p>')
     snippet.template.render = Mock()
     snippet.render()
     snippet.template.render.assert_called_with({'snippet_id': snippet.id})
Beispiel #25
0
    def test_base(self):
        # Matching snippets.
        snippet_1 = SnippetFactory.create(on_nightly=True)

        # Matching but disabled snippet.
        SnippetFactory.create(on_nightly=True, disabled=True)

        # Snippet that doesn't match.
        SnippetFactory.create(on_nightly=False),

        snippets_ok = [snippet_1]
        params = self.client_params
        response = self.client.get('/{0}/'.format('/'.join(params)))

        eq_(set(snippets_ok), set(response.context['snippets']))
        eq_(response.context['locale'], 'en-US')
Beispiel #26
0
    def test_no_locales(self):
        """
        If the form being saved has no locale field, do not alter the snippet's
        locale.
        """
        en_us = SnippetLocale(locale='en-us')
        fr = SnippetLocale(locale='fr')
        snippet = SnippetFactory.create(locale_set=[en_us, fr])
        data = {
            'name': 'test',
            'data': '{}',
            'template': snippet.template.id,
            'priority': 0,
            'weight': 100,
        }

        # FormClass has no locale field.
        class FormClass(ModelForm):
            class Meta:
                model = Snippet

        form = FormClass(data, instance=snippet)
        self._save_model(snippet, form)

        snippet = Snippet.objects.get(pk=snippet.pk)
        locales = (l.locale for l in snippet.locale_set.all())
        eq_(set(locales), set(('en-us', 'fr')))
 def test_valid_disabled_snippet_authenticated(self):
     """Test disabled snippet returns 200 to authenticated users."""
     snippet = SnippetFactory.create(disabled=True)
     User.objects.create_superuser('admin', '*****@*****.**', 'asdf')
     self.client.login(username='******', password='******')
     response = self.client.get(reverse('base.show', kwargs={'snippet_id': snippet.id}))
     eq_(response.status_code, 200)
Beispiel #28
0
    def test_base(self):
        # Matching snippets.
        snippet_1 = SnippetFactory.create(on_nightly=True)

        # Matching but disabled snippet.
        SnippetFactory.create(on_nightly=True, disabled=True)

        # Snippet that doesn't match.
        SnippetFactory.create(on_nightly=False),

        params = self.client_params
        response = self.client.get('/{0}/'.format('/'.join(params)))

        snippets_json = json.dumps([snippet_1.to_dict()])
        eq_(snippets_json, response.context['snippets_json'])
        eq_(response.context['locale'], 'en-US')
Beispiel #29
0
    def test_base(self):
        # Matching snippets.
        snippet_1 = SnippetFactory.create(on_nightly=True)

        # Matching but disabled snippet.
        SnippetFactory.create(on_nightly=True, disabled=True)

        # Snippet that doesn't match.
        SnippetFactory.create(on_nightly=False),

        snippets_ok = [snippet_1]
        params = self.client_params
        response = self.client.get('/{0}/'.format('/'.join(params)))

        eq_(set(snippets_ok), set(response.context['snippets']))
        eq_(response.context['locale'], 'en-US')
    def test_no_locales(self):
        """
        If the form being saved has no locale field, do not alter the snippet's
        locale.
        """
        en_us = SnippetLocale(locale='en-us')
        fr = SnippetLocale(locale='fr')
        snippet = SnippetFactory.create(locale_set=[en_us, fr])
        data = {
            'name': 'test',
            'data': '{}',
            'template': snippet.template.id,
            'priority': 0,
            'weight': 100,
        }

        # FormClass has no locale field.
        class FormClass(ModelForm):
            class Meta:
                model = Snippet
                fields = ('name', 'data', 'template', 'priority', 'weight')
        form = FormClass(data, instance=snippet)
        self._save_model(snippet, form)

        snippet = Snippet.objects.get(pk=snippet.pk)
        locales = (l.locale for l in snippet.locale_set.all())
        self.assertEqual(set(locales), set(('en-us', 'fr')))
    def test_publish_date_filters(self, mock_datetime):
        """
        If it is currently outside of the publish times for a snippet, it
        should not be included in the response.
        """
        mock_datetime.utcnow.return_value = datetime(2013, 4, 5)

        # Passing snippets.
        snippet_no_dates = SnippetFactory.create(on_release=True)
        snippet_after_start_date = SnippetFactory.create(
            on_release=True,
            publish_start=datetime(2013, 3, 6)
        )
        snippet_before_end_date = SnippetFactory.create(
            on_release=True,
            publish_end=datetime(2013, 6, 6)
        )
        snippet_within_range = SnippetFactory.create(
            on_release=True,
            publish_start=datetime(2013, 3, 6),
            publish_end=datetime(2013, 6, 6)
        )

        # Failing snippets.
        SnippetFactory.create(  # Before start date.
            on_release=True,
            publish_start=datetime(2013, 5, 6)
        )
        SnippetFactory.create(  # After end date.
            on_release=True,
            publish_end=datetime(2013, 3, 6)
        )
        SnippetFactory.create(  # Outside range.
            on_release=True,
            publish_start=datetime(2013, 6, 6),
            publish_end=datetime(2013, 7, 6)
        )

        params = ('4', 'Firefox', '23.0a1', '20130510041606',
                  'Darwin_Universal-gcc3', 'en-US', 'release',
                  'Darwin%2010.8.0', 'default', 'default_version')
        response = self.client.get('/{0}/'.format('/'.join(params)))

        expected = set([snippet_no_dates, snippet_after_start_date,
                       snippet_before_end_date, snippet_within_range])
        eq_(expected, set(response.context['snippets']))
    def test_base(self):
        # Matching snippets.
        snippet_1 = SnippetFactory.create(on_nightly=True)

        # Matching but disabled snippet.
        SnippetFactory.create(on_nightly=True, disabled=True)

        # Snippet that doesn't match.
        SnippetFactory.create(on_nightly=False),

        snippets_ok = [snippet_1]
        params = ('4', 'Firefox', '23.0a1', '20130510041606',
                  'Darwin_Universal-gcc3', 'en-US', 'nightly',
                  'Darwin%2010.8.0', 'default', 'default_version')
        response = self.client.get('/{0}/'.format('/'.join(params)))

        eq_(set(snippets_ok), set(response.context['snippets']))
        eq_(response.context['locale'], 'en-US')
Beispiel #33
0
    def test_esr_is_same_as_release(self):
        """ Make sure that esr channel follows release. """
        # Snippets matching nightly (and therefor should match default).
        release_snippet = SnippetFactory.create(on_release=True)

        # Snippets that don't match nightly
        SnippetFactory.create(on_release=False, on_beta=True)

        release_client = self._build_client(channel='release')
        release_snippets = Snippet.objects.match_client(release_client)

        esr_client = self._build_client(channel='esr')
        esr_snippets = Snippet.objects.match_client(esr_client)

        # Assert that both the snippets returned from release and from esr
        # are the same snippets. Just `release_snippet` in this case.
        self.assertEqual(set([release_snippet]), set(release_snippets))
        self.assertEqual(set([release_snippet]), set(esr_snippets))
Beispiel #34
0
 def test_render_no_snippet_id(self):
     """
     If a snippet that hasn't been saved to the database yet is
     rendered, the snippet ID should be set to 0.
     """
     snippet = SnippetFactory.build(template__code='<p>{{ snippet_id }}</p>')
     snippet.template.render = Mock()
     snippet.render()
     snippet.template.render.assert_called_with({'snippet_id': 0})
 def test_render_no_snippet_id(self):
     """
     If a snippet that hasn't been saved to the database yet is rendered, the snippet ID
     shouldn't be included in the template context.
     """
     snippet = SnippetFactory.build(template__code='<p>{{ snippet_id }}</p>')
     snippet.template.render = Mock()
     snippet.render()
     snippet.template.render.assert_called_with({})
    def test_default_is_same_as_nightly(self):
        """ Make sure that default channel follows nightly. """
        # Snippets matching nightly (and therefor should match default).
        nightly_snippet = SnippetFactory.create(on_nightly=True)

        # Snippets that don't match nightly
        SnippetFactory.create(on_beta=True)

        nightly_client = self._build_client(channel='nightly')
        nightly_snippets = Snippet.cached_objects.match_client(nightly_client)

        default_client = self._build_client(channel='default')
        default_snippets = Snippet.cached_objects.match_client(default_client)

        # Assert that both the snippets returned from nightly and from default
        # are the same snippets. Just `nightly_snippet` in this case.
        eq_(set([nightly_snippet]), set(nightly_snippets))
        eq_(set([nightly_snippet]), set(default_snippets))
    def test_default_is_same_as_nightly(self):
        """ Make sure that default channel follows nightly. """
        # Snippets matching nightly (and therefor should match default).
        nightly_snippet = SnippetFactory.create(on_nightly=True)

        # Snippets that don't match nightly
        SnippetFactory.create(on_beta=True)

        nightly_client = self._build_client(channel='nightly')
        nightly_snippets = Snippet.cached_objects.match_client(nightly_client)

        default_client = self._build_client(channel='default')
        default_snippets = Snippet.cached_objects.match_client(default_client)

        # Assert that both the snippets returned from nightly and from default
        # are the same snippets. Just `nightly_snippet` in this case.
        eq_(set([nightly_snippet]), set(nightly_snippets))
        eq_(set([nightly_snippet]), set(default_snippets))
 def test_match_client_multiple_locales_distinct(self):
     """
     If a snippet has multiple locales and a client matches more
     than one of them, the snippet should only be included in the
     queryset once.
     """
     params = {'locale': 'es-mx'}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locales=['es', 'es-mx'])
     self._assert_client_matches_snippets(params, [snippet])
Beispiel #39
0
 def test_match_client_multiple_locales_distinct(self):
     """
     If a snippet has multiple locales and a client matches more
     than one of them, the snippet should only be included in the
     queryset once.
     """
     params = {'locale': 'es-mx'}
     snippet = SnippetFactory.create(on_release=True, on_startpage_4=True,
                                     locales=['es', 'es-mx'])
     self._assert_client_matches_snippets(params, [snippet])
Beispiel #40
0
 def test_exclusion_cmr(self):
     cmr_el = ClientMatchRuleFactory(locale='/^el/', is_exclusion=True)
     snippet = SnippetFactory(client_match_rules=[cmr_el],
                              locale_set=[
                                  SnippetLocale(locale='pl'),
                                  SnippetLocale(locale='en')
                              ])
     cmr_to_locales_action(None, None, [snippet])
     eq_(snippet.locale_set.count(), len(LANGUAGE_VALUES) - 1)
     ok_(not snippet.locale_set.filter(locale='el').exists())
     eq_(snippet.client_match_rules.count(), 0)
 def test_render_data_with_snippet_id(self):
     """
     Any strings included in the template context should have the
     substring "<snippet_id>" replaced with the ID of the snippet.
     """
     snippet = SnippetFactory.build(template__code='<p>{{ code }}</p>',
                                    data='{"code": "snippet id <snippet_id>", "foo": true}')
     snippet.template.render = Mock()
     snippet.render()
     snippet.template.render.assert_called_with({'code': 'snippet id 0', 'snippet_id': 0,
                                                 'foo': True})
Beispiel #42
0
 def test_render_data_with_snippet_id(self):
     """
     Any strings included in the template context should have the
     substring "<snippet_id>" replaced with the ID of the snippet.
     """
     snippet = SnippetFactory.build(template__code='<p>{{ code }}</p>',
                                    data='{"code": "snippet id <snippet_id>", "foo": true}')
     snippet.template.render = Mock()
     snippet.render()
     snippet.template.render.assert_called_with({'code': 'snippet id 0', 'snippet_id': 0,
                                                 'foo': True})
    def test_render_campaign(self):
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template, data=data, campaign='foo')

        expected = Markup('<div data-snippet-id="{id}" data-weight="100" '
                          'data-campaign="foo" class="snippet-metadata">'
                          '<a href="asdf">qwer</a></div>'.format(id=snippet.id))
        self.assertEqual(snippet.render().strip(), expected)
 def test_render_data_with_snippet_id(self):
     """
     Any strings included in the template context should have the
     substring "[[snippet_id]]" replaced with the ID of the snippet.
     """
     snippet = SnippetFactory.create(
         template__code='<p>{{ code }}</p>',
         data='{"code": "snippet id [[snippet_id]]", "foo": true}')
     snippet.template.render = Mock()
     snippet.render()
     snippet.template.render.assert_called_with({'code': 'snippet id {0}'.format(snippet.id),
                                                 'snippet_id': snippet.id,
                                                 'foo': True})
    def test_match_client_multiple_locale_matches(self):
        """
        If a snippet has multiple locales and a client matches more than one of them, the snippet
        should only be included in the queryset once.
        """
        es_mx = SnippetLocale(locale='es-mx')
        es = SnippetLocale(locale='es')
        snippet = SnippetFactory.create(locale_set=[es_mx, es])

        client = self._build_client(locale='es-MX')
        snippets = Snippet.cached_objects.match_client(client)

        # Filter out any snippets that aren't the one we made, and ensure there's only one.
        eq_(len([s for s in snippets if s.pk == snippet.pk]), 1)
    def test_render_campaign(self):
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template,
                                        data=data,
                                        campaign='foo')

        expected = Markup(
            '<div data-snippet-id="{id}" data-weight="100" '
            'data-campaign="foo" class="snippet-metadata">'
            '<a href="asdf">qwer</a></div>'.format(id=snippet.id))
        self.assertEqual(snippet.render().strip(), expected)
    def test_render_no_country(self):
        """
        If the snippet isn't geolocated, don't include the data-country
        attribute.
        """
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template, data=data)

        expected = ('<div data-snippet-id="{0}" data-weight="100">'
                    '<a href="asdf">qwer</a></div>'.format(snippet.id))
        eq_(snippet.render().strip(), expected)
    def test_to_dict(self):
        snippet = SnippetFactory.create(weight=60, campaign='foo-campaign',
                                        countries=['gr', 'it'])
        snippet.render = Mock()
        snippet.render.return_value = 'rendered'

        data = {
            'code': 'rendered',
            'campaign': 'foo-campaign',
            'weight': 60,
            'countries': [u'gr', u'it'],
            'exclude_from_search_engines': [],
            'id': snippet.id,
        }
        self.assertEqual(data, snippet.to_dict())
    def test_render_no_country(self):
        """
        If the snippet isn't geolocated, don't include the data-country
        attribute.
        """
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template, data=data)

        expected = ('<div data-snippet-id="{0}" data-weight="100">'
                    '<a href="asdf">qwer</a></div>'
                    .format(snippet.id))
        eq_(snippet.render().strip(), expected)
    def test_render_multiple_countries(self):
        """
        Include multiple countries in data-countries
        """
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template, data=data, countries=['us', 'el'])

        expected = Markup(
            '<div data-snippet-id="{0}" data-weight="100" data-campaign="" '
            'class="snippet-metadata" data-countries="el,us">'
            '<a href="asdf">qwer</a></div>'.format(snippet.id))
        self.assertEqual(snippet.render().strip(), expected)
    def test_match_client_base(self):
        client_match_rule_pass_1 = ClientMatchRuleFactory(channel='nightly')
        client_match_rule_pass_2 = ClientMatchRuleFactory(channel='/(beta|nightly)/')
        client_match_rule_fail = ClientMatchRuleFactory(channel='release')

        # Matching snippets.
        snippet_1 = SnippetFactory.create(on_nightly=True,
                                          client_match_rules=[client_match_rule_pass_1])
        snippet_2 = SnippetFactory.create(on_beta=True, on_nightly=True,
                                          client_match_rules=[client_match_rule_pass_2])
        snippet_3 = SnippetFactory.create(on_nightly=True)

        # Not matching snippets.
        SnippetFactory.create(on_beta=True)
        SnippetFactory.create(on_nightly=True,
                              client_match_rules=[client_match_rule_fail])
        SnippetFactory.create(on_nightly=True,
                              client_match_rules=[client_match_rule_fail,
                                                  client_match_rule_pass_2])
        client = self._build_client(channel='nightly')
        snippets = Snippet.cached_objects.match_client(client)
        eq_(set(snippets), set([snippet_1, snippet_2, snippet_3]))
Beispiel #52
0
    def test_render(self):
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template, data=data,
                                        country='us', weight=60)

        expected = ('<div data-snippet-id="{id}" data-weight="60" class="snippet-metadata" '
                    'data-country="us"><a href="asdf">qwer</a></div>'.format(id=snippet.id))
        eq_(snippet.render().strip(), expected)
        template.render.assert_called_with({
            'url': 'asdf',
            'text': 'qwer',
            'snippet_id': snippet.id
        })
    def test_render(self):
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template, data=data,
                                        country='us', weight=60)

        expected = ('<div data-snippet-id="{0}" data-weight="60" data-country="us">'
                    '<a href="asdf">qwer</a></div>'.format(snippet.id))
        eq_(snippet.render().strip(), expected)
        template.render.assert_called_with({
            'url': 'asdf',
            'text': 'qwer',
            'snippet_id': snippet.id
        })
Beispiel #54
0
 def test_base(self):
     cmr_el = ClientMatchRuleFactory(locale='/^el/')
     cmr_ast = ClientMatchRuleFactory(locale='ast|ja-JP-mac',
                                      channel='aurora')
     cmr_es = ClientMatchRuleFactory(locale='/(es-MX)|(es-AR)/')
     cmr_bogus = ClientMatchRuleFactory(locale='/foo/')
     snippet = SnippetFactory(
         client_match_rules=[cmr_el, cmr_ast, cmr_es, cmr_bogus],
         locale_set=[
             SnippetLocale(locale='pl'),
             SnippetLocale(locale='en')
         ])
     cmr_to_locales_action(None, None, [snippet])
     eq_(snippet.locale_set.count(), 5)
     eq_(set(snippet.locale_set.values_list('locale', flat=True)),
         set(['el', 'ast', 'ja-jp-mac', 'es-mx', 'es-ar']))
     eq_(snippet.client_match_rules.count(), 1)
     eq_(snippet.client_match_rules.all()[0], cmr_ast)
 def test_render_data_with_snippet_id(self):
     """
     Any strings included in the template context should have the
     substring "[[snippet_id]]" replaced with the ID of the snippet.
     """
     snippet = SnippetFactory.create(
         template__code='<p>{{ code }}</p>',
         data='{"code": "snippet id [[snippet_id]]", "foo": true}')
     snippet.template.render = Mock()
     snippet.render()
     snippet.template.render.assert_called_with({
         'code':
         'snippet id {0}'.format(snippet.id),
         'snippet_id':
         snippet.id,
         'foo':
         True
     })
    def test_render_multiple_countries(self):
        """
        Include multiple countries in data-countries
        """
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template,
                                        data=data,
                                        countries=['us', 'el'])

        expected = Markup(
            '<div data-snippet-id="{0}" data-weight="100" data-campaign="" '
            'class="snippet-metadata" data-countries="el,us">'
            '<a href="asdf">qwer</a></div>'.format(snippet.id))
        self.assertEqual(snippet.render().strip(), expected)
 def test_encode_snippet(self):
     encoder = ActiveSnippetsEncoder()
     now = datetime.now()
     data = {'id': 99, 'publish_start': now, 'name': 'Foo bar', 'countries': ['us', 'gr']}
     snippet = SnippetFactory.create(**data)
     result = encoder.default(snippet)
     self.assertEqual(result, {'id': 99,
                               'name': 'Foo bar',
                               'type': 'Desktop Snippet',
                               'template': snippet.template.name,
                               'publish_start': now,
                               'publish_end': None,
                               'on_release': True,
                               'on_beta': False,
                               'on_aurora': False,
                               'on_nightly': False,
                               'locales': [u'en-us'],
                               'countries': [u'us', u'gr'],
                               'weight': 100
                               })
    def test_render_exclude_search_engines(self):
        """
        If the snippet must get excluded from search engines,
        include the data-exclude-from-search-engines attribute.
        """
        template = SnippetTemplateFactory.create()
        template.render = Mock()
        template.render.return_value = '<a href="asdf">qwer</a>'

        data = '{"url": "asdf", "text": "qwer"}'
        snippet = SnippetFactory.create(template=template, data=data)
        search_providers = SearchProviderFactory.create_batch(2)
        snippet.exclude_from_search_providers.add(*search_providers)

        engines = ','.join(map(lambda x: x.identifier, search_providers))
        expected = Markup(
            '<div data-snippet-id="{id}" data-weight="100" data-campaign="" '
            'class="snippet-metadata" data-exclude-from-search-engines="{engines}">'
            '<a href="asdf">qwer</a></div>'.format(id=snippet.id, engines=engines))
        self.assertEqual(snippet.render().strip(), expected)
    def test_filter_by_available(self):
        snippet_match_1 = SnippetFactory.create()
        snippet_match_2 = (SnippetFactory.create(publish_start=datetime(2012, 05, 15, 0, 0)))

        # Snippet that starts later.
        SnippetFactory.create(publish_start=datetime(2012, 07, 01, 0, 0))

        # Snippet that ended.
        SnippetFactory.create(publish_end=datetime(2012, 05, 01, 0, 0))

        with patch('snippets.base.managers.datetime') as datetime_mock:
            datetime_mock.utcnow.return_value = datetime(2012, 06, 01, 0, 0)
            matching_snippets = self.manager.all().filter_by_available()

        eq_(set([snippet_match_1, snippet_match_2]), set(matching_snippets))
    def test_filter_by_available(self):
        snippet_match_1 = SnippetFactory.create()
        snippet_match_2 = (SnippetFactory.create(publish_start=datetime(2012, 5, 15, 0, 0)))

        # Snippet that starts later.
        SnippetFactory.create(publish_start=datetime(2012, 7, 1, 0, 0))

        # Snippet that ended.
        SnippetFactory.create(publish_end=datetime(2012, 5, 1, 0, 0))

        with patch('snippets.base.managers.datetime') as datetime_mock:
            datetime_mock.utcnow.return_value = datetime(2012, 6, 1, 0, 0)
            matching_snippets = self.manager.all().filter_by_available()

        self.assertEqual(set([snippet_match_1, snippet_match_2]), set(matching_snippets))