示例#1
0
 def test_can_create_team(self):
     o = Organisation(name="New Org")
     o.save()
     self.assertTrue(o.pk)
     t = Team(name="New Team", organisation=o)
     t.save()
     self.assertTrue(t.pk)
示例#2
0
 def test_can_create_team(self):
     o = Organisation(name='New Org')
     o.save()
     self.assertTrue(o.pk)
     t = Team(name='New Team', organisation=o)
     t.save()
     self.assertTrue(t.pk)
示例#3
0
    def test_user_with_full_profile_goes_to_links(self):
        #   This user has a username and teams
        o = Organisation(name='org0001')
        o.save()
        t = Team(name='team0001', organisation=o)
        t.save()

        user = get_user_model().objects.create_user(
            userid='*****@*****.**',
            name='User 0001',
            best_way_to_find='In the kitchen',
            best_way_to_contact='By email',
            phone='00000000',
            email='*****@*****.**',
        )
        user.teams.add(t)
        user.save()

        #   Log in as user
        form = self.app.get(reverse('login')).form
        form['userid'] = '*****@*****.**'
        response = form.submit().follow()
        self.assertIn(
            'All tools',
            response.html.find('h1').text
        )
    def test_adding_new_existing_team(self):
        get_user_model().objects.create_user(userid='*****@*****.**')
        o = Organisation(name='org0001')
        o.save()
        t = Team(name='team0001', organisation=o)
        t.save()

        #   Log in as user
        form = self.app.get(reverse('login')).form
        form['userid'] = '*****@*****.**'
        form.submit()

        #   Go to the user's profile page and assert that the team is NOT
        #   showing up in the list of teams they are a member of.
        response = self.app.get(reverse(
            'user-detail',
            kwargs={'slug': 'user0001com'}))
        self.assertFalse(response.html.find('a', text='team0001'))

        #   Now go to the update profile page and check the first team
        #   in the list of teams.
        form = self.app.get(reverse(
            'user-update-teams',
            kwargs={'slug': 'user0001com'})).form
        form.get('team', index=0).checked = True
        form.submit()

        #   Go back to the users profile page to see if the team is now
        #   on the list of teams
        response = self.app.get(reverse(
            'user-detail',
            kwargs={'slug': 'user0001com'}))
        self.assertTrue(response.html.find('a', text='team0001'))
    def test_leave_button_visible(self):
        #   Create an organisation, a team and a user and assign that
        #   team to that user.
        o = Organisation(name="org0001")
        o.save()
        t = Team(name="team0001", organisation=o)
        t.save()
        u = get_user_model().objects.create_user(userid='*****@*****.**')
        u.teams.add(t)
        u.save()

        #   Now we need to log in as that user.
        form = self.app.get(reverse('login')).form
        form['userid'] = '*****@*****.**'
        form.submit().follow()

        #   Now go visit the team page...
        response = self.app.get(reverse('team-detail', kwargs={'pk': t.pk}))

        form = response.form

        self.assertEqual(form.method, 'post')

        self.assertEqual(form.action, '/teams/' + str(t.pk) + '/leave')

        # Make sure this button no longer exists
        self.assertIsNone(
            response.html.find(
                'a', attrs={'href': '/teams/' + str(t.pk) + '/leave'}))
        # Make sure this button no longer exists
        self.assertIsNone(
            response.html.find('a',
                               attrs={'href':
                                      '/teams/' + str(t.pk) + '/join'}))
示例#6
0
 def _create_base_team(self):
     self.team = Team(slug="new-team",
                      membership_policy=4,
                      video_policy=1,
                      name="New-name")
     self.team.save()
     user, created = User.objects.get_or_create(
         username=self.auth["username"])
     TeamMember.objects.create_first_member(self.team, user)
     return self.team
    def test_join_leave_buttons_work(self):
        #   Create an organisation, a team and a user and assign that
        #   team to that user.
        o = Organisation(name="org0001")
        o.save()
        t = Team(name="team0001", organisation=o)
        t.save()
        u = get_user_model().objects.create_user(userid='*****@*****.**')
        login_user(self, u)

        response = self.app.get(reverse('team-detail', kwargs={'pk': t.pk}))

        form = response.form

        self.assertEqual(form.method, 'post')

        self.assertEqual(form.action, '/teams/' + str(t.pk) + '/join')

        response = form.submit().follow()

        # Make sure the user is now in the team
        response = self.app.get(reverse('user-detail', kwargs={'slug':
                                                               u.slug}))

        self.assertTrue(
            response.html.find('a',
                               attrs={
                                   'class': 'main-list-item',
                                   'href': '/teams/' + str(t.pk)
                               }))

        # Go back to the team detail page so we can submit the link
        response = self.app.get(reverse('team-detail', kwargs={'pk': t.pk}))

        form = response.form

        self.assertEqual(form.method, 'post')

        self.assertEqual(form.action, '/teams/' + str(t.pk) + '/leave')

        response = form.submit().follow()

        # Make sure the user is no longer in the team
        response = self.app.get(reverse('user-detail', kwargs={'slug':
                                                               u.slug}))
        self.assertFalse(
            response.html.find('a',
                               attrs={
                                   'class': 'main-list-item',
                                   'href': '/teams/' + str(t.pk)
                               }))
示例#8
0
    def test_leave_button_visible(self):
        #   Create an organisation, a team and a user and assign that
        #   team to that user.
        o = Organisation(name="org0001")
        o.save()
        t = Team(name="team0001", organisation=o)
        t.save()
        u = get_user_model().objects.create_user(userid='*****@*****.**')
        u.teams.add(t)
        u.save()

        #   Now we need to log in as that user.
        form = self.app.get(reverse('login')).form
        form['userid'] = '*****@*****.**'
        form.submit().follow()

        #   Now go visit the team page...
        response = self.app.get(
            reverse(
                'team-detail',
                kwargs={'pk': t.pk}
            )
        )

        form = response.form

        self.assertEqual(
            form.method,
            'post'
        )

        self.assertEqual(
            form.action,
            '/teams/' + str(t.pk) + '/leave'
        )

        # Make sure this button no longer exists
        self.assertIsNone(
            response.html.find(
                'a',
                attrs={'href': '/teams/' + str(t.pk) + '/leave'}
            )
        )
        # Make sure this button no longer exists
        self.assertIsNone(
            response.html.find(
                'a',
                attrs={'href': '/teams/' + str(t.pk) + '/join'}
            )
        )
示例#9
0
    def test_user_can_have_multiple_teams_which_have_multiple_users(self):
        o = Organisation(name='New Org')
        o.save()

        t1 = Team(name='Team Awesome', organisation=o)
        t1.save()
        t2 = Team(name='Team Great', organisation=o)
        t2.save()

        u1 = get_user_model().objects.create_user(userid='teamplayer')
        u1.teams.add(t1)
        u1.teams.add(t2)
        u1.save()

        u2 = get_user_model().objects.create_user(userid='teamplayer2')
        u2.teams.add(t2)
        u2.save()

        self.assertIn(u1, t1.user_set.all())
        self.assertIn(u1, t2.user_set.all())
        self.assertNotIn(u2, t1.user_set.all())
        self.assertIn(u2, t2.user_set.all())

        self.assertEqual(len(t1.user_set.all()), 1)
        self.assertEqual(len(t2.user_set.all()), 2)
示例#10
0
 def test_is_visible(self):
     hidden  = Team(name='secret', slug='secret', is_visible=False)
     hidden.save()
     teams = Team.objects.all()
     url = reverse("teams:detail", kwargs={"slug":hidden.slug})
     response = self.client.get(url)
     self.assertEqual(response.status_code, 404)
     url = reverse("teams:index")
     
     response = self.client.get(url)
     teams = response.context['teams_list']
     self.assertTrue(len(teams) < 10)
     teams_pks = [t.pk for t in teams]
     print teams_pks, hidden.pk
     
     self.assertNotIn(hidden.pk, teams_pks)
示例#11
0
    def get_context_data(self, **kwargs):
        context = super(OrganisationList, self).get_context_data(**kwargs)

        context['top_teams'] = Team.with_most_members()
        context['top_organisations'] = Organisation.with_most_teams()
        context['total_organisations_in_db'] = Organisation.objects.count()

        return context
    def test_can_click_through_existing_team_link(self):
        #   Create and log in a user
        get_user_model().objects.create_user(userid='*****@*****.**')
        form = self.app.get(reverse('login')).form
        form['userid'] = 'user0001com'
        form.submit().follow()

        o = Organisation(name='New Org')
        o.save()
        team_name = 'New Team skippity bippity bop'
        t = Team(name=team_name, organisation=o)
        t.save()
        response = self.app.get(reverse('team-list'))
        response = self.app.get(
            response.html.find('a', text=team_name).attrs['href'])
        org_name = response.html.find('h1', attrs={
            'class': 'heading-xlarge'
        }).get_text(strip=True)
        self.assertEquals(org_name, 'Team' + team_name)
示例#13
0
    def test_user_has_username_teams_no_extra_info_redirected(self):
        #   This user has a username and teams
        o = Organisation(name='org0001')
        o.save()
        t = Team(name='team0001', organisation=o)
        t.save()

        user = get_user_model().objects.create_user(
            userid='*****@*****.**', name='User 0001')
        user.teams.add(t)
        user.save()

        #   Log in as user
        form = self.app.get(reverse('login')).form
        form['userid'] = '*****@*****.**'
        response = form.submit().follow()

        #   Check that the add more details text is shown
        self.assertIn(
            'enter more details',
            response.html.find(
                None, {"class": "user_id"}
            ).text
        )

        #   Check that the link in the nav is heading to the right place
        self.assertIn(
            '/users/user0001com/update-profile',
            response.html.find(
                'span', attrs={'data-slug': 'user0001com'}
            ).find('a').attrs['href'],
        )

        #   Make sure we *don't* have an alert summary heading
        self.assertEquals(
            response.html.find(
                'h3',
                attrs={'class': 'alert-summary-heading'}
            ).text,
            'Please add additional information'
        )
示例#14
0
    def test_user_has_username_teams_no_extra_info_redirected(self):
        #   This user has a username and teams
        o = Organisation(name='org0001')
        o.save()
        t = Team(name='team0001', organisation=o)
        t.save()

        user = get_user_model().objects.create_user(
            userid='*****@*****.**', name='User 0001')
        user.teams.add(t)
        user.save()

        #   Log in as user
        form = self.app.get(reverse('login')).form
        form['userid'] = '*****@*****.**'
        response = form.submit().follow()

        #   Check that the add more details text is shown
        self.assertIn(
            'enter more details',
            response.html.find(
                None, {"class": "user_id"}
            ).text
        )

        #   Check that the link in the nav is heading to the right place
        self.assertIn(
            '/users/user0001com/update-profile',
            response.html.find(
                'span', attrs={'data-slug': 'user0001com'}
            ).find('a').attrs['href'],
        )

        #   Make sure we *don't* have an alert summary heading
        self.assertEquals(
            response.html.find(
                'h3',
                attrs={'class': 'alert-summary-heading'}
            ).text,
            'Please add additional information'
        )
示例#15
0
    def setUp(self):
        fix_teams_roles()
        self.team = Team(name='test', slug='test')
        self.team.save()

        self.user = User.objects.all()[:1].get()
        self.user.is_active = True
        self.user.notify_by_email = True
        self.user.email = '*****@*****.**'
        self.user.save()

        self.tm = TeamMember(team=self.team, user=self.user)
        self.tm.save()

        v1 = Video.objects.all()[:1].get()
        self.tv1 = TeamVideo(team=self.team, video=v1, added_by=self.user)
        self.tv1.save()

        v2 = Video.objects.exclude(pk=v1.pk)[:1].get()
        self.tv2 = TeamVideo(team=self.team, video=v2, added_by=self.user)
        self.tv2.save()
示例#16
0
文件: views.py 项目: dstl/lighthouse
    def get_context_data(self, **kwargs):
        context = super(UserList, self).get_context_data(**kwargs)

        context["top_teams"] = Team.with_most_members()
        context["top_organisations"] = Organisation.with_most_teams()
        context["total_users_in_db"] = User.objects.count()

        if self.has_query():
            context["query"] = self.request.GET["q"]
            context["results_length"] = len(context["object_list"])

        return context
示例#17
0
    def get_context_data(self, **kwargs):
        context = super(UserList, self).get_context_data(**kwargs)

        context['top_teams'] = Team.with_most_members()
        context['top_organisations'] = Organisation.with_most_teams()
        context['total_users_in_db'] = User.objects.count()

        if self.has_query():
            context['query'] = self.request.GET['q']
            context['results_length'] = len(context['object_list'])

        return context
示例#18
0
def get_not_attended_team(tournament):
    enrolled_team_ids = tournament.participants.values_list('team_id',
                                                            flat=True)
    while True:
        team_name = Team.generate_name()
        team_is_enrolled = Team.objects.filter(
            name=team_name, id__in=enrolled_team_ids).exists()

        if team_is_enrolled:
            continue

        team, created = Team.objects.get_or_create(name=team_name)
        return team
示例#19
0
    def test_auto_login_on_landing_for_full_profile(self):
        o = Organisation(name='org0001')
        o.save()
        t = Team(name='team0001', organisation=o)
        t.save()

        user = get_user_model().objects.create_user(
            userid='*****@*****.**',
            name='User 0001',
            best_way_to_find='In the kitchen',
            best_way_to_contact='By email',
            phone='00000000',
            email='*****@*****.**',
        )
        user.teams.add(t)
        user.save()

        headers = {'KEYCLOAK_USERNAME': '******'}
        first_step = self.app.get(reverse('home'), headers=headers)
        self.assertEqual('http://localhost:80/login', first_step.location)

        second_response = self.app.get(first_step.location, headers=headers)
        self.assertEqual('http://localhost:80/links', second_response.location)
示例#20
0
    def test_can_click_through_existing_team_link(self):
        #   Create and log in a user
        get_user_model().objects.create_user(userid='*****@*****.**')
        form = self.app.get(reverse('login')).form
        form['userid'] = 'user0001com'
        form.submit().follow()

        o = Organisation(name='New Org')
        o.save()
        team_name = 'New Team skippity bippity bop'
        t = Team(name=team_name, organisation=o)
        t.save()
        response = self.app.get(reverse('team-list'))
        response = self.app.get(response.html.find(
                'a',
                text=team_name
            ).attrs['href']
        )
        org_name = response.html.find(
            'h1',
            attrs={'class': 'heading-xlarge'}
        ).get_text(strip=True)
        self.assertEquals(org_name, 'Team' + team_name)
示例#21
0
    def test_auto_login_for_complete_profile_goes_to_links(self):
        #   This user has a username and teams
        o = Organisation(name='org0001')
        o.save()
        t = Team(name='team0001', organisation=o)
        t.save()

        user = get_user_model().objects.create_user(
            userid='*****@*****.**',
            name='User 0001',
            best_way_to_find='In the kitchen',
            best_way_to_contact='By email',
            phone='00000000',
            email='*****@*****.**',
        )
        user.teams.add(t)
        user.save()

        headers = {'KEYCLOAK_USERNAME': '******'}
        response = self.app.get(reverse('login'), headers=headers)
        self.assertEqual(
            'http://localhost:80/links',
            response.location
        )
示例#22
0
    def setUp(self):
        self.team = Team(name='test', slug='test')
        self.team.save()
        
        self.user = User.objects.all()[:1].get()
        self.user.is_active = True
        self.user.changes_notification = True
        self.user.email = '*****@*****.**'
        self.user.save()
        
        self.tm = TeamMember(team=self.team, user=self.user)
        self.tm.save()

        v1 = Video.objects.all()[:1].get()
        self.tv1 = TeamVideo(team=self.team, video=v1, added_by=self.user)
        self.tv1.save()
        
        v2 = Video.objects.exclude(pk=v1.pk)[:1].get()
        self.tv2 = TeamVideo(team=self.team, video=v2, added_by=self.user)
        self.tv2.save()
示例#23
0
def create_organisation(name, num_teams=0, num_members=0, usernames={}):
    o = Organisation(name=name)
    o.save()
    user_global_id = 0
    for x in range(0, num_teams):
        t = Team(name='New Team %d' % (x + 1), organisation=o)
        t.save()
        for y in range(user_global_id, num_members + user_global_id):
            if y in usernames.keys():
                username = usernames[y]
            else:
                username = '******' % (y + 1)

            u = get_user_model().objects.create_user(
                userid='teammember%d' % (y + 1),
                name=username,
            )
            u.teams.add(t)
            u.save()
            t.save()
        # Before we go to the next team, increment start ID for member name
        user_global_id += num_members
    return o
示例#24
0
def create_team(name, num_members=0, usernames={}):
    o = Organisation(name="Organisation for %s" % name)
    o.save()
    t = Team(name=name, organisation=o)
    t.save()
    for x in range(0, num_members):
        if x in usernames.keys():
            username = usernames[x]
        else:
            username = '******' % (x + 1)

        u = get_user_model().objects.create_user(
            userid='teammember%d' % (x + 1),
            name=username,
        )

        # if username is not None:
        #     u.username = username

        u.teams.add(t)
        u.save()
        t.save()
    return t
示例#25
0
class ViewsTests(TestCase):
    def setUp(self):
        self.auth = {
            "username": u"admin",
            "password": u"admin"}
        self.user = test_factories.create_user(is_staff=True,
                                               is_superuser=True,
                                               **self.auth)

    def _create_base_team(self):
       self.team = Team(
           slug="new-team",
            membership_policy=4,
            video_policy =1,
           name="New-name")
       self.team.save()
       user, created = User.objects.get_or_create(
           username=self.auth["username"])
       TeamMember.objects.create_first_member(self.team, user)
       return self.team


    def test_team_create(self):
        self.client.login(**self.auth)

        #------- create ----------
        response = self.client.get(reverse("teams:create"))
        self.failUnlessEqual(response.status_code, 200)

        data = {
            "description": u"",
            "video_url": u"",
            "membership_policy": u"4",
            "video_policy": u"1",
            "logo": u"",
            "slug": u"new-team",
            "name": u"New team"
        }
        response = self.client.post(reverse("teams:create"), data)
        self.failUnlessEqual(response.status_code, 302)
        self.assertEqual(Team.objects.get(slug=data['slug']).slug, data["slug"])

    def test_team_edit(self):
        team = self._create_base_team()
        self.client.login(**self.auth)
        url = reverse("teams:settings_basic", kwargs={"slug": team.slug})

        member = self._create_member(team, TeamMember.ROLE_ADMIN)
        videos = [test_factories.create_video() for i in xrange(4)]

        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)

        for video in videos:
            test_factories.create_team_video(team, member.user, video)

        self.assertTrue(all([v.is_public for v in videos]))

        self.assertFalse(team.logo)

        data = {
            "name": u"New team",
            "is_visible": u"0",
            "description": u"testing",
            "logo": open(path.join(settings.MEDIA_ROOT, "test/71600102.jpg"), "rb")
        }

        url = reverse("teams:settings_basic", kwargs={"slug": team.slug})
        response = self.client.post(url, data)
        self.failUnlessEqual(response.status_code, 302)

        team = Team.objects.get(pk=team.pk)
        self.assertTrue(team.logo)
        self.assertEqual(team.name, u"New team")
        self.assertEqual(team.description, u"testing")
        self.assertFalse(team.is_visible)
        self.assertTrue(all([v.is_public for v in videos]))

        data = {
            "name": u"New team",
            "is_visible": u"1",
            "description": u"testing",
        }

        url = reverse("teams:settings_basic", kwargs={"slug": team.slug})
        response = self.client.post(url, data)

        self.failUnlessEqual(response.status_code, 302)
        self.assertTrue(all([v.is_public for v in videos]))

    def test_create_project(self):
        team = self._create_base_team()
        self.client.login(**self.auth)

        url = reverse("teams:add_project", kwargs={"slug": team.slug})

        data = {
            "name": u"Test Project",
            "description": u"Test Project",
            "review_allowed": u"0",
            "approve_allowed": u"0",
        }

        response = self.client.post(url, data)
        self.failUnlessEqual(response.status_code, 302)

        slug = pan_slugify(data['name'])

        project = Project.objects.get(slug=slug)
        self.assertEqual(project.name, data['name'])
        self.assertEqual(project.description, data['description'])

        # creating a duplicated project results in error
        response = self.client.post(url, data)
        self.failUnlessEqual(response.status_code, 200)
        messages = [m.message for m in list(response.context['messages'])]
        self.assertIn(u"There's already a project with this name", messages)

    def test_remove_video(self):
        team = test_factories.create_team(slug="new-team",
                                          membership_policy=4,
                                          video_policy=1,
                                          name="New-name")

        def create_member(role):
            user = test_factories.create_user(username='******' + role,
                                              password='******' + role)
            return TeamMember.objects.create(user=user, role=role, team=team)

        admin = create_member(TeamMember.ROLE_ADMIN)
        contributor = create_member(TeamMember.ROLE_CONTRIBUTOR)
        manager = create_member(TeamMember.ROLE_MANAGER)
        owner = create_member(TeamMember.ROLE_OWNER)

        def create_team_video():
            return test_factories.create_team_video(team, owner.user)

        # The video policy determines who can remove videos from teams.
        for member in [contributor, manager, admin, owner]:
            self.client.login(username=member.user.username,
                              password=member.user.username)
            tv = create_team_video()
            video_url = tv.video.get_video_url()

            url = reverse("teams:remove_video", kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url)

            self.assertEqual(response.status_code, 302)
            self.assertFalse(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertTrue(VideoUrl.objects.get(url=video_url).video)

        # Only owners can delete videos entirely.
        for role in [owner]:
            self.client.login(username=role.user.username,
                              password=role.user.username)
            tv = create_team_video()
            video_url = tv.video.get_video_url()

            url = reverse("teams:remove_video", kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url, {'del-opt': 'total-destruction'})

            self.assertEqual(response.status_code, 302)
            self.assertFalse(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertFalse(VideoUrl.objects.filter(url=video_url).exists())

        for role in [contributor, manager, admin]:
            self.client.login(username=role.user.username,
                              password=role.user.username)
            tv = create_team_video()
            video_url = tv.video.get_video_url()

            url = reverse("teams:remove_video", kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url, {'del-opt': 'total-destruction'})

            self.assertEqual(response.status_code, 302)
            self.assertTrue(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertTrue(VideoUrl.objects.filter(url=video_url).exists())

        # POST request required
        tv = create_team_video()
        video_url = tv.video.get_video_url()
        url = reverse("teams:remove_video", kwargs={"team_video_pk": tv.pk})
        self.client.login(username=self.user.username,
                          password=self.user.username)
        response = self.client.get(url)

        self.assertEqual(response.status_code, 302)
        self.assertTrue(TeamVideo.objects.filter(pk=tv.pk).exists())
        self.assertTrue(VideoUrl.objects.filter(url=video_url).exists())


    def test_move_video_allowed(self):
        # Check that moving works when the user has permission.
        video = test_factories.create_video()
        old_team = test_factories.create_team(video_policy=Team.VP_MANAGER)
        new_team = test_factories.create_team(video_policy=Team.VP_MANAGER)
        team_video = test_factories.create_team_video(old_team, self.user,
                                                      video)
        # Convenient functions for pulling models fresh from the DB.
        get_video = lambda: Video.objects.get(pk=video.pk)
        get_team_video = lambda: get_video().get_team_video()

        # Create a member that's an admin of BOTH teams.
        # This member should be able to move the video.
        member = self._create_member(old_team, TeamMember.ROLE_ADMIN)
        self._create_member(new_team, TeamMember.ROLE_ADMIN, member.user)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not start in the correct team.")

        # Move the video.
        self.client.login(username=member.user.username,
                          password=member.user.username)
        url = reverse("teams:move_video")
        response = self.client.post(url, {'team_video': get_team_video().pk,
                                          'team': new_team.pk,})
        self.assertEqual(response.status_code, 302)

        self.assertEqual(get_team_video().team.pk, new_team.pk,
                         "Video was not moved to the new team.")

        self.assertEqual(get_team_video().project.team, new_team,
                         "Video ended up with a project for the first team")

    def test_move_video_disallowed_old(self):
        # Check that moving does not work when the user is blocked by the old
        # team.
        video = test_factories.create_video()
        old_team = test_factories.create_team(video_policy=Team.VP_MANAGER)
        new_team = test_factories.create_team(video_policy=Team.VP_MANAGER)
        team_video = test_factories.create_team_video(old_team, self.user,
                                                      video)
        # Convenient functions for pulling models fresh from the DB.
        get_video = lambda: Video.objects.get(pk=video.pk)
        get_team_video = lambda: get_video().get_team_video()

        # Create a member that's a contributor to the old/current team.
        # This member should NOT be able to move the video because they cannot
        # remove it from the first team.
        member = self._create_member(old_team, TeamMember.ROLE_CONTRIBUTOR)
        self._create_member(new_team, TeamMember.ROLE_ADMIN, member.user)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not start in the correct team.")

        # Try to move the video.
        self.client.login(username=member.user.username,
                          password=member.user.username)
        url = reverse("teams:move_video")
        response = self.client.post(url, {'team_video': get_team_video().pk,
                                          'team': new_team.pk,})
        self.assertEqual(response.status_code, 302)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not stay in the old team.")

    def test_move_video_disallowed_new(self):
        # Check that moving does not work when the user is blocked by the new
        # team.
        video = test_factories.create_video()
        old_team = test_factories.create_team(video_policy=Team.VP_MANAGER)
        new_team = test_factories.create_team(video_policy=Team.VP_MANAGER)
        team_video = test_factories.create_team_video(old_team, self.user,
                                                      video)
        # Convenient functions for pulling models fresh from the DB.
        get_video = lambda: Video.objects.get(pk=video.pk)
        get_team_video = lambda: get_video().get_team_video()

        # Create a member that's a contributor to the new/target team.
        # This member should NOT be able to move the video because they cannot
        # add it to the second team.
        member = self._create_member(old_team, TeamMember.ROLE_ADMIN)
        self._create_member(new_team, TeamMember.ROLE_CONTRIBUTOR, member.user)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not start in the correct team.")

        # Try to move the video.
        self.client.login(username=member.user.username,
                          password=member.user.username)
        url = reverse("teams:move_video")
        response = self.client.post(url, {'team_video': get_team_video().pk,
                                          'team': new_team.pk,})
        self.assertEqual(response.status_code, 302)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not stay in the old team.")

    def test_team_permission(self):
        team = test_factories.create_team(slug="private-team",
                                          name="Private Team",
                                          is_visible=False)
        TeamMember.objects.create_first_member(team, self.user)
        video = test_factories.create_video()
        test_factories.create_team_video(team, self.user, video)

        url = reverse("videos:video", kwargs={"video_id": video.video_id})

        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 404)

        self.client.login(**self.auth)

        response = self.client.get(url, follow=True)
        self.assertEquals(response.status_code, 200)

        self.client.logout()

    def test_add_videos_via_feed(self):
        team = self._create_base_team()
        self.client.login(**self.auth)

        url = reverse("teams:add_videos", kwargs={"slug": team.slug})

        data = {
            'feed_url': u'http://blip.tv/coxman/rss'
        }

        old_video_count = Video.objects.count()
        old_team_video_count = TeamVideo.objects.filter(team=team).count()

        response = self.client.post(url, data)
        self.assertRedirects(response, team.get_absolute_url())

        self.assertNotEquals(old_video_count, Video.objects.count())
        self.assertNotEquals(old_team_video_count, TeamVideo.objects.filter(team=team).count())

    def test_add_videos_via_youtube_user(self):
        team = self._create_base_team()
        self.client.login(**self.auth)

        url = reverse("teams:add_videos", kwargs={"slug": team.slug})

        data = {
            'usernames': u'fernandotakai'
        }

        old_video_count = Video.objects.count()
        old_team_video_count = TeamVideo.objects.filter(team=team).count()

        response = self.client.post(url, data)
        self.assertRedirects(response, team.get_absolute_url())

        self.assertNotEquals(old_video_count, Video.objects.count())
        self.assertNotEquals(old_team_video_count, TeamVideo.objects.filter(team=team).count())

    def _create_member(self, team, role, user=None):
        if not user:
            user = User.objects.create(username='******' + role)
            user.set_password('test' + role)
            user.save()
        return TeamMember.objects.create(user=user, role=role, team=team)
示例#26
0
文件: views.py 项目: dstl/lighthouse
    def form_valid(self, form):
        userDetails = form.save(commit=False)

        #   Don't do any of this is the user isn't currently logged in
        #   or different to the currently logged in user
        if self.request.user.is_authenticated() is False or userDetails.id != self.request.user.id:
            return HttpResponseRedirect(self.get_success_url())

        #   If we have been passed a name then we have come from the
        #   user details form, if we don't have a name, then we are dealing
        #   with teams.
        if form.data.get("name") is not None:
            userDetails.save()
        else:
            user = User.objects.get(pk=userDetails.pk)
            #   Now we need to dump all the current links to teams and
            #   then add them all back in.
            user.teams.clear()
            for team in form.data.getlist("team"):
                user.teams.add(int(team))

            #   We need to see if we have been passed over a new team name
            #   if so then we have a bunch of work to do around adding that
            #   team
            team_name = form.data.get("teamname")
            if team_name is not None and team_name is not "":
                new_organisation_name = form.data.get("new_organisation")
                organisation_id = form.data.get("organisation")

                #   Now check to see if this team is using an existing
                #   organisation or a new_organisation.
                #   If it a new organisation then we need to create it.
                if new_organisation_name is not None and new_organisation_name is not "":
                    check_org = Organisation.objects.filter(name=new_organisation_name).exists()
                    if check_org is True:
                        new_organisation = Organisation.objects.get(name=new_organisation_name)
                    else:
                        new_organisation = Organisation()
                        new_organisation.name = new_organisation_name
                        new_organisation.save()
                else:
                    #   Otherwise we are going to use the organisation we
                    #   have been passed over.
                    check_org = Organisation.objects.filter(pk=organisation_id).exists()
                    if check_org is True:
                        new_organisation = Organisation.objects.get(pk=organisation_id)
                    else:
                        # TODO: Raise an error here to display on the form
                        return self.render_to_response(self.get_context_data())

                #   Either way we now have a new_organisation object that we
                #   can use to create the team.
                check_team = Team.objects.filter(name=team_name).exists()

                if check_team is True:
                    new_team = Team.objects.filter(name=team_name)
                else:
                    new_team = Team(name=team_name, organisation=new_organisation)
                    new_team.save()

                #   Now add the new team to the teams join on the user
                user.teams.add(new_team.pk)
                user.save()

        #   If the user wants to add another team, do that here
        #   TODO: add a #team thingy to the URL so we can jump down to the
        #   teams section
        submit_action = form.data.get("submit_action")
        if submit_action is not None and submit_action is not "":
            if submit_action in ["Save and add a new team", "Save and manage team membership"]:
                return HttpResponseRedirect(reverse("user-update-teams", kwargs={"slug": self.request.user.slug}))

        #   Normally we'd just go back to their profile page. So we'll do
        #   that here.
        return HttpResponseRedirect(self.get_success_url())
示例#27
0
class TestJqueryRpc(TestCase):

    def setUp(self):
        fix_teams_roles()
        self.team = Team(name='Test', slug='test')
        self.team.save()
        self.user = User.objects.all()[:1].get()
        self.rpc = TeamsApiClass()

    def test_promote_user(self):
        other_user = User.objects.exclude(pk=self.user.pk)[:1].get()
        user_tm = TeamMember(team=self.team, user=self.user)
        user_tm.save()
        other_user_tm = TeamMember(team=self.team, user=other_user)
        other_user_tm.save()

        self.assertEqual(other_user_tm.role, TeamMember.ROLE_CONTRIBUTOR)
        self.assertEqual(user_tm.role, TeamMember.ROLE_CONTRIBUTOR)

        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, TeamMember.ROLE_MANAGER, AnonymousUser())
        if not isinstance(response, Error):
            self.fail('Anonymouse user is not member of team')

        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, TeamMember.ROLE_MANAGER, self.user)
        if not isinstance(response, Error):
            self.fail('User should be manager')

        user_tm.role = TeamMember.ROLE_MANAGER
        user_tm.save()

        NEW_ROLE = TeamMember.ROLE_CONTRIBUTOR
        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, NEW_ROLE, self.user)
        self.assertTrue(isinstance(response, Msg))
        other_user_tm = refresh_obj(other_user_tm)
        self.assertEqual(other_user_tm.role, NEW_ROLE)

        response = self.rpc.promote_user(self.team.pk, user_tm.pk, TeamMember.ROLE_CONTRIBUTOR, self.user)
        if not isinstance(response, Error):
            self.fail('Can\'t promote yourself')

        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, 'undefined role 123456', self.user)
        if not isinstance(response, Error):
            self.fail('Incorrect role')

        response = self.rpc.promote_user(self.team.pk, 123456, TeamMember.ROLE_MANAGER, self.user)
        if not isinstance(response, Error):
            self.fail('Undefined team member')

        undefined_team_pk = 123456
        self.assertFalse(Team.objects.filter(pk=undefined_team_pk))
        response = self.rpc.promote_user(undefined_team_pk, other_user_tm.pk, TeamMember.ROLE_MANAGER, self.user)
        if not isinstance(response, Error):
            self.fail('Undefined team')

    def test_create_application(self):
        response = self.rpc.create_application(self.team.pk, 'Note', AnonymousUser())
        if not isinstance(response, Error):
            self.fail('User should be authenticated')
        #---------------------------------------

        response = self.rpc.create_application(None, 'Note', self.user)
        if not isinstance(response, Error):
            self.fail('Undefined team')
        #---------------------------------------
        self.team.membership_policy = Team.INVITATION_BY_MANAGER
        self.team.save()

        response = self.rpc.create_application(self.team.pk, 'Note', self.user)
        if not isinstance(response, Error):
            self.fail('Team is not opened')
        #---------------------------------------
        self.team.membership_policy = Team.OPEN
        self.team.save()

        self.assertFalse(self.team.is_member(self.user))

        response = self.rpc.create_application(self.team.pk, 'Note', self.user)

        if isinstance(response, Error):
            self.fail(response)

        self.assertTrue(self.team.is_member(self.user))
        #---------------------------------------
        self.team.members.filter(user=self.user).delete()

        self.team.membership_policy = Team.APPLICATION
        self.team.save()

        self.assertFalse(Application.objects.filter(user=self.user, team=self.team).exists())
        response = self.rpc.create_application(self.team.pk, 'Note', self.user)

        if isinstance(response, Error):
            self.fail(response)

        self.assertFalse(self.team.is_member(self.user))
        self.assertTrue(Application.objects.filter(user=self.user, team=self.team).exists())
示例#28
0
 def setUp(self):
     fix_teams_roles()
     self.team = Team(name='Test', slug='test')
     self.team.save()
     self.user = User.objects.all()[:1].get()
     self.rpc = TeamsApiClass()
示例#29
0
class TestJqueryRpc(TestCase):
    
    def setUp(self):
        self.team = Team(name='Test', slug='test')
        self.team.save()
        self.user = User.objects.all()[:1].get()
        self.rpc = TeamsApiClass()
    
    def test_promote_user(self):
        other_user = User.objects.exclude(pk=self.user.pk)[:1].get()
        user_tm = TeamMember(team=self.team, user=self.user)
        user_tm.save()
        other_user_tm = TeamMember(team=self.team, user=other_user)
        other_user_tm.save()
        
        self.assertEqual(other_user_tm.role, TeamMember.ROLE_MEMBER)
        self.assertEqual(user_tm.role, TeamMember.ROLE_MEMBER)
        
        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, TeamMember.ROLE_MANAGER, AnonymousUser())
        if not isinstance(response, Error):
            self.fail('Anonymouse user is not member of team')

        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, TeamMember.ROLE_MANAGER, self.user)
        if not isinstance(response, Error):
            self.fail('User should be manager')
            
        user_tm.role = TeamMember.ROLE_MANAGER
        user_tm.save()
        
        NEW_ROLE = TeamMember.ROLE_CONTRIBUTOR
        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, NEW_ROLE, self.user)
        self.assertTrue(isinstance(response, Msg))
        other_user_tm = refresh_obj(other_user_tm)
        self.assertEqual(other_user_tm.role, NEW_ROLE)
        
        response = self.rpc.promote_user(self.team.pk, user_tm.pk, TeamMember.ROLE_CONTRIBUTOR, self.user)
        if not isinstance(response, Error):
            self.fail('Can\'t promote yourself')        
        
        response = self.rpc.promote_user(self.team.pk, other_user_tm.pk, 'undefined role 123456', self.user)
        if not isinstance(response, Error):
            self.fail('Incorrect role')                

        response = self.rpc.promote_user(self.team.pk, 123456, TeamMember.ROLE_MANAGER, self.user)
        if not isinstance(response, Error):
            self.fail('Undefined team member')    

        undefined_team_pk = 123456
        self.assertFalse(Team.objects.filter(pk=undefined_team_pk))
        response = self.rpc.promote_user(undefined_team_pk, other_user_tm.pk, TeamMember.ROLE_MANAGER, self.user)
        if not isinstance(response, Error):
            self.fail('Undefined team')   
        
    def test_create_application(self):
        response = self.rpc.create_application(self.team.pk, '', AnonymousUser())
        if not isinstance(response, Error):
            self.fail('User should be authenticated')
        #---------------------------------------

        response = self.rpc.create_application(None, '', self.user)
        if not isinstance(response, Error):
            self.fail('Undefined team')
        #---------------------------------------    
        self.team.membership_policy = Team.INVITATION_BY_MANAGER
        self.team.save()
        
        response = self.rpc.create_application(self.team.pk, '', self.user)
        if not isinstance(response, Error):
            self.fail('Team is not opened')
        #---------------------------------------
        self.team.membership_policy = Team.OPEN
        self.team.save()
        
        self.assertFalse(self.team.is_member(self.user))
        
        response = self.rpc.create_application(self.team.pk, '', self.user)
        
        if isinstance(response, Error):
            self.fail(response)
        
        self.assertTrue(self.team.is_member(self.user))        
        #---------------------------------------
        self.team.members.filter(user=self.user).delete()
        
        self.team.membership_policy = Team.APPLICATION
        self.team.save()
        
        self.assertFalse(Application.objects.filter(user=self.user, team=self.team).exists())  
        response = self.rpc.create_application(self.team.pk, '', self.user)

        if isinstance(response, Error):
            self.fail(response)
        
        self.assertFalse(self.team.is_member(self.user))
        self.assertTrue(Application.objects.filter(user=self.user, team=self.team).exists())
示例#30
0
    def test_top_teams_and_orgs(self):
        #   Create three orgs
        o1 = Organisation(name='org0001')
        o1.save()
        o2 = Organisation(name='org0002')
        o2.save()
        o3 = Organisation(name='org0003')
        o3.save()

        #   Create SEVEN teams!!! Grouped into organistions
        t1 = Team(name='team0001', organisation=o1)
        t1.save()
        t2 = Team(name='team0002', organisation=o1)
        t2.save()
        t3 = Team(name='team0003', organisation=o1)
        t3.save()
        t4 = Team(name='team0004', organisation=o2)
        t4.save()
        t5 = Team(name='team0005', organisation=o2)
        t5.save()
        t6 = Team(name='team0006', organisation=o3)
        t6.save()
        t7 = Team(name='team0007', organisation=o3)
        t7.save()

        #   Now we need three users, and throw them into teams
        u1 = get_user_model().objects.create_user(userid='user0001')
        u1.save()
        u1.teams.add(t2, t3, t4)
        u1.save()

        u2 = get_user_model().objects.create_user(userid='user0002')
        u2.save()
        u2.teams.add(t5, t6)
        u2.save()

        u3 = get_user_model().objects.create_user(userid='user0003')
        u3.save()
        u3.teams.add(t3, t5, t6, t7)
        u3.save()

        #   Last and not least we need a tool for everyone to use
        l1 = Link(name='link0001',
                  is_external=True,
                  owner=u1,
                  destination='http://google.com')
        l1.save()

        #   Now we need to log the activity of each user.
        #
        #   User 1, is going to use the tool 4 times.
        for i in range(0, 4):
            l1.register_usage(user=u1, force_new=True)

        #   User 2, is going to use the tool 2 times.
        for i in range(0, 2):
            l1.register_usage(user=u2, force_new=True)

        #   User 3, is going to use the tool 5 times.
        for i in range(0, 5):
            l1.register_usage(user=u3, force_new=True)

        #   Login as the first user
        form = self.app.get(reverse('login')).form
        form['userid'] = 'user0001'
        form.submit()

        #   Now lets go an have a look at the details page, and check
        #   out the teams and organisations usage count.
        details_page = self.app.get(
            reverse('link-detail', kwargs={'pk': l1.pk}))

        #   Due to the counting above, we know the teams have used the tool
        #   the following amount, so lets check for that...
        #   t1:0, t2:4, t3:9, t4:4, t5:7, t6:7, t7:5
        #   i.e. there are no members is team 1.
        #   only user 1 is in team 2.
        #   users 1 & 3 are in team 3.
        usage_by_teams = details_page.html.find(
            'ul', id='usage-by-teams').findAll('li')
        self.assertEquals(usage_by_teams[0].text,
                          'team0003 have collectively used the tool 9 times')
        self.assertEquals(usage_by_teams[1].text,
                          'team0005 have collectively used the tool 7 times')
        self.assertEquals(usage_by_teams[2].text,
                          'team0006 have collectively used the tool 7 times')
        self.assertEquals(usage_by_teams[3].text,
                          'team0007 have collectively used the tool 5 times')
        self.assertEquals(usage_by_teams[4].text,
                          'team0002 have collectively used the tool 4 times')

        #   We do a similar thing with organisations, which are tricky
        #   because user 1 is in team 2 & 3, so both those teams get the
        #   4 times user 1 used the tool. But teams 2 & 3 are both in org 1,
        #   and the code has made sure to only count the useage once, rather
        #   than 4 times from team 2 and 4 again from team 3. This checks
        #   that based on the numbers above the results are as follows.
        #   o1:9, o2:11, o3:7. Ordered that's o2,o1,o3.
        used_by_organisations = details_page.html.find(
            'ul', id='usage-by-organisations').findAll('li')
        self.assertEquals(used_by_organisations[0].text,
                          'org0002 have collectively used the tool 11 times')
        self.assertEquals(used_by_organisations[1].text,
                          'org0001 have collectively used the tool 9 times')
        self.assertEquals(used_by_organisations[2].text,
                          'org0003 have collectively used the tool 7 times')
示例#31
0
 def setUp(self):
     o = Organisation(name='Existing Org')
     o.save()
     t = Team(name='Existing Team', organisation=o)
     t.save()
示例#32
0
 def test_cannot_create_duplicate_team(self):
     t = Team(name='Existing Team')
     with self.assertRaises(IntegrityError):
         t.save()
示例#33
0
class TestJqueryRpc(TestCase):
    
    def setUp(self):
        self.team = Team(name='Test', slug='test')
        self.team.save()
        self.user = User.objects.all()[:1].get()
        self.rpc = TeamsApiClass()
        
    def test_create_application(self):
        response = self.rpc.create_application(self.team.pk, '', AnonymousUser())
        if not isinstance(response, Error):
            self.fail('User should be authenticated')
        #---------------------------------------

        response = self.rpc.create_application(None, '', self.user)
        if not isinstance(response, Error):
            self.fail('Undefined team')
        #---------------------------------------    
        self.team.membership_policy = Team.INVITATION_BY_MANAGER
        self.team.save()
        
        response = self.rpc.create_application(self.team.pk, '', self.user)
        if not isinstance(response, Error):
            self.fail('Team is not opened')
        #---------------------------------------
        self.team.membership_policy = Team.OPEN
        self.team.save()
        
        self.assertFalse(self.team.is_member(self.user))
        
        response = self.rpc.create_application(self.team.pk, '', self.user)
        
        if isinstance(response, Error):
            self.fail(response)
        
        self.assertTrue(self.team.is_member(self.user))
        #---------------------------------------
        response = self.rpc.leave(self.team.pk, self.user)
        
        if not isinstance(response, Error):
            self.fail('You are the only member of team')
        
        other_user = User.objects.exclude(pk=self.user)[:1].get()
        self.rpc.join(self.team.pk, other_user)    
        
        response = self.rpc.leave(self.team.pk, self.user)
        if isinstance(response, Error):
            self.fail(response)
                    
        self.assertFalse(self.team.is_member(self.user))           
        #---------------------------------------
        self.team.membership_policy = Team.APPLICATION
        self.team.save()
        
        self.assertFalse(Application.objects.filter(user=self.user, team=self.team).exists())  
        response = self.rpc.create_application(self.team.pk, '', self.user)

        if isinstance(response, Error):
            self.fail(response)
        
        self.assertFalse(self.team.is_member(self.user))
        self.assertTrue(Application.objects.filter(user=self.user, team=self.team).exists())
        #---------------------------------------
        
    def test_join(self):
        self.team.membership_policy = Team.OPEN
        self.team.save()
        
        self.assertFalse(self.team.is_member(self.user))
        
        response = self.rpc.join(self.team.pk, self.user)
        
        if isinstance(response, Error):
            self.fail(response)
        
        self.assertTrue(self.team.is_member(self.user))            
示例#34
0
 def test_cannot_create_duplicate_team(self):
     t = Team(name="Existing Team")
     with self.assertRaises(IntegrityError):
         t.save()
示例#35
0
    def test_remove_video(self):
        video_url = Video.objects.all()[0].get_video_url()

        team = Team(slug="new-team",
                    membership_policy=4,
                    video_policy=1,
                    name="New-name")
        team.save()

        TeamMember.objects.create_first_member(
            team, User.objects.create(username='******'))

        def create_member(role):
            user = User.objects.create(username='******' + role)
            user.set_password('test' + role)
            user.save()
            return TeamMember.objects.create(user=user, role=role, team=team)

        admin = create_member(TeamMember.ROLE_ADMIN)
        contributor = create_member(TeamMember.ROLE_CONTRIBUTOR)
        manager = create_member(TeamMember.ROLE_MANAGER)
        owner = create_member(TeamMember.ROLE_OWNER)

        def create_team_video():
            v, c = Video.get_or_create_for_url(video_url)
            tv, c = TeamVideo.objects.get_or_create(
                video=v, team=team, defaults={'added_by': owner.user})
            return tv

        # The video policy determines who can remove videos from teams.
        for member in [contributor, manager, admin, owner]:
            self.client.login(username=member.user.username,
                              password=member.user.username)
            tv = create_team_video()

            url = reverse("teams:remove_video",
                          kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url)

            self.assertEqual(response.status_code, 302)
            self.assertFalse(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertTrue(VideoUrl.objects.get(url=video_url).video)

        # Only owners can delete videos entirely.
        for role in [owner]:
            self.client.login(username=role.user.username,
                              password=role.user.username)
            tv = create_team_video()

            url = reverse("teams:remove_video",
                          kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url, {'del-opt': 'total-destruction'})

            self.assertEqual(response.status_code, 302)
            self.assertFalse(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertFalse(VideoUrl.objects.filter(url=video_url).exists())

        for role in [contributor, manager, admin]:
            self.client.login(username=role.user.username,
                              password=role.user.username)
            tv = create_team_video()

            url = reverse("teams:remove_video",
                          kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url, {'del-opt': 'total-destruction'})

            self.assertEqual(response.status_code, 302)
            self.assertTrue(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertTrue(VideoUrl.objects.filter(url=video_url).exists())

        # POST request required
        tv = create_team_video()
        url = reverse("teams:remove_video", kwargs={"team_video_pk": tv.pk})
        self.client.login(username=self.user.username,
                          password=self.user.username)
        response = self.client.get(url)

        self.assertEqual(response.status_code, 302)
        self.assertTrue(TeamVideo.objects.filter(pk=tv.pk).exists())
        self.assertTrue(VideoUrl.objects.filter(url=video_url).exists())
示例#36
0
class ViewsTests(TestCase):
    fixtures = [
        "staging_users.json", "staging_videos.json", "staging_teams.json"
    ]

    def setUp(self):
        self.auth = {"username": u"admin", "password": u"admin"}
        self.user = User.objects.get(username=self.auth["username"])

    def _create_base_team(self):
        self.team = Team(slug="new-team",
                         membership_policy=4,
                         video_policy=1,
                         name="New-name")
        self.team.save()
        user, created = User.objects.get_or_create(
            username=self.auth["username"])
        TeamMember.objects.create_first_member(self.team, user)
        return self.team

    def test_team_create(self):

        self.client.login(**self.auth)

        #------- create ----------
        response = self.client.get(reverse("teams:create"))
        self.failUnlessEqual(response.status_code, 200)

        data = {
            "description": u"",
            "video_url": u"",
            "membership_policy": u"4",
            "video_policy": u"1",
            "logo": u"",
            "slug": u"new-team",
            "name": u"New team"
        }
        response = self.client.post(reverse("teams:create"), data)
        self.failUnlessEqual(response.status_code, 302)
        self.assertEqual(
            Team.objects.get(slug=data['slug']).slug, data["slug"])

    def test_team_edit(self):
        team = self._create_base_team()
        self.client.login(**self.auth)
        url = reverse("teams:settings_basic", kwargs={"slug": team.slug})
        response = self.client.get(url)

        self.failUnlessEqual(response.status_code, 200)

        self.assertFalse(team.logo)

        data = {
            "name": u"New team",
            "is_visible": u"1",
            "description": u"testing",
            "logo": open(path.join(settings.MEDIA_ROOT, "test/71600102.jpg"),
                         "rb")
        }
        url = reverse("teams:settings_basic", kwargs={"slug": team.slug})
        response = self.client.post(url, data)
        self.failUnlessEqual(response.status_code, 302)

        team = Team.objects.get(pk=team.pk)
        self.assertTrue(team.logo)
        self.assertEqual(team.name, u"New team")
        self.assertEqual(team.description, u"testing")
        self.assertTrue(team.is_visible)

    def test_create_project(self):
        team = self._create_base_team()
        self.client.login(**self.auth)

        url = reverse("teams:add_project", kwargs={"slug": team.slug})

        data = {
            "name": u"Test Project",
            "description": u"Test Project",
            "review_allowed": u"0",
            "approve_allowed": u"0",
        }

        response = self.client.post(url, data)
        self.failUnlessEqual(response.status_code, 302)

        slug = pan_slugify(data['name'])

        project = Project.objects.get(slug=slug)
        self.assertEqual(project.name, data['name'])
        self.assertEqual(project.description, data['description'])

        # creating a duplicated project results in error
        response = self.client.post(url, data)
        self.failUnlessEqual(response.status_code, 200)
        messages = [m.message for m in list(response.context['messages'])]
        self.assertIn(u"There's already a project with this name", messages)

    def test_remove_video(self):
        video_url = Video.objects.all()[0].get_video_url()

        team = Team(slug="new-team",
                    membership_policy=4,
                    video_policy=1,
                    name="New-name")
        team.save()

        TeamMember.objects.create_first_member(
            team, User.objects.create(username='******'))

        def create_member(role):
            user = User.objects.create(username='******' + role)
            user.set_password('test' + role)
            user.save()
            return TeamMember.objects.create(user=user, role=role, team=team)

        admin = create_member(TeamMember.ROLE_ADMIN)
        contributor = create_member(TeamMember.ROLE_CONTRIBUTOR)
        manager = create_member(TeamMember.ROLE_MANAGER)
        owner = create_member(TeamMember.ROLE_OWNER)

        def create_team_video():
            v, c = Video.get_or_create_for_url(video_url)
            tv, c = TeamVideo.objects.get_or_create(
                video=v, team=team, defaults={'added_by': owner.user})
            return tv

        # The video policy determines who can remove videos from teams.
        for member in [contributor, manager, admin, owner]:
            self.client.login(username=member.user.username,
                              password=member.user.username)
            tv = create_team_video()

            url = reverse("teams:remove_video",
                          kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url)

            self.assertEqual(response.status_code, 302)
            self.assertFalse(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertTrue(VideoUrl.objects.get(url=video_url).video)

        # Only owners can delete videos entirely.
        for role in [owner]:
            self.client.login(username=role.user.username,
                              password=role.user.username)
            tv = create_team_video()

            url = reverse("teams:remove_video",
                          kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url, {'del-opt': 'total-destruction'})

            self.assertEqual(response.status_code, 302)
            self.assertFalse(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertFalse(VideoUrl.objects.filter(url=video_url).exists())

        for role in [contributor, manager, admin]:
            self.client.login(username=role.user.username,
                              password=role.user.username)
            tv = create_team_video()

            url = reverse("teams:remove_video",
                          kwargs={"team_video_pk": tv.pk})
            response = self.client.post(url, {'del-opt': 'total-destruction'})

            self.assertEqual(response.status_code, 302)
            self.assertTrue(TeamVideo.objects.filter(pk=tv.pk).exists())
            self.assertTrue(VideoUrl.objects.filter(url=video_url).exists())

        # POST request required
        tv = create_team_video()
        url = reverse("teams:remove_video", kwargs={"team_video_pk": tv.pk})
        self.client.login(username=self.user.username,
                          password=self.user.username)
        response = self.client.get(url)

        self.assertEqual(response.status_code, 302)
        self.assertTrue(TeamVideo.objects.filter(pk=tv.pk).exists())
        self.assertTrue(VideoUrl.objects.filter(url=video_url).exists())

    def test_move_video_allowed(self):
        '''Check that moving works when the user has permission.'''
        video_pk = Video.objects.all()[0].pk

        # Convenient functions for pulling models fresh from the DB.
        get_video = lambda: Video.objects.get(pk=video_pk)
        get_team_video = lambda: get_video().get_team_video()

        old_team = Team.objects.get(pk=1)
        new_team = Team.objects.get(pk=2)

        # Create a member that's an admin of BOTH teams.
        # This member should be able to move the video.
        member = self._create_member(old_team, TeamMember.ROLE_ADMIN)
        self._create_member(new_team, TeamMember.ROLE_ADMIN, member.user)

        self._create_team_video(get_video().get_video_url(), old_team,
                                member.user)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not start in the correct team.")

        # Move the video.
        self.client.login(username=member.user.username,
                          password=member.user.username)
        url = reverse("teams:move_video")
        response = self.client.post(url, {
            'team_video': get_team_video().pk,
            'team': new_team.pk,
        })
        self.assertEqual(response.status_code, 302)

        self.assertEqual(get_team_video().team.pk, new_team.pk,
                         "Video was not moved to the new team.")

        self.assertEqual(get_team_video().project.team, new_team,
                         "Video ended up with a project for the first team")

    def test_move_video_disallowed_old(self):
        '''Check that moving does not work when the user is blocked by the old team.'''
        video_pk = Video.objects.all()[0].pk

        get_video = lambda: Video.objects.get(pk=video_pk)
        get_team_video = lambda: get_video().get_team_video()

        old_team = Team.objects.get(pk=1)
        new_team = Team.objects.get(pk=2)

        # Create a member that's a contributor to the old/current team.
        # This member should NOT be able to move the video because they cannot
        # remove it from the first team.
        member = self._create_member(old_team, TeamMember.ROLE_CONTRIBUTOR)
        self._create_member(new_team, TeamMember.ROLE_ADMIN, member.user)

        self._create_team_video(get_video().get_video_url(), old_team,
                                member.user)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not start in the correct team.")

        # Try to move the video.
        self.client.login(username=member.user.username,
                          password=member.user.username)
        url = reverse("teams:move_video")
        response = self.client.post(url, {
            'team_video': get_team_video().pk,
            'team': new_team.pk,
        })
        self.assertEqual(response.status_code, 302)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not stay in the old team.")

    def test_move_video_disallowed_new(self):
        '''Check that moving does not work when the user is blocked by the new team.'''
        video_pk = Video.objects.all()[0].pk

        get_video = lambda: Video.objects.get(pk=video_pk)
        get_team_video = lambda: get_video().get_team_video()

        old_team = Team.objects.get(pk=1)
        new_team = Team.objects.get(pk=2)

        # Create a member that's a contributor to the new/target team.
        # This member should NOT be able to move the video because they cannot
        # add it to the second team.
        member = self._create_member(old_team, TeamMember.ROLE_ADMIN)
        self._create_member(new_team, TeamMember.ROLE_CONTRIBUTOR, member.user)

        self._create_team_video(get_video().get_video_url(), old_team,
                                member.user)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not start in the correct team.")

        # Try to move the video.
        self.client.login(username=member.user.username,
                          password=member.user.username)
        url = reverse("teams:move_video")
        response = self.client.post(url, {
            'team_video': get_team_video().pk,
            'team': new_team.pk,
        })
        self.assertEqual(response.status_code, 302)

        self.assertEqual(get_team_video().team.pk, old_team.pk,
                         "Video did not stay in the old team.")

    def _create_team_video(self, video_url, team, user):
        v, c = Video.get_or_create_for_url(video_url)
        tv, c = TeamVideo.objects.get_or_create(video=v,
                                                team=team,
                                                defaults={'added_by': user})
        return tv

    def _create_member(self, team, role, user=None):
        if not user:
            user = User.objects.create(username='******' + role)
            user.set_password('test' + role)
            user.save()
        return TeamMember.objects.create(user=user, role=role, team=team)
示例#37
0
 def setUp(self):
     self.team = Team(name='Test', slug='test')
     self.team.save()
     self.user = User.objects.all()[:1].get()
     self.rpc = TeamsApiClass()
示例#38
0
    def test_join_leave_buttons_work(self):
        #   Create an organisation, a team and a user and assign that
        #   team to that user.
        o = Organisation(name="org0001")
        o.save()
        t = Team(name="team0001", organisation=o)
        t.save()
        u = get_user_model().objects.create_user(userid='*****@*****.**')
        login_user(self, u)

        response = self.app.get(
            reverse(
                'team-detail',
                kwargs={'pk': t.pk}
            )
        )

        form = response.form

        self.assertEqual(
            form.method,
            'post'
        )

        self.assertEqual(
            form.action,
            '/teams/' + str(t.pk) + '/join'
        )

        response = form.submit().follow()

        # Make sure the user is now in the team
        response = self.app.get(
            reverse(
                'user-detail',
                kwargs={'slug': u.slug}
            )
        )

        self.assertTrue(
            response.html.find(
                'a',
                attrs={
                    'class': 'main-list-item',
                    'href': '/teams/' + str(t.pk)
                }
            )
        )

        # Go back to the team detail page so we can submit the link
        response = self.app.get(
            reverse(
                'team-detail',
                kwargs={'pk': t.pk}
            )
        )

        form = response.form

        self.assertEqual(
            form.method,
            'post'
        )

        self.assertEqual(
            form.action,
            '/teams/' + str(t.pk) + '/leave'
        )

        response = form.submit().follow()

        # Make sure the user is no longer in the team
        response = self.app.get(
            reverse(
                'user-detail',
                kwargs={'slug': u.slug}
            )
        )
        self.assertFalse(
            response.html.find(
                'a',
                attrs={
                    'class': 'main-list-item',
                    'href': '/teams/' + str(t.pk)
                }
            )
        )
示例#39
0
    def test_all_views(self):
        self.client.login(**self.auth)

        team = Team(
           slug="new-team",
            membership_policy=4,
            video_policy =1,
           name="New-name")
        team.save()
        tm = TeamMember.objects.create_first_member(team, self.user)
        #------- create ----------

        data = {
            "description": u"",
            "video_url": u"",
            "membership_policy": u"4",
            "video_policy": u"1",
            "logo": u"",
            "slug": u"new-team",
            "name": u"New team"
        }

        #---------- index -------------
        response = self.client.get(reverse("teams:index"))
        self.failUnlessEqual(response.status_code, 200)

        response = self.client.get(reverse("teams:index"), {'q': 'vol'})
        self.failUnlessEqual(response.status_code, 200)

        data = {
            "q": u"vol",
            "o": u"date"
        }
        response = self.client.get(reverse("teams:index"), data)
        self.failUnlessEqual(response.status_code, 200)

        response = self.client.get(reverse("teams:index"), {'o': 'my'})
        self.failUnlessEqual(response.status_code, 200)

        #-------------- applications ----------------
        url = reverse("teams:applications", kwargs={"slug": team.slug})
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)

        #------------ detail ---------------------
        url = reverse("teams:detail", kwargs={"slug": team.slug})
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)

        url = reverse("teams:detail", kwargs={"slug": team.pk})
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)

        url = reverse("teams:detail", kwargs={"slug": team.slug})
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)

        url = reverse("teams:detail", kwargs={"slug": team.slug})
        response = self.client.get(url, {'q': 'Lions'})
        self.failUnlessEqual(response.status_code, 200)

        url = reverse("teams:detail", kwargs={"slug": team.slug})
        response = self.client.get(url, {'q': 'empty result'})
        self.failUnlessEqual(response.status_code, 200)

        #------------ detail members -------------

        url = reverse("teams:detail_members", kwargs={"slug": team.slug})
        response = self.client.get(url)
        self.failUnlessEqual(response.status_code, 200)

        url = reverse("teams:detail_members", kwargs={"slug": team.slug})
        response = self.client.get(url, {'q': 'test'})
        self.failUnlessEqual(response.status_code, 200)

        #-------------members activity ---------------
        #Deprecated
        #url = reverse("teams:members_actions", kwargs={"slug": team.slug})
        #response = self.client.get(url)
        #self.failUnlessEqual(response.status_code, 200)

        #------------- add video ----------------------
        self.client.login(**self.auth)

        data = {
            "languages-MAX_NUM_FORMS": u"",
            "description": u"",
            "language": u"en",
            "title": u"",
            "languages-0-language": u"be",
            "languages-0-id": u"",
            "languages-TOTAL_FORMS": u"1",
            "video_url": u"http://www.youtube.com/watch?v=Hhgfz0zPmH4&feature=grec_index",
            "thumbnail": u"",
            "languages-INITIAL_FORMS": u"0",
            "project":team.default_project.pk,
        }
        tv_len = team.teamvideo_set.count()
        url = reverse("teams:add_video", kwargs={"slug": team.slug})
        response = self.client.post(url, data)
        self.assertEqual(tv_len+1, team.teamvideo_set.count())
        self.assertRedirects(response, reverse("teams:detail", kwargs={"slug": team.slug}))

        #-------edit team video -----------------
        team = Team.objects.get(pk=1)
        tv = team.teamvideo_set.get(pk=1)
        tv.title = ''
        tv.description = ''
        tv.save()
        data = {
            "languages-MAX_NUM_FORMS": u"",
            "languages-INITIAL_FORMS": u"0",
            "title": u"change title",
            "languages-0-language": u"el",
            "languages-0-id": u"",
            "languages-TOTAL_FORMS": u"1",
            "languages-0-completed": u"on",
            "thumbnail": u"",
            "description": u"and description",
            "author": u"Test Author",
            "creation_date": u"2011-01-01",
            "project": team.default_project.pk
        }
        url = reverse("teams:team_video", kwargs={"team_video_pk": tv.pk})
        response = self.client.post(url, data)
        self.assertRedirects(response, reverse("teams:team_video", kwargs={"team_video_pk": tv.pk}))
        tv = team.teamvideo_set.get(pk=1)
        self.assertEqual(tv.title, u"change title")
        self.assertEqual(tv.description, u"and description")
        meta = tv.video.metadata()
        self.assertEqual(meta.get('author'), 'Test Author')
        self.assertEqual(meta.get('creation_date'), date(2011, 1, 1))

        #-----------delete video -------------
        url = reverse("teams:remove_video", kwargs={"team_video_pk": tv.pk})
        response = self.client.post(url)
        self.failUnlessEqual(response.status_code, 302)
        try:
            team.teamvideo_set.get(pk=1)
            self.fail()
        except ObjectDoesNotExist:
            pass

        #----------inviting to team-----------
        user2 = User.objects.get(username="******")
        TeamMember.objects.filter(user=user2, team=team).delete()

        member = TeamMember.objects.get(user=self.user, team=team)
        member.role = TeamMember.ROLE_OWNER
        member.save()

        data = {
            "user_id": user2.id,
            "message": u"test message",
            "role": TeamMember.ROLE_CONTRIBUTOR,
        }
        user_mail_box_count = Message.objects.unread().filter(user=user2).count()
        invite_url = reverse("teams:invite_members", args=(), kwargs={'slug': team.slug})
        response = self.client.post(invite_url, data, follow=True)
        self.failUnlessEqual(response.status_code, 200)

        self.assertEqual(user_mail_box_count + 1,
                         Message.objects.unread().filter(user=user2).count())


        invite = Invite.objects.get(user__username=user2.username, team=team)
        self.assertEqual(invite.role, TeamMember.ROLE_CONTRIBUTOR)
        self.assertEqual(invite.note, u'test message')

        ct = ContentType.objects.get_for_model(Invite)
        Message.objects.filter(object_pk=invite.pk, content_type=ct, user=user2)

        members_count = team.members.count()

        self.client.login(username = user2.username, password ='******')
        url = reverse("teams:accept_invite", kwargs={"invite_pk": invite.pk})
        response = self.client.get(url)

        self.assertEqual(members_count+1, team.members.count())

        self.client.login(**self.auth)

        tm,c = TeamMember.objects.get_or_create(user=self.user, team=team)
        tm.role = TeamMember.ROLE_ADMIN
        tm.save()
        url = reverse("teams:remove_member", kwargs={"user_pk": user2.pk, "slug": team.slug})
        response = self.client.post(url)
        self.failUnlessEqual(response.status_code, 302)

        self.assertFalse(team.is_member(user2))

        url = reverse("teams:activity", kwargs={"slug": team.slug})
        response = self.client.post(url)
        self.failUnlessEqual(response.status_code, 200)

        self.client.login()
        TeamMember.objects.filter(user=self.user, team=team).delete()
        self.assertFalse(team.is_member(self.user))
        url = reverse("teams:join_team", kwargs={"slug": team.slug})
        response = self.client.post(url)
        self.failUnlessEqual(response.status_code, 302)
        self.assertTrue(team.is_member(self.user))
示例#40
0
class TestNotification(TestCase):

    fixtures = ["test.json"]

    def setUp(self):
        fix_teams_roles()
        self.team = Team(name='test', slug='test')
        self.team.save()

        self.user = User.objects.all()[:1].get()
        self.user.is_active = True
        self.user.notify_by_email = True
        self.user.email = '*****@*****.**'
        self.user.save()

        self.tm = TeamMember(team=self.team, user=self.user)
        self.tm.save()

        v1 = Video.objects.all()[:1].get()
        self.tv1 = TeamVideo(team=self.team, video=v1, added_by=self.user)
        self.tv1.save()

        v2 = Video.objects.exclude(pk=v1.pk)[:1].get()
        self.tv2 = TeamVideo(team=self.team, video=v2, added_by=self.user)
        self.tv2.save()

    def test_new_team_video_notification(self):
        #check initial data
        self.assertEqual(self.team.teamvideo_set.count(), 2)
        self.assertEqual(self.team.users.count(), 1)


        #mockup for send_templated_email to test context of email
        import utils

        send_templated_email = utils.send_templated_email

        def send_templated_email_mockup(to, subject, body_template, body_dict, *args, **kwargs):
            send_templated_email_mockup.context = body_dict
            send_templated_email(to, subject, body_template, body_dict, *args, **kwargs)

        utils.send_templated_email = send_templated_email_mockup
        reload(tasks)

        #test notification about two new videos
        TeamVideo.objects.filter(pk__in=[self.tv1.pk, self.tv2.pk]).update(created=datetime.today())
        self.assertEqual(TeamVideo.objects.filter(created__gt=self.team.last_notification_time).count(), 2)
        mail.outbox = []
        self.user.notify_by_email = True
        self.user.save()
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 1)
        
        self.assertIn(self.user.email, mail.outbox[0].to[0] )
        self.assertEqual(len(send_templated_email_mockup.context['team_videos']), 2)

        self.user.notify_by_email = False
        self.user.save()
        #test if user turn off notification
        self.user.is_active = False
        self.user.save()
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 0)

        self.user.is_active = True
        self.user.notify_by_email = False
        self.user.save()
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 0)


        self.tm.save()

        self.user.notify_by_email = True
        self.user.save()
        #test notification if one video is new
        created_date = self.team.last_notification_time + timedelta(seconds=10)
        TeamVideo.objects.filter(pk=self.tv1.pk).update(created=created_date)

        self.assertEqual(TeamVideo.objects.filter(created__gt=self.team.last_notification_time).count(), 1)
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(len(send_templated_email_mockup.context['team_videos']), 1)
        self.assertEqual(send_templated_email_mockup.context['team_videos'][0], self.tv1)

        #test notification if all videos are already old
        created_date = self.team.last_notification_time - timedelta(seconds=10)
        TeamVideo.objects.filter(team=self.team).update(created=created_date)
        self.assertEqual(TeamVideo.objects.filter(created__gt=self.team.last_notification_time).count(), 0)
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 0)
示例#41
0
    def form_valid(self, form):
        userDetails = form.save(commit=False)

        #   Don't do any of this is the user isn't currently logged in
        #   or different to the currently logged in user
        if (self.request.user.is_authenticated() is False or
                userDetails.id != self.request.user.id):
            return HttpResponseRedirect(self.get_success_url())

        #   If we have been passed a name then we have come from the
        #   user details form, if we don't have a name, then we are dealing
        #   with teams.
        if form.data.get('name') is not None:
            userDetails.save()
        else:
            user = User.objects.get(pk=userDetails.pk)
            #   Now we need to dump all the current links to teams and
            #   then add them all back in.
            user.teams.clear()
            for team in form.data.getlist('team'):
                user.teams.add(int(team))

            #   We need to see if we have been passed over a new team name
            #   if so then we have a bunch of work to do around adding that
            #   team
            team_name = form.data.get('teamname')
            if (team_name is not None and team_name is not ''):
                new_organisation_name = form.data.get('new_organisation')
                organisation_id = form.data.get('organisation')

                #   Now check to see if this team is using an existing
                #   organisation or a new_organisation.
                #   If it a new organisation then we need to create it.
                if (new_organisation_name is not None and
                        new_organisation_name is not ''):
                    check_org = Organisation.objects.filter(
                        name=new_organisation_name
                    ).exists()
                    if check_org is True:
                        new_organisation = Organisation.objects.get(
                            name=new_organisation_name
                        )
                    else:
                        new_organisation = Organisation()
                        new_organisation.name = new_organisation_name
                        new_organisation.save()
                else:
                    #   Otherwise we are going to use the organisation we
                    #   have been passed over.
                    check_org = Organisation.objects.filter(
                        pk=organisation_id).exists()
                    if check_org is True:
                        new_organisation = Organisation.objects.get(
                            pk=organisation_id
                        )
                    else:
                        # TODO: Raise an error here to display on the form
                        return self.render_to_response(self.get_context_data())

                #   Either way we now have a new_organisation object that we
                #   can use to create the team.
                check_team = Team.objects.filter(name=team_name).exists()

                if check_team is True:
                    new_team = Team.objects.filter(name=team_name)
                else:
                    new_team = Team(
                        name=team_name,
                        organisation=new_organisation
                    )
                    new_team.save()

                #   Now add the new team to the teams join on the user
                user.teams.add(new_team.pk)
                user.save()

        #   If the user wants to add another team, do that here
        #   TODO: add a #team thingy to the URL so we can jump down to the
        #   teams section
        submit_action = form.data.get('submit_action')
        if (submit_action is not None and submit_action is not ''):
            if submit_action in ['Save and add a new team',
                                 'Save and manage team membership']:
                return HttpResponseRedirect(
                    reverse(
                        'user-update-teams',
                        kwargs={
                            'slug': self.request.user.slug
                        }
                    )
                )

        #   Normally we'd just go back to their profile page. So we'll do
        #   that here.
        return HttpResponseRedirect(self.get_success_url())
示例#42
0
 def test_cannot_add_team_without_organisation(self):
     t = Team(name='New Team')
     self.assertIsNone(t.pk)
示例#43
0
 def setUp(self):
     o = Organisation(name="Existing Org")
     o.save()
     t = Team(name="Existing Team", organisation=o)
     t.save()
示例#44
0
class TestNotification(TestCase):
    
    fixtures = ["test.json"]
    
    def setUp(self):
        self.team = Team(name='test', slug='test')
        self.team.save()
        
        self.user = User.objects.all()[:1].get()
        self.user.is_active = True
        self.user.changes_notification = True
        self.user.email = '*****@*****.**'
        self.user.save()
        
        self.tm = TeamMember(team=self.team, user=self.user)
        self.tm.save()

        v1 = Video.objects.all()[:1].get()
        self.tv1 = TeamVideo(team=self.team, video=v1, added_by=self.user)
        self.tv1.save()
        
        v2 = Video.objects.exclude(pk=v1.pk)[:1].get()
        self.tv2 = TeamVideo(team=self.team, video=v2, added_by=self.user)
        self.tv2.save()
        
    def test_new_team_video_notification(self):
        #check initial data
        self.assertEqual(self.team.teamvideo_set.count(), 2)
        self.assertEqual(self.team.users.count(), 1)

        
        #mockup for send_templated_email to test context of email
        import utils
        
        send_templated_email = utils.send_templated_email
        
        def send_templated_email_mockup(to, subject, body_template, body_dict, *args, **kwargs):
            send_templated_email_mockup.context = body_dict
            send_templated_email(to, subject, body_template, body_dict, *args, **kwargs)
        
        utils.send_templated_email = send_templated_email_mockup        
        reload(tasks)
        
        #test notification about two new videos
        TeamVideo.objects.filter(pk__in=[self.tv1.pk, self.tv2.pk]).update(created=datetime.today())
        self.assertEqual(TeamVideo.objects.filter(created__gt=self.team.last_notification_time).count(), 2)
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].to, [self.user.email])
        self.assertEqual(len(send_templated_email_mockup.context['team_videos']), 2)
        
        #test if user turn off notification
        self.user.is_active = False
        self.user.save()
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 0)
        
        self.user.is_active = True
        self.user.changes_notification = False
        self.user.save()
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 0)        

        self.user.changes_notification = True
        self.user.save()
        self.tm.changes_notification = False
        self.tm.save()
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 0)    

        self.tm.changes_notification = True
        self.tm.save()
        
        #test notification if one video is new
        created_date = self.team.last_notification_time + timedelta(seconds=10)
        TeamVideo.objects.filter(pk=self.tv1.pk).update(created=created_date)
        
        self.assertEqual(TeamVideo.objects.filter(created__gt=self.team.last_notification_time).count(), 1)
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(len(send_templated_email_mockup.context['team_videos']), 1)
        self.assertEqual(send_templated_email_mockup.context['team_videos'][0], self.tv1)

        #test notification if all videos are already old
        created_date = self.team.last_notification_time - timedelta(seconds=10)
        TeamVideo.objects.filter(team=self.team).update(created=created_date)        
        self.assertEqual(TeamVideo.objects.filter(created__gt=self.team.last_notification_time).count(), 0)
        mail.outbox = []
        tasks.add_videos_notification.delay()
        self.team = Team.objects.get(pk=self.team.pk)
        self.assertEqual(len(mail.outbox), 0)
    def test_top_teams_and_orgs(self):
        #   Create three orgs
        o1 = Organisation(name='org0001')
        o1.save()
        o2 = Organisation(name='org0002')
        o2.save()
        o3 = Organisation(name='org0003')
        o3.save()

        #   Create SEVEN teams!!! Grouped into organistions
        t1 = Team(name='team0001', organisation=o1)
        t1.save()
        t2 = Team(name='team0002', organisation=o1)
        t2.save()
        t3 = Team(name='team0003', organisation=o1)
        t3.save()
        t4 = Team(name='team0004', organisation=o2)
        t4.save()
        t5 = Team(name='team0005', organisation=o2)
        t5.save()
        t6 = Team(name='team0006', organisation=o3)
        t6.save()
        t7 = Team(name='team0007', organisation=o3)
        t7.save()

        #   Now we need three users, and throw them into teams
        u1 = get_user_model().objects.create_user(userid='user0001')
        u1.save()
        u1.teams.add(t2, t3, t4)
        u1.save()

        u2 = get_user_model().objects.create_user(userid='user0002')
        u2.save()
        u2.teams.add(t5, t6)
        u2.save()

        u3 = get_user_model().objects.create_user(userid='user0003')
        u3.save()
        u3.teams.add(t3, t5, t6, t7)
        u3.save()

        #   Last and not least we need a tool for everyone to use
        l1 = Link(
            name='link0001',
            is_external=True,
            owner=u1,
            destination='http://google.com'
        )
        l1.save()

        #   Now we need to log the activity of each user.
        #
        #   User 1, is going to use the tool 4 times.
        for i in range(0, 4):
            l1.register_usage(user=u1, force_new=True)

        #   User 2, is going to use the tool 2 times.
        for i in range(0, 2):
            l1.register_usage(user=u2, force_new=True)

        #   User 3, is going to use the tool 5 times.
        for i in range(0, 5):
            l1.register_usage(user=u3, force_new=True)

        #   Login as the first user
        form = self.app.get(reverse('login')).form
        form['userid'] = 'user0001'
        form.submit()

        #   Now lets go an have a look at the details page, and check
        #   out the teams and organisations usage count.
        details_page = self.app.get(
            reverse('link-detail', kwargs={'pk': l1.pk}))

        #   Due to the counting above, we know the teams have used the tool
        #   the following amount, so lets check for that...
        #   t1:0, t2:4, t3:9, t4:4, t5:7, t6:7, t7:5
        #   i.e. there are no members is team 1.
        #   only user 1 is in team 2.
        #   users 1 & 3 are in team 3.
        usage_by_teams = details_page.html.find(
            'ul',
            id='usage-by-teams'
        ).findAll('li')
        self.assertEquals(usage_by_teams[0].text,
                          'team0003 have collectively used the tool 9 times')
        self.assertEquals(usage_by_teams[1].text,
                          'team0005 have collectively used the tool 7 times')
        self.assertEquals(usage_by_teams[2].text,
                          'team0006 have collectively used the tool 7 times')
        self.assertEquals(usage_by_teams[3].text,
                          'team0007 have collectively used the tool 5 times')
        self.assertEquals(usage_by_teams[4].text,
                          'team0002 have collectively used the tool 4 times')

        #   We do a similar thing with organisations, which are tricky
        #   because user 1 is in team 2 & 3, so both those teams get the
        #   4 times user 1 used the tool. But teams 2 & 3 are both in org 1,
        #   and the code has made sure to only count the useage once, rather
        #   than 4 times from team 2 and 4 again from team 3. This checks
        #   that based on the numbers above the results are as follows.
        #   o1:9, o2:11, o3:7. Ordered that's o2,o1,o3.
        used_by_organisations = details_page.html.find(
            'ul',
            id='usage-by-organisations'
        ).findAll('li')
        self.assertEquals(used_by_organisations[0].text,
                          'org0002 have collectively used the tool 11 times')
        self.assertEquals(used_by_organisations[1].text,
                          'org0001 have collectively used the tool 9 times')
        self.assertEquals(used_by_organisations[2].text,
                          'org0003 have collectively used the tool 7 times')