tests.py 10.6 KB
Newer Older
1
import datetime
2
from unittest import skipUnless
3

4
from django.contrib import auth
5
from django.core import mail
6
from django.core.exceptions import ValidationError
7
from django.test import TestCase
8
from django.urls import reverse
9
from django.utils.safestring import SafeData
10
from django.utils.translation import ugettext as _
11

12
from common.utils import pyicu_present
13
from people.models import Person, obfuscate_email
14
from people import forms
15

16

17 18
class PeopleTestCase(TestCase):

19
    def _create_person(self, seq='', **kwargs):
20
        pn = Person(first_name='John', last_name='Nothing',
21 22 23
            email='jn%s@devnull.com' % seq, username= 'jn%s' % seq)
        for key, arg in kwargs.items():
            setattr(pn, key, arg)
24 25 26 27
        pn.set_password('password')
        pn.save()
        return pn

28
    def test_register(self):
29 30 31 32 33 34
        username = 'tèst01'
        response = self.client.post(
            reverse('register'),
            {'username': username, 'password1': '1234567',
             'password2': '1234567', 'email': 'test01@example.org'}
        )
35
        self.assertRedirects(response, reverse('register_success'))
36
        self.assertEqual(Person.objects.filter(username=username).count(), 1)
Claude Paroz's avatar
Claude Paroz committed
37
        self.assertEqual(len(mail.outbox), 1)
38
        self.assertIn(_('Account activation'), mail.outbox[0].subject)
39

40 41 42 43 44 45 46 47 48 49 50 51 52
    def test_activate_account(self):
        # Testing if is_active is False by default
        response = self.client.post(reverse('register'),
            {'username': 'newuser', 'email': 'newuser@example.org',
             'password1': 'blah012', 'password2': 'blah012'})

        self.newu = Person.objects.get(username='newuser')
        self.assertFalse(self.newu.is_active)

        # Testing with a invalid activation key
        response = self.client.get('/register/activate/a_invalid_key')
        self.assertContains(response, 'Sorry, the key you provided is not valid.')

Claude Paroz's avatar
Claude Paroz committed
53
        response = self.client.get('/register/activate/%s' % self.newu.activation_key, follow=True)
54 55 56 57 58
        self.assertContains(response,  'Your account has been activated.')

        self.newu = Person.objects.get(username='newuser')
        self.assertTrue(self.newu.is_active)

59 60
    def test_login_message(self):
        self.pn = self._create_person()
61 62 63 64 65 66
        response = self.client.get(reverse('login'), HTTP_REFERER='http://foo/bar')
        self.assertContains(
            response,
            '<input type="hidden" name="referer" value="http://foo/bar">',
            html=True
        )
67 68 69 70 71 72 73 74
        response = self.client.post(
            reverse('login'), data={'username': 'jn', 'password': 'password'}, follow=True
        )
        self.assertContains(
            response,
            'You have not joined any translation team yet. '
            'You can do it from <a href="/users/team_join/">your profile</a>.'
        )
75 76 77 78 79 80
        response = self.client.get(reverse('login'))
        self.assertContains(
            response,
            'You are already logged in as jn.'
        )
        self.assertNotContains(response, 'id="login-form"')
81 82 83 84 85 86 87 88 89 90 91 92 93 94

    def test_login_by_email(self):
        self.pn = self._create_person()
        response = self.client.post(
            reverse('login'), data={'username': 'notexist@devnull.com', 'password': 'password'}
        )
        user = auth.get_user(self.client)
        self.assertFalse(user.is_authenticated)
        response = self.client.post(
            reverse('login'), data={'username': 'jn@devnull.com', 'password': 'password'}
        )
        user = auth.get_user(self.client)
        self.assertTrue(user.is_authenticated)

95 96 97 98 99 100
    def test_person_list(self):
        self.pn = self._create_person()
        response = self.client.get(reverse('people'))
        self.assertContains(response, "GNOME is being developed by following people:")
        self.assertContains(response, "John Nothing")

101 102
    def test_login_link(self):
        self.pn = self._create_person()
103
        self.assertTrue(self.client.login(username='jn', password='password'))
104 105 106
        response = self.client.get(reverse('home'))
        self.assertContains(
            response,
Tom Tryfonidis's avatar
Tom Tryfonidis committed
107
            '<a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle hidden-xs avatar" href="%s"><img class="img-circle" alt="generic person icon" src="/static/img/nobody.png"></a>' % (
108 109
                reverse('person_detail_username', args=[self.pn.username]),),
            html=True
110 111
        )

112
    def test_edit_details(self):
113
        self.pn = self._create_person()
114
        self.client.login(username='jn', password='password')
Claude Paroz's avatar
Claude Paroz committed
115 116
        response = self.client.get(reverse('person_detail_change'))
        self.assertContains(response, "First name")
117
        post_data = {
118 119
            'username': 'jn2', 'first_name': "Johnny", 'last_name': "Nothing",
            'email': 'test02@example.org',
120 121 122
            'image': '', 'webpage_url': "http://www.example.org/"
        }
        response = self.client.post(reverse('person_detail_change'), post_data)
123 124
        self.pn.refresh_from_db()
        self.assertEqual(self.pn.username, 'jn2')
125
        self.assertEqual(self.pn.email, 'test02@example.org')
126 127 128 129 130
        # bad image url
        post_data['image'] = "http://http://www.example.org/image.jpg"
        form = forms.DetailForm(post_data, instance=self.pn)
        self.assertFalse(form.is_valid())
        self.assertTrue('image' in form.errors)
131 132 133 134 135 136 137 138 139 140

    def test_obsolete_accounts(self):
        from teams.models import Team, Role
        from stats.models import Module, Branch, Domain
        from languages.models import Language
        from vertimus.models import StateTranslating
        module = Module.objects.create(name="gnome-hello")
        Branch.checkout_on_creation = False
        branch = Branch(name='gnome-2-24', module=module)
        branch.save(update_statistics=False)
141
        domain = Domain.objects.create(module=module, name='po', layout='po/{lang}.po')
142 143 144 145 146 147
        team = Team.objects.create(name='fr', description='French', mailing_list='french_ml@example.org')
        lang = Language.objects.create(name='French', locale='fr', team=team)

        # Create Users
        p1 = self._create_person(seq='1', last_login=datetime.datetime.now()-datetime.timedelta(days=700))
        p2 = self._create_person(seq='2', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
148
        Role.objects.create(team=team, person=p2, role='coordinator')
149 150 151
        p3 = self._create_person(seq='3', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
        module.maintainers.add(p3)
        p4 = self._create_person(seq='4', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
152 153
        StateTranslating.objects.create(branch=branch, domain=domain, language=lang, person=p4)
        self._create_person(seq='5', last_login=datetime.datetime.now()-datetime.timedelta(days=800))
154 155 156 157 158
        # Test only p5 should be deleted
        self.assertEqual(Person.objects.all().count(), 5)
        Person.clean_obsolete_accounts()
        self.assertEqual(Person.objects.all().count(), 4)
        self.assertEqual(set(Person.objects.all()), set([p1, p2, p3, p4]))
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

    def test_obfuscate_email(self):
        self.assertEqual(obfuscate_email(''), '')
        self.assertEqual(
            obfuscate_email('me.company@domain.org'),
            'me&nbsp;dot&nbsp;company&nbsp;at&nbsp;domain&nbsp;dot&nbsp;org'
        )
        self.assertIsInstance(obfuscate_email('me.company@domain.org'), SafeData)
        self.assertEqual(
            obfuscate_email('George P. McLain <george@domain.org'),
            'George&nbsp;P.&nbsp;McLain&nbsp;&lt;george&nbsp;at&nbsp;domain&nbsp;dot&nbsp;org'
        )
        self.assertEqual(
            obfuscate_email('Me <me.company@domain.org>\nYou <some-address@example.com>'),
            'Me&nbsp;&lt;me&nbsp;dot&nbsp;company&nbsp;at&nbsp;domain&nbsp;dot&nbsp;org&gt;\n'
            'You&nbsp;&lt;some-address&nbsp;at&nbsp;example&nbsp;dot&nbsp;com&gt;'
        )
176

177 178 179 180 181 182 183 184
    def test_people_image_tag(self):
        """
        Test the people_image template tag.
        """
        from people.templatetags import people
        pn = self._create_person()
        self.assertHTMLEqual(
            people.people_image(pn),
Tom Tryfonidis's avatar
Tom Tryfonidis committed
185
            '<img class="img-circle" src="/static/img/nobody.png" alt="generic person icon">'
186 187 188 189
        )
        pn.image = 'http://www.example.org/my_image.png'
        self.assertHTMLEqual(
            people.people_image(pn),
Tom Tryfonidis's avatar
Tom Tryfonidis committed
190
            '<img class="img-circle" alt="John Nothing" onerror="this.onerror = null; this.src=\'/static/img/nobody.png\'" src="http://www.example.org/my_image.png" />'
191 192 193 194 195
        )
        pn.last_name = "<script>Some XSS content</script>"
        self.assertIn("&lt;script&gt;Some XSS content&lt;/script&gt;", people.people_image(pn))
        self.assertHTMLEqual(
            people.people_image(pn),
Tom Tryfonidis's avatar
Tom Tryfonidis committed
196
            '<img class="img-circle" alt="John &lt;script&gt;Some XSS content&lt;/script&gt;" onerror="this.onerror = null; this.src=\'/static/img/nobody.png\'" src="http://www.example.org/my_image.png" />'
197
        )
198
        pn.avatar_service = 'gravatar.com'
199 200
        self.assertHTMLEqual(
            people.people_image(pn),
Tom Tryfonidis's avatar
Tom Tryfonidis committed
201
            '<img class="img-circle" alt="avatar icon" src="https://secure.gravatar.com/avatar/618b8b6c1c973c780ec218242c49cbe7.jpg?s=80&d=identicon&r=g">'
202
        )
203 204 205
        pn.avatar_service = 'libravatar.org'
        self.assertHTMLEqual(
            people.people_image(pn),
Tom Tryfonidis's avatar
Tom Tryfonidis committed
206
            '<img class="img-circle" alt="avatar icon" src="https://seccdn.libravatar.org/avatar/618b8b6c1c973c780ec218242c49cbe7?s=80&d=identicon&r=g">'
207 208
        )

209

210 211 212 213 214 215 216 217 218 219 220 221 222 223
    def test_get_image_size(self):
        from people.forms import get_image_size
        self.assertEqual(
            get_image_size("https://l10n.gnome.org/static/img/nobody.png"),
            (48, 48)
        )
        invalid_urls = (
            "absolutely invalid",
            "http://hopefullythisurlshouldnotexist.com/grstzqwer.jpg",
        )
        for url in invalid_urls:
            with self.assertRaises(ValidationError):
                get_image_size(url)

224 225 226 227
    @skipUnless(pyicu_present, "PyICU package is required for this test")
    def test_all_languages_list_order(self):
        """
        The order of the languages should be case insensitive.
228
        This tests that "français" appears before "Gaeilge".
229 230 231 232 233 234 235
        """
        Person.objects.create(username='jn', password='password')
        self.client.login(username='jn', password='password')
        url = reverse('person_detail_username', kwargs={'slug': 'jn'})
        response = self.client.get(url)
        all_languages = response.context['all_languages']
        self.assertGreater(
236
            all_languages.index(('ga', 'Gaeilge')),
237 238 239
            all_languages.index(('fr', "français")),
            "français is not before Frisian"
        )