def test_basic(self):
        variable1 = SnippetTemplateVariableFactory()
        variable2 = SnippetTemplateVariableFactory()
        template1 = SnippetTemplateFactory.create(
            variable_set=[variable1, variable2])

        variable3 = SnippetTemplateVariableFactory()
        template2 = SnippetTemplateFactory.create(variable_set=[variable3])

        choices = (('', 'blank'), (template1.pk, 't1'), (template2.pk, 't2'))
        widget = TemplateSelect(choices=choices)
        d = pq(widget.render('blah', None))

        # Blank option should have no data attributes.
        blank_option = d('option:contains("blank")')
        eq_(blank_option.attr('data-variables'), None)

        # Option 1 should have two variables in the data attribute.
        option1 = d('option:contains("t1")')
        variables = json.loads(option1.attr('data-variables'))
        eq_(len(variables), 2)
        ok_({'name': variable1.name, 'type': variable1.type,
             'description': variable1.description} in variables)
        ok_({'name': variable2.name, 'type': variable2.type,
             'description': variable1.description} in variables)

        # Option 2 should have just one variable.
        option2 = d('option:contains("t2")')
        variables = json.loads(option2.attr('data-variables'))
        eq_(variables, [{'name': variable3.name, 'type': variable3.type,
                         'description': variable3.description}])
    def test_save_related_remove_old(self):
        """
        save_related should delete TemplateVariables that don't exist in the
        saved template anymore.
        """
        template = SnippetTemplateFactory.create(code="""
            <p>Testing {{ sample_var }}</p>
            {% if not another_test_var %}
              <p>Blah</p>
            {% endif %}
        """)
        SnippetTemplateVariableFactory.create(
            name='does_not_exist', template=template)
        SnippetTemplateVariableFactory.create(
            name='does_not_exist_2', template=template)

        self.assertTrue(SnippetTemplateVariable.objects
                        .filter(template=template, name='does_not_exist').exists())
        self.assertTrue(SnippetTemplateVariable.objects
                        .filter(template=template, name='does_not_exist_2').exists())

        variables = self._save_related(template)
        self.assertEqual(len(variables), 2)
        self.assertTrue('sample_var' in variables)
        self.assertTrue('another_test_var' in variables)

        self.assertFalse(SnippetTemplateVariable.objects
                         .filter(template=template, name='does_not_exist').exists())

        self.assertFalse(SnippetTemplateVariable.objects
                         .filter(template=template, name='does_not_exist_2').exists())
    def test_render_not_cached(self, mock_from_string, mock_sha1):
        """If the template isn't in the cache, add it."""
        template = SnippetTemplateFactory(code='asdf')
        mock_cache = {}

        with patch('snippets.base.models.template_cache', mock_cache):
            result = template.render({})

        jinja_template = mock_from_string.return_value
        cache_key = mock_sha1.return_value.hexdigest.return_value
        eq_(mock_cache, {cache_key: jinja_template})

        mock_sha1.assert_called_with('asdf')
        mock_from_string.assert_called_with('asdf')
        jinja_template.render.assert_called_with({'snippet_id': 0})
        eq_(result, jinja_template.render.return_value)
 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_cached(self, mock_from_string, mock_sha1):
        """
        If the template is in the cache, use the cached version instead
        of bothering to compile it.
        """
        template = SnippetTemplateFactory(code='asdf')
        cache_key = mock_sha1.return_value.hexdigest.return_value
        jinja_template = Mock()
        mock_cache = {cache_key: jinja_template}

        with patch('snippets.base.models.template_cache', mock_cache):
            result = template.render({})

        mock_sha1.assert_called_with('asdf')
        ok_(not mock_from_string.called)
        jinja_template.render.assert_called_with({'snippet_id': 0})
        eq_(result, jinja_template.render.return_value)
 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')
 def test_valid_args_activity_stream(self):
     """If template_id and data are both valid, return the preview page."""
     template = SnippetTemplateFactory.create()
     data = '{"a": "b"}'
     response = self._preview_snippet(template_id=template.id, activity_stream=True, data=data)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(response.context['client'].startpage_version, 5)
     self.assertTemplateUsed(response, 'base/preview_as.jinja')
Example #8
0
    def test_invalid_data(self):
        """If data is missing or invalid, return a 400 Bad Request."""
        template = SnippetTemplateFactory.create()
        response = self._preview_snippet(template_id=template.id)
        eq_(response.status_code, 400)

        response = self._preview_snippet(template_id=template.id,
                                         data='{invalid."json]')
        eq_(response.status_code, 400)
    def test_valid_args(self):
        """If template_id and data are both valid, return the preview page."""
        template = SnippetTemplateFactory.create()
        data = '{"a": "b"}'

        response = self._preview_snippet(template_id=template.id, data=data)
        self.assertEqual(response.status_code, 200)
        snippet = response.context['snippets_json']
        self.assertTrue(json.loads(snippet))
Example #10
0
    def test_valid_args(self):
        """If template_id and data are both valid, return the preview page."""
        template = SnippetTemplateFactory.create()
        data = '{"a": "b"}'

        response = self._preview_snippet(template_id=template.id, data=data)
        eq_(response.status_code, 200)

        snippet = response.context['snippet']
        eq_(snippet.template, template)
        eq_(snippet.data, data)
    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_save_related_add_new(self):
     """
     save_related should add new TemplateVariables for any new variables in
     the template code.
     """
     template = SnippetTemplateFactory.create(code="""
         <p>Testing {{ sample_var }}</p>
         {% if not another_test_var %}
           <p>Blah</p>
         {% endif %}
     """)
     variables = self._save_related(template)
     self.assertEqual(len(variables), 2)
     self.assertTrue('sample_var' in variables)
     self.assertTrue('another_test_var' in variables)
    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)
Example #14
0
    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)
Example #15
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="{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
        })
    def test_save_related_reserved_name(self):
        """
        save_related should not add new TemplateVariables for variables that
        are in the RESERVED_VARIABLES list.
        """
        template = SnippetTemplateFactory.create(code="""
            <p>Testing {{ reserved_name }}</p>
            {% if not another_test_var %}
              <p>Blah</p>
            {% endif %}
        """)
        variables = self._save_related(template)
        self.assertEqual(len(variables), 1)
        self.assertTrue('another_test_var' in variables)

        self.assertFalse(SnippetTemplateVariable.objects
                         .filter(template=template, name='reserved_name').exists())
Example #17
0
    def test_save_related_reserved_name(self):
        """
        save_related should not add new TemplateVariables for variables that
        are in the RESERVED_VARIABLES list.
        """
        template = SnippetTemplateFactory.create(code="""
            <p>Testing {{ reserved_name }}</p>
            {% if not another_test_var %}
              <p>Blah</p>
            {% endif %}
        """)
        variables = self._save_related(template)
        eq_(len(variables), 1)
        ok_('another_test_var' in variables)

        ok_(not SnippetTemplateVariable.objects.filter(
            template=template, name='reserved_name').exists())
    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_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_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
        })
    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)
Example #22
0
 def setUp(self):
     template = SnippetTemplateFactory()
     self.data = {
         'name':
         'Test Snippet',
         'template':
         template.id,
         'client_option_version_lower_bound':
         'any',
         'client_option_version_upper_bound':
         'any',
         'client_option_is_developer':
         'any',
         'client_option_is_default_browser':
         'any',
         'client_option_screen_resolutions':
         ['0-1024', '1024-1920', '1920-50000'],
         'client_option_has_fxaccount':
         'any',
         'client_option_sessionage_lower_bound':
         -1,
         'client_option_sessionage_upper_bound':
         -1,
         'client_option_profileage_lower_bound':
         -1,
         'client_option_profileage_upper_bound':
         -1,
         'client_option_bookmarks_count_lower_bound':
         -1,
         'client_option_bookmarks_count_upper_bound':
         -1,
         'client_option_addon_check_type':
         'any',
         'data':
         '{}',
         'weight':
         100,
         'on_release':
         'on',
     }
Example #23
0
 def test_render_snippet_id(self):
     """If the template context doesn't have a snippet_id entry, add one set to 0."""
     template = SnippetTemplateFactory(code='<p>{{ snippet_id }}</p>')
     eq_(template.render({'myvar': 'foo'}), '<p>0</p>')
    def test_publish_permission_check(self):
        variable1 = SnippetTemplateVariableFactory()
        variable2 = SnippetTemplateVariableFactory()
        self.template1 = SnippetTemplateFactory.create(
            variable_set=[variable1, variable2])
        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')

        perm_beta = Permission.objects.get(
            codename='can_publish_on_beta',
            content_type__model='snippet'
        )
        user.user_permissions.add(perm_beta)

        perm_nightly = Permission.objects.get(
            codename='can_publish_on_nightly',
            content_type__model='snippet'
        )
        user.user_permissions.add(perm_nightly)

        data = {
            'name': 'Test',
            'weight': 100,
            'client_option_is_developer': 'any',
            'client_option_addon_check_type': 'any',
            'client_option_sessionage_lower_bound': -1,
            'client_option_sessionage_upper_bound': -1,
            'client_option_profileage_lower_bound': -1,
            'client_option_profileage_upper_bound': -1,
            'client_option_bookmarks_count_lower_bound': -1,
            'client_option_bookmarks_count_upper_bound': -1,
            'client_option_version_lower_bound': 'any',
            'client_option_version_upper_bound': 'any',
            'client_option_is_default_browser': 'any',
            'client_option_has_fxaccount': 'any',
            'client_option_screen_resolutions': ['0-1024'],
            'on_startpage_5': True,
            'template': self.template1.id,
            'data': '{}',
        }

        # User should get an error trying to publish on Release
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_release'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue('You are not allowed to edit or publish on Release channel.' in
                        form.errors['__all__'][0])

        # User should get an error trying to edit or publish  on Release even though Beta
        # is selected too.
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_release'] = True
        new_data['on_beta'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue('You are not allowed to edit or publish on Release channel.' in
                        form.errors['__all__'][0])

        # Form is valid if user tries to edit or publish on Beta.
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_beta'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertTrue(form.is_valid())

        # Form is valid if user tries to publish or edit on Beta and Nightly.
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertTrue(form.is_valid())

        # Form is invalid if user tries edit published Snippet on Release.
        instance = SnippetFactory.create(published=True, on_release=True)
        new_data = data.copy()
        new_data['on_release'] = True
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue('You are not allowed to edit or publish on Release channel.' in
                        form.errors['__all__'][0])

        # User cannot unset Release channel and save.
        instance = SnippetFactory.create(published=True, on_release=True)
        new_data = data.copy()
        new_data['on_release'] = False
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue('You are not allowed to edit or publish on Release channel.' in
                        form.errors['__all__'][0])

        # User can un-publish if they have permission on all channels.
        instance = SnippetFactory.create(published=True, on_release=False, on_beta=True,
                                         on_nightly=True)
        new_data = data.copy()
        new_data['published'] = False
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertTrue(form.is_valid())

        # User cannot un-publish if they don't have permission on all channels.
        instance = SnippetFactory.create(published=True, on_release=True, on_nightly=True)
        new_data = data.copy()
        new_data['on_release'] = True
        new_data['on_nightly'] = True
        new_data['published'] = False
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue('You are not allowed to edit or publish on Release channel.' in
                        form.errors['__all__'][0])
Example #25
0
 def test_render(self):
     template = SnippetTemplateFactory(code='<p>{{myvar}}</p>')
     eq_(template.render({'myvar': 'foo'}), '<p>foo</p>')
Example #26
0
    def test_publish_permission_check(self):
        variable1 = SnippetTemplateVariableFactory()
        variable2 = SnippetTemplateVariableFactory()
        self.template1 = SnippetTemplateFactory.create(
            variable_set=[variable1, variable2])
        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')

        perm_beta = Permission.objects.get(codename='can_publish_on_beta',
                                           content_type__model='snippet')
        user.user_permissions.add(perm_beta)

        perm_nightly = Permission.objects.get(
            codename='can_publish_on_nightly', content_type__model='snippet')
        user.user_permissions.add(perm_nightly)

        data = {
            'name': 'Test',
            'weight': 100,
            'client_option_is_developer': 'any',
            'client_option_addon_check_type': 'any',
            'client_option_sessionage_lower_bound': -1,
            'client_option_sessionage_upper_bound': -1,
            'client_option_profileage_lower_bound': -1,
            'client_option_profileage_upper_bound': -1,
            'client_option_bookmarks_count_lower_bound': -1,
            'client_option_bookmarks_count_upper_bound': -1,
            'client_option_version_lower_bound': 'any',
            'client_option_version_upper_bound': 'any',
            'client_option_is_default_browser': 'any',
            'client_option_has_fxaccount': 'any',
            'client_option_screen_resolutions': ['0-1024'],
            'on_startpage_5': True,
            'template': self.template1.id,
            'data': '{}',
        }

        # User should get an error trying to publish on Release
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_release'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue(
            'You are not allowed to edit or publish on Release channel.' in
            form.errors['__all__'][0])

        # User should get an error trying to edit or publish  on Release even though Beta
        # is selected too.
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_release'] = True
        new_data['on_beta'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue(
            'You are not allowed to edit or publish on Release channel.' in
            form.errors['__all__'][0])

        # Form is valid if user tries to edit or publish on Beta.
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_beta'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertTrue(form.is_valid())

        # Form is valid if user tries to publish or edit on Beta and Nightly.
        new_data = data.copy()
        new_data['published'] = True
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data)
        form.current_user = user
        self.assertTrue(form.is_valid())

        # Form is invalid if user tries edit published Snippet on Release.
        instance = SnippetFactory.create(published=True, on_release=True)
        new_data = data.copy()
        new_data['on_release'] = True
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue(
            'You are not allowed to edit or publish on Release channel.' in
            form.errors['__all__'][0])

        # User cannot unset Release channel and save.
        instance = SnippetFactory.create(published=True, on_release=True)
        new_data = data.copy()
        new_data['on_release'] = False
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue(
            'You are not allowed to edit or publish on Release channel.' in
            form.errors['__all__'][0])

        # User can un-publish if they have permission on all channels.
        instance = SnippetFactory.create(published=True,
                                         on_release=False,
                                         on_beta=True,
                                         on_nightly=True)
        new_data = data.copy()
        new_data['published'] = False
        new_data['on_beta'] = True
        new_data['on_nightly'] = True
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertTrue(form.is_valid())

        # User cannot un-publish if they don't have permission on all channels.
        instance = SnippetFactory.create(published=True,
                                         on_release=True,
                                         on_nightly=True)
        new_data = data.copy()
        new_data['on_release'] = True
        new_data['on_nightly'] = True
        new_data['published'] = False
        form = SnippetAdminForm(new_data, instance=instance)
        form.current_user = user
        self.assertFalse(form.is_valid())
        self.assertTrue(
            'You are not allowed to edit or publish on Release channel.' in
            form.errors['__all__'][0])
 def test_render_snippet_id(self):
     """If the template context doesn't have a snippet_id entry, add one set to 0."""
     template = SnippetTemplateFactory(code='<p>{{ snippet_id }}</p>')
     self.assertEqual(template.render({'myvar': 'foo'}), '<p>0</p>')
 def test_render(self):
     template = SnippetTemplateFactory(code='<p>{{myvar}}</p>')
     self.assertEqual(template.render({'myvar': 'foo'}), '<p>foo</p>')