Beispiel #1
0
    def testOverallPoints(self):
        """Check that retrieving the points for the floor is correct."""
        # Create a test user.
        user = User(username="******", password="******")
        user.save()
        user_points = 10
        user.get_profile().floor = self.test_floor

        self.assertEqual(self.test_floor.points(), 0,
                         "Check that the floor does not have any points yet.")

        user.get_profile().add_points(user_points, datetime.datetime.today(),
                                      "test")
        user.get_profile().save()

        self.assertEqual(
            self.test_floor.points(), user_points,
            "Check that the number of points are equal for one user.")

        # Create another test user and check again.
        user = User(username="******", password="******")
        user.save()
        user.get_profile().floor = self.test_floor
        user.get_profile().add_points(user_points, datetime.datetime.today(),
                                      "test")
        user.get_profile().save()

        self.assertEqual(
            self.test_floor.points(), 2 * user_points,
            "Check that the number of points are equal for two users.")
Beispiel #2
0
    def testOverallRankWithSubmissionDate(self):
        """Check that rank calculation is correct in the case of ties."""
        # Create a test user.
        user = User(username="******", password="******")
        user.save()
        user_points = 10
        user.get_profile().team = self.test_team
        user.get_profile().add_points(user_points,
                                      datetime.datetime.today(),
                                      "test")
        user.get_profile().save()

        # Create a test user on a different team.
        test_team2 = Team(name="B", group=self.group)
        test_team2.save()

        user = User(username="******", password="******")
        user.save()
        user.get_profile().team = test_team2
        user.get_profile().add_points(user_points,
                                      datetime.datetime.today() + datetime.timedelta(days=1),
                                      "test")
        user.get_profile().save()

        self.assertEqual(self.test_team.rank(),
                         2,
                         "Check that the team is ranked second.")
Beispiel #3
0
    def testTeamRankForCurrentRound(self):
        """Test that we can retrieve the rank for the user in the current
        round."""
        test_utils.set_competition_round()

        group = Group(name="Test group")
        group.save()
        team = Team(name="A", group=group)
        team.save()

        user = User(username="******", password="******")
        user.save()

        profile = user.get_profile()
        top_user = Profile.objects.all()[0]
        profile.add_points(top_user.points() + 1, datetime.datetime.today(),
                           "Test")
        profile.team = team
        profile.save()

        self.assertEqual(profile.current_round_team_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points() + 1, datetime.datetime.today(),
                            "Test")
        profile2.team = team
        profile2.save()

        self.assertEqual(profile.current_round_team_rank(), 2,
                         "Check that the user is now number 2.")
Beispiel #4
0
    def testOverallRankWithSubmissionDate(self):
        """Check that rank calculation is correct in the case of ties."""
        # Create a test user.
        user = User(username="******", password="******")
        user.save()
        user_points = 10
        user.get_profile().floor = self.test_floor
        user.get_profile().add_points(
            user_points,
            datetime.datetime.today() - datetime.timedelta(days=3), "test")
        user.get_profile().save()

        # Create a test user on a different floor.
        test_floor2 = Floor(number="B", dorm=self.dorm)
        test_floor2.save()

        user = User(username="******", password="******")
        user.save()
        user.get_profile().floor = test_floor2
        user.get_profile().add_points(user_points, datetime.datetime.today(),
                                      "test")
        user.get_profile().save()

        self.assertEqual(self.test_floor.rank(), 2,
                         "Check that the floor is ranked second.")
Beispiel #5
0
    def testOverallRankWithSubmissionDate(self):
        """Check that rank calculation is correct in the case of ties."""
        # Create a test user.
        user = User(username="******", password="******")
        user.save()
        user_points = 10
        user.get_profile().team = self.test_team
        user.get_profile().add_points(user_points, datetime.datetime.today(),
                                      "test")
        user.get_profile().save()

        # Create a test user on a different team.
        test_team2 = Team(name="B", group=self.group)
        test_team2.save()

        user = User(username="******", password="******")
        user.save()
        user.get_profile().team = test_team2
        user.get_profile().add_points(
            user_points,
            datetime.datetime.today() + datetime.timedelta(days=1), "test")
        user.get_profile().save()

        self.assertEqual(self.test_team.rank(), 2,
                         "Check that the team is ranked second.")
Beispiel #6
0
    def testOverallRankWithPoints(self):
        """Check that calculating the rank is correct based on point value."""
        # Create a test user.
        user = User(username="******", password="******")
        user.save()
        user_points = 10
        user.get_profile().team = self.test_team

        # Test the team is ranked last if they haven't done anything yet.
        team_rank = 1
        self.assertEqual(self.test_team.rank(), team_rank,
                         "Check the team is ranked last.")

        user.get_profile().add_points(user_points, datetime.datetime.today(),
                                      "test")
        user.get_profile().save()

        self.assertEqual(self.test_team.rank(), 1,
                         "Check the team is now ranked number 1.")

        # Create a test user on a different team.
        test_team2 = Team(name="B", group=self.group)
        test_team2.save()

        user2 = User(username="******", password="******")
        user2.save()
        user2.get_profile().team = test_team2
        user2.get_profile().add_points(user_points + 1,
                                       datetime.datetime.today(), "test")
        user2.get_profile().save()

        self.assertEqual(self.test_team.rank(), 2,
                         "Check that the team is now ranked number 2.")
Beispiel #7
0
    def testOverallRankForCurrentRound(self):
        """Test that we can retrieve the rank for the user in the current
        round."""
        test_utils.set_competition_round()

        user = User(username="******", password="******")
        user.save()

        profile = user.get_profile()
        top_user = player_mgr.points_leader()
        profile.add_points(top_user.points() + 1, datetime.datetime.today(),
            "Test")
        profile.save()

        self.assertEqual(profile.current_round_overall_rank(), 1,
            "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points() + 1, datetime.datetime.today(),
            "Test")
        profile2.save()

        self.assertEqual(profile.current_round_overall_rank(), 2,
            "Check that the user is now number 2.")
Beispiel #8
0
    def testOverallRankWithSubmissionDate(self):
        """Tests that the overall_rank method accurately computes the rank
        when two users have the same number of points."""
        user = User(username="******", password="******")
        user.save()

        profile = user.get_profile()
        top_user = Profile.objects.all()[0]
        profile.add_points(
            top_user.points() + 1,
            datetime.datetime.today() - datetime.timedelta(days=1), "Test")
        profile.save()

        self.assertEqual(profile.overall_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points(), datetime.datetime.today(),
                            "Test")
        profile2.save()

        self.assertEqual(profile.overall_rank(), 2,
                         "Check that the user is now rank 2.")
Beispiel #9
0
    def testOverallRankForCurrentRound(self):
        """Test that we can retrieve the rank for the user in the current
        round."""
        test_utils.set_competition_round()

        user = User(username="******", password="******")
        user.save()

        profile = user.get_profile()
        top_user = player_mgr.points_leader()
        profile.add_points(top_user.points() + 1, datetime.datetime.today(),
                           "Test")
        profile.save()

        self.assertEqual(profile.current_round_overall_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points() + 1, datetime.datetime.today(),
                            "Test")
        profile2.save()

        self.assertEqual(profile.current_round_overall_rank(), 2,
                         "Check that the user is now number 2.")
Beispiel #10
0
    def testFloorRankWithSubmissionDate(self):
        """Tests that the floor_rank method accurately computes the rank when users have the same number of points."""
        user = User(username="******", password="******")
        user.save()
        dorm = Dorm(name="Test dorm")
        dorm.save()
        floor = Floor(number="A", dorm=dorm)
        floor.save()

        profile = user.get_profile()
        profile.floor = floor
        top_user = Profile.objects.all().order_by("-points")[0]
        profile.add_points(
            top_user.points + 1,
            datetime.datetime.today() - datetime.timedelta(minutes=1), "Test")
        profile.save()

        self.assertEqual(profile.floor_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points, datetime.datetime.today(), "Test")
        profile2.save()

        profile2.floor = floor
        profile2.save()
        print profile.points
        print profile2.points
        self.assertEqual(profile.floor_rank(), 2,
                         "Check that the user is now rank 2.")
Beispiel #11
0
    def testTeamRankForCurrentRound(self):
        """Test that we can retrieve the rank for the user in the current
        round."""
        test_utils.set_competition_round()

        group = Group(name="Test group")
        group.save()
        team = Team(name="A", group=group)
        team.save()

        user = User(username="******", password="******")
        user.save()

        profile = user.get_profile()
        top_user = Profile.objects.all()[0]
        profile.add_points(top_user.points() + 1, datetime.datetime.today(), "Test")
        profile.team = team
        profile.save()

        self.assertEqual(profile.current_round_team_rank(), 1, "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points() + 1, datetime.datetime.today(), "Test")
        profile2.team = team
        profile2.save()

        self.assertEqual(profile.current_round_team_rank(), 2, "Check that the user is now number 2.")
Beispiel #12
0
    def testTeamRankWithSubmissionDate(self):
        """Tests that the team_rank method accurately computes the rank when
        users have the same number of points,"""
        user = User(username="******", password="******")
        user.save()
        group = Group(name="Test group")
        group.save()
        team = Team(name="A", group=group)
        team.save()

        profile = user.get_profile()
        profile.team = team
        top_user = player_mgr.points_leader()
        profile.add_points(top_user.points() + 1, datetime.datetime.today() - datetime.timedelta(minutes=1), "Test")
        profile.save()

        self.assertEqual(profile.team_rank(), 1, "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points(), datetime.datetime.today(), "Test")
        profile2.save()

        profile2.team = team
        profile2.save()

        self.assertEqual(profile.team_rank(), 2, "Check that the user is now rank 2.")
Beispiel #13
0
 def testFloorRankWithSubmissionDate(self):
   """Tests that the floor_rank method accurately computes the rank when users have the same number of points."""
   user = User(username="******", password="******")
   user.save()
   dorm = Dorm(name="Test dorm")
   dorm.save()
   floor = Floor(number="A", dorm=dorm)
   floor.save()
   
   profile = user.get_profile()
   profile.floor = floor
   top_user  = Profile.objects.all().order_by("-points")[0]
   profile.add_points(top_user.points + 1, datetime.datetime.today() - datetime.timedelta(minutes=1), "Test")
   profile.save()
   
   self.assertEqual(profile.floor_rank(), 1, "Check that the user is number 1.")
   
   user2 = User(username="******", password="******")
   user2.save()
   
   profile2 = user2.get_profile()
   profile2.add_points(profile.points, datetime.datetime.today(), "Test")
   profile2.save()
                 
   profile2.floor = floor
   profile2.save()
   print profile.points
   print profile2.points
   self.assertEqual(profile.floor_rank(), 2, "Check that the user is now rank 2.")
Beispiel #14
0
class UserBuilder(ReloadableDbBuilderInterface):
    def __init__(self, username, full_name=None, email=None, is_superuser=False, is_staff=False):
        email = email or u"{}@example.com".format(username)
        self.user = User(username=username, email=email, is_superuser=is_superuser, is_staff=is_staff)
        self.user.set_password("test")
        self.user.full_clean()
        self.user.save()
        profile = self.user.get_profile()
        if full_name:
            profile.full_name = full_name
        profile.save()

    def update(self, **attributes):
        for attrname, value in attributes.iteritems():
            setattr(self.user, attrname, value)
        self.user.save()
        self.reload_from_db()

    def update_profile(self, **attributes):
        profile = self.user.get_profile()
        for attrname, value in attributes.iteritems():
            setattr(profile, attrname, value)
        profile.save()
        self.reload_from_db()

    def reload_from_db(self):
        self.user = User.objects.get(id=self.user.id)
Beispiel #15
0
 def testOverallRankWithPoints(self):
   """Tests that the rank method accurately computes the rank with points."""
   user = User(username="******", password="******")
   user.save()
   profile = user.get_profile()
   
   # Check if the rank works if the user has done nothing.
   rank = Profile.objects.filter(points__gt=profile.points).count() + 1
   self.assertEqual(profile.overall_rank(), rank, "Check that the user is at least tied for last.")
   
   # Make the user ranked 1st.
   top_user  = Profile.objects.all().order_by("-points")[0]
   profile.add_points(top_user.points + 1, datetime.datetime.today(), "Test")
   profile.save()
   
   self.assertEqual(profile.overall_rank(), 1, "Check that the user is number 1.")
   
   user2 = User(username="******", password="******")
   user2.save()
   
   profile2 = user2.get_profile()
   profile2.add_points(profile.points + 1, datetime.datetime.today(), "Test")
   profile2.save()
   
   self.assertEqual(profile.overall_rank(), 2, "Check that the user is now rank 2.")
Beispiel #16
0
 def testOverallRankForCurrentRound(self):
   """Test that we can retrieve the rank for the user in the current round."""
   saved_rounds = settings.COMPETITION_ROUNDS
   current_round = "Round 1"
   start = datetime.date.today()
   end = start + datetime.timedelta(days=7)
   
   settings.COMPETITION_ROUNDS = {
     "Round 1" : {
       "start": start.strftime("%Y-%m-%d"),
       "end": end.strftime("%Y-%m-%d"),
     },
   }
   
   user = User(username="******", password="******")
   user.save()
   
   profile = user.get_profile()
   top_user  = Profile.objects.all().order_by("-points")[0]
   profile.add_points(top_user.points + 1, datetime.datetime.today(), "Test")
   profile.save()
   
   self.assertEqual(profile.current_round_overall_rank(), 1, "Check that the user is number 1.")
   
   user2 = User(username="******", password="******")
   user2.save()
   
   profile2 = user2.get_profile()
   profile2.add_points(profile.points + 1, datetime.datetime.today(), "Test")
   profile2.save()
   
   self.assertEqual(profile.current_round_overall_rank(), 2, "Check that the user is now number 2.")
   
   # Restore saved rounds.
   settings.COMPETITION_ROUNDS = saved_rounds
Beispiel #17
0
    def test_get_quota(self):
        """
        Tests cluster.get_quota() method

        Verifies:
            * if no user is passed, return default quota values
            * if user has quota, return values from Quota
            * if user doesn't have quota, return default cluster values
        """
        default_quota = {'default': 1, 'ram': 1,
                         'virtual_cpus': None, 'disk': 3}
        user_quota = {'default': 0, 'ram': 4, 'virtual_cpus': 5, 'disk': None}

        cluster = Cluster(hostname='foo.fake.hostname')
        cluster.__dict__.update(default_quota)
        cluster.save()
        user = User(username='******')
        user.save()

        # default quota
        self.assertEqual(default_quota, cluster.get_quota())

        # user without quota, defaults to default
        self.assertEqual(default_quota, cluster.get_quota(user.get_profile()))

        # user with custom quota
        quota = Quota(cluster=cluster, user=user.get_profile())
        quota.__dict__.update(user_quota)
        quota.save()
        self.assertEqual(user_quota, cluster.get_quota(user.get_profile()))

        quota.delete()
        cluster.delete()
        user.delete()
Beispiel #18
0
    def testOverallPoints(self):
        """Check that retrieving the points for the floor is correct."""
        # Create a test user.
        user = User(username="******", password="******")
        user.save()
        user_points = 10
        user.get_profile().floor = self.test_floor

        self.assertEqual(self.test_floor.points(), 0, "Check that the floor does not have any points yet.")

        user.get_profile().add_points(user_points, datetime.datetime.today())
        user.get_profile().save()

        self.assertEqual(
            self.test_floor.points(), user_points, "Check that the number of points are equal for one user."
        )

        # Create another test user and check again.
        user = User(username="******", password="******")
        user.save()
        user.get_profile().floor = self.test_floor
        user.get_profile().add_points(user_points, datetime.datetime.today())
        user.get_profile().save()

        self.assertEqual(
            self.test_floor.points(), 2 * user_points, "Check that the number of points are equal for two users."
        )
Beispiel #19
0
    def testOverallRankWithPoints(self):
        """Tests that the rank method accurately computes the rank with
        points."""
        user = User(username="******", password="******")
        user.save()
        profile = user.get_profile()

        # Check if the rank works if the user has done nothing.
        rank = 1
        self.assertEqual(profile.overall_rank(), rank,
                         "Check that the user is at least tied for last.")

        # Make the user ranked 1st.
        top_user = Profile.objects.all()[0]
        profile.add_points(top_user.points() + 1, datetime.datetime.today(),
                           "Test")
        profile.save()

        self.assertEqual(profile.overall_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points() + 1, datetime.datetime.today(),
                            "Test")
        profile2.save()

        self.assertEqual(profile.overall_rank(), 2,
                         "Check that the user is now rank 2.")
Beispiel #20
0
    def testOverallRankWithPoints(self):
        """Check that calculating the rank is correct based on point value."""
        # Create a test user.
        user = User(username="******", password="******")
        user.save()
        user_points = 10
        user.get_profile().floor = self.test_floor

        # Test the floor is ranked last if they haven't done anything yet.
        floor_rank = (
            Floor.objects.annotate(
                floor_points=Sum("profile__points"), last_awarded_submission=Max("profile__last_awarded_submission")
            )
            .filter(floor_points__gt=self.test_floor.points)
            .count()
            + 1
        )
        self.assertEqual(self.test_floor.rank(), floor_rank, "Check the floor is ranked last.")

        user.get_profile().add_points(user_points, datetime.datetime.today())
        user.get_profile().save()

        self.assertEqual(self.test_floor.rank(), 1, "Check the floor is now ranked number 1.")

        # Create a test user on a different floor.
        test_floor2 = Floor(number="B", dorm=self.dorm)
        test_floor2.save()

        user2 = User(username="******", password="******")
        user2.save()
        user2.get_profile().floor = test_floor2
        user2.get_profile().add_points(user_points + 1, datetime.datetime.today())
        user2.get_profile().save()

        self.assertEqual(self.test_floor.rank(), 2, "Check that the floor is now ranked number 2.")
Beispiel #21
0
    def testTeamRankWithSubmissionDate(self):
        """Tests that the team_rank method accurately computes the rank when
        users have the same number of points,"""
        user = User(username="******", password="******")
        user.save()
        group = Group(name="Test group")
        group.save()
        team = Team(name="A", group=group)
        team.save()

        profile = user.get_profile()
        profile.team = team
        top_user = player_mgr.points_leader()
        profile.add_points(
            top_user.points() + 1,
            datetime.datetime.today() - datetime.timedelta(minutes=1), "Test")
        profile.save()

        self.assertEqual(profile.team_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points(), datetime.datetime.today(),
                            "Test")
        profile2.save()

        profile2.team = team
        profile2.save()

        self.assertEqual(profile.team_rank(), 2,
                         "Check that the user is now rank 2.")
Beispiel #22
0
 def test_set_owner(self):
     controller = self.create("Part1")
     user = User(username="******")
     user.save()
     user.get_profile().is_contributor = True
     user.get_profile().save()
     controller.set_owner(user)
     self.assertEqual(controller.owner, user)
Beispiel #23
0
def report(request):
    stats = {}
    stats['individual'] = getIndividualStats(User.get_profile(request.user))
    stats['group'] = getGroupStats(User.get_profile(request.user))
    
    if not request.mobile:
        return render_to_response('report.html', {'stats': stats, 'user': request.user, 'base': BASE_TEMPLATE, 'mobileDevice': request.mobile}, context_instance=RequestContext(request))
    else:
        return render_to_response('report.html', {'stats': stats, 'user': request.user, 'base': MOBILE_BASE_TEMPLATE, 'mobileDevice': request.mobile}, context_instance=RequestContext(request)) 
Beispiel #24
0
 def test_set_sign_error1(self):
     """Test sign error : bad level"""
     controller = self.create("Part1")
     user = User(username="******")
     user.save()
     user.get_profile().is_contributor = True
     user.get_profile().save()
     self.assertRaises(exc.PermissionError, controller.set_role, user,
                       level_to_sign_str(1664))
Beispiel #25
0
 def test_set_sign1(self):
     controller = self.create("Part1")
     user = User(username="******")
     user.save()
     user.get_profile().is_contributor = True
     user.get_profile().save()
     controller.set_signer(user, level_to_sign_str(0))
     link = models.PLMObjectUserLink.objects.get(role=level_to_sign_str(0),
                                          plmobject=controller.object)
     self.assertEqual(user, link.user)
Beispiel #26
0
    def test_creation(self):
        from django.contrib.auth.models import User
        from lck.dummy.defaults.models import Profile

        u = User(username='******', email='*****@*****.**',
                 first_name='Pinky', last_name='Mouse')
        with self.assertRaises(Profile.DoesNotExist):
            u.get_profile()
        u.save()
        self.assertEqual(u.username, u.get_profile().nick)
Beispiel #27
0
 def testAwardRollback(self):
   """Tests that the last_awarded_submission field rolls back to a previous task."""
   user = User(username="******", password="******")
   user.save()
   
   activity1 = Activity(
               title="Test activity",
               slug="test-activity",
               description="Testing!",
               duration=10,
               point_value=10,
               pub_date=datetime.datetime.today(),
               expire_date=datetime.datetime.today() + datetime.timedelta(days=7),
               confirm_type="text",
               type="activity",
   )
   activity1.save()
   
   activity2 = Activity(
               title="Test activity 2",
               slug="test-activity-2",
               description="Testing!",
               duration=10,
               point_value=15,
               pub_date=datetime.datetime.today(),
               expire_date=datetime.datetime.today() + datetime.timedelta(days=7),
               confirm_type="text",
               type="activity",
   )
   activity2.save()
   activities = [activity1, activity2]
   
   # Submit the first activity.  This is what we're going to rollback to.
   activity_member = ActivityMember(user=user, activity=activities[0], submission_date=datetime.datetime.today())
   activity_member.approval_status = "approved"
   activity_member.submission_date = datetime.datetime.today() - datetime.timedelta(days=1)
   activity_member.save()
   
   points = user.get_profile().points
   submit_date = user.get_profile().last_awarded_submission
   
   # Submit second activity.
   activity_member = ActivityMember(user=user, activity=activities[1], submission_date=datetime.datetime.today())
   activity_member.approval_status = "approved"
   activity_member.submission_date = datetime.datetime.today()
   activity_member.save()
   logs = user.pointstransaction_set.count()
   
   activity_member.approval_status = "rejected"
   activity_member.submission_date = datetime.datetime.today()
   activity_member.save()
   
   # Verify that we rolled back to the previous activity.
   self.assertEqual(points, user.get_profile().points)
Beispiel #28
0
    def test_creation(self):
        from django.contrib.auth.models import User
        from lck.dummy.defaults.models import Profile

        u = User(username='******',
                 email='*****@*****.**',
                 first_name='Pinky',
                 last_name='Mouse')
        with self.assertRaises(Profile.DoesNotExist):
            u.get_profile()
        u.save()
        self.assertEqual(u.username, u.get_profile().nick)
Beispiel #29
0
def test_updateranking():
    from pesranking.pes.models import Team, Match, UserProfile
    from django.contrib.auth.models import User
    #
    pippo = User(username='******')
    pippo.save()
    pluto = User(username='******')
    pluto.save()
    assert pippo.get_profile().ranking == 1600
    #
    topolinia = Team(name='topolinia',
                att=10, dif=10, fis=10, vel=10, tat=10, tec=10)
    assert topolinia.ranking() == 10
    topolinia.save()
    #
    match1 = Match(userA=pippo, userB=pluto,
                   teamA=topolinia, teamB=topolinia,
                   goalA=3, goalB=0)
    match2 = Match(userA=pippo, userB=pluto,
                   teamA=topolinia, teamB=topolinia,
                   goalA=3, goalB=0)
    #
    match1.save()
    match2.save()
    Match.updateranking()
    # refresh the data
    match1 = Match.objects.get(pk=match1.id)
    match2 = Match.objects.get(pk=match2.id)
    # check the deltas for the first match
    delta = match1.deltaA
    assert delta > 0
    assert match1.deltaB == -delta
    #
    # the delta for the second match are the same
    assert match2.deltaA == delta
    assert match2.deltaB == -delta
    #
    # check that we updated the users
    for obj in (pippo, pluto):
        try:
            del obj._profile_cache
        except AttributeError:
            pass
    assert pippo.get_profile().ranking == 1600 + delta*2
    assert pluto.get_profile().ranking == 1600 - delta*2
    #
    # play another match
    match3 = Match(userA=pippo, userB=pluto,
                   teamA=topolinia, teamB=topolinia,
                   goalA=0, goalB=0)
    delta3 = match3.deltaA
    assert delta3 < 0 # because we expected pippo to beat pluto
Beispiel #30
0
    def testDisplayNameUnique(self):
        user1 = User(username="******", password="******")
        user1.save()
        user2 = User(username="******", password="******")
        user2.save()

        profile1 = user1.get_profile()
        profile1.name = "Test User"
        profile1.save()

        profile2 = user2.get_profile()
        profile2.name = "Test User"
        self.assertRaises(IntegrityError, profile2.save)
Beispiel #31
0
def create_anonymous_user(anonymous_token):
    try:
        user = User.objects.get(username=anonymous_token)
    except User.DoesNotExist:
        #Create User
        user = User(username=anonymous_token, first_name='Anonymous', last_name='Bixly')
        #Set Anonymous Token as password
        user.set_password(anonymous_token)
        user.save()
        #Update UserProfile
        user.get_profile().is_anonymous = True                     
        user.get_profile().save()
    return user
Beispiel #32
0
 def testDisplayNameUnique(self):
   user1 = User(username="******", password="******")
   user1.save()
   user2 = User(username="******", password="******")
   user2.save()
   
   profile1 = user1.get_profile()
   profile1.name = "Test User"
   profile1.save()
   
   profile2 = user2.get_profile()
   profile2.name = "Test User"
   self.assertRaises(IntegrityError, profile2.save)
Beispiel #33
0
    def authenticate(self, **credentials):
        access_token = credentials.get('token')
        request = credentials.get('request')
        if access_token is None:
            return None

        auth = tweepy.OAuthHandler(
            settings.TWITTER_CONSUMER_KEY,
            settings.TWITTER_CONSUMER_SECRET
        )
        auth.access_token = access_token
        api = tweepy.API(auth)
        if not api.verify_credentials():
            return None
        else:
            credentials = api.me()

        username = '******' % (str(credentials.id))
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # Check to see if there is already a UserProfile with a matching
            # screen_name. This is so that we can allow users to change their
            # default Django auth usernames.
            try:
                profile = UserProfile.objects.get(twitter_id=credentials.screen_name)
            except UserProfile.DoesNotExist:
                user = User(username=username)
                user.save()
                user.set_password(utils.get_random_password())
                profile = user.get_profile()
                profile.twitter_id = credentials.screen_name
                profile.twitter_access_token = unicode(auth.access_token)
                profile.save()
                request.session['is_new_user_account'] = True
            else:
                user = profile.user
                if profile.twitter_access_token != auth.access_token:
                    profile.twitter_access_token = unicode(auth.access_token)
                    profile.save()
        else:
            profile = user.get_profile()
            if profile.twitter_access_token != auth.access_token:
                # We have a new access token. Update the one we have
                # stored for this user.
                profile.twitter_access_token = unicode(auth.access_token)
                profile.save()

        return user
Beispiel #34
0
 def test_toggle(self):
     ii = User()
     
     ii.provider = 'Facebook'
     ii.uid = '001'
     
     ii.save()
     
     print(ii.provider)
     
     ii.get_profile().is_upfo = False
     
     toggle_upfo(ii)
     
     self.assertEquals(ii.get_profile().is_upfo, True)
Beispiel #35
0
def create_anonymous_user(anonymous_token):
    try:
        user = User.objects.get(username=anonymous_token)
    except User.DoesNotExist:
        #Create User
        user = User(username=anonymous_token,
                    first_name='Anonymous',
                    last_name='Bixly')
        #Set Anonymous Token as password
        user.set_password(anonymous_token)
        user.save()
        #Update UserProfile
        user.get_profile().is_anonymous = True
        user.get_profile().save()
    return user
Beispiel #36
0
 def norun_test_add_challenge(self):
     # get reference to a school and a class
     school = add_school(school_name="Rock School")
     school_class = add_class(school_id=school.id, _class_name="Geology 101")
     
     # get or create a user, let's assume this user is an admin
     # TODO: Do we need a flag for that?
     user1 = User(username="******")
     user2 = User(username="******")
     
     user1.save()
     user2.save()
     
     # Now that we have profile objects, associate a khan user with each
     # user id. We haven't set these yet, so we'll see warnings and no
     # proficiency will exist.
     user1.get_profile().access_token = self.gmail_token
     user2.get_profile().access_token = self.facebook_token
     
     # Save the updated stuff
     user1.save()
     user2.save()
     
     # Add the users to the groups they should belong to.
     # (technically we could skip to the teams, but let's be accurate here.
     add_user_to_school(user1, school)
     add_user_to_school(user2, school)
     
     add_user_to_class(user1, school_class)
     add_user_to_class(user2, school_class)
     
     #
     #
     # Let's group the class into Teams. Create two teams, put some users in each.
     team1 = add_team_to_class(school_class.id, "The Rockettes")
     team2 = add_team_to_class(school_class.id, "The Slugs")
     
     add_user_to_team(user1, team1)
     add_user_to_team(user2, team2)
     
     # Create a challenge, name it Challenge Set One or something
     challenge_of_decimals = create_challenge_for_class(school_class, "Understanding Decimal Stuff")
     
     add_team_to_challenge(team1, challenge_of_decimals);
     add_team_to_challenge(team2, challenge_of_decimals);
     
     print "Challenge groups: %s" % challenge_of_decimals.challenge_groups.all().count()
     pass
Beispiel #37
0
    def handle(self, *args, **options):
        self.stdout.write('Creating user\n')
        user = User()
        username = raw_input("Username (default: %s): " % getuser()) if options["username"] is None else options["username"]
        if not username:
            username = getuser()
        user.username = username
        password = getpass("Password (default: 'test'): ") if options["password"] is None else options["password"]
        if not password:
            password = '******'
        first_name = raw_input("Firstname (default: John): ") if options["first_name"] is None else options["first_name"]
        if not first_name:
            first_name = "John"
        last_name = raw_input("Lastname (default: Smith): ") if options["last_name"] is None else options["last_name"]
        if not last_name:
            last_name = "Smith"
        user.first_name = first_name
        user.last_name = last_name
        user.set_password(password)
        user.save()
        profile = user.get_profile()
        profile.name = first_name + " " + last_name
        profile.email = '*****@*****.**'
        profile.photo = '/static/images/gaston.gif'
        profile.save()
        
        #Second user for tests
        user2 = User()
        user2.username="******"
        user2.first_name="Bertrand"
        user2.last_name="Labévue"
        user2.set_password(password)
        user2.save()
        profile2 = user2.get_profile()
        profile2.name = user2.first_name + " " + user2.last_name
        profile2.email = '*****@*****.**'
        profile2.photo = '/static/images/labevue.gif'
        profile2.save()
        self.stdout.write("Second user {} with password {} created\n".format(
            user2.username, password
        ))

        tree = json.load(open('parsing/tree.json'))
        self.courseList = json.load(open('parsing/cours.json'))
        self.USER = profile
        Root = Category.objects.create(name='P402', description='Bring back real student cooperation !')
        self.walk(tree, Root)
        self.stdout.write("\n")
Beispiel #38
0
def generate_names():
    from django.contrib.auth.models import User
    from components.floors.models import Floor

    names = [
        "alana", "maile", "makani", "kalena", "ikaika", "pono", "kanani",
        "kanoe", "kahea", "kawika", "makena", "keoni", "keoki", "anuhea",
        "kealii"
    ]
    initials = "abcdefghijklmnopqrstuvwxyz"
    floors = Floor.objects.all()

    for i in range(0, 600):
        user = None
        while not user:
            try:
                username = string.join(
                    random.sample(names, 1) + random.sample(initials, 1), "")
                user = User(username=username)
                user.save()
            except IntegrityError:
                user = None

        profile = user.get_profile()
        profile.name = user.username[0:len(user.username) - 1].capitalize()
        profile.floor = random.sample(floors, 1)[0]

        profile.save()
Beispiel #39
0
def run():
    from django.contrib.sites.models import Site

    django_site_1 = Site.objects.all()[0]
    django_site_1.domain = u'localhost:8000'
    django_site_1.name = u'localhost:8000'
    django_site_1.save()

    from corehq.apps.domain.models import Domain

    domain_domain_1 = Domain()
    domain_domain_1.name = u'test'
    domain_domain_1.is_active = True
    domain_domain_1.save()

    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u'*****@*****.**'
    auth_user_1.first_name = u''
    auth_user_1.last_name = u''
    auth_user_1.email = u'*****@*****.**'
    auth_user_1.password = u'sha1$f8d4b$b6d2f6431c423687c227ad261caa46faaf16917d'
    auth_user_1.is_staff = True
    auth_user_1.is_active = True
    auth_user_1.is_superuser = True
    auth_user_1.last_login = datetime.datetime(2010, 9, 10, 14, 40, 30, 501416)
    auth_user_1.date_joined = datetime.datetime(2010, 9, 10, 14, 37, 22, 677987)
    auth_user_1.save()

    auth_user_2 = User()
    auth_user_2.username = u'*****@*****.**'
    auth_user_2.first_name = u'test'
    auth_user_2.last_name = u'test'
    auth_user_2.email = u'*****@*****.**'
    auth_user_2.password = u'sha1$f09cf$551ac80804020ad3e1d9943a583ee1ea52284797'
    auth_user_2.is_staff = False
    auth_user_2.is_active = True
    auth_user_2.is_superuser = False
    auth_user_2.last_login = datetime.datetime(2010, 9, 10, 14, 40, 53, 818764)
    auth_user_2.date_joined = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    auth_user_2.save()

    couch_user = auth_user_2.get_profile().get_couch_user()
    couch_user.add_domain_membership(domain_domain_1.name)
    couch_user.save()

    from corehq.apps.domain.models import RegistrationRequest

    domain_registration_request_1 = RegistrationRequest()
    domain_registration_request_1.tos_confirmed = True
    domain_registration_request_1.request_time = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442)
    domain_registration_request_1.request_ip = '127.0.0.1'
    domain_registration_request_1.activation_guid = u'368ce6b8bd1311df932c5cff350164a3'
    domain_registration_request_1.confirm_time = datetime.datetime(2010, 9, 10, 14, 40, 25, 219783)
    domain_registration_request_1.confirm_ip = '127.0.0.1'
    domain_registration_request_1.domain = domain_domain_1
    domain_registration_request_1.new_user = auth_user_2
    domain_registration_request_1.requesting_user = None
    domain_registration_request_1.save()
Beispiel #40
0
  def testCurrentRoundPoints(self):
    """Tests that we can retrieve the points for the user in the current round."""
    # Save the round information and set up a test round.
    saved_rounds = settings.COMPETITION_ROUNDS
    current_round = "Round 1"
    start = datetime.date.today()
    end = start + datetime.timedelta(days=7)

    settings.COMPETITION_ROUNDS = {
      "Round 1" : {
        "start": start.strftime("%Y-%m-%d"),
        "end": end.strftime("%Y-%m-%d"),
      },
    }

    user = User(username="******", password="******")
    user.save()

    profile = user.get_profile()
    points = profile.points
    profile.add_points(10, datetime.datetime.today(), "Test")
    profile.save()

    self.assertEqual(profile.current_round_points(), points + 10, "Check that the user has 10 more points in the current round.")

    profile.add_points(10, datetime.datetime.today() - datetime.timedelta(days=1), "Test")

    self.assertEqual(profile.current_round_points(), points + 10, 
        "Check that the number of points did not change when points are awarded outside of a round.")

    # Restore saved rounds.
    settings.COMPETITION_ROUNDS = saved_rounds
Beispiel #41
0
  def testRoundRankWithoutEntry(self):
    """Tests that the overall rank calculation is correct even if a user has not done anything yet."""
    dorm = Dorm(name="Test dorm")
    dorm.save()
    floor = Floor(number="A", dorm=dorm)
    floor.save()
    
    profile = self.user.get_profile()
    # Rank will be the number of users who have points plus one.
    overall_rank = Profile.objects.filter(points__gt=0).count() + 1
    floor_rank = Profile.objects.filter(points__gt=0, floor=floor).count() + 1

    self.assertEqual(ScoreboardEntry.user_round_overall_rank(self.user, self.current_round), overall_rank, 
                    "Check user is last overallfor the current round.")
    self.assertEqual(ScoreboardEntry.user_round_floor_rank(self.user, self.current_round), floor_rank, 
                    "Check user is last in their floor for the current round.")
                    
    user2 = User(username="******", password="******")
    user2.save()

    profile2 = user2.get_profile()
    entry2, created = ScoreboardEntry.objects.get_or_create(
                        profile=profile2, 
                        round_name=self.current_round,
                      )
    entry2.points = 10
    entry2.last_awarded_submission = datetime.datetime.today()
    entry2.floor = floor
    entry2.save()

    self.assertEqual(ScoreboardEntry.user_round_overall_rank(self.user, self.current_round), overall_rank + 1, 
                    "Check that the user's overall rank has moved down.")
    self.assertEqual(ScoreboardEntry.user_round_floor_rank(self.user, self.current_round), floor_rank + 1, 
                    "Check that the user's floor rank has moved down.")
Beispiel #42
0
def user(**kwargs):
    """Return a user with all necessary defaults filled in.

    Default password is 'testpass' unless you say otherwise in a
    kwarg.

    """
    save = kwargs.pop('save', True)
    is_vouched = kwargs.pop('is_vouched', None)
    vouched_by = kwargs.pop('vouched_by', None)
    defaults = {}
    defaults['username'] = kwargs.get('username',
                                      ''.join(random.choice(letters)
                                              for x in xrange(15)))
    defaults['email'] = kwargs.get(
        'email', ''.join(
            random.choice(letters) for x in xrange(10)) + '@example.com')
    u = User(**defaults)
    u.set_password(kwargs.get('password', 'testpass'))
    if save:
        u.save()
        profile = u.get_profile()
        if is_vouched is not None:
            profile.is_vouched = is_vouched
        if vouched_by is not None:
            profile.vouched_by = vouched_by
        profile.full_name = kwargs.get('full_name', '')
        profile.save()
    return u
Beispiel #43
0
 def authenticate(self, identifier, user_info):
     user = None
     
     if isinstance(identifier, str) and isinstance(user_info, dict):
         try:
             user = User.objects.get(profile__openid=identifier)
         except User.DoesNotExist:
             # creating a new user with the user info
             if user_info.has_key("nickname") and user_info.has_key("email"):
                 username = user_info["nickname"]
                 email = user_info["email"]
                 user = User(username=username, email=email)
                 if user_info.has_key("fullname"):
                     user.first_name, user.last_name = self._parse_fullname(user_info["fullname"])
                 # if there's already a user with that username, simply
                 # redirect to the login page informing the user
                 try:
                     user.save()
                     # creating user profile.. in order to create a profile
                     # the user must be already created..
                     user.profile.create()
                     # associating openid identifier with the user
                     profile = user.get_profile()
                     profile.openid = identifier
                     profile.save()
                 except IntegrityError:
                     raise OpenIDUsernameExistsError
     return user
Beispiel #44
0
  def create_user(self, request=None, random_password=False):
    """
    Given a validated form, return a new User.
    Takes care of referrals too (if an HttpRequest object is passed).
    """
    cd = self.cleaned_data

    # Create user
    user = User()
    user.username = cd['username']
    user.first_name = cd['first_name']
    user.last_name = cd['last_name']
    user.email = cd['email']
    user.save()

    if random_password:
      user.random_password = "".join(random.sample(string.lowercase, 8))
      user.set_password(user.random_password)
    else:
      user.set_password(cd['password'])
    user.save()

    if request is not None:
      # If we have a referral code, set the profile's 'referral' field to it.
      # Note: there *should* be a profile here, as a signal will have created it automatically.
      name = request.session.get('referral', '').strip()
      if name:
        referral, _ = enginemodels.Referral.objects.get_or_create(name__iexact=name)
        profile = user.get_profile()
        profile.referral = referral
        profile.save()

    return user
Beispiel #45
0
def signup(request):
    """Регистрация"""
    user = User()
    user_profile = UserProfile()
    if request.method == "POST":
        user_form = UserForm(request.POST, instance=user)
        user_profile_form = UserProfileForm(request.POST,
                                            instance=user_profile)
        if user_form.is_valid() and user_profile_form.is_valid():
            user_data = user_form.cleaned_data
            user.username = user_data['email']
            user.first_name = user_data['firstname']
            user.last_name = user_data['lastname']
            user.email = user_data['email']
            user.set_password(user_data['pass1'])
            user.save()

            user_profile = user.get_profile()
            user_profile_data = user_profile_form.cleaned_data
            user_profile.weight = user_profile_data['weight']
            user_profile.save()
            user = authenticate(username=user_data['username'],
                                password=user_data['pass1'])
            login(request, user)
            return redirect("/accounts/profile/")
    else:
        user_form = UserForm(instance=user)
        user_profile_form = UserProfileForm(instance=user_profile)
    return render(
        request, "accounts/signup.html", {
            "user_": user,
            "user_profile": user_profile,
            "user_form": user_form,
            "user_profile_form": user_profile_form
        })
Beispiel #46
0
  def testUserOverallRoundRankWithPoints(self):
    """Tests that the overall rank calculation for a user in a round is correct based on points."""
    profile = self.user.get_profile()
    top_entry  = ScoreboardEntry.objects.filter(round_name=self.current_round).order_by("-points")[0]
    entry, created = ScoreboardEntry.objects.get_or_create(
                        profile=self.user.get_profile(), 
                        round_name=self.current_round,
                      )
    entry.points = top_entry.points + 1
    entry.last_awarded_submission = datetime.datetime.today()
    entry.save()
    
    self.assertEqual(ScoreboardEntry.user_round_overall_rank(self.user, self.current_round), 1, 
                    "Check user is ranked #1 for the current round.")
    
    user2 = User(username="******", password="******")
    user2.save()

    profile2 = user2.get_profile()
    entry2, created = ScoreboardEntry.objects.get_or_create(
                        profile=profile2, 
                        round_name=self.current_round,
                      )
    entry2.points = entry.points + 1
    entry2.last_awarded_submission = entry.last_awarded_submission
    entry2.save()
    
    self.assertEqual(ScoreboardEntry.user_round_overall_rank(self.user, self.current_round), 2, 
                    "Check user is now second.")
Beispiel #47
0
    def create_user(self, request=None, random_password=False):
        """
    Given a validated form, return a new User.
    Takes care of referrals too (if an HttpRequest object is passed).
    """
        cd = self.cleaned_data

        # Create user
        user = User()
        user.username = cd['username']
        user.first_name = cd['first_name']
        user.last_name = cd['last_name']
        user.email = cd['email']
        user.save()

        if random_password:
            user.random_password = "".join(random.sample(string.lowercase, 8))
            user.set_password(user.random_password)
        else:
            user.set_password(cd['password'])
        user.save()

        if request is not None:
            # If we have a referral code, set the profile's 'referral' field to it.
            # Note: there *should* be a profile here, as a signal will have created it automatically.
            name = request.session.get('referral', '').strip()
            if name:
                referral, _ = enginemodels.Referral.objects.get_or_create(
                    name__iexact=name)
                profile = user.get_profile()
                profile.referral = referral
                profile.save()

        return user
Beispiel #48
0
def user(**kwargs):
    """Return a user with all necessary defaults filled in.

    Default password is 'testpass' unless you say otherwise in a
    kwarg.

    """
    save = kwargs.pop('save', True)
    is_vouched = kwargs.pop('is_vouched', None)
    vouched_by = kwargs.pop('vouched_by', None)
    defaults = {}
    defaults['username'] = kwargs.get(
        'username', ''.join(random.choice(letters) for x in xrange(15)))
    defaults['email'] = kwargs.get(
        'email',
        ''.join(random.choice(letters) for x in xrange(10)) + '@example.com')
    u = User(**defaults)
    u.set_password(kwargs.get('password', 'testpass'))
    if save:
        u.save()
        profile = u.get_profile()
        if is_vouched is not None:
            profile.is_vouched = is_vouched
        if vouched_by is not None:
            profile.vouched_by = vouched_by
        profile.full_name = kwargs.get('full_name', '')
        profile.save()
    return u
Beispiel #49
0
    def save(self):
        "Creates the User and Member records with the field data and returns the user"
        if not self.is_valid():
            raise Exception('The form must be valid in order to save')

        first = self.cleaned_data['first_name'].strip().title()
        if len(first) == 0: raise forms.ValidationError("First Name Required.")
        last = self.cleaned_data['last_name'].strip().title()
        if len(last) == 0: raise forms.ValidationError("Last Name Required.")
        username = "******" % (first.lower(), last.lower())
        if User.objects.filter(username=username).count() > 0:
            raise forms.ValidationError("That username is already in use.")
        email = self.cleaned_data['email'].strip().lower()
        if len(email) == 0: raise forms.ValidationError("Email Required.")
        if User.objects.filter(email=email).count() > 0:
            raise forms.ValidationError(
                "That email address is already in use.")

        user = User(username=username,
                    first_name=first,
                    last_name=last,
                    email=email)
        user.save()
        member = user.get_profile()
        member.phone = self.cleaned_data['phone'].strip()
        member.save()

        return user
Beispiel #50
0
 def save(self):
     "Creates the User and Member records with the field data and returns the user"
     if not self.is_valid():
         raise Exception('The form must be valid in order to save')
     user = User(username=self.cleaned_data['username'],
                 first_name=self.cleaned_data['first_name'],
                 last_name=self.cleaned_data['last_name'],
                 email=self.cleaned_data['email'])
     user.save()
     member = user.get_profile()
     member.email2 = self.cleaned_data['email2']
     member.phone = self.cleaned_data['phone']
     member.phone = self.cleaned_data['phone2']
     member.address1 = self.cleaned_data['address1']
     member.address2 = self.cleaned_data['address2']
     member.city = self.cleaned_data['city']
     member.state = self.cleaned_data['state']
     member.zipcode = self.cleaned_data['zipcode']
     member.url_personal = self.cleaned_data['url_personal']
     member.url_professional = self.cleaned_data['url_professional']
     member.url_facebook = self.cleaned_data['url_facebook']
     member.url_twitter = self.cleaned_data['url_twitter']
     member.url_linkedin = self.cleaned_data['url_linkedin']
     member.url_github = self.cleaned_data['url_github']
     member.url_aboutme = self.cleaned_data['url_aboutme']
     member.gender = self.cleaned_data['gender']
     member.howHeard = self.cleaned_data['howHeard']
     member.industry = self.cleaned_data['industry']
     member.neighborhood = self.cleaned_data['neighborhood']
     member.has_kids = self.cleaned_data['has_kids']
     member.self_emplyed = self.cleaned_data['self_employed']
     member.company_name = self.cleaned_data['company_name']
     member.photo = self.cleaned_data['photo']
     member.save()
     return user
Beispiel #51
0
    def create_dummy(first_name="", email=None, **kwargs):

        # Generate a random string to use as a username. Keep it short
        # so that it doesn't overflow the username field!
        username = uuid.uuid4().hex[:16]

        if email is None:
            email = "*****@*****.**" % username
        user = User(username=username, first_name=first_name, email=email)
        data = {'user': user}

        # If the caller of create_dummy passes in a user, then we won't use the
        # user defined above
        data.update(kwargs)

        # Save the user after the update, so we don't save a new user if one
        # was never needed
        user = data['user']
        user.save()
        person = user.get_profile()

        for key, value in data.items():
            setattr(person, key, value)
        person.save()

        return person
Beispiel #52
0
    def create_dummy(first_name="", email=None, **kwargs):

        # Generate a random string to use as a username. Keep it short
        # so that it doesn't overflow the username field!
        username = uuid.uuid4().hex[:16]

        if email is None:
            email = "*****@*****.**" % username
        user = User(username=username, first_name=first_name, email=email)
        data = {'user': user}

        # If the caller of create_dummy passes in a user, then we won't use the
        # user defined above
        data.update(kwargs)

        # Save the user after the update, so we don't save a new user if one
        # was never needed
        user = data['user']
        user.save()
        person = user.get_profile()

        for key, value in data.items():
            setattr(person, key, value)
        person.save()

        return person
Beispiel #53
0
def user_signup(request):
	if request.user.is_authenticated():
		return redirect('joust-selfserve-tournament')
	#process form
	if request.POST:
		signupform = forms.UserSignupForm(request.POST)
		if signupform.is_valid():
			if not User.objects.filter(username=signupform.cleaned_data['handle']).count():
				u = User(
						username=signupform.cleaned_data['handle'],
						email=signupform.cleaned_data['email'],
						first_name=signupform.cleaned_data['first_name'],
						last_name=signupform.cleaned_data['last_name'],
					)
				u.set_unusable_password()
				u.save()
				try:
					if settings.JOUST_SMS_NOTIFICATIONS == True:
						p = u.get_profile()
						p.phone_number = signupform.cleaned_data['phone_number']
				except:
					pass
				login(request, u)
				return redirect('joust-selfserve-tournament')
			else:
				signupform._errors['handle'] = _(u'This handle has been taken.')
				
	#generate blank form
	else:
		signupform = forms.UserSignupForm()
		
	return render_to_response('joust/self-service/signup.html', {'signupform':signupform}, 
								context_instance=RequestContext(request))
Beispiel #54
0
 def handle(self, *args, **options):
     self.stdout.write('Creating user\n')
     user = User()
     username = raw_input(
         "Username (default: %s): " %
         getuser()) if options["username"] is None else options["username"]
     if not username:
         username = getuser()
     user.username = username
     password = getpass(
         "Password (default: 'test'): "
     ) if options["password"] is None else options["password"]
     if not password:
         password = '******'
     first_name = raw_input(
         "Firstname (default: John): "
     ) if options["first_name"] is None else options["first_name"]
     if not first_name:
         first_name = "John"
     last_name = raw_input(
         "Lastname (default: Smith): "
     ) if options["last_name"] is None else options["last_name"]
     if not last_name:
         last_name = "Smith"
     user.first_name = first_name
     user.last_name = last_name
     user.set_password(password)
     user.save()
     profile = user.get_profile()
     profile.name = first_name + " " + last_name
     profile.email = '*****@*****.**'
     profile.save()
     print "User id : " + str(profile.id)
    def authenticate(self, **credentials):
        fb = credentials.get('fb')
        request = credentials.get('request')
        if fb is None:
            return None

        username = '******' % (str(fb.uid))
        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            # Check to see if we already have a UserProfile with the fb.uid in
            # store. This is so that we can allow users to change their default
            # Django auth usernames.
            try:
                profile = UserProfile.objects.get(facebook_id=fb.uid)
                user = profile.user
            except UserProfile.DoesNotExist:
                user = User(username=username)
                user.set_password(utils.get_random_password())
                user.save()
                profile = user.get_profile()
                profile.facebook_id = fb.uid
                try:
                    user_info = fb.users.getInfo(fb.uid,
                                                 fields=['first_name'])[0]
                    profile.facebook_name = user_info['first_name']
                except:
                    pass
                profile.save()
                request.session['is_new_user_account'] = True

        return user
Beispiel #56
0
	def save(self):
		"Creates the User and Member records with the field data and returns the user"
		if not self.is_valid(): raise Exception('The form must be valid in order to save')
		user = User(username=self.cleaned_data['username'], first_name=self.cleaned_data['first_name'], last_name=self.cleaned_data['last_name'], email=self.cleaned_data['email'])
		user.save()
		member = user.get_profile()
		member.email2 = self.cleaned_data['email2']
		member.phone = self.cleaned_data['phone']
		member.phone = self.cleaned_data['phone2']
		member.address1 = self.cleaned_data['address1']
		member.address2 = self.cleaned_data['address2']
		member.city = self.cleaned_data['city']
		member.state = self.cleaned_data['state']
		member.zipcode = self.cleaned_data['zipcode']
		member.url_personal = self.cleaned_data['url_personal']
		member.url_professional = self.cleaned_data['url_professional']
		member.url_facebook = self.cleaned_data['url_facebook']
		member.url_twitter = self.cleaned_data['url_twitter']
		member.url_linkedin = self.cleaned_data['url_linkedin']
		member.url_biznik = self.cleaned_data['url_biznik']
		member.url_github = self.cleaned_data['url_github']
		member.url_aboutme = self.cleaned_data['url_aboutme']
		member.gender = self.cleaned_data['gender']
		member.howHeard = self.cleaned_data['howHeard']
		member.industry = self.cleaned_data['industry']
		member.neighborhood = self.cleaned_data['neighborhood']
		member.has_kids = self.cleaned_data['has_kids']
		member.self_emplyed = self.cleaned_data['self_employed']
		member.company_name = self.cleaned_data['company_name']
		member.notes = self.cleaned_data['notes']
		member.photo = self.cleaned_data['photo']
		member.save()
		return user
Beispiel #57
0
def add_author_to_article(article, author):
    if isinstance(author, DjangoUser):
        author = DjangoUser.get_profile()
    if author not in article.authors.all():
        article.authors.add(author)
        article.save()
        return author
    logger.error('author already in article authors ...')
Beispiel #58
0
    def testFloorRankForCurrentRound(self):
        """Test that we can retrieve the rank for the user in the current round."""
        saved_rounds = settings.COMPETITION_ROUNDS
        current_round = "Round 1"
        start = datetime.date.today()
        end = start + datetime.timedelta(days=7)

        settings.COMPETITION_ROUNDS = {
            "Round 1": {
                "start": start.strftime("%Y-%m-%d"),
                "end": end.strftime("%Y-%m-%d"),
            },
        }

        dorm = Dorm(name="Test dorm")
        dorm.save()
        floor = Floor(number="A", dorm=dorm)
        floor.save()

        user = User(username="******", password="******")
        user.save()

        profile = user.get_profile()
        top_user = Profile.objects.all().order_by("-points")[0]
        profile.add_points(top_user.points + 1, datetime.datetime.today(),
                           "Test")
        profile.floor = floor
        profile.save()

        self.assertEqual(profile.current_round_floor_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points + 1, datetime.datetime.today(),
                            "Test")
        profile2.floor = floor
        profile2.save()

        self.assertEqual(profile.current_round_floor_rank(), 2,
                         "Check that the user is now number 2.")

        # Restore saved rounds.
        settings.COMPETITION_ROUNDS = saved_rounds
Beispiel #59
0
    def testTeamRankWithPoints(self):
        """Tests that the team_rank method accurately computes the rank based
         on points."""
        user = User(username="******", password="******")
        user.save()
        group = Group(name="Test group")
        group.save()
        team = Team(name="A", group=group)
        team.save()

        profile = user.get_profile()
        profile.team = team

        # Check that the user is ranked last if they haven't done anything.
        rank = 1
        self.assertEqual(profile.team_rank(), rank,
                         "Check that the user is ranked last.")

        # Make the user number 1 overall.
        top_user = Profile.objects.all()[0]
        profile.add_points(top_user.points() + 1, datetime.datetime.today(),
                           "Test")
        profile.save()

        self.assertEqual(profile.team_rank(), 1,
                         "Check that the user is number 1.")

        user2 = User(username="******", password="******")
        user2.save()

        profile2 = user2.get_profile()
        profile2.add_points(profile.points() + 1, datetime.datetime.today(),
                            "Test")
        profile2.save()

        self.assertEqual(
            profile.team_rank(), 1,
            "Check that the user is still number 1 if the new "
            "profile is not on the same team.")

        profile2.team = team
        profile2.save()

        self.assertEqual(profile.team_rank(), 2,
                         "Check that the user is now rank 2.")