Ejemplo n.º 1
0
class TestMatchSerializer(TestCase):
    def setUp(self):
        self.characters = [
            Character(name='Test1', role=Character.DAMAGE),
            Character(name='Test2', role=Character.DAMAGE)
        ]
        for c in self.characters:
            c.save()

        self.user = User.objects.create_user('testuser')

        self.match = Match(user=self.user, mmr_after=1000)
        self.match.save()
        self.match.characters.set(self.characters)
    
    def testSerializingMatch(self):
        # Test if match serialization works correctly
        expected_data = {
            'id': self.match.id,
            'characters': [c.id for c in self.match.characters.all()],
            'date': DateTimeField().to_representation(self.match.date),
            'mmr_after': self.match.mmr_after
        }
        serializer = MatchSerializer(self.match)
        self.assertEqual(
            expected_data,
            serializer.data,
            'Serializer should return data in expected format'
        )
Ejemplo n.º 2
0
    def post(self, request, pk):
        form = WagerChallengeForm(request.POST, user=request.user)
        myrequest = WagerRequest.objects.get(pk=pk)
        challenge = form.instance
        challenge.creator = self.request.user
        if form.is_valid():
            challenger = UserProfile.objects.get(
                user__username=challenge.creator)
            if challenger.credits < myrequest.credits:
                messages.error(
                    self.request,
                    "You do not have enough credits in your account to challenge this team"
                )
                return redirect('wagers:list')
            if challenge.team == myrequest.team:
                messages.error(self.request,
                               "A team cannot challenge it's own wager")
                return redirect('wagers:list')
            for y in challenge.team.players.all():
                for x in myrequest.team.players.all():
                    if x == y:
                        messages.error(
                            self.request,
                            "A player cannot be on both teams at the same time"
                        )
                        return redirect('wagers:list')
            challenge.save()
            myrequest.challenge_accepted = True
            myrequest.challenge = challenge
            myrequest.save()
            match = Match(type='w',
                          game=myrequest.game,
                          platform=myrequest.platform,
                          hometeam=myrequest.team,
                          awayteam=challenge.team,
                          bestof=myrequest.bestof,
                          teamformat=myrequest.teamformat,
                          info="Home Team: " + myrequest.info + "\n" +
                          "Away Team: " + challenge.info)
            match.save()
            wmatch = WagerMatch(match=match, credits=myrequest.credits)
            wmatch.save()
            myrequest.wmatch = wmatch
            myrequest.save()
            challenger.credits = challenger.credits - myrequest.credits
            challenge.save()
            myrequest.creator.credits = myrequest.creator.credits - myrequest.credits
            myrequest.save()
            messages.success(
                request,
                "Wager Challenge Created! You have 30 minutes to play your match and report the scores"
            )
            return redirect('wagers:match_detail', pk=wmatch.pk)

        messages.error(self.request,
                       "Something went wrong (this shouldn't be seen")
        return redirect('wagers:request_detail', pk=pk)
Ejemplo n.º 3
0
 def _create_two_person_match(self, order_num=None):
     m = Match(card=self.card)
     if order_num is not None:
         m.order = order_num
     m.save()
     m.add_competitor(self.w1)
     m.add_competitor(self.w2)
     m.save()
     return m
Ejemplo n.º 4
0
class TestIsOwnerPermission(TestCase):
    def setUp(self):
        self.character = Character(name='Test', role=Character.DAMAGE)
        self.character.save()

        self.owner = User.objects.create_user('owner')
        self.notOwner = User.objects.create_user('notowner')

        self.match = Match(user=self.owner, mmr_after=1000)
        self.match.save()
        self.match.characters.set([self.character])

        self.permission = IsMatchOwner()

    def testPermissionGrantedToOwner(self):
        """
        If user currently logged in is owner of match, permission should
        be granted, both for safe (GET) and unsafe (e. g. POST) methods
        """
        factory = APIRequestFactory()
        get_request = factory.get('/path_does_not_matter_here/')
        force_authenticate(get_request, user=self.owner)
        get_request.user = self.owner # there is no .user in request generated by APIRequestFactory
        self.assertTrue(
            self.permission.has_object_permission(get_request, None, self.match),
            'Permission should be granted for GET request with user which is match owner'
        )

        post_request = factory.post('/path_does_not_matter_here/')
        force_authenticate(post_request, user=self.owner)
        post_request.user = self.owner # there is no .user in request generated by APIRequestFactory
        self.assertTrue(
            self.permission.has_object_permission(post_request, None, self.match),
            'Permission should be granted for unsafe (e.g. POST) request with user which is match owner'
        )
    
    def testPermissionDeniedToNotOwner(self):
        """
        If user currently logged in is not owner of match, permission should
        be denied, both for safe (GET) and unsafe (e. g. POST) methods
        """
        factory = APIRequestFactory()
        get_request = factory.get('/path_does_not_matter_here/')
        force_authenticate(get_request, user=self.notOwner)
        get_request.user = self.notOwner # there is no .user in request generated by APIRequestFactory
        self.assertFalse(
            self.permission.has_object_permission(get_request, None, self.match),
            'Permission should be denied for GET request with user which is not match owner'
        )

        post_request = factory.post('/path_does_not_matter_here/')
        force_authenticate(post_request, user=self.notOwner)
        post_request.user = self.notOwner # there is no .user in request generated by APIRequestFactory
        self.assertFalse(
            self.permission.has_object_permission(post_request, None, self.match),
            'Permission should be denied for unsafe (e.g. POST) request with user which is not match owner'
        )
Ejemplo n.º 5
0
def new_matches(match, index, tournament):
    new_match = Match()
    if match:
        new_match.next_match = match
    new_match.start_position = index
    new_match.turnaj = tournament
    index -= 1
    new_match.save()
    if index > 0:
        new_matches(new_match, index, tournament)
        new_matches(new_match, index, tournament)
Ejemplo n.º 6
0
    def _generate_matches(self):
        """
        Create a match for each set of 2 players in the pool, and rounds to hold
        them
        """
        from matches.models import Match, Round

        rounds = {}
        players = [player for player in self.players.all()]

        if len(players) % 2 != 0: players.append(None)

        iterator = list(range(len(players)))
        for x in iterator:
            if x == 0: continue
            round = Round(pool=self, number=x)
            round.save()
            rounds[round] = []

        for x in iterator:
            if not players[x]: continue

            others_iterator = iterator.copy()
            others_iterator.remove(x)

            for y in others_iterator:
                if not players[y]: continue

                match_exists = Match.objects.filter(
                    player_1_init=players[x],
                    player_2_init=players[y]).exists()
                inverse_match_exists = Match.objects.filter(
                    player_1_init=players[y],
                    player_2_init=players[x]).exists()

                if match_exists or inverse_match_exists:
                    continue

                for scheduled_round, players_in_round in rounds.items():
                    if (players[x] not in players_in_round) and (
                            players[y] not in players_in_round):
                        break

                match = Match(player_1_init=players[x],
                              player_2_init=players[y],
                              round=scheduled_round,
                              round_index=0)
                match.save()
                rounds[scheduled_round] += [players[x], players[y]]
Ejemplo n.º 7
0
    def _generate_matches(self):
        """
        Create a match for each set of 2 players in the pool, and rounds to hold
        them
        """
        from matches.models import Match, Round

        rounds = {}
        players = [player for player in self.players.all()]

        if len(players) % 2 != 0: players.append(None)

        iterator = list(range(len(players)))
        for x in iterator:
            if x == 0: continue
            round = Round(pool=self, number=x)
            round.save()
            rounds[round] = []

        for x in iterator:
            if not players[x]: continue

            others_iterator = iterator.copy()
            others_iterator.remove(x)

            for y in others_iterator:
                if not players[y]: continue

                match_exists = Match.objects.filter(player_1_init=players[x], player_2_init=players[y]).exists()
                inverse_match_exists = Match.objects.filter(player_1_init=players[y], player_2_init=players[x]).exists()

                if match_exists or inverse_match_exists:
                    continue

                for scheduled_round, players_in_round in rounds.items():
                    if (players[x] not in players_in_round) and (players[y] not in players_in_round):
                        break

                match = Match(
                    player_1_init=players[x],
                    player_2_init=players[y],
                    round=scheduled_round,
                    round_index=0
                )
                match.save()
                rounds[scheduled_round] += [players[x], players[y]]
def create_match_from_json(team1, team2, match_json):
    global total_requests

    try:
        match_ext_id = match_json['id']
        print("Processing match with ID %s" % match_ext_id)
        match = Match.objects.get(external_id=match_ext_id)
    except Match.DoesNotExist:
        # Continue creating match
        print("Creating new match from json..")
        localteam_id = match_json['localteam_id']
        visitorteam_id = match_json['visitorteam_id']
        if int(team1.external_id) == localteam_id and int(
                team2.external_id) == visitorteam_id:
            local_team = team1
            visitor_team = team2
        else:
            local_team = team2
            visitor_team = team1

        match = Match()
        match.external_id = match_ext_id
        match.stage = None
        match.status = Match.FINISHED
        match.stage_detail = match_json['stage']['data']['name'].lower()
        from datetime import datetime
        datetime_str = match_json['time']['starting_at']['date_time']
        datetime_object = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        match.date = datetime_object
        match.stadium = match_json['venue']['data']['name']
        match.team1 = local_team
        match.team1_score = match_json['scores']['localteam_score']
        match.team2 = visitor_team
        match.team2_score = match_json['scores']['visitorteam_score']
        match.is_live = False
        match.is_history = True  # Historical match <<<
        match.save()
        print("Match saved: %s" % match)
    else:
        print("Match %s already exist (skiped).." % match)
    return match
Ejemplo n.º 9
0
    def testMatchLogics(self):
        team1 = Team(short_name="SP", full_name="São Paulo FC")
        team2 = Team(short_name="Palmeiras", full_name="Palmeiras FC")
        team1.save()
        team2.save()

        season = Season(start_year=2012, end_year=2012)
        season.save()

        cp = Championship(name="Brasileirao", start_date=timezone.now())
        cp.season = season
        cp.save()

        match1 = Match()

        match1.championship = cp
        match1.home_team = team1
        match1.away_team = team2
        match1.match_date = timezone.now()

        match1.save()
Ejemplo n.º 10
0
    def generate_bracket(self):
        teams = len(self.teams.all())
        myteams = self.teams.all()
        self.current_round = 1
        self.save()
        round1 = SingleTournamentRound(tournament=self, roundnum=1)
        round1.save()
        if teams % 2 == 0:
            # no byes required - get 2 teams and make a match
            while len(myteams) != 0:
                temp1 = myteams.all().order_by("?").first()
                myteams.remove(temp1)
                myteams.save()
                temp2 = myteams.all().order_by("?").first()
                tempmatch = Match(awayteam=temp1, hometeam=temp2, maps=self.map_pool, game=self.game, platform=self.platform)
                tempmatch.save()
                myteams.remove(temp2)
                myteams.save()
                round1.matches.add(tempmatch)
                round1.save()

        else:
            # take the first team and give them a bye
            # TODO: verify this randomly grabs a random team
            bteam = self.teams.all.order_by("?").first()
            bmatch = Match(hometeam=None, bye_1=True, awayteam=bteam, winner=bteam, completed=True,
                           type='singletournament', maps=self.map_pool, game=self.game, platform=self.platform)
            bmatch.save()
            round1.matches.add(bmatch)
            myteams.remove(bteam)
            if len(myteams) % 2 != 0:
                print("ITS BROKEN YOU SUCK")
                return
            while len(myteams) != 0:
                temp1 = myteams.all().order_by("?").first()
                myteams.remove(temp1)
                myteams.save()
                temp2 = myteams.all().order_by("?").first()
                tempmatch = Match(awayteam=temp1, hometeam=temp2, maps=self.map_pool, game=self.game, platform=self.platform)
                tempmatch.save()
                myteams.remove(temp2)
                myteams.save()
                round1.matches.add(tempmatch)
                round1.save()

        round1.save()
Ejemplo n.º 11
0
def create_match_from_json(match_json,
                           competition_id,
                           stage_name,
                           set_live=False):
    global total_requests
    try:  # First try to get or create teh country
        print("Looking for competition with ID %s .." % competition_id)
        competition = Competition.objects.get(external_id=competition_id)
    except Exception as e:
        print("Error Looking for competition with ID %s .." % competition_id)
        exit(1)
    try:
        match_ext_id = match_json['id']
        print("Processing match with ID %s" % match_ext_id)
        match = Match.objects.get(external_id=match_ext_id)
    except Match.DoesNotExist:
        # Get or create teams
        try:
            team1_ext_id = match_json['localteam_id']
            print("Looking for team1 ext ID %s.." % team1_ext_id)
            team1 = Team.objects.get(competition=competition,
                                     external_id=team1_ext_id)
        except Team.DoesNotExist:
            print("Team with id %s not found" % team1_ext_id)
            return None
        else:
            print("Team 1 found: %s" % team1)

        try:
            team2_ext_id = match_json['visitorteam_id']
            print("Looking for team1 ext ID %s.." % team2_ext_id)
            team2 = Team.objects.get(competition=competition,
                                     external_id=team2_ext_id)
        except Team.DoesNotExist:
            print("Team with id %s not found" % team2_ext_id)
            return None
        else:
            print("Team 2 found: %s" % team2)

        # Continue creating match
        print("Creating new match from json..")
        match = Match()
        match.external_id = match_ext_id
        match.stage = CompetitionStage.objects.get(competition=competition,
                                                   name=stage_name)
        try:
            group_name = match_json['group']['data']['name']
        except Exception:
            try:
                group_name = match_json['stage']['data']['name']
            except Exception:
                group_name = ""
        match.stage_detail = group_name
        from datetime import datetime
        datetime_str = match_json['time']['starting_at']['date_time']
        datetime_object = datetime.strptime(datetime_str, '%Y-%m-%d %H:%M:%S')
        match.date = datetime_object
        match.stadium = match_json['venue']['data']['name']
        match.team1 = team1
        match.team1_score = match_json['scores']['localteam_score']
        match.team2 = team2
        match.team2_score = match_json['scores']['visitorteam_score']
        match.is_live = set_live
        match.save()
        print("Match saved: %s" % match)
    else:
        print("Match %s already exist (skiped).." % match)
    return match
Ejemplo n.º 12
0
class TestMatchesViewset(TestCase):
    def setUp(self):
        self.character = Character(name='Test', role=Character.DAMAGE)
        self.character.save()

        self.owner = User.objects.create_user('owner')
        self.notOwner = User.objects.create_user('notowner')

        self.match = Match(user=self.owner, mmr_after=1000)
        self.match.save()
        self.match.characters.set([self.character])

        self.client = APIClient()
    
    API_MATCHES_LIST_URL = '/api/matches/'
    def testListsOnlyMatchesOfLoggedUser(self):
        """
        GET request to API_MATCHES_LIST_URL should return only matches of logged user
        """
        self.client.force_authenticate(user=self.owner)
        response = self.client.get(self.API_MATCHES_LIST_URL)
        self.assertEqual(
            status.HTTP_200_OK,
            response.status_code,
            'Request response code should be 200 (OK)'
        )
        self.assertEqual(
            1,
            len(response.data),
            'Response data should contain 1 object'
        )
        self.assertEqual(
            self.match.pk,
            response.data[0]['id'],
            'Object in response data should be match that belongs to user'
        )
        self.client.logout()

        self.client.force_authenticate(user=self.notOwner)
        response = self.client.get(self.API_MATCHES_LIST_URL)
        self.assertEqual(
            status.HTTP_200_OK,
            response.status_code,
            'Request response code should be 200 (OK)'
        )
        self.assertEqual(
            0,
            len(response.data),
            'Response data should contain 0 objects'
        )
        self.client.logout()

    API_MEW_MATCH_URL = API_MATCHES_LIST_URL
    def testCreatedMatchBelongsToCurrenltyLoggedInUser(self):
        """
        POST request to API_NEW_MATCH_URL should automatically assign User
        """
        data = {
            'characters': [self.character.pk],
            'mmr_after': 5000
        }
        self.client.force_authenticate(user=self.owner)
        response = self.client.post(self.API_MEW_MATCH_URL, data=data)
        self.assertEqual(
            status.HTTP_201_CREATED,
            response.status_code,
            'Request response code should be 201 (Created)'
        )
        new_match = Match.objects.get(id=response.data['id'])
        self.assertEqual(
            new_match.user,
            self.owner,
            'User field of recently created match should be assigned to currently logged user'
        )
        self.client.logout()
Ejemplo n.º 13
0
    def _parse_fixture(self, simulate, fixture_season, fixture_date, club_team, fields):
        """ Creates/updated a match model instance based on the relevant fields from the CSV file."""
        # Slight hack to decide whether the fixture is specified or not
        if fields[OFFSET['fixture_type']] == "":
            print "No match for {} on {}".format(club_team['name'], fixture_date)
            return

        team_name = club_team['name']
        our_team = club_team['team']
        fixture_type = fields[OFFSET['fixture_type']]
        opp_team_name = fields[OFFSET['opposition']]
        venue_name = fields[OFFSET['venue']]
        fixture_time_str = fields[OFFSET['time']]
        home_away = fields[OFFSET['home_away']]

        try:
            opp = Team.objects.get(name=opp_team_name)
        except Team.DoesNotExist:
            print "ERROR: Could not find opposition team with name '{}'".format(opp_team_name)
            return

        # Create or retrieve Match model (based on opposition team, our team and date)
        if not simulate:
            match, created = Match.objects.get_or_create(season=fixture_season, opp_team=opp, our_team=our_team, date=fixture_date)
        else:
            created = not Match.objects.filter(season=fixture_season, opp_team=opp, our_team=our_team, date=fixture_date).exists()
            match = Match(season=fixture_season, opp_team=opp, our_team=our_team, date=fixture_date)

        # Match home/away designation
        try:
            match.home_away = HOME_AWAY[home_away.lower()]
        except:
            print "ERROR: Invalid Home/Away designation '{}' for {} on {}".format(home_away, team_name, fixture_date)
            return

        # Match fixture type (League/Cup/Friendly)
        try:
            match.fixture_type = MATCH_TYPE[fixture_type.lower()]
        except:
            print "ERROR: Invalid fixture type designation '{}' for {} on {}".format(fixture_type, team_name, fixture_date)
            return

        # Match time (can be null)
        if fixture_time_str:
            try:
                match.time = datetime.strptime(fixture_time_str, "%H:%M").time()
            except:
                print "ERROR: Could not parse fixture time '{}' for {} on {}".format(fixture_time_str, team_name, fixture_date)
                return
        else:
            match.time = None


        # Match Venue (can be null)
        if venue_name.lower() == 'away' or (home_away.lower() == 'a' and venue_name.lower() == ''):
            match.venue = None
        else:
            try:
                name_q = Q(name=venue_name) | Q(short_name=venue_name)
                match.venue = Venue.objects.get(name_q)
            except Venue.DoesNotExist:
                print "ERROR: Could not find venue '{}' for {} on {}".format(venue_name, team_name, fixture_date)
                return

        if not simulate:
            match.save()

        print "{} {}".format("Created" if created else "Updated", match)