def start(self, date_time): """Summary of start. Args: date_time Returns: list: Description of return value """ rank_p = sorted(self.players, key=lambda x: x.rank) length = len(rank_p) middle_index = length//2 first_half = rank_p[:middle_index] second_half = rank_p[middle_index:] matches = [] for i in range(middle_index): matches.append(Match(first_half[i].first_name + ' ' + first_half[i].last_name, 0, second_half[i].first_name + ' ' + second_half[i].last_name, 0)) first_half_play = next((x for x in self.players if x.first_name + ' ' + x.last_name == first_half[i].first_name + ' ' + first_half[i].last_name), None) second_half_play = next((x for x in self.players if x.first_name + ' ' + x.last_name == second_half[i].first_name + ' ' + second_half[i].last_name), None) first_half_play.opponents.append(second_half_play.first_name + ' ' + second_half_play.last_name) second_half_play.opponents.append(first_half_play.first_name + ' ' + first_half_play.last_name) if length > middle_index*2: matches.append(Match("Pas d'adversaire", 0, second_half[middle_index].first_name + ' ' + second_half[middle_index].last_name, 0)) second_half_play = next((x for x in self.players if x.first_name + ' ' + x.last_name == second_half[middle_index].first_name + ' ' + second_half[middle_index].last_name), None) second_half_play.opponents.append("Pas d'adversaire") for i in range(self.round_count): if i == 0: self.rounds.append(Round("Round {}".format(i + 1), date_time, "", matches)) else: matches = [] self.rounds.append(Round("Round {}".format(i + 1), "", "", matches))
def generate_matches(self): """ sort players and creates matches depending of the number of rounds: If the game has 8 players: if it's the first round: Player 1 VS Player 5, Players 2 VS Player 6, etc if it's an other round: Player 1 VS Player 2 (except if they have already played against : Players 1 VS Player 3) Player 3 VS Player 4 etc """ matches = [] round = self.create_round() players = self.get_suisse_sorted_players() if len(self.rounds) == 1: for i in range(self.rounds_total): match = Match(players[i][0], players[i + self.rounds_total][0]) matches.append(match) else: while len(players) > 1: y = 1 while self.played_against(players[0][0], players[y][0]): y += 1 match = Match(players[0][0], players[y][0]) matches.append(match) del players[y] del players[0] round.add_matches(matches)
def test_eq(self): """ Test match equality """ a = Match(alpha_passage=u'one', alpha_indices=(3, 5), beta_passage=u'two', beta_indices=(9, 11)) b = Match(alpha_passage=u'two', alpha_indices=(9, 11), beta_passage=u'one', beta_indices=(3, 5)) c = Match(alpha_passage=u'five', alpha_indices=(44, 47), beta_passage=u'six', beta_indices=(0, 3)) self.assertTrue(a == b) self.assertFalse(a == c) self.assertFalse(b == c) # If objects are equal their hashes must also be equal hash_a = hash(a) hash_b = hash(b) hash_c = hash(c) self.assertTrue(hash_a == hash_b) self.assertFalse(hash_a == hash_c) self.assertFalse(hash_b == hash_c)
def setUp(self): self.team_1 = Team( "France", { "played": 1, "won": 0, "drawn": 1, "lost": 0, "for": 2, "against": 2, "difference": 0, "points": 1, "rank": None }) self.team_2 = Team( "Germany", { "played": 1, "won": 0, "drawn": 1, "lost": 0, "for": 2, "against": 2, "difference": 0, "points": 1, "rank": None }) self.match_1 = Match("1", datetime.datetime(2016, 6, 10, 20, 0), "Stade de France", "A", self.team_1, self.team_2) self.match_2 = Match("Round of 16", datetime.datetime(2016, 6, 25, 14, 0), "Parc des Princes", None, self.team_1, self.team_2)
def test_youtube_videos_formatted(self): # Test timestamp conversion data = { '5m6s': '306', '1m02s': '62', '10s': '10', '2m': '120', '12345': '12345', '5h': '18000', '1h2m3s': '3723', } for old_ts, seconds in data.items(): match = Match(youtube_videos=['TqY324xLU4s#t=' + old_ts]) self.assertListEqual(match.youtube_videos_formatted, ['TqY324xLU4s?start=' + seconds]) match = Match(youtube_videos=['TqY324xLU4s?t=' + old_ts]) self.assertListEqual(match.youtube_videos_formatted, ['TqY324xLU4s?start=' + seconds]) # Test that nothing is changed if there is no timestamp match = Match(youtube_videos=['TqY324xLU4s']) self.assertListEqual(match.youtube_videos_formatted, ['TqY324xLU4s'])
def test_match_videos_add(self): self.video_auth.put() match1 = Match( id="2014casj_qm1", alliances_json= """{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""", comp_level="qm", event=ndb.Key(Event, '2014casj'), year=2014, set_number=1, match_number=1, team_key_names=[ u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073' ], youtube_videos=["abcdef"]) match1.put() match2 = Match( id="2014casj_sf1m1", alliances_json= """{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""", comp_level="sf", event=ndb.Key(Event, '2014casj'), year=2014, set_number=1, match_number=1, team_key_names=[ u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073' ], ) match2.put() match_videos = {'qm1': 'aFZy8iibMD0', 'sf1m1': 'RpSgUrsghv4'} request_body = json.dumps(match_videos) request_path = '/api/trusted/v1/event/2014casj/match_videos/add' sig = md5.new('{}{}{}'.format('321tEsTsEcReT', request_path, request_body)).hexdigest() response = self.testapp.post(request_path, request_body, headers={ 'X-TBA-Auth-Id': 'tEsT_id_5', 'X-TBA-Auth-Sig': sig }, expect_errors=True) self.assertEqual(response.status_code, 200) self.assertEqual(set(Match.get_by_id('2014casj_qm1').youtube_videos), {'abcdef', 'aFZy8iibMD0'}) self.assertEqual(set(Match.get_by_id('2014casj_sf1m1').youtube_videos), {'RpSgUrsghv4'})
def post(self): self._require_admin() event_key = self.request.get('event_key') matches_csv = self.request.get('matches_csv') matches = OffseasonMatchesParser.parse(matches_csv) event = Event.get_by_id(event_key) matches = [ Match(id=Match.renderKeyName(event.key.id(), match.get("comp_level", None), match.get("set_number", 0), match.get("match_number", 0)), event=event.key, game=Match.FRC_GAMES_BY_YEAR.get(event.year, "frc_unknown"), set_number=match.get("set_number", 0), match_number=match.get("match_number", 0), comp_level=match.get("comp_level", None), team_key_names=match.get("team_key_names", None), alliances_json=match.get("alliances_json", None)) for match in matches ] try: FirebasePusher.updated_event(event.key_name) except: logging.warning("Enqueuing Firebase push failed!") self.redirect('/admin/event/{}'.format(event_key))
def post(self, match_key): self._require_admin() alliances_json = self.request.get("alliances_json") score_breakdown_json = self.request.get("score_breakdown_json") # Ignore u'None' from form POST score_breakdown_json = score_breakdown_json if score_breakdown_json != "None" else None # Fake JSON load of the score breakdown to ensure the JSON is proper before attempting to save to the DB if score_breakdown_json: json.loads(score_breakdown_json) alliances = json.loads(alliances_json) tba_videos = json.loads(self.request.get( "tba_videos")) if self.request.get("tba_videos") else [] youtube_videos = json.loads(self.request.get( "youtube_videos")) if self.request.get("youtube_videos") else [] team_key_names = list() for alliance in alliances: team_key_names.extend(alliances[alliance].get('teams', None)) match = Match( id=match_key, event=Event.get_by_id(self.request.get("event_key_name")).key, set_number=int(self.request.get("set_number")), match_number=int(self.request.get("match_number")), comp_level=self.request.get("comp_level"), team_key_names=team_key_names, alliances_json=alliances_json, score_breakdown_json=score_breakdown_json, tba_videos=tba_videos, youtube_videos=youtube_videos # no_auto_update = str(self.request.get("no_auto_update")).lower() == "true", #TODO ) MatchManipulator.createOrUpdate(match, auto_union=False) self.redirect("/admin/match/" + match.key_name)
def store_match(data): match = Match(id=data['key']) match.event = ndb.Key(Event, data['event_key']) match.year = int(data['key'][:4]) match.comp_level = data['comp_level'] match.set_number = data['set_number'] match.match_number = data['match_number'] if data.get('time'): match.time = datetime.datetime.fromtimestamp(int(data['time'])) if data.get('actual_time'): match.actual_time = datetime.datetime.fromtimestamp( int(data['actual_time'])) if data.get('predicted_time'): match.predicted_time = datetime.datetime.fromtimestamp( int(data['predicted_time'])) if data.get('post_result_time'): match.post_result_time = datetime.datetime.fromtimestamp( int(data['post_result_time'])) match.score_breakdown_json = json.dumps(data['score_breakdown']) for alliance in ['red', 'blue']: data['alliances'][alliance]['teams'] = data['alliances'][alliance].pop( 'team_keys') data['alliances'][alliance]['surrogates'] = data['alliances'][ alliance].pop('surrogate_team_keys') match.alliances_json = json.dumps(data['alliances']) return MatchManipulator.createOrUpdate(match)
def generate_next_round(self, previous_round, tournois_obj): """Create the next round. Keyword arguments: previous_round : Round -- round instance that has just ended tournois_obj : Tournament -- Instance of Tournament """ # Check tour number if len(tournois_obj.round_list) < DEFAULT_TOUR_NUMBER: match_list = Suisse().generate_next_round(previous_round, tournois_obj) self.round = Round().create_round(f'Round {len(tournois_obj.round_list)+1}') RoundView().start_new_round(self.round) for match in match_list: formated_match = Match().create_match(match[0][0], match[0][1], match[1][0], match[1][1]) self.round.add_match_to_round(formated_match) tournois_obj.add_round(self.round) self.view_controller.display_match_of_round(self.round) # end of tournament => display final score else: # récupérer la liste triée: players = Suisse().get_players_list_with_score(tournois_obj.round_list[-1]) sorted_list = Suisse().sort_list_by_score(players) self.score.display_final_score(sorted_list) tournois_obj.set_final_score(sorted_list) print("Fin du tournois")
def create_match(self, participant_1, participant_2): participant_1.old_matchs.add(participant_2.id) participant_2.old_matchs.add(participant_1.id) return Match( self.player_controller.get_by_id(participant_1.id), 0, self.player_controller.get_by_id(participant_2.id), 0 )
def post(self, match_key): self._require_admin() alliances_json = self.request.get("alliances_json") alliances = json.loads(alliances_json) youtube_videos = json.loads(self.request.get("youtube_videos")) team_key_names = list() for alliance in alliances: team_key_names.extend(alliances[alliance].get('teams', None)) match = Match( id=match_key, event=Event.get_by_id(self.request.get("event_key_name")).key, set_number=int(self.request.get("set_number")), match_number=int(self.request.get("match_number")), comp_level=self.request.get("comp_level"), team_key_names=team_key_names, alliances_json=alliances_json, # no_auto_update = str(self.request.get("no_auto_update")).lower() == "true", #TODO ) match = MatchManipulator.createOrUpdate(match) match.youtube_videos = youtube_videos match.dirty = True # hacky MatchManipulator.createOrUpdate(match) self.redirect("/admin/match/" + match.key_name)
def post(self, match_key): self._require_admin() alliances_json = self.request.get("alliances_json") score_breakdown_json = self.request.get("score_breakdown_json") alliances = json.loads(alliances_json) tba_videos = json.loads(self.request.get( "tba_videos")) if self.request.get("tba_videos") else [] youtube_videos = json.loads(self.request.get( "youtube_videos")) if self.request.get("youtube_videos") else [] team_key_names = list() for alliance in alliances: team_key_names.extend(alliances[alliance].get('teams', None)) match = Match( id=match_key, event=Event.get_by_id(self.request.get("event_key_name")).key, set_number=int(self.request.get("set_number")), match_number=int(self.request.get("match_number")), comp_level=self.request.get("comp_level"), team_key_names=team_key_names, alliances_json=alliances_json, score_breakdown_json=score_breakdown_json, tba_videos=tba_videos, youtube_videos=youtube_videos # no_auto_update = str(self.request.get("no_auto_update")).lower() == "true", #TODO ) MatchManipulator.createOrUpdate(match, auto_union=False) self.redirect("/admin/match/" + match.key_name)
def post(self): self._require_admin() event_key = self.request.get('event_key') matches_csv = self.request.get('matches_csv') matches, _ = OffseasonMatchesParser.parse(matches_csv) event = Event.get_by_id(event_key) matches = [Match( id=Match.renderKeyName( event.key.id(), match.get("comp_level", None), match.get("set_number", 0), match.get("match_number", 0)), event=event.key, year=event.year, set_number=match.get("set_number", 0), match_number=match.get("match_number", 0), comp_level=match.get("comp_level", None), team_key_names=match.get("team_key_names", None), alliances_json=match.get("alliances_json", None) ) for match in matches] MatchManipulator.createOrUpdate(matches) self.redirect('/admin/event/{}'.format(event_key))
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() ndb.get_context().clear_cache( ) # Prevent data from leaking between tests self.event = Event(id="2010sc", name="Palmetto Regional", event_type_enum=EventType.REGIONAL, short_name="Palmetto", event_short="sc", year=2010, end_date=datetime.datetime(2010, 03, 27), official=True, location='Clemson, SC', start_date=datetime.datetime(2010, 03, 24)) self.event.put() self.match = Match( id="2010sc_qm1", alliances_json= """{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""", comp_level="qm", event=self.event.key, year=2010, set_number=1, match_number=1, team_key_names=[ u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073' ]) self.match.put()
def _process_request(self, request, event_key): event = Event.get_by_id(event_key) year = int(event_key[:4]) matches = [] needs_time = [] for match in JSONMatchesParser.parse(request.body, year): match = Match( id=Match.renderKeyName(event.key.id(), match.get("comp_level", None), match.get("set_number", 0), match.get("match_number", 0)), event=event.key, year=event.year, set_number=match.get("set_number", 0), match_number=match.get("match_number", 0), comp_level=match.get("comp_level", None), team_key_names=match.get("team_key_names", None), alliances_json=match.get("alliances_json", None), score_breakdown_json=match.get("score_breakdown_json", None), time_string=match.get("time_string", None), time=match.get("time", None), ) if (not match.time or match.time == "") and match.time_string: # We can calculate the real time from the time string needs_time.append(match) matches.append(match) if needs_time: try: logging.debug("Calculating time!") MatchHelper.add_match_times(event, needs_time) except Exception, e: logging.error("Failed to calculate match times")
def create_match(self, player_1, player_2): match = Match() match.player_1.append(player_1) match.player_2.append(player_2) return match
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() ndb.get_context().clear_cache( ) # Prevent data from leaking between tests self.account = Account.get_or_insert("123", email="*****@*****.**", registered=True) self.account.put() event = Event(id="2016test", name="Test Event", event_short="Test Event", year=2016, event_type_enum=EventType.OFFSEASON) event.put() self.match = Match(id="2016test_f1m1", event=ndb.Key(Event, "2016test"), year=2016, comp_level="f", set_number=1, match_number=1, alliances_json='') self.match.put()
def get_fixture(self): r = requests.get(self.fixture_url, headers=config.HEADERS) data = r.json() match_list = [] for item in data['fixtures']: match_list.append(Match(item)) return match_list
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() ndb.get_context().clear_cache() # Prevent data from leaking between tests self.testbed.init_taskqueue_stub(root_path=".") self.event = Event( id="2012ct", event_short="ct", year=2012 ) self.old_match = Match( id="2012ct_qm1", alliances_json="""{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""", score_breakdown_json=json.dumps({ 'red': {'auto': 20, 'assist': 40, 'truss+catch': 20, 'teleop_goal+foul': 20}, 'blue': {'auto': 40, 'assist': 60, 'truss+catch': 10, 'teleop_goal+foul': 40}, }), comp_level="qm", event=self.event.key, year=2012, set_number=1, match_number=1, team_key_names=[u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073'], youtube_videos=[u'P3C2BOtL7e8', u'tst1', u'tst2', u'tst3'] ) self.new_match = Match( id="2012ct_qm1", alliances_json="""{"blue": {"score": 57, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": 74, "teams": ["frc69", "frc571", "frc176"]}}""", score_breakdown_json=json.dumps({ 'red': {'auto': 80, 'assist': 40, 'truss+catch': 20, 'teleop_goal+foul': 20}, 'blue': {'auto': 40, 'assist': 60, 'truss+catch': 10, 'teleop_goal+foul': 40}, }), comp_level="qm", event=self.event.key, year=2012, set_number=1, match_number=1, team_key_names=[u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073'], youtube_videos=[u'TqY324xLU4s', u'tst1', u'tst3', u'tst4'] )
def create_match(self, match_number, player1, player2): try: match_number = int(match_number) except: raise ValueError("match_number should be number.") match_number = int(match_number) self.matches[match_number] = Match(match_number, player1, player2) return self.matches[match_number]
def setUp(self): app = webapp2.WSGIApplication([ webapp2.Route( r'/<match_key:>', ApiMatchController, methods=['GET']) ], debug=True) self.testapp = webtest.TestApp(app) self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_urlfetch_stub() self.testbed.init_memcache_stub() ndb.get_context().clear_cache( ) # Prevent data from leaking between tests self.testbed.init_taskqueue_stub(root_path=".") self.match = Match(id="2014cc_f1m1", event=ndb.Key(Event, "2014cc"), year=2014, comp_level="f", set_number=1, match_number=1, team_key_names=[ u'frc846', u'frc2135', u'frc971', u'254', u'frc1678', u'frc973' ], time=datetime.datetime.fromtimestamp(1409527874), time_string="4:31 PM", youtube_videos=["JbwUzl3W9ug", "bHGyTjxbLz8"], tba_videos=[], alliances_json='{\ "blue": {\ "score": 270,\ "teams": [\ "frc846",\ "frc2135",\ "frc971"]},\ "red": {\ "score": 310,\ "teams": [\ "frc254",\ "frc1678",\ "frc973"]}}', score_breakdown_json='{\ "blue": {\ "auto": 70,\ "teleop_goal+foul": 40,\ "assist": 120,\ "truss+catch": 40\ },"red": {\ "auto": 70,\ "teleop_goal+foul": 50,\ "assist": 150,\ "truss+catch": 40}}') self.match.put()
def populate_matches(): with open( '/Users/stanleyhoucke/coding_projects/euros_predictor/app/db/euro2020-matches.csv', mode='r') as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: date = datetime.strptime(row["Date"], '%d/%m/%Y %H:%M') if len(row["Round Number"]) == 1: team_1 = team_repository.select_by_name(row["Home Team"]) team_2 = team_repository.select_by_name(row["Away Team"]) match = Match(row["Round Number"], date, row["Location"], row["Group"], team_1, team_2) match_repository.save(match) else: match = Match(row["Round Number"], date, row["Location"], row["Group"], None, None) match_repository.save(match) csv_file.close()
def load_round(self, data): round_list = [ Round(round['name'], [ Match(self.player_controller.get_by_id( match["p1"]["id"]), match["p1"]["score"], self.player_controller.get_by_id(match["p2"]["id"]), match["p2"]["score"]) for match in round["match_list"] ], round["start_time"], round["end_time"]) for round in data ] return round_list
def setUp(self): self.alpha_name = 'a_name' self.alpha_passage = 'a_passage' self.alpha_indices = (0, 12) self.beta_name = 'b_name' self.beta_passage = 'b_passage' self.beta_indices = (12, 24) self.match = Match(alpha_passage=self.alpha_passage, alpha_indices=self.alpha_indices, beta_passage=self.beta_passage, beta_indices=self.beta_indices)
def getMatches(self, event): matches_url = self.YEAR_MATCH_RESULTS_URL_PATTERN.get( event.year, self.DEFAULT_MATCH_RESULTS_URL_PATTERN) % ( event.year, self.EVENT_SHORT_EXCEPTIONS.get(event.event_short, event.event_short)) match_dicts, _ = self.parse(matches_url, self.YEAR_MATCH_PARSER.get(event.year, self.DEFAULT_MATCH_PARSER)) if not match_dicts: # Matches have not been played, but qual match schedule may be out # If this is run when there are already matches in the DB, it will overwrite scores! # Check to make sure event has no existing matches if len(Match.query(Match.event == event.key).fetch(1, keys_only=True)) == 0: logging.warning("No matches found for {}. Trying to parse qual match schedule.".format(event.key.id())) qual_match_sched_url = self.MATCH_SCHEDULE_QUAL_URL_PATTERN % ( event.year, self.EVENT_SHORT_EXCEPTIONS.get(event.event_short, event.event_short)) match_dicts, _ = self.parse(qual_match_sched_url, self.MATCH_SCHEDULE_PARSER) for match_dict in match_dicts: alliances = json.loads(match_dict['alliances_json']) if (alliances['red']['score'] == -1 or alliances['blue']['score'] == -1 or match_dict['comp_level'] in Match.ELIM_LEVELS): break else: # Only qual matches have been played and they have all been played # If this is run when there are already elim matches in the DB, it will overwrite scores! # Check to make sure event has no existing elim matches if len(Match.query(Match.event == event.key, Match.comp_level.IN(Match.ELIM_LEVELS)).fetch(1, keys_only=True)) == 0: logging.warning("No elim matches found for {}. Trying to parse elim match schedule.".format(event.key.id())) elim_match_sched_url = self.MATCH_SCHEDULE_ELIMS_URL_PATTERN % ( event.year, self.EVENT_SHORT_EXCEPTIONS.get(event.event_short, event.event_short)) elim_match_dicts, _ = self.parse(elim_match_sched_url, self.MATCH_SCHEDULE_PARSER) match_dicts += elim_match_dicts matches = [Match( id=Match.renderKeyName( event.key.id(), match_dict.get("comp_level", None), match_dict.get("set_number", 0), match_dict.get("match_number", 0)), event=event.key, game=Match.FRC_GAMES_BY_YEAR.get(event.year, "frc_unknown"), set_number=match_dict.get("set_number", 0), match_number=match_dict.get("match_number", 0), comp_level=match_dict.get("comp_level", None), team_key_names=match_dict.get("team_key_names", None), time_string=match_dict.get("time_string", None), alliances_json=match_dict.get("alliances_json", None) ) for match_dict in match_dicts] MatchHelper.add_match_times(event, matches) return matches
def buildTestMatch(self, comp_level, set_number, match_number, complete): teams = random.sample(self.event.teams, 6) youtube_videos = [] tba_videos = [] if complete: red_score = random.randint(0, 100) blue_score = random.randint(0, 100) if random.choice([True, False]): youtube_videos.append("P3C2BOtL7e8") if random.choice([True, False]): youtube_videos.append("TqY324xLU4s") if random.choice([True, False]): tba_videos.append('mp4') else: red_score = -1 blue_score = -1 alliances = { "red": { "teams": [team.key_name for team in teams[:3]], "score": red_score }, "blue": { "teams": [team.key_name for team in teams[3:]], "score": blue_score } } if comp_level == "qm": id_string = "{}_{}{}".format( self.event.key_name, comp_level, match_number) else: id_string = "{}_{}{}m{}".format( self.event.key_name, comp_level, set_number, match_number) return Match( id=id_string, alliances_json=json.dumps(alliances), comp_level=comp_level, event=self.event.key, year=datetime.datetime.now().year, set_number=set_number, match_number=match_number, team_key_names=[team.key_name for team in teams], youtube_videos=youtube_videos, tba_videos=tba_videos, time=datetime.datetime.now() + datetime.timedelta(hours=2) + datetime.timedelta(minutes=6) * match_number )
def setUp(self): app = webapp2.WSGIApplication([ webapp2.Route( r'/<event_key:>', ApiEventMatchesController, methods=['GET']) ], debug=True) self.testapp = webtest.TestApp(app) self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_urlfetch_stub() self.testbed.init_memcache_stub() ndb.get_context().clear_cache( ) # Prevent data from leaking between tests self.testbed.init_taskqueue_stub(root_path=".") self.event = Event( id="2010sc", name="Palmetto Regional", event_type_enum=EventType.REGIONAL, short_name="Palmetto", event_short="sc", year=2010, end_date=datetime(2010, 03, 27), official=True, city="Clemson", state_prov="SC", country="USA", start_date=datetime(2010, 03, 24), ) self.event.put() self.match = Match( id="2010sc_qm1", alliances_json= """{"blue": {"score": 57, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": 74, "teams": ["frc281", "frc571", "frc176"]}}""", comp_level="qm", event=self.event.key, year=2010, set_number=1, match_number=1, team_key_names=[ u'frc281', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073' ], youtube_videos=["94UGXIq6jUA"], tba_videos=[".mp4"], time=datetime.fromtimestamp(1409527874)) self.match.put()
def setUp(self): self.testbed = testbed.Testbed() self.testbed.activate() self.testbed.init_datastore_v3_stub() self.testbed.init_memcache_stub() self.testbed.init_taskqueue_stub() self.event = Event(id="2012ct", event_short="ct", year=2012) self.old_match = Match( id="2012ct_qm1", alliances_json= """{"blue": {"score": -1, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": -1, "teams": ["frc69", "frc571", "frc176"]}}""", comp_level="qm", event=self.event.key, game="frc_2012_rebr", set_number=1, match_number=1, team_key_names=[ u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073' ], youtube_videos=[u'P3C2BOtL7e8', u'tst1', u'tst2', u'tst3']) self.new_match = Match( id="2012ct_qm1", alliances_json= """{"blue": {"score": 57, "teams": ["frc3464", "frc20", "frc1073"]}, "red": {"score": 74, "teams": ["frc69", "frc571", "frc176"]}}""", comp_level="qm", event=self.event.key, game="frc_2012_rebr", set_number=1, match_number=1, team_key_names=[ u'frc69', u'frc571', u'frc176', u'frc3464', u'frc20', u'frc1073' ], youtube_videos=[u'TqY324xLU4s', u'tst1', u'tst3', u'tst4'])
def matchDictToMatches(self, match_dicts): return [Match(id=Match.renderKeyName(self.event.key.id(), match_dict.get("comp_level", None), match_dict.get("set_number", 0), match_dict.get("match_number", 0)), event=self.event.key, year=self.event.year, set_number=match_dict.get("set_number", 0), match_number=match_dict.get("match_number", 0), comp_level=match_dict.get("comp_level", None), team_key_names=match_dict.get("team_key_names", None), time_string=match_dict.get("time_string", None), alliances_json=match_dict.get("alliances_json", None)) for match_dict in match_dicts]