Best Python code snippet using tavern
test_route_finals.py
Source:test_route_finals.py
1import unittest2from routes.utils import fetch_entity3from mock import MagicMock4from routes.finals import initialize_division_final,create_simplified_division_results,remove_missing_final_player,create_division_final_players,get_tiebreakers_for_division,get_important_tiebreakers_for_division,record_tiebreaker_results,generate_brackets,resolve_unimportant_ties,calculate_points_for_game,calculate_points_for_match,calculate_tiebreakers,resolve_tiebreakers,record_scores,generate_division_final_match_game_result,generate_division_final_match_player_results,generate_division_final_matches,bracket_template_4_player_groups_24_players,generate_division_final_rounds,reset_tiebreaker_info_on_score_change,generate_match_players_groupings,complete_round,calculate_final_rankings,undo_final_round5from util import db_util6from td_types import ImportedTables7import json8def generate_test_match(with_ties=False,with_scores=True,without_players=False,half_completed=False):9 final_player_ids=[None,None,None,None]10 if without_players:11 final_player_ids[0]=None 12 final_player_ids[1]=None 13 final_player_ids[2]=None 14 final_player_ids[3]=None 15 else:16 final_player_ids[0]=9 17 final_player_ids[1]=1718 final_player_ids[2]=1819 final_player_ids[3]=2420 test_match_dict = {21 "completed":False,22 "expected_num_tiebreaker_winners": None,23 "final_match_game_results":[],24 "final_match_player_results": [25 {26 'final_player_id':final_player_ids[0],27 'needs_tiebreaker':False,28 'papa_points_sum':None,29 'winner':None,30 'won_tiebreaker':None31 },32 {33 'final_player_id': final_player_ids[1],34 'needs_tiebreaker':False,35 'papa_points_sum':None,36 'winner':None,37 'won_tiebreaker':None38 },39 {40 'final_player_id':final_player_ids[2],41 'needs_tiebreaker':False,42 'papa_points_sum':None,43 'winner':None,44 'won_tiebreaker':None45 },46 {47 'final_player_id':final_player_ids[3],48 'needs_tiebreaker':False,49 'papa_points_sum':None,50 'winner':None,51 'won_tiebreaker':None52 }53 54 ]55 }56 if without_players:57 return test_match_dict58 if with_ties:59 test_match_dict['final_match_game_results']=[60 generate_test_game_result(fill_in_scores_and_points=True,scores=[4,1,2,0]), 61 generate_test_game_result(fill_in_scores_and_points=True,scores=[4,0,1,2]),62 generate_test_game_result(fill_in_scores_and_points=True,scores=[0,4,2,1])63 ]64 else: 65 test_match_dict['final_match_game_results']=[66 generate_test_game_result(fill_in_scores_and_points=with_scores), 67 generate_test_game_result(fill_in_scores_and_points=with_scores)68 ]69 if half_completed is False:70 test_match_dict['final_match_game_results'].append(generate_test_game_result(fill_in_scores_and_points=with_scores))71 return test_match_dict72def generate_test_game_result(fill_in_scores_and_points=False,scores=None,without_players=False):73 final_player_ids=[None,None,None,None] 74 if without_players:75 final_player_ids[0]=None 76 final_player_ids[1]=None 77 final_player_ids[2]=None 78 final_player_ids[3]=None 79 else:80 final_player_ids[0]=9 81 final_player_ids[1]=1782 final_player_ids[2]=1883 final_player_ids[3]=2484 85 game_result = {86 "completed": False, 87 "division_final_match_game_player_results": [88 {89 "division_final_match_game_player_result_id": 1, 90 "division_final_match_game_result_id": 1, 91 "final_player": {92 "adjusted_seed": 9, 93 "division_final_id": 1, 94 "final_player_id": 9, 95 "initial_seed": 8, 96 "overall_rank": None, 97 "player_id": 108, 98 "player_name": "Una Beddard9", 99 "removed": None, 100 "team_id": None101 }, 102 "final_player_id": final_player_ids[0],103 "papa_points": None, 104 "play_order": None, 105 "score": None106 }, 107 {108 "division_final_match_game_player_result_id": 2, 109 "division_final_match_game_result_id": 1, 110 "final_player": {111 "adjusted_seed": 16, 112 "division_final_id": 1, 113 "final_player_id": 17, 114 "initial_seed": 16, 115 "overall_rank": None, 116 "player_id": 116, 117 "player_name": "Brad Agtarap17", 118 "removed": None, 119 "team_id": None120 }, 121 "final_player_id":final_player_ids[1], 122 "papa_points": None, 123 "play_order": None, 124 "score": None125 }, 126 {127 "division_final_match_game_player_result_id": 3, 128 "division_final_match_game_result_id": 1, 129 "final_player": {130 "adjusted_seed": 17, 131 "division_final_id": 1, 132 "final_player_id": 18, 133 "initial_seed": 16, 134 "overall_rank": None, 135 "player_id": 117, 136 "player_name": "Dorothea Alvidrez18", 137 "removed": None, 138 "team_id": None139 }, 140 "final_player_id":final_player_ids[2],141 "papa_points": None, 142 "play_order": None, 143 "score": None144 }, 145 {146 "division_final_match_game_player_result_id": 4, 147 "division_final_match_game_result_id": 1, 148 "final_player": {149 "adjusted_seed": 24, 150 "division_final_id": 1, 151 "final_player_id": 24, 152 "initial_seed": 24, 153 "overall_rank": None, 154 "player_id": 123, 155 "player_name": "Nathanael Balsiger24", 156 "removed": None, 157 "team_id": None158 }, 159 "final_player_id":final_player_ids[3],160 "papa_points": None, 161 "play_order": None, 162 "score": None163 }164 ], 165 "division_final_match_game_result_id": 1, 166 "division_final_match_id": 1, 167 "division_machine_id": None, 168 "division_machine_string": None, 169 "ready_to_be_completed": False170 }171 if without_players:172 return game_result 173 if fill_in_scores_and_points and scores is None:174 game_result['division_final_match_game_player_results'][0]['score']=0175 game_result['division_final_match_game_player_results'][0]['papa_points']=0176 game_result['division_final_match_game_player_results'][1]['score']=1177 game_result['division_final_match_game_player_results'][1]['papa_points']=1178 game_result['division_final_match_game_player_results'][2]['score']=2179 game_result['division_final_match_game_player_results'][2]['papa_points']=2180 game_result['division_final_match_game_player_results'][3]['score']=4181 game_result['division_final_match_game_player_results'][3]['papa_points']=4182 if fill_in_scores_and_points and scores:183 game_result['division_final_match_game_player_results'][0]['score']=scores[0] 184 game_result['division_final_match_game_player_results'][1]['score']=scores[1] 185 game_result['division_final_match_game_player_results'][2]['score']=scores[2] 186 game_result['division_final_match_game_player_results'][3]['score']=scores[3]187 sorted_game_results = sorted(game_result['division_final_match_game_player_results'], key= lambda e: e['score']) 188 sorted_game_results[0]['papa_points']=0189 sorted_game_results[1]['papa_points']=1190 sorted_game_results[2]['papa_points']=2191 sorted_game_results[3]['papa_points']=4192 game_result['division_final_match_game_player_results']=sorted_game_results193 return game_result194class RouteFinalsTD(unittest.TestCase): 195 def setUp(self):196 self.mock_app = MagicMock()197 self.db_handle = db_util.create_db_handle_no_app() 198 self.tables = ImportedTables(self.db_handle) 199 self.tables.DivisionFinal.query = MagicMock()200 self.tables.DivisionFinalPlayer.query = MagicMock()201 self.tables.DivisionFinalRound.query = MagicMock() 202 self.tables.DivisionFinalMatchPlayerResult.query = MagicMock()203 self.tables.DivisionFinalMatch.query = MagicMock()204 205 206 #self.tables.DivisionFinal.query.filter_by.return_value.all.return_value.qualifiers.__getitem__.return_value=99207 208 209 self.mock_app.tables = self.tables210 self.mock_app.tables.db_handle = MagicMock()211 self.generated_brackets_match_game_dict = generate_test_game_result() 212 213 self.division_results = [214 [215 0, 216 {217 "ifpa_ranking": 10, 218 "player_id": 1, 219 "player_name": "Bowen Kerins", 220 "sum": 512221 }222 ], 223 [224 1, 225 {226 "ifpa_ranking": 7, 227 "player_id": 223, 228 "player_name": "Cayle George", 229 "sum": 503230 }231 ], 232 [233 2, 234 {235 "ifpa_ranking": 1, 236 "player_id": 517, 237 "player_name": "Keith Elwin", 238 "sum": 497239 }240 ], 241 [242 3, 243 {244 "ifpa_ranking": 6, 245 "player_id": 121, 246 "player_name": "Robert Gagno", 247 "sum": 493248 }249 ], 250 [251 3, 252 {253 "ifpa_ranking": 3, 254 "player_id": 298, 255 "player_name": "Jorian Engelbrektsson", 256 "sum": 493257 }258 ], 259 [260 5, 261 {262 "ifpa_ranking": 12, 263 "player_id": 300, 264 "player_name": "Kevin Birrell", 265 "sum": 491266 }267 ], 268 [269 6, 270 {271 "ifpa_ranking": 30, 272 "player_id": 178, 273 "player_name": "Joshua Henderson", 274 "sum": 490275 }276 ]277 ]278 self.final_players = [279 {'adjusted_seed': None, 'overall_rank': None, 'final_player_id': 1, 'initial_seed': 0, 'team_id': None, 'player_name': 'player 1', 'player_id': 1, 'removed': None, 'division_final_id': None, 'type':'result'},280 {'adjusted_seed': None, 'overall_rank': None, 'final_player_id': 2, 'initial_seed': 1, 'team_id': None, 'player_id': 223, 'player_name': 'player 223', 'removed': None, 'division_final_id': None, 'type':'result'},281 {'adjusted_seed': None, 'overall_rank': None, 'final_player_id': 3, 'initial_seed': 2, 'team_id': None, 'player_id': 517, 'player_name': 'player 517', 'removed': None, 'division_final_id': None, 'type':'result'},282 {'adjusted_seed': None, 'overall_rank': None, 'final_player_id': 4, 'initial_seed': 3, 'team_id': None, 'player_id': 121, 'player_name': 'player 121', 'removed': None, 'division_final_id': None, 'type':'result'},283 {'adjusted_seed': None, 'overall_rank': None, 'final_player_id': 5, 'initial_seed': 3, 'team_id': None, 'player_id': 298, 'player_name': 'player 298', 'removed': None, 'division_final_id': None, 'type':'result'},284 {'adjusted_seed': None, 'overall_rank': None, 'final_player_id': 6, 'initial_seed': 5, 'team_id': None, 'player_id': 300, 'player_name': 'player 300', 'removed': None, 'division_final_id': None, 'type':'result'},285 {'adjusted_seed': None, 'overall_rank': None, 'final_player_id': 7, 'initial_seed': 6, 'team_id': None, 'player_id': 178, 'player_name': 'player 178', 'removed': None, 'division_final_id': None, 'type':'result'}286 ]287 self.tiebreaker_results = [288 {289 'final_player_id':4,290 'initial_seed':3,291 'player_name':'player_test4',292 'player_score':"1"293 },294 {295 'final_player_id':5,296 'initial_seed':3,297 'player_name':'player_test5',298 'player_score':"2"299 } 300 ]301 def generate_results(self,number_of_players):302 results = []303 for index in range(number_of_players):304 result = [] 305 result.append(index)306 result.append({307 'ifpa_ranking':index,308 'player_id':index+1,309 'player_name':'player %s'%(index+1),310 'sum':100-index311 })312 results.append(result) 313 return results314 315 def generate_final_players(self,number_of_players):316 final_players = [] 317 for index in range(number_of_players):318 final_player = {}319 final_player['adjusted_seed']=None320 final_player['overall_rank']=None321 final_player['final_player_id']=index+1322 final_player['initial_seed']=index323 final_player['team_id']=None324 final_player['player_name']="player %s"%(index+1)325 final_player['player_id']=index+1326 final_player['removed']=None327 final_player['division_final_id']=None328 final_player['type']='result'329 final_players.append(final_player)330 return final_players331 332 def test_remove_missing_final_player(self): 333 pruned_final_player_list = remove_missing_final_player(self.final_players,self.mock_app)334 self.assertEquals(len(pruned_final_player_list),7)335 self.final_players[0]['removed']=True336 pruned_final_player_list = remove_missing_final_player(self.final_players,self.mock_app)337 self.assertEquals(len(pruned_final_player_list),7) 338 self.assertEquals(pruned_final_player_list[0]['player_id'],1)339 self.assertEquals(pruned_final_player_list[0]['removed'],True)340 self.assertEquals(pruned_final_player_list[1]['removed'],None)341 def test_generate_division_final_match_game_results(self): 342 division_final_match_game_results = generate_division_final_match_game_result(self.mock_app)343 self.assertEquals(len(division_final_match_game_results),3)344 self.assertEquals(len(division_final_match_game_results[0].division_final_match_game_player_results),4)345 self.assertEquals(len(division_final_match_game_results[1].division_final_match_game_player_results),4)346 self.assertEquals(len(division_final_match_game_results[2].division_final_match_game_player_results),4) 347 def test_generate_division_final_match_player_results(self): 348 division_final_match_player_results = generate_division_final_match_player_results(self.mock_app)349 self.assertEquals(len(division_final_match_player_results),4) 350 def test_generate_division_final_rounds(self): 351 final_players = []352 for final_player_id in range(30):353 final_players.append(self.mock_app.tables.DivisionFinalPlayer(354 final_player_id=final_player_id,355 adjusted_seed=final_player_id-1356 ))357 division_final_rounds = generate_division_final_rounds(self.mock_app,bracket_template_4_player_groups_24_players,1,final_players)358 self.assertEquals(division_final_rounds[0].round_number,1) 359 self.assertEquals(division_final_rounds[1].round_number,2) 360 self.assertEquals(division_final_rounds[2].round_number,3) 361 self.assertEquals(division_final_rounds[3].round_number,4) 362 self.assertEquals(division_final_rounds[0].division_final_matches[0].final_match_player_results[0].final_player_id,9) 363 self.assertEquals(division_final_rounds[0].division_final_matches[0].final_match_player_results[1].final_player_id,16) 364 self.assertEquals(division_final_rounds[0].division_final_matches[0].final_match_player_results[2].final_player_id,17) 365 self.assertEquals(division_final_rounds[0].division_final_matches[0].final_match_player_results[3].final_player_id,24)366 367 self.assertEquals(division_final_rounds[0].division_final_matches[1].final_match_player_results[0].final_player_id,10) 368 self.assertEquals(division_final_rounds[0].division_final_matches[1].final_match_player_results[1].final_player_id,15) 369 self.assertEquals(division_final_rounds[0].division_final_matches[1].final_match_player_results[2].final_player_id,18) 370 self.assertEquals(division_final_rounds[0].division_final_matches[1].final_match_player_results[3].final_player_id,23) 371 372 self.assertEquals(division_final_rounds[0].division_final_matches[2].final_match_player_results[0].final_player_id,11) 373 self.assertEquals(division_final_rounds[0].division_final_matches[2].final_match_player_results[1].final_player_id,14) 374 self.assertEquals(division_final_rounds[0].division_final_matches[2].final_match_player_results[2].final_player_id,19) 375 self.assertEquals(division_final_rounds[0].division_final_matches[2].final_match_player_results[3].final_player_id,22) 376 377 self.assertEquals(division_final_rounds[0].division_final_matches[3].final_match_player_results[0].final_player_id,12) 378 self.assertEquals(division_final_rounds[0].division_final_matches[3].final_match_player_results[1].final_player_id,13) 379 self.assertEquals(division_final_rounds[0].division_final_matches[3].final_match_player_results[2].final_player_id,20) 380 self.assertEquals(division_final_rounds[0].division_final_matches[3].final_match_player_results[3].final_player_id,21) 381 382 def test_generate_division_final_matches(self): 383 division_final_matches = generate_division_final_matches(self.mock_app,4)384 self.assertEquals(len(division_final_matches),4) 385 self.assertEquals(len(division_final_matches[0].final_match_game_results),3) 386 self.assertEquals(len(division_final_matches[0].final_match_player_results),4) 387 self.assertEquals(len(division_final_matches[1].final_match_game_results),3) 388 self.assertEquals(len(division_final_matches[1].final_match_player_results),4) 389 self.assertEquals(len(division_final_matches[2].final_match_game_results),3) 390 self.assertEquals(len(division_final_matches[2].final_match_player_results),4) 391 self.assertEquals(len(division_final_matches[3].final_match_game_results),3) 392 self.assertEquals(len(division_final_matches[3].final_match_player_results),4) 393 394 def test_generate_brackets(self): 395 #FIXME : need test for generate_division_final_rounds396 division_final = self.tables.DivisionFinal()397 final_results = self.generate_results(30)398 final_players = self.generate_final_players(30)399 400 create_division_final_players(division_final,final_results,self.mock_app)401 for index,final_player in enumerate(division_final.qualifiers):402 division_final.qualifiers[index].final_player_id=index+1403 division_final.qualifiers[index].player_name="test player"+str(index+1)404 405 self.mock_app.tables.DivisionFinalPlayer.query.filter_by.return_value.all.return_value=division_final.qualifiers406 #final_players_from_db = self.generate_final_players(30)407 for player in final_players:408 player['reranked_seed']=player['initial_seed'] 409 final_players[0]['reranked_seed']=4410 final_players[4]['reranked_seed']=0 411 simplified_results = create_simplified_division_results(final_players,7,self.mock_app) 412 final_rounds = generate_brackets(self.mock_app,1,simplified_results,7) 413 self.assertTrue(division_final.qualifiers[3].adjusted_seed!=division_final.qualifiers[4].adjusted_seed)414 self.assertTrue(division_final.qualifiers[3].adjusted_seed==3 or division_final.qualifiers[3].adjusted_seed==4 )415 #self.assertTrue(results[3]['reranked_seed']==3 or results[3]['reranked_seed']==4) 416 417 def test_resolve_unimportant_ties(self): 418 for player in self.final_players:419 player['reranked_seed']=player['initial_seed'] 420 #self.final_players[0]['removed']=True421 simplified_results = create_simplified_division_results(self.final_players,7,self.mock_app)422 results = resolve_unimportant_ties(simplified_results,7) 423 self.assertTrue(results[3]['reranked_seed']!=results[4]['reranked_seed']) 424 self.assertTrue(results[3]['reranked_seed']==3 or results[3]['reranked_seed']==4) 425 426 def test_remove_missing_final_player_with_simplified_list(self): 427 for player in self.final_players:428 player['reranked_seed']=player['initial_seed'] 429 self.final_players[0]['removed']=True430 simplified_results = create_simplified_division_results(self.final_players,3,self.mock_app)431 pruned_final_player_list = remove_missing_final_player(simplified_results,self.mock_app)432 self.assertEquals(len(pruned_final_player_list),7) 433 self.assertEquals(pruned_final_player_list[3]['type'],'result')434 self.assertEquals(pruned_final_player_list[0]['player_id'],1)435 self.assertEquals(pruned_final_player_list[0]['removed'],True)436 self.assertEquals(pruned_final_player_list[1]['removed'],None)437 438 def test_initialize_division_final(self): 439 self.tables.DivisionFinal.query.filter_by.return_value.all.return_value=None440 division_final = initialize_division_final(1,"test_division",self.division_results,self.mock_app)441 self.assertEquals(division_final.division_id,1)442 self.assertEquals(len(division_final.qualifiers),7)443 self.assertEquals(division_final.qualifiers[0].initial_seed,0)444 def test_initialize_division_final_with_existing_division_final(self): 445 existing_division_final = self.tables.DivisionFinal()446 self.tables.DivisionFinal.query.filter_by.return_value.all.return_value=existing_division_final447 division_final = initialize_division_final(1,"test_division",self.division_results,self.mock_app)448 self.assertEquals(division_final,existing_division_final)449 def test_create_division_final_players(self):450 division_final = self.tables.DivisionFinal()451 division_final.qualifiers=[]452 453 create_division_final_players(division_final,self.division_results,self.mock_app)454 self.assertEquals(len(division_final.qualifiers),7)455 def test_create_simplified_division_results(self): 456 for player in self.final_players:457 player['reranked_seed']=player['initial_seed'] 458 simplified_division_results = create_simplified_division_results(self.final_players, 4, self.mock_app)459 self.assertEquals(len(simplified_division_results),8) 460 self.assertEquals(simplified_division_results[5]['type'],"divider")461 self.final_players[5]['removed']=True462 self.final_players[6]['initial_seed']=self.final_players[6]['initial_seed']-1 463 self.final_players[6]['reranked_seed']=self.final_players[6]['initial_seed']-1 464 simplified_division_results = create_simplified_division_results(self.final_players, 6, self.mock_app) 465 self.assertEquals(len(simplified_division_results),8) 466 self.assertEquals(simplified_division_results[7]['type'],"divider")467 468 def test_create_division_final_players(self):469 division_final = self.tables.DivisionFinal()470 division_final.qualifiers=[]471 create_division_final_players(division_final,self.division_results,self.mock_app)472 self.assertEquals(len(division_final.qualifiers),7) 473 self.assertEquals(division_final.qualifiers[0].initial_seed,0)474 def test_get_important_tiebreakers_for_division(self):475 division_final = self.tables.DivisionFinal()476 division_final.division_final_id=1477 division_final_players = create_division_final_players(division_final,self.division_results,self.mock_app) 478 for index,final_player in enumerate(division_final_players):479 division_final_players[index].final_player_id=index+1480 division_final_players[index].player_name="test player"+str(index+1)481 division_final_players[6].initial_seed=5482 important_tiebreaker_ranks = get_important_tiebreakers_for_division(division_final_players,6,{'qualifying':3})483 self.assertEquals(important_tiebreaker_ranks['qualifying'],3) 484 important_tiebreaker_ranks = get_important_tiebreakers_for_division(division_final_players,6,{'qualifying':4}) 485 self.assertTrue('qualifying' not in important_tiebreaker_ranks) 486 important_tiebreaker_ranks = get_important_tiebreakers_for_division(division_final_players,6,{'bye':3})487 self.assertEquals(important_tiebreaker_ranks['bye'],3) 488 important_tiebreaker_ranks = get_important_tiebreakers_for_division(division_final_players,6,{'bye':4})489 self.assertTrue('bye' not in important_tiebreaker_ranks) 490 491 important_tiebreaker_ranks = get_important_tiebreakers_for_division(division_final_players,7,{'qualifying':5,'bye':3})492 self.assertEquals(important_tiebreaker_ranks['bye'],3)493 self.assertEquals(important_tiebreaker_ranks['qualifying'],5) 494 important_tiebreaker_ranks = get_important_tiebreakers_for_division(division_final_players,7,{'qualifying':6,'bye':4})495 self.assertTrue('bye' not in important_tiebreaker_ranks) 496 self.assertEquals(important_tiebreaker_ranks['qualifying'],5) 497 498 def test_get_tiebreakers_for_division(self):499 division_final = self.tables.DivisionFinal()500 division_final.division_final_id=1501 division_final_players = create_division_final_players(division_final,self.division_results,self.mock_app) 502 for index,final_player in enumerate(division_final_players):503 division_final_players[index].final_player_id=index+1504 division_final_players[index].player_name="test player"+str(index+1)505 506 tiebreakers = get_tiebreakers_for_division(division_final_players,6) 507 self.assertEquals(len(tiebreakers[0]),2)508 self.assertEquals(tiebreakers[0][0]['final_player_id'],4) 509 self.assertEquals(tiebreakers[0][1]['final_player_id'],5) 510 def test_set_tiebreaker_results_for_division(self):511 division_final = self.tables.DivisionFinal()512 division_final.division_final_id=1513 division_final_players = create_division_final_players(division_final,self.division_results,self.mock_app) 514 515 for index,final_player in enumerate(division_final_players):516 division_final_players[index].final_player_id=index+1517 division_final_players[index].player_name="test player"+str(index+1) 518 519 results = record_tiebreaker_results(division_final_players,self.tiebreaker_results,self.mock_app) 520 self.assertEquals(division_final.qualifiers[4].initial_seed,3) 521 self.assertEquals(division_final.qualifiers[3].initial_seed,4) 522 self.assertEquals(results[0]['initial_seed'],4) 523 524 def test_calculate_points_for_game_without_enough_scores(self): 525 calculate_points_for_game(self.generated_brackets_match_game_dict)526 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['papa_points'],None)527 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['papa_points'],None)528 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][2]['papa_points'],None)529 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][3]['papa_points'],None)530 self.assertEquals(self.generated_brackets_match_game_dict['completed'],False) 531 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['score']=126532 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['score']=125533 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][2]['score']=124 534 calculate_points_for_game(self.generated_brackets_match_game_dict) 535 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['papa_points'],None)536 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['papa_points'],None)537 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][2]['papa_points'],None)538 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][3]['papa_points'],None)539 self.assertEquals(self.generated_brackets_match_game_dict['completed'],False) 540 def test_calculate_points_for_game_with_enough_scores(self): 541 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['score']=126542 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['score']=125543 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][2]['score']=124 544 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][3]['score']=123 545 calculate_points_for_game(self.generated_brackets_match_game_dict) 546 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['final_player_id'],24)547 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['papa_points'],0)548 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['final_player_id'],18)549 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['papa_points'],1)550 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][2]['final_player_id'],17)551 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][2]['papa_points'],2)552 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][3]['final_player_id'],9)553 self.assertEquals(self.generated_brackets_match_game_dict['division_final_match_game_player_results'][3]['papa_points'],4)554 self.assertEquals(self.generated_brackets_match_game_dict['completed'],True) 555 556 def test_calculate_points_for_match_uncompleted(self): 557 test_match_dict = generate_test_match(half_completed=True) 558 calculate_points_for_match(test_match_dict) 559 self.assertEquals(test_match_dict['completed'],False)560 self.assertEquals(test_match_dict['final_match_player_results'][0]['papa_points_sum'],0)561 self.assertEquals(test_match_dict['final_match_player_results'][1]['papa_points_sum'],2)562 self.assertEquals(test_match_dict['final_match_player_results'][2]['papa_points_sum'],4)563 self.assertEquals(test_match_dict['final_match_player_results'][3]['papa_points_sum'],8)564 def test_calculate_points_for_match_with_enough_scores(self): 565 test_match_dict = generate_test_match() 566 calculate_points_for_match(test_match_dict) 567 self.assertEquals(test_match_dict['completed'],True)568 self.assertEquals(test_match_dict['final_match_player_results'][0]['papa_points_sum'],0)569 self.assertEquals(test_match_dict['final_match_player_results'][1]['papa_points_sum'],3)570 self.assertEquals(test_match_dict['final_match_player_results'][2]['papa_points_sum'],6)571 self.assertEquals(test_match_dict['final_match_player_results'][3]['papa_points_sum'],12)572 self.assertEquals(test_match_dict['final_match_player_results'][0]['winner'],False)573 self.assertEquals(test_match_dict['final_match_player_results'][1]['winner'],False)574 self.assertEquals(test_match_dict['final_match_player_results'][2]['winner'],True)575 self.assertEquals(test_match_dict['final_match_player_results'][3]['winner'],True)576 577 def test_calculate_tiebreakers(self): 578 test_match_dict = generate_test_match(with_ties=True) 579 calculate_points_for_match(test_match_dict)580 tiebreaker_final_player_ids=calculate_tiebreakers(test_match_dict)581 #print tiebreaker_final_player_ids582 self.assertEquals(test_match_dict['completed'],False)583 self.assertEquals(test_match_dict['expected_num_tiebreaker_winners'],1)584 self.assertEquals(test_match_dict['final_match_player_results'][0]['needs_tiebreaker'],False)585 self.assertEquals(test_match_dict['final_match_player_results'][1]['needs_tiebreaker'],True)586 self.assertEquals(test_match_dict['final_match_player_results'][2]['needs_tiebreaker'],True)587 self.assertEquals(test_match_dict['final_match_player_results'][3]['needs_tiebreaker'],False)588 def test_calculate_tiebreakers_report_only(self): 589 test_match_dict = generate_test_match(with_ties=True) 590 test_match_dict['final_match_player_results'][0]['papa_points_sum']=8591 test_match_dict['final_match_player_results'][1]['papa_points_sum']=5592 test_match_dict['final_match_player_results'][2]['papa_points_sum']=5593 test_match_dict['final_match_player_results'][3]['papa_points_sum']=4594 tiebreaker_final_player_ids=calculate_tiebreakers(test_match_dict,report_only=True) 595 self.assertEquals(len(tiebreaker_final_player_ids),2)596 self.assertEquals(tiebreaker_final_player_ids[0],17)597 self.assertEquals(tiebreaker_final_player_ids[1],18)598 self.assertEquals(test_match_dict['completed'],False)599 self.assertEquals(test_match_dict['expected_num_tiebreaker_winners'],None)600 self.assertEquals(test_match_dict['final_match_player_results'][0]['needs_tiebreaker'],False)601 self.assertEquals(test_match_dict['final_match_player_results'][1]['needs_tiebreaker'],False)602 self.assertEquals(test_match_dict['final_match_player_results'][2]['needs_tiebreaker'],False)603 self.assertEquals(test_match_dict['final_match_player_results'][3]['needs_tiebreaker'],False)604 605 def test_calculate_points_for_match_with_ties(self): 606 test_match_dict = generate_test_match(with_ties=True) 607 calculate_points_for_match(test_match_dict) 608 self.assertEquals(test_match_dict['completed'],False)609 self.assertEquals(test_match_dict['final_match_player_results'][0]['papa_points_sum'],8)610 self.assertEquals(test_match_dict['final_match_player_results'][1]['papa_points_sum'],5)611 self.assertEquals(test_match_dict['final_match_player_results'][2]['papa_points_sum'],5)612 self.assertEquals(test_match_dict['final_match_player_results'][3]['papa_points_sum'],3)613 self.assertEquals(test_match_dict['final_match_player_results'][0]['winner'],None)614 self.assertEquals(test_match_dict['final_match_player_results'][1]['winner'],None)615 self.assertEquals(test_match_dict['final_match_player_results'][2]['winner'],None)616 self.assertEquals(test_match_dict['final_match_player_results'][3]['winner'],None)617 618 def test_calculate_points_for_match_without_players(self): 619 test_match_dict = generate_test_match(without_players=True) 620 calculate_points_for_match(test_match_dict) 621 self.assertEquals(test_match_dict['completed'],False)622 self.assertEquals(test_match_dict['final_match_player_results'][0]['papa_points_sum'],None)623 self.assertEquals(test_match_dict['final_match_player_results'][1]['papa_points_sum'],None)624 self.assertEquals(test_match_dict['final_match_player_results'][2]['papa_points_sum'],None)625 self.assertEquals(test_match_dict['final_match_player_results'][3]['papa_points_sum'],None)626 627 def test_resolve_tiebreakers(self):628 tiebreaker_scores_dict={629 "expected_num_tiebreaker_winners":2,630 "division_final_match_id":1,631 "final_match_player_results":[632 {633 "final_player_id":9,634 "tiebreaker_score":"1",635 "needs_tiebreaker":True,636 "final_player":{637 "player_name":"poopinstein"638 }639 },640 {641 "final_player_id":24,642 "tiebreaker_score":"2",643 "needs_tiebreaker":True,644 "final_player":{645 "player_name":"poopinstein2"646 } 647 }648 ]649 }650 651 652 self.tables.DivisionFinalMatchPlayerResult.query.filter_by.return_value = MagicMock()653 division_final_match_player_results = [654 self.tables.DivisionFinalMatchPlayerResult(655 final_player_id=9656 ),657 self.tables.DivisionFinalMatchPlayerResult(658 final_player_id=24659 ) 660 ]661 self.tables.DivisionFinalMatchPlayerResult.query.filter_by.return_value.all.return_value = division_final_match_player_results662 division_final_match = self.tables.DivisionFinalMatch()663 self.tables.DivisionFinalMatch.query.filter_by.return_value.first.return_value = division_final_match664 665 resolve_tiebreakers(tiebreaker_scores_dict,self.mock_app)666 667 self.assertEquals(division_final_match_player_results[1].won_tiebreaker,True)668 self.assertEquals(division_final_match_player_results[0].won_tiebreaker,False)669 self.assertEquals(division_final_match.completed,True)670 def test_resolve_tiebreakers_with_3_ties(self):671 tiebreaker_scores_dict={672 "expected_num_tiebreaker_winners":2,673 "division_final_match_id":1,674 "final_match_player_results":[675 {676 "final_player_id":9,677 "tiebreaker_score":"1",678 "needs_tiebreaker":True,679 "final_player":{680 "player_name":"poopinstein"681 }682 },683 {684 "final_player_id":24,685 "tiebreaker_score":"2",686 "needs_tiebreaker":True,687 "final_player":{688 "player_name":"poopinstein2"689 }690 },691 {692 "final_player_id":17,693 "tiebreaker_score":"3",694 "needs_tiebreaker":True,695 "final_player":{696 "player_name":"poopinstein3"697 }698 } 699 ]700 }701 self.tables.DivisionFinalMatchPlayerResult.query.filter_by.return_value = MagicMock()702 division_final_match_player_results = [703 self.tables.DivisionFinalMatchPlayerResult(704 final_player_id=9705 ),706 self.tables.DivisionFinalMatchPlayerResult(707 final_player_id=24708 ),709 self.tables.DivisionFinalMatchPlayerResult(710 final_player_id=17711 ) 712 ]713 self.tables.DivisionFinalMatchPlayerResult.query.filter_by.return_value.all.return_value = division_final_match_player_results714 division_final_match = self.tables.DivisionFinalMatch()715 self.tables.DivisionFinalMatch.query.filter_by.return_value.first.return_value = division_final_match 716 resolve_tiebreakers(tiebreaker_scores_dict,self.mock_app)717 718 self.assertEquals(division_final_match_player_results[0].won_tiebreaker,False)719 self.assertEquals(division_final_match_player_results[1].won_tiebreaker,True)720 self.assertEquals(division_final_match_player_results[2].won_tiebreaker,True)721 self.assertEquals(division_final_match.completed,True)722 tiebreaker_scores_dict['final_match_player_results'][0]['tiebreaker_score']="1"723 tiebreaker_scores_dict['final_match_player_results'][1]['tiebreaker_score']="2"724 tiebreaker_scores_dict['final_match_player_results'][2]['tiebreaker_score']="3"725 division_final_match = self.tables.DivisionFinalMatch()726 self.tables.DivisionFinalMatch.query.filter_by.return_value.first.return_value = division_final_match 727 tiebreaker_scores_dict["expected_num_tiebreaker_winners"]=1728 resolve_tiebreakers(tiebreaker_scores_dict,self.mock_app)729 self.assertEquals(division_final_match_player_results[0].won_tiebreaker,False)730 self.assertEquals(division_final_match_player_results[1].won_tiebreaker,False)731 self.assertEquals(division_final_match_player_results[2].won_tiebreaker,True)732 self.assertEquals(division_final_match.completed,True)733 734 def test_record_scores_half_completed(self): 735 game_player_results = [736 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(737 division_final_match_game_player_result_id=1738 ),739 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(740 division_final_match_game_player_result_id=2741 ),742 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(743 division_final_match_game_player_result_id=3744 ),745 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(746 division_final_match_game_player_result_id=4747 )748 ]749 750 game_result = self.mock_app.tables.DivisionFinalMatchGameResult(751 division_final_match_game_player_results=game_player_results752 )753 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['score']=126754 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['score']=125755 self.generated_brackets_match_game_dict['division_machine_string']="new machine"756 757 record_scores(self.generated_brackets_match_game_dict,game_result,self.mock_app)758 self.assertEquals(game_result.division_machine_string,'new machine') 759 self.assertEquals(game_player_results[0].score,126)760 self.assertEquals(game_player_results[1].score,125)761 self.assertEquals(game_player_results[2].score,None)762 self.assertEquals(game_player_results[3].score,None)763 def test_record_scores_completed(self): 764 game_player_results = [765 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(766 division_final_match_game_player_result_id=1767 ),768 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(769 division_final_match_game_player_result_id=2770 ),771 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(772 division_final_match_game_player_result_id=3773 ),774 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(775 division_final_match_game_player_result_id=4776 )777 ]778 779 game_result = self.mock_app.tables.DivisionFinalMatchGameResult(780 division_final_match_game_player_results=game_player_results781 )782 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][0]['score']=126783 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][1]['score']=125784 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][2]['score']=124785 self.generated_brackets_match_game_dict['division_final_match_game_player_results'][3]['score']=123786 787 self.generated_brackets_match_game_dict['division_machine_string']="new machine"788 789 record_scores(self.generated_brackets_match_game_dict,game_result,self.mock_app)790 self.assertEquals(game_result.division_machine_string,'new machine') 791 self.assertEquals(game_player_results[0].score,126)792 self.assertEquals(game_player_results[1].score,125)793 self.assertEquals(game_player_results[2].score,124)794 self.assertEquals(game_player_results[3].score,123)795 796 def test_reset_tiebreaker_info_on_score_change(self):797 match = self.mock_app.tables.DivisionFinalMatch(798 expected_num_tiebreaker_winners=1799 )800 for match_player_result_id in range(4):801 match.final_match_player_results.append(self.mock_app.tables.DivisionFinalMatchPlayerResult(802 needs_tiebreaker=True,803 won_tiebreaker=True804 ))805 reset_tiebreaker_info_on_score_change(match,self.mock_app)806 for final_match_player_index in range(4):807 self.assertFalse(match.final_match_player_results[final_match_player_index].needs_tiebreaker)808 for final_match_player_index in range(4): 809 self.assertEquals(match.final_match_player_results[final_match_player_index].won_tiebreaker,None)810 self.assertEquals(match.expected_num_tiebreaker_winners,None)811 def test_generate_match_players_groupings(self): 812 bobo_results = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]813 pruned_bobo_results = generate_match_players_groupings(bobo_results)814 self.assertEquals(pruned_bobo_results,[16,9,8,1])815 pruned_bobo_results = generate_match_players_groupings(bobo_results)816 self.assertEquals(pruned_bobo_results,[15,10,7,2])817 def generate_division_final_match_game_player_result(self,num_to_generate,scores=None):818 if scores is None:819 scores=["1","2","3","4"]820 final_match_game_player_results = []821 for num in range(num_to_generate):822 final_match_game_player_results.append(823 self.mock_app.tables.DivisionFinalMatchGamePlayerResult(824 final_player_id=num+1,825 score=scores[num]826 )827 )828 def generate_division_final_round_db_obj(self,round_number,with_players=True,num_matches=4):829 division_final_round=self.mock_app.tables.DivisionFinalRound(830 division_final_round_id=round_number,831 round_number=round_number832 )833 division_final_matches = []834 for division_final_match_id in range(num_matches):835 game_results = [ self.mock_app.tables.DivisionFinalMatchGameResult( 836 division_final_match_game_player_results = [self.mock_app.tables.DivisionFinalMatchGamePlayerResult() for i in range(4)]837 ) for j in range(3)] 838 division_final_matches.append(self.mock_app.tables.DivisionFinalMatch(839 final_match_game_results=game_results840 ))841 division_final_round.division_final_matches=division_final_matches842 player_count=0843 for division_final_match_index in range(num_matches): 844 division_final_match_player_results = [] 845 for division_final_match_player_index in range(4):846 if with_players:847 final_player_id=division_final_match_player_index+1+player_count848 else:849 final_player_id=None850 division_final_match_player_results.append(self.mock_app.tables.DivisionFinalMatchPlayerResult(851 final_player_id=final_player_id, 852 final_player = self.mock_app.tables.DivisionFinalPlayer( 853 final_player_id=final_player_id854 )855 ))856 division_final_matches[division_final_match_index].final_match_player_results=division_final_match_player_results 857 player_count=player_count+4 858 division_final_round.division_final_matches=division_final_matches859 return division_final_round860 861 def fill_in_bobo_rounds(self,division_final_round,next_division_final_round,num_matches=4):862 match_1_seeds=[9,16,17,24] 863 if num_matches > 1:864 match_2_seeds=[10,15,18,23]865 else:866 match_2_seeds=[]867 if num_matches > 2:868 match_3_seeds=[11,14,19,22]869 match_4_seeds=[12,13,20,21]870 else:871 match_3_seeds=[]872 match_4_seeds=[]873 874 match_5_seeds=[1,8,None,None]875 match_6_seeds=[2,7,None,None]876 match_7_seeds=[3,6,None,None]877 match_8_seeds=[4,5,None,None]878 879 for index,seed in enumerate(match_1_seeds):880 division_final_round.division_final_matches[0].final_match_player_results[index].final_player.adjusted_seed=seed881 division_final_round.division_final_matches[0].final_match_player_results[index].final_player_id=seed882 for index,seed in enumerate(match_2_seeds):883 division_final_round.division_final_matches[1].final_match_player_results[index].final_player.adjusted_seed=seed884 division_final_round.division_final_matches[1].final_match_player_results[index].final_player_id=seed885 for index,seed in enumerate(match_3_seeds):886 division_final_round.division_final_matches[2].final_match_player_results[index].final_player.adjusted_seed=seed887 division_final_round.division_final_matches[2].final_match_player_results[index].final_player_id=seed888 for index,seed in enumerate(match_4_seeds):889 division_final_round.division_final_matches[3].final_match_player_results[index].final_player.adjusted_seed=seed890 division_final_round.division_final_matches[3].final_match_player_results[index].final_player_id=seed891 for match_index in range(num_matches): 892 division_final_round.division_final_matches[match_index].final_match_player_results[1].winner=True893 division_final_round.division_final_matches[match_index].final_match_player_results[0].winner=True894 895 if next_division_final_round is None:896 return897 for index,seed in enumerate(match_5_seeds):898 next_division_final_round.division_final_matches[0].final_match_player_results[index].final_player.adjusted_seed=seed899 next_division_final_round.division_final_matches[0].final_match_player_results[index].final_player_id=seed900 for index,seed in enumerate(match_6_seeds):901 next_division_final_round.division_final_matches[1].final_match_player_results[index].final_player.adjusted_seed=seed902 next_division_final_round.division_final_matches[1].final_match_player_results[index].final_player_id=seed903 for index,seed in enumerate(match_7_seeds):904 next_division_final_round.division_final_matches[2].final_match_player_results[index].final_player.adjusted_seed=seed905 next_division_final_round.division_final_matches[2].final_match_player_results[index].final_player_id=seed906 for index,seed in enumerate(match_8_seeds):907 next_division_final_round.division_final_matches[3].final_match_player_results[index].final_player.adjusted_seed=seed908 next_division_final_round.division_final_matches[3].final_match_player_results[index].final_player_id=seed909 910 def test_complete_round(self):911 division_final=self.mock_app.tables.DivisionFinal()912 division_final_round = self.generate_division_final_round_db_obj(1,with_players=False)913 next_division_final_round = self.generate_division_final_round_db_obj(2,with_players=False)914 self.assertFalse(division_final_round.completed)915 self.fill_in_bobo_rounds(division_final_round,next_division_final_round)916 917 self.mock_app.tables.DivisionFinalRound.query.filter_by.return_value.first.return_value=next_division_final_round918 self.mock_app.tables.DivisionFinalMatch.query.filter_by.return_value.all.return_value=next_division_final_round.division_final_matches919 920 complete_round(division_final,division_final_round,self.mock_app)921 self.assertTrue(division_final_round.completed)922 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[0].final_player_id,16)923 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[1].final_player_id,9)924 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[2].final_player_id,8)925 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[3].final_player_id,1)926 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[0].final_player_id,15)927 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[1].final_player_id,10)928 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[2].final_player_id,7)929 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[3].final_player_id,2)930 self.assertEquals(next_division_final_round.division_final_matches[2].final_match_player_results[0].final_player_id,14)931 self.assertEquals(next_division_final_round.division_final_matches[2].final_match_player_results[1].final_player_id,11)932 self.assertEquals(next_division_final_round.division_final_matches[2].final_match_player_results[2].final_player_id,6)933 self.assertEquals(next_division_final_round.division_final_matches[2].final_match_player_results[3].final_player_id,3)934 self.assertEquals(next_division_final_round.division_final_matches[3].final_match_player_results[0].final_player_id,13)935 self.assertEquals(next_division_final_round.division_final_matches[3].final_match_player_results[1].final_player_id,12)936 self.assertEquals(next_division_final_round.division_final_matches[3].final_match_player_results[2].final_player_id,5)937 self.assertEquals(next_division_final_round.division_final_matches[3].final_match_player_results[3].final_player_id,4)938 939 def test_complete_round_two(self):940 division_final=self.mock_app.tables.DivisionFinal()941 division_final_round = self.generate_division_final_round_db_obj(2,with_players=False)942 next_division_final_round = self.generate_division_final_round_db_obj(3,with_players=False,num_matches=2)943 self.assertFalse(division_final_round.completed)944 self.fill_in_bobo_rounds(division_final_round,None)945 946 self.mock_app.tables.DivisionFinalRound.query.filter_by.return_value.first.return_value=next_division_final_round947 self.mock_app.tables.DivisionFinalMatch.query.filter_by.return_value.all.return_value=next_division_final_round.division_final_matches948 complete_round(division_final,division_final_round,self.mock_app) 949 self.assertTrue(division_final_round.completed)950 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[0].final_player_id,16)951 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[1].final_player_id,13)952 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[2].final_player_id,12)953 self.assertEquals(next_division_final_round.division_final_matches[0].final_match_player_results[3].final_player_id,9)954 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[0].final_player_id,15)955 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[1].final_player_id,14)956 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[2].final_player_id,11)957 self.assertEquals(next_division_final_round.division_final_matches[1].final_match_player_results[3].final_player_id,10)958 def test_complete_round_final(self):959 division_final=self.mock_app.tables.DivisionFinal()960 division_final_round = self.generate_division_final_round_db_obj(2,with_players=False,num_matches=2)961 next_division_final_round = self.generate_division_final_round_db_obj(3,with_players=False,num_matches=1)962 self.assertFalse(division_final_round.completed)963 self.fill_in_bobo_rounds(division_final_round,None,num_matches=2)964 965 self.mock_app.tables.DivisionFinalRound.query.filter_by.return_value.first.return_value=None966 self.mock_app.tables.DivisionFinalMatch.query.filter_by.return_value.all.return_value=None967 complete_round(division_final,division_final_round,self.mock_app)968 self.assertTrue(division_final_round.completed)969 970 def test_calculate_final_rankings(self):971 division_final=self.mock_app.tables.DivisionFinal()972 division_final_round = self.generate_division_final_round_db_obj(2,with_players=False)973 next_division_final_round = self.generate_division_final_round_db_obj(3,with_players=False,num_matches=2)974 self.assertFalse(division_final_round.completed)975 self.fill_in_bobo_rounds(division_final_round,None)976 977 self.mock_app.tables.DivisionFinalRound.query.filter_by.return_value.first.return_value=next_division_final_round978 self.mock_app.tables.DivisionFinalMatch.query.filter_by.return_value.all.return_value=next_division_final_round.division_final_matches979 980 division_final_round.completed=True981 round_dicts = [division_final_round.to_dict_simple(),next_division_final_round.to_dict_simple()]982 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][0]['papa_points_sum']=4983 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][1]['papa_points_sum']=3984 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][2]['papa_points_sum']=2985 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][3]['papa_points_sum']=1986 round_dicts[0]['division_final_matches'][1]['final_match_player_results'][0]['papa_points_sum']=8987 round_dicts[0]['division_final_matches'][1]['final_match_player_results'][1]['papa_points_sum']=7988 round_dicts[0]['division_final_matches'][1]['final_match_player_results'][2]['papa_points_sum']=6989 round_dicts[0]['division_final_matches'][1]['final_match_player_results'][3]['papa_points_sum']=5990 round_dicts[0]['division_final_matches'][2]['final_match_player_results'][0]['papa_points_sum']=12991 round_dicts[0]['division_final_matches'][2]['final_match_player_results'][1]['papa_points_sum']=11992 round_dicts[0]['division_final_matches'][2]['final_match_player_results'][2]['papa_points_sum']=10993 round_dicts[0]['division_final_matches'][2]['final_match_player_results'][3]['papa_points_sum']=9994 round_dicts[0]['division_final_matches'][3]['final_match_player_results'][0]['papa_points_sum']=16995 round_dicts[0]['division_final_matches'][3]['final_match_player_results'][1]['papa_points_sum']=15996 round_dicts[0]['division_final_matches'][3]['final_match_player_results'][2]['papa_points_sum']=14997 round_dicts[0]['division_final_matches'][3]['final_match_player_results'][3]['papa_points_sum']=13 998 calculate_final_rankings(round_dicts) 999 self.assertEquals(round_dicts[0]['division_final_matches'][0]['final_match_player_results'][2]['final_rank'],23)1000 self.assertEquals(round_dicts[0]['division_final_matches'][0]['final_match_player_results'][3]['final_rank'],24) 1001 self.assertTrue('final_rank' not in round_dicts[0]['division_final_matches'][0]['final_match_player_results'][0])1002 self.assertTrue('final_rank' not in round_dicts[0]['division_final_matches'][0]['final_match_player_results'][1]) 1003 self.assertEquals(round_dicts[0]['division_final_matches'][1]['final_match_player_results'][2]['final_rank'],21)1004 self.assertEquals(round_dicts[0]['division_final_matches'][1]['final_match_player_results'][3]['final_rank'],22) 1005 self.assertTrue('final_rank' not in round_dicts[1]['division_final_matches'][0]['final_match_player_results'][0])1006 self.assertTrue('final_rank' not in round_dicts[1]['division_final_matches'][1]['final_match_player_results'][1]) 1007 self.assertEquals(round_dicts[0]['division_final_matches'][2]['final_match_player_results'][2]['final_rank'],19)1008 self.assertEquals(round_dicts[0]['division_final_matches'][2]['final_match_player_results'][3]['final_rank'],20) 1009 self.assertTrue('final_rank' not in round_dicts[0]['division_final_matches'][2]['final_match_player_results'][0])1010 self.assertTrue('final_rank' not in round_dicts[0]['division_final_matches'][2]['final_match_player_results'][1]) 1011 self.assertEquals(round_dicts[0]['division_final_matches'][3]['final_match_player_results'][2]['final_rank'],17)1012 self.assertEquals(round_dicts[0]['division_final_matches'][3]['final_match_player_results'][3]['final_rank'],18) 1013 self.assertTrue('final_rank' not in round_dicts[0]['division_final_matches'][3]['final_match_player_results'][0])1014 self.assertTrue('final_rank' not in round_dicts[0]['division_final_matches'][3]['final_match_player_results'][1]) 1015 1016 def test_calculate_final_rankings_finals(self):1017 division_final=self.mock_app.tables.DivisionFinal()1018 division_final_round = self.generate_division_final_round_db_obj(2,with_players=False,num_matches=1) 1019 self.assertFalse(division_final_round.completed)1020 self.fill_in_bobo_rounds(division_final_round,None,num_matches=1)1021 1022 self.mock_app.tables.DivisionFinalRound.query.filter_by.return_value.first.return_value=None1023 self.mock_app.tables.DivisionFinalMatch.query.filter_by.return_value.all.return_value=None1024 #complete_round(division_final,division_final_round,self.mock_app)1025 division_final_round.completed=True1026 round_dicts = [division_final_round.to_dict_simple()]1027 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][0]['papa_points_sum']=41028 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][1]['papa_points_sum']=31029 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][2]['papa_points_sum']=21030 round_dicts[0]['division_final_matches'][0]['final_match_player_results'][3]['papa_points_sum']=11031 1032 calculate_final_rankings(round_dicts) 1033 self.assertEquals(round_dicts[0]['division_final_matches'][0]['final_match_player_results'][0]['final_rank'],1)1034 self.assertEquals(round_dicts[0]['division_final_matches'][0]['final_match_player_results'][1]['final_rank'],2)1035 self.assertEquals(round_dicts[0]['division_final_matches'][0]['final_match_player_results'][2]['final_rank'],3)1036 self.assertEquals(round_dicts[0]['division_final_matches'][0]['final_match_player_results'][3]['final_rank'],4)1037 # score1038 # tiebreakers1039 # round completed1040 1041 1042 def test_undo_final_round(self):1043 division_final=self.mock_app.tables.DivisionFinal()1044 division_final_round = self.generate_division_final_round_db_obj(1,num_matches=4) 1045 next_division_final_round = self.generate_division_final_round_db_obj(2,num_matches=4)1046 division_final_round.completed=True1047 next_division_final_round.completed=True1048 self.fill_in_bobo_rounds(division_final_round,None,num_matches=4)1049 self.fill_in_bobo_rounds(next_division_final_round,None,num_matches=4)1050 1051 for round in [division_final_round,next_division_final_round]:1052 for match in round.division_final_matches:1053 for player_result in match.final_match_player_results:1054 player_result.needs_tiebreaker=True1055 player_result.won_tiebreaker=True 1056 for game in match.final_match_game_results:1057 fake_score = 11058 for score in game.division_final_match_game_player_results:1059 score.score=fake_score1060 fake_score=fake_score+11061 undo_final_round([division_final_round,next_division_final_round],self.mock_app)1062 for round in [division_final_round,next_division_final_round]:1063 self.assertEquals(round.completed,False)1064 for match in round.division_final_matches:1065 for player_result in match.final_match_player_results:1066 self.assertEquals(player_result.needs_tiebreaker,False)1067 self.assertEquals(player_result.won_tiebreaker,None)1068 self.assertEquals(player_result.final_player_id,None) 1069 for game in match.final_match_game_results: 1070 for score in game.division_final_match_game_player_results:1071 self.assertEquals(score.score,None) 1072 self.assertEquals(score.final_player_id,None) ...
tests.py
Source:tests.py
1'''2matchmaker tests3'''4import json5import tempfile6from unittest import mock7from unittest.mock import patch8from django.test import TestCase, Client9from django.test.client import encode_multipart10from django.conf import settings11from django.forms.models import model_to_dict12import arrow13from PIL import Image14from google.cloud.language_v1.proto import language_service_pb215from google.api_core.exceptions import InvalidArgument16from userapp.tests import create_dummy_user17from matchmaker.models import Match, Category, Interest, Participation18from matchmaker.serializers import MatchSerializer19from matchmaker import nlp20BOUNDARY = 'BoUnDaRyStRiNg'21MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY22def create_dummy_category():23 '''create dummy category'''24 return Category.objects.create(name='TEST_NAME', indexes=[0])25def create_dummy_match(test_user, test_category):26 '''create dummy match'''27 return Match.objects.create(28 title='TEST_TITLE', category=test_category, host_user=test_user,29 capacity=4, location_text='TEST_LOCATION')30# pylint: disable=too-few-public-methods, no-self-use, unused-argument, invalid-name31class GoogleCloudLanguageMock:32 '''GoogleCloudLanguageMock'''33 class LanguageServiceClient:34 '''LanguageServiceClient'''35 # google_category_response = client.classify_text(document=document)36 def classify_text(self, document=None):37 '''classify_text'''38 category = language_service_pb2.ClassificationCategory(39 name='/Internet & Telecom/Mobile & Wireless',40 confidence=0.6100000143051147)41 response = language_service_pb2.ClassifyTextResponse(42 categories=[category])43 return response44 # google_analysis_response = client.analyze_entities(document=document)45 def analyze_entities(self, document=None):46 '''analyze_entities'''47 entity_location = language_service_pb2.Entity(48 name="Amphitheatre Pkwy", type=2)49 entity_event = language_service_pb2.Entity(50 name="Consumer Electronic Show", type=4)51 entity_address = language_service_pb2.Entity(52 name="Mountain View (1600 Amphitheatre Pkwy", type=10)53 response = language_service_pb2.AnalyzeEntitiesResponse(54 entities=[entity_location, entity_event, entity_address])55 return response56 class LanguageServiceClientEmpty:57 '''LanguageServiceClient'''58 # google_category_response = client.classify_text(document=document)59 def classify_text(self, document=None):60 '''classify_text'''61 return language_service_pb2.ClassifyTextResponse()62 # google_analysis_response = client.analyze_entities(document=document)63 def analyze_entities(self, document=None):64 '''analyze_entities'''65 entity_anything_else = language_service_pb2.Entity(66 name="Anything Else", type=3)67 return language_service_pb2.AnalyzeEntitiesResponse(entities=[entity_anything_else])68 class LanguageServiceClientInvalid:69 '''LanguageServiceClient'''70 # google_category_response = client.classify_text(document=document)71 def classify_text(self, document=None):72 '''classify_text'''73 raise InvalidArgument(74 'Invalid text content: too few tokens (words) to process.')75 '''76 document = types.Document(77 content=text,78 type=enums.Document.Type.PLAIN_TEXT)79 '''80 class types:81 '''types'''82 class Document:83 '''Document'''84 # enums.Document.Type.PLAIN_TEXT85 class enums:86 '''enums'''87 class Document:88 '''Document'''89 class Type:90 '''Type'''91 PLAIN_TEXT = ''92# pylint: enable=too-few-public-methods, no-self-use, unused-argument, invalid-name93class MatchMakerTestCase(TestCase):94 '''Tests for the app Matchmaker'''95 def setUp(self):96 pass97 def test_matchserializer(self):98 '''test match serializer'''99 client = Client(enforce_csrf_checks=True)100 response = client.get('/api/token/')101 csrftoken = response.cookies['csrftoken'].value102 test_user = create_dummy_user('TEST_EMAIL@test.com')103 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')104 test_category = create_dummy_category()105 test_match = create_dummy_match(test_user, test_category)106 with tempfile.NamedTemporaryFile(suffix='.jpg') as temp_file:107 test_image = Image.new('RGB', (100, 100))108 test_image.save(temp_file)109 temp_file.seek(0)110 form = encode_multipart(BOUNDARY, {111 'matchThumbnail': temp_file,112 'title': 'TEST_TITLE',113 'category': '0',114 'capacity': 5,115 'locationText': 'TEST_LOCATION_TEXT',116 'period': 3,117 'additionalInfo': 'TEST_ADDITIONAL_INFO',118 'isAgeRestricted': True,119 'restrictAgeFrom': 4,120 'restrictAgeTo': 7,121 'isGenderRestricted': True,122 'restrictedGender': settings.MALE,123 'timeBegin': '2019-11-03T08:07:46+09:00',124 'timeEnd': '2019-11-03T08:07:46+09:00',125 })126 response = client.post('/api/match/',127 data=form,128 content_type=MULTIPART_CONTENT,129 HTTP_X_CSRFTOKEN=csrftoken)130 self.assertEqual(response.status_code, 201)131 serializer = MatchSerializer(response.json(), data=response.json())132 self.assertEqual(serializer.is_valid(), True)133 self.assertEqual(serializer.data['num_participants'], 1)134 test_match_dict = model_to_dict(test_match)135 test_match_dict['category'] = test_category136 test_match_dict['host_user_id'] = test_user.id137 del test_match_dict['host_user']138 del test_match_dict['match_thumbnail']139 test_match_dict = {'id': 7, 'title': 'TEST_TITLE', 'category': test_category,140 'capacity': 4, 'location_text': 'TEST_LOCATION_TEXT',141 'period': 3, 'additional_info': 'TEST_ADDITIONAL_INFO',142 'is_age_restricted': True, 'restrict_age_from': 4,143 'restrict_age_to': 7, 'is_gender_restricted': True,144 'restricted_gender': True,145 'time_begin': arrow.get('2019-11-03T08:07:46+09:00').datetime,146 'time_end': arrow.get('2019-11-03T08:07:46+09:00').datetime,147 'host_user_id': test_user.id}148 serializer = MatchSerializer(test_match_dict, data=test_match_dict)149 self.assertEqual(serializer.is_valid(), True)150 self.assertEqual(serializer.data['num_participants'], 0)151 def test_category(self):152 '''test category'''153 dummy_category = create_dummy_category()154 self.assertEqual(dummy_category.__str__(), 'TEST_NAME')155 def test_http_response_404(self):156 '''Checks if the views module handles bad requests correctly.'''157 with tempfile.NamedTemporaryFile() as temp_file:158 client = Client(enforce_csrf_checks=True)159 response = client.get('/api/token/')160 csrftoken = response.cookies['csrftoken'].value161 create_dummy_user('TEST_EMAIL@test.com')162 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')163 # starts here164 form = encode_multipart(BOUNDARY, {165 "matchThumbnail": temp_file,166 'title': 'TEST_TITLE',167 'category': 9999,168 'capacity': 4,169 'locationText': 'TEST_LOCATION_TEXT',170 'period': 3,171 'additionalInfo': 'TEST_ADDITIONAL_INFO',172 'isAgeRestricted': True,173 'restrictAgeFrom': 4,174 'restrictAgeTo': 7,175 'isGenderRestricted': True,176 'restrictedGender': settings.MALE,177 'timeBegin': '2019-11-03T08:07:46+09:00',178 'timeEnd': '2019-11-03T08:07:46+09:00',179 })180 response = client.post('/api/match/',181 data=form,182 content_type=MULTIPART_CONTENT,183 HTTP_X_CSRFTOKEN=csrftoken)184 self.assertEqual(response.status_code, 404)185 response = client.post(f'/api/match/9999/join/',186 HTTP_X_CSRFTOKEN=csrftoken)187 self.assertEqual(response.status_code, 404)188 # starts here189 response = client.get('/api/match/2/', HTTP_X_CSRFTOKEN=csrftoken)190 self.assertEqual(response.status_code, 404)191 def test_http_response_405(self):192 '''Checks if the views module handles bad requests correctly.'''193 client = Client(enforce_csrf_checks=True)194 response = client.get('/api/token/')195 csrftoken = response.cookies['csrftoken'].value196 test_category = create_dummy_category()197 test_user = create_dummy_user('TEST_EMAIL@test.com')198 test_match = create_dummy_match(test_user, test_category)199 # add signup&signin here when implemented200 # starts here201 response = client.delete('/api/match/', HTTP_X_CSRFTOKEN=csrftoken)202 self.assertEqual(response.status_code, 405)203 response = client.delete('/api/match/new/', HTTP_X_CSRFTOKEN=csrftoken)204 self.assertEqual(response.status_code, 405)205 response = client.delete('/api/match/hot/', HTTP_X_CSRFTOKEN=csrftoken)206 self.assertEqual(response.status_code, 405)207 response = client.delete(208 '/api/match/recommend/', HTTP_X_CSRFTOKEN=csrftoken)209 self.assertEqual(response.status_code, 405)210 response = client.delete('/api/match/search',211 HTTP_X_CSRFTOKEN=csrftoken)212 self.assertEqual(response.status_code, 405)213 response = client.put('/api/match/3/',214 json.dumps({'title': 'TEST_TITLE', }),215 content_type='application/json',216 HTTP_X_CSRFTOKEN=csrftoken)217 self.assertEqual(response.status_code, 405)218 response = client.put(f'/api/match/{test_match.id}/join/',219 HTTP_X_CSRFTOKEN=csrftoken)220 self.assertEqual(response.status_code, 405)221 response = client.delete(f'/api/match/nlp/',222 HTTP_X_CSRFTOKEN=csrftoken)223 self.assertEqual(response.status_code, 405)224 def test_http_response_401(self):225 '''Checks if the views module handles malformed requests correctly.'''226 client = Client(enforce_csrf_checks=True)227 response = client.get('/api/token/')228 csrftoken = response.cookies['csrftoken'].value229 test_category = create_dummy_category()230 test_user = create_dummy_user('TEST_EMAIL@test.com')231 test_match = create_dummy_match(test_user, test_category)232 # starts here233 response = client.post(f'/api/match/{test_match.id}/join/',234 HTTP_X_CSRFTOKEN=csrftoken)235 self.assertEqual(response.status_code, 401)236 def test_http_response_400(self):237 '''Checks if the views module handles malformed requests correctly.'''238 client = Client(enforce_csrf_checks=True)239 response = client.get('/api/token/')240 csrftoken = response.cookies['csrftoken'].value241 test_category = create_dummy_category()242 test_user = create_dummy_user('TEST_EMAIL@test.com')243 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')244 test_match = create_dummy_match(test_user, test_category)245 # starts here246 response = client.post('/api/match/',247 json.dumps({'x': 'hello', 'y': 'match'}),248 content_type='application/json',249 HTTP_X_CSRFTOKEN=csrftoken)250 self.assertEqual(response.status_code, 400)251 response = client.post('/api/match/',252 json.dumps({'title': 'TEST_TITLE',253 'category': '0',254 'capacity': 'TEST_ERR_STR',255 'locationText': 'TEST_LOCATION_TEXT',256 'period': 'TEST_ERR_STR',257 'additionalInfo': 'TEST_ADDITIONAL_INFO',258 'isAgeRestricted': 'TEST_ERR_STR',259 'restrictAgeFrom': 'TEST_ERR_STR',260 'restrictAgeTo': 'TEST_ERR_STR',261 'isGenderRestricted': 'TEST_ERR_STR',262 'restrictedGender': settings.MALE,263 'timeBegin': '2019-11-03T08:07:46+09:00',264 'timeEnd': '2019-11-03T08:07:46+09:00', }),265 content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken)266 self.assertEqual(response.status_code, 400)267###############268 with tempfile.NamedTemporaryFile() as temp_file:269 form = encode_multipart(BOUNDARY, {270 'matchThumbnail': temp_file,271 'title': 'TEST_TITLE',272 'category': '0',273 'capacity': 5,274 'locationText': 'TEST_LOCATION_TEXT',275 'period': 3,276 'additionalInfo': 'TEST_ADDITIONAL_INFO',277 'isAgeRestricted': True,278 'restrictAgeFrom': 4,279 'restrictAgeTo': 7,280 'isGenderRestricted': True,281 'restrictedGender': settings.MALE,282 'timeBegin': '2019-11-03T08:07:46+09:00',283 'timeEnd': '2019-11-03T08:07:46+09:00',284 })285 response = client.post('/api/match/',286 data=form,287 content_type=MULTIPART_CONTENT,288 HTTP_X_CSRFTOKEN=csrftoken)289 self.assertEqual(response.status_code, 400)290 response = client.post(f'/api/match/{test_match.id}/',291 json.dumps({'title': 'TEST_TITLE',292 'category': '0',293 'capacity': 'TEST_ERR_STR',294 'locationText': 'TEST_LOCATION_TEXT',295 'period': 'TEST_ERR_STR',296 'additionalInfo': 'TEST_ADDITIONAL_INFO',297 'isAgeRestricted': 'TEST_ERR_STR',298 'restrictAgeFrom': 'TEST_ERR_STR',299 'restrictAgeTo': 'TEST_ERR_STR',300 'isGenderRestricted': 'TEST_ERR_STR',301 'restrictedGender': settings.MALE,302 'timeBegin': '2019-11-03T08:07:46+09:00',303 'timeEnd': '2019-11-03T08:07:46+09:00', }),304 content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken)305 self.assertEqual(response.status_code, 400)306 response = client.post(f'/api/match/{test_match.id}/',307 json.dumps({'x': 'hello', 'y': 'match'}),308 content_type='application/json',309 HTTP_X_CSRFTOKEN=csrftoken)310 self.assertEqual(response.status_code, 400)311 response = client.post('/api/match/nlp/',312 json.dumps({'x': 'hello'}),313 content_type='application/json',314 HTTP_X_CSRFTOKEN=csrftoken)315 self.assertEqual(response.status_code, 400)316 def test_match(self):317 '''Checks if the views module handles various match-related requests correctly.'''318 with tempfile.NamedTemporaryFile(suffix='.jpg') as temp_file:319 test_image = Image.new('RGB', (100, 100))320 test_image.save(temp_file)321 temp_file.seek(0)322 client = Client(enforce_csrf_checks=True)323 response = client.get('/api/token/')324 csrftoken = response.cookies['csrftoken'].value325 test_user = create_dummy_user('TEST_EMAIL@test.com')326 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')327 test_category = create_dummy_category()328 test_match = Match.objects.create(329 title='TEST_TITLE', host_user=test_user, category=test_category)330 self.assertEqual(test_match.__str__(), 'TEST_TITLE')331 form = encode_multipart(BOUNDARY, {332 'matchThumbnail': temp_file,333 'title': 'TEST_TITLE',334 'category': '0',335 'capacity': 4,336 'locationText': 'TEST_LOCATION_TEXT',337 'period': 3,338 'additionalInfo': 'TEST_ADDITIONAL_INFO',339 'isAgeRestricted': True,340 'restrictAgeFrom': 4,341 'restrictAgeTo': 7,342 'isGenderRestricted': True,343 'restrictedGender': settings.MALE,344 'timeBegin': '2019-11-03T08:07:46+09:00',345 'timeEnd': '2019-11-03T08:07:46+09:00',346 })347 response = client.post('/api/match/',348 data=form,349 content_type=MULTIPART_CONTENT,350 HTTP_X_CSRFTOKEN=csrftoken)351 self.assertEqual(response.status_code, 201)352 match_id = response.json()['id']353 response = client.get(354 f'/api/match/{match_id}/', HTTP_X_CSRFTOKEN=csrftoken)355 match = response.json()356 self.assertEqual(response.status_code, 200)357 self.assertEqual(match['title'], 'TEST_TITLE')358 self.assertEqual(match['category']['indexes'], '[0]')359 test_match = Match.objects.get(id=match_id)360 self.assertEqual(test_match.view_count, 1)361 response = client.get(362 f'/api/match/{match_id}/', HTTP_X_CSRFTOKEN=csrftoken)363 self.assertEqual(test_match.view_count, 1)364 with tempfile.NamedTemporaryFile(suffix='.jpg') as temp_file:365 test_image = Image.new('RGB', (100, 100))366 test_image.save(temp_file)367 temp_file.seek(0)368 response = client.post(f'/api/match/{match_id}/',369 data=form,370 content_type=MULTIPART_CONTENT,371 HTTP_X_CSRFTOKEN=csrftoken)372 self.assertEqual(response.status_code, 200)373 form = encode_multipart(BOUNDARY, {374 'title': 'TEST_TITLE',375 'category': '0',376 'capacity': 5,377 'locationText': 'TEST_LOCATION_TEXT',378 'period': 3,379 'additionalInfo': 'TEST_ADDITIONAL_INFO',380 'isAgeRestricted': True,381 'restrictAgeFrom': 4,382 'restrictAgeTo': 7,383 'isGenderRestricted': True,384 'restrictedGender': settings.MALE,385 'timeBegin': '2019-11-03T08:07:46+09:00',386 'timeEnd': '2019-11-03T08:07:46+09:00',387 })388 response = client.post(f'/api/match/{match_id}/',389 data=form,390 content_type=MULTIPART_CONTENT,391 HTTP_X_CSRFTOKEN=csrftoken)392 self.assertEqual(response.status_code, 200)393 with tempfile.NamedTemporaryFile() as temp_file:394 form = encode_multipart(BOUNDARY, {395 'matchThumbnail': temp_file,396 'title': 'TEST_TITLE',397 'category': '0',398 'capacity': 5,399 'locationText': 'TEST_LOCATION_TEXT',400 'period': 3,401 'additionalInfo': 'TEST_ADDITIONAL_INFO',402 'isAgeRestricted': True,403 'restrictAgeFrom': 4,404 'restrictAgeTo': 7,405 'isGenderRestricted': True,406 'restrictedGender': settings.MALE,407 'timeBegin': '2019-11-03T08:07:46+09:00',408 'timeEnd': '2019-11-03T08:07:46+09:00',409 })410 response = client.post(f'/api/match/{match_id}/',411 data=form,412 content_type=MULTIPART_CONTENT,413 HTTP_X_CSRFTOKEN=csrftoken)414 self.assertEqual(response.status_code, 400)415 client2 = Client()416 response = client2.post(f'/api/match/{match_id}/',417 data=form,418 content_type=MULTIPART_CONTENT,419 HTTP_X_CSRFTOKEN=csrftoken)420 self.assertEqual(response.status_code, 403)421 @patch.object(nlp, 'enums', mock.Mock(side_effect=GoogleCloudLanguageMock.enums))422 @patch.object(nlp, 'types', mock.Mock(side_effect=GoogleCloudLanguageMock.types))423 @patch.object(nlp, 'LanguageServiceClient',424 mock.Mock(side_effect=GoogleCloudLanguageMock.LanguageServiceClient))425 def test_nlp(self):426 '''Checks if nlp query works correctly.'''427 client = Client(enforce_csrf_checks=True)428 response = client.get('/api/token/')429 csrftoken = response.cookies['csrftoken'].value430 create_dummy_user('TEST_EMAIL@test.com')431 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')432 response = client.post('/api/match/nlp/', json.dumps({433 'nlp_text': 'Google, headquartered in Mountain View'}),434 content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken)435 self.assertEqual(response.status_code, 200)436 response = client.post('/api/match/nlp/', json.dumps({437 'nlp_text': 'Google, headquartered in Mountain View (1600 Amphitheatre '438 'Pkwy, Mountain View, CA 940430), unveiled the new Android phone for $799'439 ' at the Consumer Electronic Show. Sundar Pichai said in his keynote that'440 ' users love their new Android phones.'}),441 content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken)442 response_dict = json.loads(response.content.decode())443 self.assertEqual(response_dict['categories'],444 [{'name': '/Internet & Telecom/Mobile & Wireless',445 'confidence': 0.6100000143051147}])446 self.assertEqual(response_dict['locations'],447 [{'name': 'Amphitheatre Pkwy', 'type': 'LOCATION'}])448 self.assertEqual(response_dict['events'],449 [{'name': 'Consumer Electronic Show', 'type': 'EVENT'}])450 @patch.object(nlp, 'enums', mock.Mock(side_effect=GoogleCloudLanguageMock.enums))451 @patch.object(nlp, 'types', mock.Mock(side_effect=GoogleCloudLanguageMock.types))452 @patch.object(nlp, 'LanguageServiceClient',453 mock.Mock(side_effect=GoogleCloudLanguageMock.LanguageServiceClientEmpty))454 def test_nlp_empty(self):455 '''Checks if the empty nlp response is handled correctly.'''456 client = Client(enforce_csrf_checks=True)457 response = client.get('/api/token/')458 csrftoken = response.cookies['csrftoken'].value459 create_dummy_user('TEST_EMAIL@test.com')460 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')461 response = client.post('/api/match/nlp/', json.dumps({462 'nlp_text': 'Google, headquartered in Mountain View (1600 Amphitheatre '463 'Pkwy, Mountain View, CA 940430), unveiled the new Android phone for $799'464 ' at the Consumer Electronic Show. Sundar Pichai said in his keynote that'465 ' users love their new Android phones.'}),466 content_type='application/json', HTTP_X_CSRFTOKEN=csrftoken)467 self.assertEqual(response.status_code, 200)468 @patch.object(nlp, 'enums', mock.Mock(side_effect=GoogleCloudLanguageMock.enums))469 @patch.object(nlp, 'types', mock.Mock(side_effect=GoogleCloudLanguageMock.types))470 @patch.object(nlp, 'LanguageServiceClient',471 mock.Mock(side_effect=GoogleCloudLanguageMock.LanguageServiceClientInvalid))472 def test_nlp_invalid_argument(self):473 '''Checks if the invalid argument error is handled correctly.'''474 client = Client()475 response = client.get('/api/token/')476 csrftoken = response.cookies['csrftoken'].value477 create_dummy_user('TEST_EMAIL@test.com')478 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')479 response = client.post('/api/match/nlp/', json.dumps({'nlp_text': ' '}),480 content_type='application/json',481 HTTP_X_CSRFOKEN=csrftoken)482 self.assertEqual(response.status_code, 200)483 response_dict = json.loads(response.content.decode())484 self.assertEqual(response_dict['categories'], [{'name': ''}])485 self.assertEqual(response_dict['locations'], [{'name': ''}])486 self.assertEqual(response_dict['events'], [{'name': ''}])487 response = client.post('/api/match/nlp/', json.dumps({'nlp_text': 'Another Invalid Text'}),488 content_type='application/json',489 HTTP_X_CSRFOKEN=csrftoken)490 self.assertEqual(response.status_code, 200)491 def test_search(self):492 '''Checks if the views module handles search query correctly.'''493 client = Client(enforce_csrf_checks=True)494 test_user = create_dummy_user('TEST_EMAIL@test.com')495 test_category = create_dummy_category()496 create_dummy_match(test_user, test_category)497 response = client.get('/api/match/search?query=TEST_TITLE&category=0')498 self.assertEqual(len(json.loads(response.content.decode())), 1)499 response = client.get('/api/match/search?query=TEST_TITLE')500 self.assertEqual(len(json.loads(response.content.decode())), 1)501 response = client.get('/api/match/search?category=0')502 self.assertEqual(len(json.loads(response.content.decode())), 1)503 response = client.get('/api/match/search')504 self.assertEqual(len(json.loads(response.content.decode())), 1)505 def test_match_new(self):506 '''Checks if get_new_match performs correctly.'''507 client = Client()508 test_user = create_dummy_user('TEST_EMAIL@test.com')509 test_category = create_dummy_category()510 create_dummy_match(test_user, test_category)511 response = client.get('/api/match/new/')512 self.assertEqual(len(json.loads(response.content.decode())), 1)513 def test_match_hot(self):514 '''Checks if get_hot_match performs correctly.'''515 client = Client()516 test_user = create_dummy_user('TEST_EMAIL@test.com')517 test_category = create_dummy_category()518 create_dummy_match(test_user, test_category)519 response = client.get('/api/match/hot/')520 self.assertEqual(len(json.loads(response.content.decode())), 1)521 def test_match_recommend(self):522 '''Checks if get_recommend_match performs correctly.'''523 client = Client()524 test_user = create_dummy_user('TEST_EMAIL@test.com')525 test_user_2 = create_dummy_user('TEST_SECOND_EMAIL@test.com')526 test_category = create_dummy_category()527 test_match = create_dummy_match(test_user_2, test_category)528 response = client.get('/api/match/recommend/')529 self.assertEqual(response.status_code, 401)530 client.login(email='TEST_SECOND_EMAIL@test.com',531 password='TEST_PASSWORD')532 Interest.objects.create(user=test_user_2, category=test_category)533 Participation.objects.create(match=test_match, user=test_user_2)534 response = client.get('/api/match/recommend/')535 self.assertEqual(len(json.loads(response.content.decode())), 0)536 client.logout()537 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')538 response = client.get('/api/match/recommend/')539 self.assertEqual(len(json.loads(response.content.decode())), 0)540 Interest.objects.create(user=test_user, category=test_category)541 Interest.objects.create(user=test_user, category=test_category)542 response = client.get('/api/match/recommend/')543 self.assertEqual(len(json.loads(response.content.decode())), 1)544 def test_match_join(self):545 '''Checks if match_join performs correctly.'''546 client = Client(enforce_csrf_checks=True)547 response = client.get('/api/token/')548 csrftoken = response.cookies['csrftoken'].value549 test_user = create_dummy_user('TEST_EMAIL@test.com')550 create_dummy_user('TEST_SECOND_EMAIL@test.com')551 test_category = create_dummy_category()552 test_match = create_dummy_match(test_user, test_category)553 # quit not authenticated554 response = client.delete(f'/api/match/{test_match.id}/join/',555 HTTP_X_CSRFTOKEN=csrftoken)556 self.assertEqual(response.status_code, 401)557 # not host user558 client.login(email='TEST_SECOND_EMAIL@test.com',559 password='TEST_PASSWORD')560 response = client.post(f'/api/match/{test_match.id}/join/',561 HTTP_X_CSRFTOKEN=csrftoken)562 self.assertEqual(response.status_code, 200)563 # quit and delete participation564 response = client.delete(f'/api/match/{test_match.id}/join/',565 HTTP_X_CSRFTOKEN=csrftoken)566 self.assertEqual(response.status_code, 200)567 # host user568 client.logout()569 client.login(email='TEST_EMAIL@test.com', password='TEST_PASSWORD')570 response = client.get('/api/token/')571 csrftoken = response.cookies['csrftoken'].value572 response = client.post(f'/api/match/{test_match.id}/join/',573 HTTP_X_CSRFTOKEN=csrftoken)574 # quit and delete match575 response = client.delete(f'/api/match/{test_match.id}/join/',576 HTTP_X_CSRFTOKEN=csrftoken)...
main.py
Source:main.py
1import numpy as np2import cv23import time4import matplotlib.pyplot as plt5import gzip6import random7from keras.datasets import mnist8from tensorflow import keras9from tensorflow.keras import layers10def first_weird_work():11 file = './data/train-images-idx3-ubyte.gz'12 f = gzip.open(file,'r')13 image_size = 2814 num_images = 515 f.read(16)16 buf = f.read(image_size * image_size * num_images)17 data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)18 data = data.reshape(num_images, image_size, image_size, 1)19 image = np.asarray(data[2]).squeeze()20 plt.imshow(image)21 plt.show()22def another_read():23 (train_X, train_y), (test_X, test_y) = mnist.load_data()24 test_X = test_X[:50]25 print('X_train: ' + str(train_X.shape))26 print('Y_train: ' + str(train_y.shape))27 print('X_test: ' + str(test_X.shape))28 print('Y_test: ' + str(test_y.shape))29 test_halves = []30 train_halves = []31 test_match_dict = {}32 train_match_dict = {}33 cut_ammount = 134 train_y = train_y[:int(len(train_y)/cut_ammount)]35 for i in range(int(len(train_X)/cut_ammount)):36 image = np.array(train_X[i])37 first_half, second_half = np.hsplit(image,[14])38 train_halves.append(first_half)39 train_halves.append(second_half)40 train_match_dict[len(train_halves) - 1] = len(train_halves) - 241 train_match_dict[len(train_halves) - 2] = len(train_halves) - 142 # plt.imshow(first_half)43 # plt.show()44 for i in range(len(test_X)):45 image = np.array(train_X[i])46 first_half, second_half = np.hsplit(image, [14])47 test_halves.append(first_half)48 test_halves.append(second_half)49 test_match_dict[len(test_halves) - 1] = len(test_halves) - 250 test_match_dict[len(test_halves) - 2] = len(test_halves) - 151 return test_halves, train_halves, test_match_dict, train_match_dict, train_y52def solve_by_random(train_halves):53 results_dict = {}54 idx_list = list(range(len(train_halves)))55 while len(idx_list) > 0:56 idx1 = idx_list[random.randrange(0, len(idx_list))]57 idx_list.remove(idx1)58 idx2 = idx_list[random.randrange(0, len(idx_list))]59 idx_list.remove(idx2)60 results_dict[idx1] = [idx2]61 results_dict[idx2] = [idx1]62 return results_dict63def get_difference(img1, img2):64 total_diff = 065 for x_index in range(len(img1)):66 val1 = int(img1[x_index][-1])67 val2 = int(img2[x_index][0])68 diff = abs(val1 - val2)69 total_diff += diff70 return total_diff71def solve_by_difference(train_halves):72 results_dict = {}73 results_dict_extended = {}74 for idx in range(len(train_halves)):75 min_diff = 100000076 min_idy = 077 all_diffs = []78 for idy in range(len(train_halves)):79 if idx != idy:80 diff = get_difference(train_halves[idx], train_halves[idy])81 if diff < min_diff and diff >= 1:82 min_diff = diff83 min_idy = idy84 all_diffs.append([diff, idy])85 all_diffs.sort(key = lambda x:x[0], reverse = False)86 all_diffs = all_diffs[:30]87 results_dict[idx] = [min_idy]88 results_dict[min_idy] = [idx]89 for el in all_diffs:90 if el[1] not in results_dict_extended:91 results_dict_extended[el[1]] = [idx]92 else:93 results_dict_extended[el[1]].append(idx)94 if idx not in results_dict_extended:95 results_dict_extended[idx] = [el[1]]96 else:97 results_dict_extended[idx].append(el[1])98 return results_dict, results_dict_extended99def compare_results(orig_dict, result_dict):100 count = len(orig_dict.keys())101 correct_guesses = 0.0102 false_guesses = 0.0103 for key in orig_dict.keys():104 if key not in result_dict.keys():105 false_guesses += 1106 else:107 if orig_dict[key] in result_dict[key]:108 correct_guesses += 1109 else:110 false_guesses += 1111 print("No of data points: ", count)112 print(" We have an accuracy of: ", correct_guesses/count)113def train_model(train_x, train_y):114 x_train = np.array(train_x)115 y_train = train_y116 num_classes = 10117 input_shape = (28, 14, 1)118 print('X_train: ' + str(x_train.shape))119 print('Y_train: ' + str(y_train.shape))120 x_train = x_train.astype("float32") / 255121 x_train = np.expand_dims(x_train, -1)122 print("x_train shape:", x_train.shape)123 print(x_train.shape[0], "train samples")124 y_train = keras.utils.to_categorical(y_train, num_classes)125 model = keras.Sequential(126 [127 keras.Input(shape=input_shape),128 layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),129 layers.MaxPooling2D(pool_size=(2, 2)),130 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),131 layers.MaxPooling2D(pool_size=(2, 2)),132 layers.Flatten(),133 layers.Dropout(0.5),134 layers.Dense(num_classes, activation="softmax"),135 ]136 )137 model.summary()138 batch_size = 128139 epochs = 15140 model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])141 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=0.1)142 return model143def is_left(image):144 if np.sum(image[:, 0]) > 1:145 return False146 return True147def solve_by_model(train_halves, train_y, test_halves, results_dict_extended):148 train_halves1 = [train_halves[i * 2] for i in range(int(len(train_halves)/2))]149 train_halves2 = [train_halves[i * 2 + 1] for i in range(int(len(train_halves)/2))]150 model_left = train_model(train_halves1, train_y)151 model_right = train_model(train_halves2, train_y)152 for key in list(results_dict_extended.keys()):153 # print("key: ", key)154 if is_left(test_halves[key]):155 label_orig = model_left.predict(test_halves[key].reshape((1, 28, 14, 1)))[0]156 # print("orig:", label_orig)157 for current_sec in results_dict_extended[key]:158 label_sec = model_right.predict(test_halves[current_sec].reshape((1, 28, 14, 1)))[0]159 # print("sec:", label_sec)160 if not list(label_sec) == list(label_orig):161 results_dict_extended[key].remove(current_sec)162 results_dict_extended[current_sec].remove(key)163 else:164 label_orig = model_right.predict(test_halves[key].reshape((1, 28, 14, 1)))[0]165 # print("orig:", label_orig)166 for current_sec in results_dict_extended[key]:167 label_sec = model_left.predict(test_halves[current_sec].reshape((1, 28, 14, 1)))[0]168 # print("sec:", label_sec)169 if not list(label_sec) == list(label_orig):170 results_dict_extended[key].remove(current_sec)171 results_dict_extended[current_sec].remove(key)172 result_dict = {}173 topx = 5174 for key in list(results_dict_extended.keys()):175 if results_dict_extended[key] == []:176 del results_dict_extended[key]177 print("DELETED A DATA POINT")178 elif len(results_dict_extended[key]) >= topx:179 results_dict_extended[key] = results_dict_extended[key][:topx]180 result_dict[key] = [results_dict_extended[key][0]]181 else:182 print("TOO FEW CHOICES IN A DATA POINT")183 print(result_dict)184 print(results_dict_extended)185 return result_dict, results_dict_extended186def main():187 print("_" * 10)188 print("Reading data points..")189 test_halves, train_halves, test_match_dict, train_match_dict,train_y = another_read()190 # random method usually gets close to 0 correct results191 print("_" * 10)192 print("Solving by random method..")193 result_dict = solve_by_random(test_halves)194 # difference method usually gets close to 0 correct results195 print("_" * 10)196 print("Solving by difference method..")197 result_dict, results_dict_extended = solve_by_difference(test_halves)198 # this method get 10-25% right on first choice , 41-75% right on top three199 print("_" * 10)200 print("Calculating extended results..")201 compare_results(test_match_dict, results_dict_extended)202 print("Calculating results..")203 compare_results(test_match_dict, result_dict)204 # train a simple model205 result_dict, results_dict_extended = solve_by_model(train_halves, train_y, test_halves, results_dict_extended)206 # this improved method get 25% right on first choice , 58-70% right on top three/ five207 print("_" * 10)208 print("Calculating extended results..")209 compare_results(test_match_dict, results_dict_extended)210 print("Calculating results..")211 compare_results(test_match_dict, result_dict)212 debug(results_dict_extended, train_halves)213def debug(results,train_halves):214 for key in list(results.keys())[:7]:215 print("original:")216 plt.imshow(train_halves[key])217 plt.show()218 print("first choice:")219 plt.imshow(train_halves[results[key][0]])220 plt.show()221 print("second choice:")222 plt.imshow(train_halves[results[key][1]])223 plt.show()224 print("third choice:")225 plt.imshow(train_halves[results[key][2]])226 plt.show()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!