Best JavaScript code snippet using pact-foundation-pact
Test.py
Source:Test.py
1############################################################2###Test.py Chess Test file ### 3###Written by Nicholas Maselli ### 4### ### 5###Purpose: Thoroughly tests the chess engine. ###6### ###7###Version: 1.0 ###8###Date: 6-30-17 ###9############################################################10from chess import Chess1112class Test():13 def test_Chess():14 chess = Chess() 15 correctCount = 016 print('Testing the __init__() function')17 18 #Test 119 correctOutput = 'Board size: 8'20 givenOutput = 'Board size: {}'.format(chess.size)21 if (correctOutput == givenOutput):22 print('Test 1: Correct')23 correctCount += 124 else:25 print('Test 1: Incorrect')26 print('Correct output:\n{}'.format(correctOutput))27 print('Given output:\n{}'.format(givenOutput))28 print()29 30 #Test 231 correctOutput = ('rnbqkbnr\n'32 'pppppppp\n'33 '········\n'34 '········\n'35 '········\n'36 '········\n'37 'PPPPPPPP\n'38 'RNBQKBNR\n')39 givenOutput = Test.boardString(chess) 40 if (correctOutput == givenOutput):41 print('Test 2: Correct')42 correctCount += 143 else:44 print('Test 2: Incorrect')45 print('Correct output:\n{}'.format(correctOutput))46 print('Given output:\n{}'.format(givenOutput))47 print() 48 49 #Test 350 correctOutput = 'P: ((-1, 0), (-2, 0), (-1, -1), (-1, 1))'51 givenOutput = 'P: {}'.format(chess.directions['P'])52 if (correctOutput == givenOutput):53 print('Test 3: Correct')54 correctCount += 155 else:56 print('Test 3: Incorrect')57 print('Correct output:\n{}'.format(correctOutput))58 print('Given output:\n{}'.format(givenOutput))59 print()60 61 #Test 462 correctOutput = 'R: ((-1, 0), (0, 1), (1, 0), (0, -1))'63 givenOutput = 'R: {}'.format(chess.directions['R'])64 if (correctOutput == givenOutput):65 print('Test 4: Correct')66 correctCount += 167 else:68 print('Test 4: Incorrect')69 print('Correct output:\n{}'.format(correctOutput))70 print('Given output:\n{}'.format(givenOutput))71 print()72 73 #Test 574 correctOutput = 'N: ((-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1))'75 givenOutput = 'N: {}'.format(chess.directions['N'])76 if (correctOutput == givenOutput):77 print('Test 5: Correct')78 correctCount += 179 else:80 print('Test 5: Incorrect')81 print('Correct output:\n{}'.format(correctOutput))82 print('Given output:\n{}'.format(givenOutput))83 print() 84 85 #Test 686 correctOutput = 'B: ((-1, 1), (1, 1), (1, -1), (-1, -1))'87 givenOutput = 'B: {}'.format(chess.directions['B'])88 if (correctOutput == givenOutput):89 print('Test 6: Correct')90 correctCount += 191 else:92 print('Test 6: Incorrect')93 print('Correct output:\n{}'.format(correctOutput))94 print('Given output:\n{}'.format(givenOutput))95 print()96 97 #Test 7 98 correctOutput = 'Q: ((-1, 0), (0, 1), (1, 0), (0, -1), (-1, 1), (1, 1), (1, -1), (-1, -1))'99 givenOutput = 'Q: {}'.format(chess.directions['Q'])100 if (correctOutput == givenOutput):101 print('Test 7: Correct')102 correctCount += 1103 else:104 print('Test 7: Incorrect')105 print('Correct output:\n{}'.format(correctOutput))106 print('Given output:\n{}'.format(givenOutput))107 print()108 109 #Test 8110 correctOutput = 'K: ((-1, 0), (0, 1), (1, 0), (0, -1), (-1, 1), (1, 1), (1, -1), (-1, -1))'111 givenOutput = 'K: {}'.format(chess.directions['K'])112 if (correctOutput == givenOutput):113 print('Test 8: Correct')114 correctCount += 1115 else:116 print('Test 8: Incorrect')117 print('Correct output:\n{}'.format(correctOutput))118 print('Given output:\n{}'.format(givenOutput))119 print()120 121 print('{} correct tests out of 8'.format(correctCount))122 print()123 124 #Testing the move_piece() function125 def test_move_piece():126 chess = Chess()127 128 correctCount = 0129 print('Testing the move_piece() function')130 131 #Test 1132 move = 'e2e4'133 coordinateMove = chess.notation_to_coordinate(move) 134 chess.move_piece(coordinateMove) 135 136 correctOutput = ('RNBQKBNR\n'137 'PPPP·PPP\n'138 '········\n'139 '····P···\n'140 '········\n'141 '········\n'142 'pppppppp\n'143 'rnbqkbnr\n')144 givenOutput = Test.boardString(chess)145 if (correctOutput == givenOutput):146 print('Test 1: Correct')147 correctCount += 1148 else:149 print('Test 1: Incorrect')150 print('Correct output:\n{}'.format(correctOutput))151 print('Given output:\n{}'.format(givenOutput))152 print()153 154 #Test 2155 move = 'b1c3'156 coordinateMove = chess.notation_to_coordinate(move) 157 chess.move_piece(coordinateMove)158 159 correctOutput = ('r·bqkbnr\n'160 'pppppppp\n'161 '··n·····\n'162 '········\n'163 '····P···\n'164 '········\n'165 'PPPP·PPP\n'166 'RNBQKBNR\n')167 givenOutput = Test.boardString(chess)168 if (correctOutput == givenOutput):169 print('Test 2: Correct')170 correctCount += 1171 else:172 print('Test 2: Incorrect')173 print('Correct output:\n{}'.format(correctOutput))174 print('Given output:\n{}'.format(givenOutput))175 print()176 177 #Test 3178 move = 'd2d4'179 coordinateMove = chess.notation_to_coordinate(move)180 chess.move_piece(coordinateMove)181 182 move = 'e2e4'183 coordinateMove = chess.notation_to_coordinate(move) 184 chess.move_piece(coordinateMove)185 186 move = 'd1d3'187 coordinateMove = chess.notation_to_coordinate(move) 188 chess.move_piece(coordinateMove)189 190 correctOutput = ('RNB·KBNR\n'191 'PPP··PPP\n'192 '···Q····\n'193 '···PP···\n'194 '····p···\n'195 '··n·····\n'196 'pppp·ppp\n'197 'r·bqkbnr\n')198 199 givenOutput = Test.boardString(chess)200 if (correctOutput == givenOutput):201 print('Test 3: Correct')202 correctCount += 1203 else:204 print('Test 3: Incorrect')205 print('Correct output:\n{}'.format(correctOutput))206 print('Given output:\n{}'.format(givenOutput))207 print()208 209 #Test 4210 move = 'f1c4'211 coordinateMove = chess.notation_to_coordinate(move)212 chess.move_piece(coordinateMove)213 214 correctOutput = ('r·bqk·nr\n'215 'pppp·ppp\n'216 '··n·····\n'217 '··b·p···\n'218 '···PP···\n'219 '···Q····\n'220 'PPP··PPP\n'221 'RNB·KBNR\n')222 223 givenOutput = Test.boardString(chess)224 if (correctOutput == givenOutput):225 print('Test 4: Correct')226 correctCount += 1227 else:228 print('Test 4: Incorrect')229 print('Correct output:\n{}'.format(correctOutput))230 print('Given output:\n{}'.format(givenOutput))231 print()232 233 #Test 5 Castle234 move = 'c1d2'235 coordinateMove = chess.notation_to_coordinate(move) 236 chess.move_piece(coordinateMove)237 238 move = 'g1h3'239 coordinateMove = chess.notation_to_coordinate(move) 240 chess.move_piece(coordinateMove)241 242 move = 'b1c3'243 coordinateMove = chess.notation_to_coordinate(move) 244 chess.move_piece(coordinateMove)245 246 #black castle247 move = 'e1g1'248 coordinateMove = chess.notation_to_coordinate(move) 249 chess.move_piece(coordinateMove)250 251 #white castle252 move = 'e1c1'253 coordinateMove = chess.notation_to_coordinate(move) 254 chess.move_piece(coordinateMove)255 256 correctOutput = ('··KR·BNR\n'257 'PPPB·PPP\n'258 '··NQ····\n'259 '···PP···\n'260 '··b·p···\n'261 '··n····n\n'262 'pppp·ppp\n'263 'r·bq·rk·\n')264 265 givenOutput = Test.boardString(chess)266 if (correctOutput == givenOutput):267 print('Test 5: Correct')268 correctCount += 1269 else:270 print('Test 5: Incorrect')271 print('Correct output:\n{}'.format(correctOutput))272 print('Given output:\n{}'.format(givenOutput))273 print()274 275 #Reset Chess board276 chess = Chess()277 278 #Test 6 Pre Pawn promotion279 280 move = 'b2b4'281 coordinateMove = chess.notation_to_coordinate(move) 282 chess.move_piece(coordinateMove)283 284 move = 'b2b7'285 coordinateMove = chess.notation_to_coordinate(move) 286 chess.move_piece(coordinateMove)287 288 move = 'b1a3'289 coordinateMove = chess.notation_to_coordinate(move) 290 chess.move_piece(coordinateMove) 291 292 correctOutput = ('R·BQKBNR\n'293 'PpPPPPPP\n'294 'N·······\n'295 '·P······\n'296 '········\n'297 '········\n'298 'p·pppppp\n'299 'rnbqkbnr\n')300 301 givenOutput = Test.boardString(chess)302 if (correctOutput == givenOutput):303 print('Test 6: Correct')304 correctCount += 1305 else:306 print('Test 6: Incorrect')307 print('Correct output:\n{}'.format(correctOutput))308 print('Given output:\n{}'.format(givenOutput))309 print()310 311 #Test 7: Pawn Promotion312 move = 'b7b8'313 coordinateMove = chess.notation_to_coordinate(move) 314 chess.move_piece(coordinateMove) 315 316 correctOutput = ('rnbqkbnr\n'317 'p·pppppp\n'318 '········\n'319 '········\n'320 '·P······\n'321 'N·······\n'322 'P·PPPPPP\n'323 'RqBQKBNR\n')324 givenOutput = Test.boardString(chess)325 if (correctOutput == givenOutput):326 print('Test 7: Correct')327 correctCount += 1328 else:329 print('Test 7: Incorrect')330 print('Correct output:\n{}'.format(correctOutput))331 print('Given output:\n{}'.format(givenOutput))332 print()333 334 #Reset Chessboard335 chess = Chess()336 337 #Test 8: Castle Status338 move = 'e2e4'339 coordinateMove = chess.notation_to_coordinate(move) 340 chess.move_piece(coordinateMove) 341 342 correctOutput = '[True, True], [True, True]'343 givenOutput = '{}, {}'.format(str(chess.state.white_castle), str(chess.state.black_castle))344 if (correctOutput == givenOutput):345 print('Test 8: Correct')346 correctCount += 1347 else:348 print('Test 8: Incorrect')349 print('Correct output:\n{}'.format(correctOutput))350 print('Given output:\n{}'.format(givenOutput))351 print()352 353 #Test 9: En passant Status 354 correctOutput = '[(3, 3), (3, 5)]'355 givenOutput = '{}'.format(str(chess.state.en_passant))356 if (correctOutput == givenOutput):357 print('Test 9: Correct')358 correctCount += 1359 else:360 print('Test 9: Incorrect')361 print('Correct output:\n{}'.format(correctOutput))362 print('Given output:\n{}'.format(givenOutput))363 print()364 365 #Test 10: Rotate board (now in move) ensuring checking status doesnt mess this up366 correctOutput = ('RNBQKBNR\n'367 'PPPP·PPP\n'368 '········\n'369 '····P···\n'370 '········\n'371 '········\n'372 'pppppppp\n'373 'rnbqkbnr\n')374 375 givenOutput = Test.boardString(chess)376 if (correctOutput == givenOutput):377 print('Test 10: Correct')378 correctCount += 1379 else:380 print('Test 10: Incorrect')381 print('Correct output:\n{}'.format(correctOutput))382 print('Given output:\n{}'.format(givenOutput))383 print()384 385 #Test 11: Move piece on rotated board386 move = 'e2e4'387 coordinateMove = chess.notation_to_coordinate(move) 388 chess.move_piece(coordinateMove) 389 correctOutput = ('rnbqkbnr\n'390 'pppp·ppp\n'391 '········\n'392 '····p···\n'393 '····P···\n'394 '········\n'395 'PPPP·PPP\n'396 'RNBQKBNR\n')397 398 givenOutput = Test.boardString(chess)399 if (correctOutput == givenOutput):400 print('Test 11: Correct')401 correctCount += 1402 else:403 print('Test 11: Incorrect')404 print('Correct output:\n{}'.format(correctOutput))405 print('Given output:\n{}'.format(givenOutput))406 print()407 408 #Test 12: Move king, check castle criteria409 move = 'e1e2'410 coordinateMove = chess.notation_to_coordinate(move) 411 chess.move_piece(coordinateMove)412 413 correctOutput = '[False, False], [True, True]' 414 givenOutput = '{}, {}'.format(chess.state.white_castle, chess.state.black_castle)415 if (correctOutput == givenOutput):416 print('Test 12: Correct')417 correctCount += 1418 else:419 print('Test 12: Incorrect')420 print('Correct output:\n{}'.format(correctOutput))421 print('Given output:\n{}'.format(givenOutput))422 print()423 424 #Reset board425 chess = Chess()426 427 #Test 13: Move king on rest board, check castle criteria428 move = 'e2e4'429 coordinateMove = chess.notation_to_coordinate(move) 430 chess.move_piece(coordinateMove)431 432 move = 'd2d4'433 coordinateMove = chess.notation_to_coordinate(move) 434 chess.move_piece(coordinateMove)435 436 move = 'e4d5'437 coordinateMove = chess.notation_to_coordinate(move) 438 chess.move_piece(coordinateMove)439 440 move = 'e1e2'441 coordinateMove = chess.notation_to_coordinate(move) 442 chess.move_piece(coordinateMove)443 444 correctOutput = '[True, True], [False, False]' 445 givenOutput = '{}, {}'.format(chess.state.white_castle, chess.state.black_castle)446 if (correctOutput == givenOutput):447 print('Test 13: Correct')448 correctCount += 1449 else:450 print('Test 13: Incorrect')451 print('Correct output:\n{}'.format(correctOutput))452 print('Given output:\n{}'.format(givenOutput))453 print()454 455 #Reset board456 chess = Chess()457 458 #Test 14: Check turn 459 correctOutput = 'white' 460 givenOutput = '{}'.format(chess.state.turn)461 if (correctOutput == givenOutput):462 print('Test 14: Correct')463 correctCount += 1464 else:465 print('Test 14: Incorrect')466 print('Correct output:\n{}'.format(correctOutput))467 print('Given output:\n{}'.format(givenOutput))468 print()469 470 #Test 15: rotate, move piece check turn471 move = 'b1c3' 472 coordinateMove = chess.notation_to_coordinate(move)473 chess.move_piece(coordinateMove)474 475 correctOutput = 'black' 476 givenOutput = '{}'.format(chess.state.turn)477 if (correctOutput == givenOutput):478 print('Test 15: Correct')479 correctCount += 1480 else:481 print('Test 15: Incorrect')482 print('Correct output:\n{}'.format(correctOutput))483 print('Given output:\n{}'.format(givenOutput))484 print()485 486 #Reset board487 chess = Chess()488 489 #Test 16: En passant kept through rotate490 move = 'e2e5'491 coordinateMove = chess.notation_to_coordinate(move) 492 chess.move_piece(coordinateMove) 493 494 move = 'c1e3'495 coordinateMove = chess.notation_to_coordinate(move) 496 chess.move_piece(coordinateMove)497 498 move = 'd2d4'499 coordinateMove = chess.notation_to_coordinate(move) 500 chess.move_piece(coordinateMove) 501 502 correctOutput = '[(3, 2), (3, 4)]'503 givenOutput = '{}'.format(str(chess.state.en_passant))504 if (correctOutput == givenOutput):505 print('Test 16: Correct')506 correctCount += 1507 else:508 print('Test 16: Incorrect')509 print('Correct output:\n{}'.format(correctOutput))510 print('Given output:\n{}'.format(givenOutput))511 print()512 513 #Test 17: Make move, rotate, check enpassant 514 move = 'b1c3'515 coordinateMove = chess.notation_to_coordinate(move) 516 chess.move_piece(coordinateMove) 517 518 correctOutput = '[]'519 givenOutput = '{}'.format(str(chess.state.en_passant))520 if (correctOutput == givenOutput):521 print('Test 17: Correct')522 correctCount += 1523 else:524 print('Test 17: Incorrect')525 print('Correct output:\n{}'.format(correctOutput))526 print('Given output:\n{}'.format(givenOutput))527 print()528 529 #Test 18 actually perform the previous en passant530 chess = Chess()531 532 move = 'e2e5'533 coordinateMove = chess.notation_to_coordinate(move) 534 chess.move_piece(coordinateMove)535 536 move = 'd2d4'537 coordinateMove = chess.notation_to_coordinate(move) 538 chess.move_piece(coordinateMove)539 540 move = 'e5d6' 541 coordinateMove = chess.notation_to_coordinate(move) 542 chess.move_piece(coordinateMove)543 544 correctOutput = ('RNBQKBNR\n'545 'PPPP·PPP\n'546 '········\n'547 '········\n'548 '········\n'549 '···P····\n'550 'ppp·pppp\n'551 'rnbqkbnr\n')552 givenOutput = Test.boardString(chess)553 if (correctOutput == givenOutput):554 print('Test 18: Correct')555 correctCount += 1556 else:557 print('Test 18: Incorrect')558 print('Correct output:\n{}'.format(correctOutput))559 print('Given output:\n{}'.format(givenOutput))560 print()561 562 #Reset Board563 chess = Chess()564 565 #Test 19: En passant next to a wall566 move = 'a2a5'567 coordinateMove = chess.notation_to_coordinate(move)568 chess.move_piece(coordinateMove) 569 570 move = 'b2b4'571 coordinateMove = chess.notation_to_coordinate(move) 572 chess.move_piece(coordinateMove)573 574 move = 'a5b6'575 coordinateMove = chess.notation_to_coordinate(move) 576 chess.move_piece(coordinateMove)577 578 correctOutput = ('RNBQKBNR\n'579 '·PPPPPPP\n'580 '········\n'581 '········\n'582 '········\n'583 '·P······\n'584 'p·pppppp\n'585 'rnbqkbnr\n')586 587 givenOutput = Test.boardString(chess)588 if (correctOutput == givenOutput):589 print('Test 19: Correct')590 correctCount += 1591 else:592 print('Test 19: Incorrect')593 print('Correct output:\n{}'.format(correctOutput))594 print('Given output:\n{}'.format(givenOutput))595 print() 596 597 #Test 20: Take opponents rook and check castle 598 chess = Chess()599 600 move = 'h2h3' 601 coordinateMove = chess.notation_to_coordinate(move) 602 chess.move_piece(coordinateMove)603 604 move = 'd1h8'605 coordinateMove = chess.notation_to_coordinate(move) 606 chess.move_piece(coordinateMove)607 608 correctOutput = ('[True, False], [True, True]')609 givenOutput = '{}, {}'.format(chess.state.white_castle, chess.state.black_castle) 610 if (correctOutput == givenOutput):611 print('Test 20: Correct')612 correctCount += 1613 else:614 print('Test 20: Incorrect')615 print('Correct output:\n{}'.format(correctOutput))616 print('Given output:\n{}'.format(givenOutput))617 618 #Test 21: Test castle if other rook moves619 move = 'a1a3'620 coordinateMove = chess.notation_to_coordinate(move) 621 chess.move_piece(coordinateMove)622 623 move = 'a1h1'624 coordinateMove = chess.notation_to_coordinate(move) 625 chess.move_piece(coordinateMove)626 627 correctOutput = ('[False, False], [False, True]')628 givenOutput = '{}, {}'.format(chess.state.white_castle, chess.state.black_castle) 629 if (correctOutput == givenOutput):630 print('Test 21: Correct')631 correctCount += 1632 else:633 print('Test 21: Incorrect')634 print('Correct output:\n{}'.format(correctOutput))635 print('Given output:\n{}'.format(givenOutput))636 637 print('{} correct tests out of 21'.format(correctCount))638 print()639 640 #Testing the value in the move_piece() function641 def test_value():642 chess = Chess()643 644 correctCount = 0645 print('Testing the value in the move_piece() function')646 647 #Test 1 starting board values648 correctOutput = (23905, 23905, 0) 649 givenOutput = (chess.state.white_value, chess.state.black_value, chess.state.value)650 if (correctOutput == givenOutput):651 print('Test 1: Correct')652 correctCount += 1653 else:654 print('Test 1: Incorrect')655 print('Correct output:\n{}'.format(correctOutput))656 print('Given output:\n{}'.format(givenOutput))657 print()658 659 #Test 2 starting board values660 chess = Chess()661 662 move = 'e2e4' 663 coordinateMove = chess.notation_to_coordinate(move) 664 chess.move_piece(coordinateMove)665 666 correctOutput = (23945, 23905, 40) 667 givenOutput = (chess.state.white_value, chess.state.black_value, chess.state.value)668 if (correctOutput == givenOutput):669 print('Test 2: Correct')670 correctCount += 1671 else:672 print('Test 2: Incorrect')673 print('Correct output:\n{}'.format(correctOutput))674 print('Given output:\n{}'.format(givenOutput))675 print()676 677 #Test 3 starting board values678 move = 'e2e4' 679 coordinateMove = chess.notation_to_coordinate(move) 680 chess.move_piece(coordinateMove)681 682 correctOutput = (23945, 23945, 0) 683 givenOutput = (chess.state.white_value, chess.state.black_value, chess.state.value)684 if (correctOutput == givenOutput):685 print('Test 3: Correct')686 correctCount += 1687 else:688 print('Test 3: Incorrect')689 print('Correct output:\n{}'.format(correctOutput))690 print('Given output:\n{}'.format(givenOutput))691 print()692 693 print('{} correct tests out of 3'.format(correctCount))694 print()695 696 #Testing gen_moves function697 def test_gen_moves():698 chess = Chess()699 700 correctCount = 0701 print('Testing the gen_moves() function')702 703 #Test 1704 correctOutput = ("((6, 0), (5, 0))\n"705 "((6, 0), (4, 0))\n"706 "((6, 1), (5, 1))\n"707 "((6, 1), (4, 1))\n"708 "((6, 2), (5, 2))\n"709 "((6, 2), (4, 2))\n"710 "((6, 3), (5, 3))\n"711 "((6, 3), (4, 3))\n"712 "((6, 4), (5, 4))\n"713 "((6, 4), (4, 4))\n"714 "((6, 5), (5, 5))\n"715 "((6, 5), (4, 5))\n"716 "((6, 6), (5, 6))\n"717 "((6, 6), (4, 6))\n"718 "((6, 7), (5, 7))\n"719 "((6, 7), (4, 7))\n"720 "((7, 1), (5, 2))\n"721 "((7, 1), (5, 0))\n"722 "((7, 6), (5, 7))\n"723 "((7, 6), (5, 5))\n")724 725 givenOutput = ''726 for moves in chess.gen_moves():727 givenOutput += str(moves)728 givenOutput += '\n'729 if (correctOutput == givenOutput):730 print('Test 1: Correct')731 correctCount += 1732 else:733 print('Test 1: Incorrect')734 print('Correct output:\n{}'.format(correctOutput))735 print('Given output:\n{}'.format(givenOutput))736 print()737 738 #Test 2 739 move = 'b1c3' 740 coordinateMove = chess.notation_to_coordinate(move) 741 chess.move_piece(coordinateMove)742 743 744 correctOutput = ("((6, 0), (5, 0))\n"745 "((6, 0), (4, 0))\n"746 "((6, 1), (5, 1))\n"747 "((6, 1), (4, 1))\n"748 "((6, 2), (5, 2))\n"749 "((6, 2), (4, 2))\n"750 "((6, 3), (5, 3))\n"751 "((6, 3), (4, 3))\n"752 "((6, 4), (5, 4))\n"753 "((6, 4), (4, 4))\n"754 "((6, 5), (5, 5))\n"755 "((6, 5), (4, 5))\n"756 "((6, 6), (5, 6))\n"757 "((6, 6), (4, 6))\n"758 "((6, 7), (5, 7))\n"759 "((6, 7), (4, 7))\n"760 "((7, 1), (5, 2))\n"761 "((7, 1), (5, 0))\n"762 "((7, 6), (5, 7))\n"763 "((7, 6), (5, 5))\n")764 givenOutput = ''765 for moves in chess.gen_moves():766 givenOutput += str(moves)767 givenOutput += '\n'768 if (correctOutput == givenOutput):769 print('Test 2: Correct')770 correctCount += 1771 else:772 print('Test 2: Incorrect')773 print('Correct output:\n{}'.format(correctOutput))774 print('Given output:\n{}'.format(givenOutput))775 print()776 777 #Test 3:778 move = 'e2e4' 779 coordinateMove = chess.notation_to_coordinate(move) 780 chess.move_piece(coordinateMove)781 782 783 correctOutput = ("((5, 2), (3, 3))\n"784 "((5, 2), (4, 4))\n"785 "((5, 2), (7, 1))\n"786 "((5, 2), (4, 0))\n"787 "((5, 2), (3, 1))\n"788 "((6, 0), (5, 0))\n"789 "((6, 0), (4, 0))\n"790 "((6, 1), (5, 1))\n"791 "((6, 1), (4, 1))\n"792 "((6, 3), (5, 3))\n"793 "((6, 3), (4, 3))\n"794 "((6, 4), (5, 4))\n"795 "((6, 4), (4, 4))\n"796 "((6, 5), (5, 5))\n"797 "((6, 5), (4, 5))\n"798 "((6, 6), (5, 6))\n"799 "((6, 6), (4, 6))\n"800 "((6, 7), (5, 7))\n"801 "((6, 7), (4, 7))\n"802 "((7, 0), (7, 1))\n"803 "((7, 6), (5, 7))\n"804 "((7, 6), (5, 5))\n")805 givenOutput = ''806 for moves in chess.gen_moves():807 givenOutput += str(moves)808 givenOutput += '\n'809 if (correctOutput == givenOutput):810 print('Test 3: Correct')811 correctCount += 1812 else:813 print('Test 3: Incorrect')814 print('Correct output:\n{}'.format(correctOutput))815 print('Given output:\n{}'.format(givenOutput))816 print()817 818 #Test 4:819 move = 'd2d4'820 coordinateMove = chess.notation_to_coordinate(move) 821 chess.move_piece(coordinateMove) 822 823 correctOutput = ("((4, 4), (3, 4))\n"824 "((4, 4), (3, 3))\n"825 "((6, 0), (5, 0))\n"826 "((6, 0), (4, 0))\n"827 "((6, 1), (5, 1))\n"828 "((6, 1), (4, 1))\n"829 "((6, 2), (5, 2))\n"830 "((6, 2), (4, 2))\n"831 "((6, 3), (5, 3))\n"832 "((6, 3), (4, 3))\n"833 "((6, 5), (5, 5))\n"834 "((6, 5), (4, 5))\n"835 "((6, 6), (5, 6))\n"836 "((6, 6), (4, 6))\n"837 "((6, 7), (5, 7))\n"838 "((6, 7), (4, 7))\n"839 "((7, 1), (5, 2))\n"840 "((7, 1), (5, 0))\n"841 "((7, 3), (6, 4))\n"842 "((7, 3), (5, 5))\n"843 "((7, 3), (4, 6))\n"844 "((7, 3), (3, 7))\n"845 "((7, 4), (6, 4))\n"846 "((7, 5), (6, 4))\n"847 "((7, 5), (5, 3))\n"848 "((7, 5), (4, 2))\n"849 "((7, 5), (3, 1))\n"850 "((7, 5), (2, 0))\n"851 "((7, 6), (5, 7))\n"852 "((7, 6), (6, 4))\n"853 "((7, 6), (5, 5))\n")854 givenOutput = ''855 for moves in chess.gen_moves():856 givenOutput += str(moves)857 givenOutput += '\n'858 if (correctOutput == givenOutput):859 print('Test 4: Correct')860 correctCount += 1861 else:862 print('Test 4: Incorrect')863 print('Correct output:\n{}'.format(correctOutput))864 print('Given output:\n{}'.format(givenOutput))865 print()866 867 #Test 5:868 move = 'e4d5'869 coordinateMove = chess.notation_to_coordinate(move) 870 chess.move_piece(coordinateMove)871 872 873 correctOutput = ("((5, 2), (3, 3))\n"874 "((5, 2), (4, 4))\n"875 "((5, 2), (7, 1))\n"876 "((5, 2), (4, 0))\n"877 "((5, 2), (3, 1))\n"878 "((6, 0), (5, 0))\n"879 "((6, 0), (4, 0))\n"880 "((6, 1), (5, 1))\n"881 "((6, 1), (4, 1))\n"882 "((6, 4), (5, 4))\n"883 "((6, 4), (4, 4))\n"884 "((6, 5), (5, 5))\n"885 "((6, 5), (4, 5))\n"886 "((6, 6), (5, 6))\n"887 "((6, 6), (4, 6))\n"888 "((6, 7), (5, 7))\n"889 "((6, 7), (4, 7))\n"890 "((7, 0), (7, 1))\n"891 "((7, 2), (6, 3))\n"892 "((7, 2), (5, 4))\n"893 "((7, 2), (4, 5))\n"894 "((7, 2), (3, 6))\n"895 "((7, 2), (2, 7))\n"896 "((7, 3), (6, 3))\n"897 "((7, 3), (5, 3))\n"898 "((7, 3), (4, 3))\n"899 "((7, 4), (6, 3))\n"900 "((7, 6), (5, 7))\n"901 "((7, 6), (5, 5))\n")902 givenOutput = ''903 for moves in chess.gen_moves():904 givenOutput += str(moves)905 givenOutput += '\n'906 if (correctOutput == givenOutput):907 print('Test 5: Correct')908 correctCount += 1909 else:910 print('Test 5: Incorrect')911 print('Correct output:\n{}'.format(correctOutput))912 print('Given output:\n{}'.format(givenOutput))913 print()914 915 #Test 6: Queen takes pawn d1d4916 move = 'd1d4'917 coordinateMove = chess.notation_to_coordinate(move) 918 chess.move_piece(coordinateMove)919 920 921 correctOutput = ("((6, 0), (5, 0))\n"922 "((6, 0), (4, 0))\n"923 "((6, 1), (5, 1))\n"924 "((6, 1), (4, 1))\n"925 "((6, 2), (5, 2))\n"926 "((6, 2), (4, 2))\n"927 "((6, 3), (5, 3))\n"928 "((6, 3), (4, 3))\n"929 "((6, 5), (5, 5))\n"930 "((6, 5), (4, 5))\n"931 "((6, 6), (5, 6))\n"932 "((6, 6), (4, 6))\n"933 "((6, 7), (5, 7))\n"934 "((6, 7), (4, 7))\n"935 "((7, 1), (5, 2))\n"936 "((7, 1), (5, 0))\n"937 "((7, 3), (6, 4))\n"938 "((7, 3), (5, 5))\n"939 "((7, 3), (4, 6))\n"940 "((7, 3), (3, 7))\n"941 "((7, 4), (6, 4))\n"942 "((7, 5), (6, 4))\n"943 "((7, 5), (5, 3))\n"944 "((7, 5), (4, 2))\n"945 "((7, 5), (3, 1))\n"946 "((7, 5), (2, 0))\n"947 "((7, 6), (5, 7))\n"948 "((7, 6), (6, 4))\n"949 "((7, 6), (5, 5))\n")950 givenOutput = ''951 for moves in chess.gen_moves():952 givenOutput += str(moves)953 givenOutput += '\n'954 if (correctOutput == givenOutput):955 print('Test 6: Correct')956 correctCount += 1957 else:958 print('Test 6: Incorrect')959 print('Correct output:\n{}'.format(correctOutput))960 print('Given output:\n{}'.format(givenOutput))961 print()962 963 print('{} correct tests out of 6'.format(correctCount))964 print()965 966 #Testing generating opponent's attaks967 def test_gen_check_attacks():968 chess = Chess()969 970 correctCount = 0971 print('Testing the gen_check_attacks() function')972 973 #Test 1974 correctOutput = ('(0, 1): [[((0, 0), (0, 1)), (0, 1), 0, None]]\n'975 '(0, 2): [[((0, 3), (0, 2)), (0, -1), 0, None]]\n'976 '(0, 3): [[((0, 4), (0, 3)), (0, -1), 0, None]]\n'977 '(0, 4): [[((0, 3), (0, 4)), (0, 1), 0, None]]\n'978 '(0, 5): [[((0, 4), (0, 5)), (0, 1), 0, None]]\n'979 '(0, 6): [[((0, 7), (0, 6)), (0, -1), 0, None]]\n'980 '(1, 0): [[((0, 0), (1, 0)), (1, 0), 0, None]]\n'981 '(1, 1): [[((0, 2), (1, 1)), (1, -1), 0, None]]\n'982 '(1, 2): [[((0, 3), (1, 2)), (1, -1), 0, None]]\n'983 '(1, 3): [[((0, 1), (1, 3)), (1, 2), 0, None], [((0, 2), (1, 3)), (1, 1), 0, None], [((0, 3), (1, 3)), (1, 0), 0, None], [((0, 4), (1, 3)), (1, -1), 0, None]]\n'984 '(1, 4): [[((0, 3), (1, 4)), (1, 1), 0, None], [((0, 4), (1, 4)), (1, 0), 0, None], [((0, 5), (1, 4)), (1, -1), 0, None], [((0, 6), (1, 4)), (1, -2), 0, None]]\n'985 '(1, 5): [[((0, 4), (1, 5)), (1, 1), 0, None]]\n'986 '(1, 6): [[((0, 5), (1, 6)), (1, 1), 0, None]]\n'987 '(1, 7): [[((0, 7), (1, 7)), (1, 0), 0, None]]\n'988 '(2, 0): [[((0, 1), (2, 0)), (2, -1), 0, None], [((1, 1), (2, 0)), (1, -1), 0, None]]\n'989 '(2, 1): [[((1, 0), (2, 1)), (1, 1), 0, None], [((1, 2), (2, 1)), (1, -1), 0, None]]\n'990 '(2, 2): [[((0, 1), (2, 2)), (2, 1), 0, None], [((1, 1), (2, 2)), (1, 1), 0, None], [((1, 3), (2, 2)), (1, -1), 0, None]]\n'991 '(2, 3): [[((1, 2), (2, 3)), (1, 1), 0, None], [((1, 4), (2, 3)), (1, -1), 0, None]]\n'992 '(2, 4): [[((1, 3), (2, 4)), (1, 1), 0, None], [((1, 5), (2, 4)), (1, -1), 0, None]]\n'993 '(2, 5): [[((0, 6), (2, 5)), (2, -1), 0, None], [((1, 4), (2, 5)), (1, 1), 0, None], [((1, 6), (2, 5)), (1, -1), 0, None]]\n'994 '(2, 6): [[((1, 5), (2, 6)), (1, 1), 0, None], [((1, 7), (2, 6)), (1, -1), 0, None]]\n'995 '(2, 7): [[((0, 6), (2, 7)), (2, 1), 0, None], [((1, 6), (2, 7)), (1, 1), 0, None]]\n')996 997 input_dict = chess.gen_check_attacks()998 givenOutput = ''999 for key in sorted(input_dict):1000 givenOutput += '{}: '.format(key)1001 givenOutput += str(input_dict[key])1002 givenOutput += '\n'1003 1004 if (correctOutput == givenOutput):1005 print('Test 1: Correct')1006 correctCount += 11007 else:1008 print('Test 1: Incorrect')1009 print('Correct output:\n{}'.format(correctOutput))1010 print('Given output:\n{}'.format(givenOutput))1011 print()1012 1013 #Test 21014 move = 'e2e4'1015 coordinateMove = chess.notation_to_coordinate(move) 1016 chess.move_piece(coordinateMove) 1017 1018 1019 move = 'e2e4'1020 coordinateMove = chess.notation_to_coordinate(move) 1021 chess.move_piece(coordinateMove) 1022 1023 1024 move = 'a2a4'1025 coordinateMove = chess.notation_to_coordinate(move) 1026 chess.move_piece(coordinateMove) 1027 1028 1029 move = 'd1e2'1030 coordinateMove = chess.notation_to_coordinate(move) 1031 chess.move_piece(coordinateMove) 1032 1033 1034 move = 'h2h3'1035 coordinateMove = chess.notation_to_coordinate(move) 1036 chess.move_piece(coordinateMove) 1037 1038 1039 move = 'd2d4'1040 coordinateMove = chess.notation_to_coordinate(move) 1041 chess.move_piece(coordinateMove) 1042 1043 1044 correctOutput = ('(0, 1): [[((0, 0), (0, 1)), (0, 1), 0, None]]\n'1045 '(0, 3): [[((0, 4), (0, 3)), (0, -1), 0, None], [((1, 4), (0, 3)), (-1, -1), 0, None]]\n'1046 '(0, 4): [[((1, 4), (0, 4)), (-1, 0), 0, None]]\n'1047 '(0, 5): [[((0, 4), (0, 5)), (0, 1), 0, None], [((1, 4), (0, 5)), (-1, 1), 0, None]]\n'1048 '(0, 6): [[((0, 7), (0, 6)), (0, -1), 0, None]]\n'1049 '(1, 0): [[((0, 0), (1, 0)), (1, 0), 0, None]]\n'1050 '(1, 1): [[((0, 2), (1, 1)), (1, -1), 0, None]]\n'1051 '(1, 2): [[((1, 4), (1, 2)), (0, -1), 0, None]]\n'1052 '(1, 3): [[((0, 1), (1, 3)), (1, 2), 0, None], [((0, 2), (1, 3)), (1, 1), 0, None], [((0, 4), (1, 3)), (1, -1), 0, None], [((1, 4), (1, 3)), (0, -1), 0, None]]\n'1053 '(1, 4): [[((0, 4), (1, 4)), (1, 0), 0, None], [((0, 5), (1, 4)), (1, -1), 0, None], [((0, 6), (1, 4)), (1, -2), 0, None]]\n'1054 '(1, 5): [[((0, 4), (1, 5)), (1, 1), 0, None], [((1, 4), (1, 5)), (0, 1), 0, None]]\n'1055 '(1, 6): [[((0, 5), (1, 6)), (1, 1), 0, None]]\n'1056 '(1, 7): [[((0, 7), (1, 7)), (1, 0), 0, None]]\n'1057 '(2, 0): [[((0, 1), (2, 0)), (2, -1), 0, None], [((1, 1), (2, 0)), (1, -1), 0, None]]\n'1058 '(2, 1): [[((1, 0), (2, 1)), (1, 1), 0, None], [((1, 2), (2, 1)), (1, -1), 0, None]]\n'1059 '(2, 2): [[((0, 1), (2, 2)), (2, 1), 0, None], [((1, 1), (2, 2)), (1, 1), 0, None]]\n'1060 '(2, 3): [[((1, 2), (2, 3)), (1, 1), 0, None], [((1, 4), (2, 3)), (1, -1), 0, None]]\n'1061 '(2, 4): [[((0, 2), (2, 4)), (1, 1), 0, None], [((1, 4), (2, 4)), (1, 0), 0, None], [((1, 5), (2, 4)), (1, -1), 0, None]]\n'1062 '(2, 5): [[((0, 6), (2, 5)), (2, -1), 0, None], [((1, 4), (2, 5)), (1, 1), 0, None], [((1, 6), (2, 5)), (1, -1), 0, None]]\n'1063 '(2, 6): [[((1, 5), (2, 6)), (1, 1), 0, None], [((1, 7), (2, 6)), (1, -1), 0, None]]\n'1064 '(2, 7): [[((0, 6), (2, 7)), (2, 1), 0, None], [((1, 6), (2, 7)), (1, 1), 0, None]]\n'1065 '(3, 2): [[((1, 4), (3, 2)), (1, -1), 0, None]]\n'1066 '(3, 4): [[((1, 4), (3, 4)), (1, 0), 0, None]]\n'1067 '(3, 5): [[((0, 2), (3, 5)), (1, 1), 0, None]]\n'1068 '(3, 6): [[((1, 4), (3, 6)), (1, 1), 0, None]]\n'1069 '(4, 1): [[((1, 4), (4, 1)), (1, -1), 0, None]]\n'1070 '(4, 2): [[((3, 3), (4, 2)), (1, -1), 0, None]]\n'1071 '(4, 3): [[((3, 4), (4, 3)), (1, -1), 0, None]]\n'1072 '(4, 4): [[((3, 3), (4, 4)), (1, 1), 0, None]]\n'1073 '(4, 5): [[((3, 4), (4, 5)), (1, 1), 0, None]]\n'1074 '(4, 6): [[((0, 2), (4, 6)), (1, 1), 0, None]]\n'1075 '(4, 7): [[((1, 4), (4, 7)), (1, 1), 0, None]]\n'1076 '(5, 0): [[((1, 4), (5, 0)), (1, -1), 0, None]]\n'1077 '(5, 7): [[((0, 2), (5, 7)), (1, 1), 1, (5, 7)]]\n')10781079 input_dict = chess.gen_check_attacks()1080 givenOutput = ''1081 for key in sorted(input_dict):1082 givenOutput += '{}: '.format(key)1083 givenOutput += str(input_dict[key])1084 givenOutput += '\n'1085 1086 if (correctOutput == givenOutput):1087 print('Test 2: Correct')1088 correctCount += 11089 else:1090 print('Test 2: Incorrect')1091 print('Correct output:\n{}'.format(correctOutput))1092 print('Given output:\n{}'.format(givenOutput))1093 print()1094 1095 #Test 31096 move = 'd2d4'1097 coordinateMove = chess.notation_to_coordinate(move) 1098 chess.move_piece(coordinateMove) 1099 1100 1101 move = 'e4d5'1102 coordinateMove = chess.notation_to_coordinate(move) 1103 chess.move_piece(coordinateMove) 1104 1105 1106 correctOutput = ('(0, 1): [[((0, 0), (0, 1)), (0, 1), 0, None]]\n'1107 '(0, 3): [[((0, 4), (0, 3)), (0, -1), 0, None], [((1, 4), (0, 3)), (-1, -1), 0, None]]\n'1108 '(0, 4): [[((1, 4), (0, 4)), (-1, 0), 0, None]]\n'1109 '(0, 5): [[((0, 4), (0, 5)), (0, 1), 0, None], [((1, 4), (0, 5)), (-1, 1), 0, None]]\n'1110 '(0, 6): [[((0, 7), (0, 6)), (0, -1), 0, None]]\n'1111 '(1, 0): [[((0, 0), (1, 0)), (1, 0), 0, None]]\n'1112 '(1, 1): [[((0, 2), (1, 1)), (1, -1), 0, None]]\n'1113 '(1, 2): [[((1, 4), (1, 2)), (0, -1), 0, None]]\n'1114 '(1, 3): [[((0, 1), (1, 3)), (1, 2), 0, None], [((0, 2), (1, 3)), (1, 1), 0, None], [((0, 4), (1, 3)), (1, -1), 0, None], [((1, 4), (1, 3)), (0, -1), 0, None]]\n'1115 '(1, 4): [[((0, 4), (1, 4)), (1, 0), 0, None], [((0, 5), (1, 4)), (1, -1), 0, None], [((0, 6), (1, 4)), (1, -2), 0, None]]\n'1116 '(1, 5): [[((0, 4), (1, 5)), (1, 1), 0, None], [((1, 4), (1, 5)), (0, 1), 0, None]]\n'1117 '(1, 6): [[((0, 5), (1, 6)), (1, 1), 0, None]]\n'1118 '(1, 7): [[((0, 7), (1, 7)), (1, 0), 0, None]]\n'1119 '(2, 0): [[((0, 1), (2, 0)), (2, -1), 0, None], [((1, 1), (2, 0)), (1, -1), 0, None]]\n'1120 '(2, 1): [[((1, 0), (2, 1)), (1, 1), 0, None], [((1, 2), (2, 1)), (1, -1), 0, None]]\n'1121 '(2, 2): [[((0, 1), (2, 2)), (2, 1), 0, None], [((1, 1), (2, 2)), (1, 1), 0, None]]\n'1122 '(2, 3): [[((1, 2), (2, 3)), (1, 1), 0, None], [((1, 4), (2, 3)), (1, -1), 0, None]]\n'1123 '(2, 4): [[((0, 2), (2, 4)), (1, 1), 0, None], [((1, 4), (2, 4)), (1, 0), 0, None], [((1, 5), (2, 4)), (1, -1), 0, None]]\n'1124 '(2, 5): [[((0, 6), (2, 5)), (2, -1), 0, None], [((1, 4), (2, 5)), (1, 1), 0, None], [((1, 6), (2, 5)), (1, -1), 0, None]]\n'1125 '(2, 6): [[((1, 5), (2, 6)), (1, 1), 0, None], [((1, 7), (2, 6)), (1, -1), 0, None]]\n'1126 '(2, 7): [[((0, 6), (2, 7)), (2, 1), 0, None], [((1, 6), (2, 7)), (1, 1), 0, None]]\n'1127 '(3, 2): [[((1, 4), (3, 2)), (1, -1), 0, None]]\n'1128 '(3, 4): [[((1, 4), (3, 4)), (1, 0), 0, None]]\n'1129 '(3, 5): [[((0, 2), (3, 5)), (1, 1), 0, None]]\n'1130 '(3, 6): [[((1, 4), (3, 6)), (1, 1), 0, None]]\n'1131 '(4, 1): [[((1, 4), (4, 1)), (1, -1), 0, None]]\n'1132 '(4, 2): [[((3, 3), (4, 2)), (1, -1), 0, None]]\n'1133 '(4, 4): [[((1, 4), (4, 4)), (1, 0), 1, (4, 4)], [((3, 3), (4, 4)), (1, 1), 0, None]]\n'1134 '(4, 6): [[((0, 2), (4, 6)), (1, 1), 0, None]]\n'1135 '(4, 7): [[((1, 4), (4, 7)), (1, 1), 0, None]]\n'1136 '(5, 0): [[((1, 4), (5, 0)), (1, -1), 0, None]]\n'1137 '(5, 2): [[((4, 3), (5, 2)), (1, -1), 0, None]]\n'1138 '(5, 4): [[((1, 4), (5, 4)), (1, 0), 1, (4, 4)], [((4, 3), (5, 4)), (1, 1), 0, None]]\n'1139 '(5, 7): [[((0, 2), (5, 7)), (1, 1), 1, (5, 7)]]\n'1140 '(6, 4): [[((1, 4), (6, 4)), (1, 0), 1, (4, 4)]]\n'1141 '(7, 4): [[((1, 4), (7, 4)), (1, 0), 1, (4, 4)]]\n')11421143 input_dict = chess.gen_check_attacks()1144 givenOutput = ''1145 for key in sorted(input_dict):1146 givenOutput += '{}: '.format(key)1147 givenOutput += str(input_dict[key])1148 givenOutput += '\n'1149 1150 if (correctOutput == givenOutput):1151 print('Test 3: Correct')1152 correctCount += 11153 else:1154 print('Test 3: Incorrect')1155 print('Correct output:\n{}'.format(correctOutput))1156 print('Given output:\n{}'.format(givenOutput))1157 print()1158 1159 #Test 41160 move = 'd1e2'1161 coordinateMove = chess.notation_to_coordinate(move) 1162 chess.move_piece(coordinateMove)11631164 move = 'a2a4'1165 coordinateMove = chess.notation_to_coordinate(move) 1166 chess.move_piece(coordinateMove) 1167 1168 1169 correctOutput = ('(0, 1): [[((0, 0), (0, 1)), (0, 1), 0, None]]\n'1170 '(0, 3): [[((0, 4), (0, 3)), (0, -1), 0, None], [((1, 4), (0, 3)), (-1, -1), 0, None]]\n'1171 '(0, 4): [[((1, 4), (0, 4)), (-1, 0), 0, None]]\n'1172 '(0, 5): [[((0, 4), (0, 5)), (0, 1), 0, None], [((1, 4), (0, 5)), (-1, 1), 0, None]]\n'1173 '(0, 6): [[((0, 7), (0, 6)), (0, -1), 0, None]]\n'1174 '(1, 0): [[((0, 0), (1, 0)), (1, 0), 0, None]]\n'1175 '(1, 1): [[((0, 2), (1, 1)), (1, -1), 0, None]]\n'1176 '(1, 2): [[((1, 4), (1, 2)), (0, -1), 0, None]]\n'1177 '(1, 3): [[((0, 1), (1, 3)), (1, 2), 0, None], [((0, 2), (1, 3)), (1, 1), 0, None], [((0, 4), (1, 3)), (1, -1), 0, None], [((1, 4), (1, 3)), (0, -1), 0, None]]\n'1178 '(1, 4): [[((0, 4), (1, 4)), (1, 0), 0, None], [((0, 5), (1, 4)), (1, -1), 0, None], [((0, 6), (1, 4)), (1, -2), 0, None]]\n'1179 '(1, 5): [[((0, 4), (1, 5)), (1, 1), 0, None], [((1, 4), (1, 5)), (0, 1), 0, None]]\n'1180 '(1, 6): [[((0, 5), (1, 6)), (1, 1), 0, None]]\n'1181 '(1, 7): [[((0, 7), (1, 7)), (1, 0), 0, None]]\n'1182 '(2, 0): [[((0, 0), (2, 0)), (1, 0), 0, None], [((0, 1), (2, 0)), (2, -1), 0, None], [((1, 1), (2, 0)), (1, -1), 0, None]]\n'1183 '(2, 1): [[((1, 2), (2, 1)), (1, -1), 0, None]]\n'1184 '(2, 2): [[((0, 1), (2, 2)), (2, 1), 0, None], [((1, 1), (2, 2)), (1, 1), 0, None]]\n'1185 '(2, 3): [[((1, 2), (2, 3)), (1, 1), 0, None], [((1, 4), (2, 3)), (1, -1), 0, None]]\n'1186 '(2, 4): [[((0, 2), (2, 4)), (1, 1), 0, None], [((1, 4), (2, 4)), (1, 0), 0, None], [((1, 5), (2, 4)), (1, -1), 0, None]]\n'1187 '(2, 5): [[((0, 6), (2, 5)), (2, -1), 0, None], [((1, 4), (2, 5)), (1, 1), 0, None], [((1, 6), (2, 5)), (1, -1), 0, None]]\n'1188 '(2, 6): [[((1, 5), (2, 6)), (1, 1), 0, None], [((1, 7), (2, 6)), (1, -1), 0, None]]\n'1189 '(2, 7): [[((0, 6), (2, 7)), (2, 1), 0, None], [((1, 6), (2, 7)), (1, 1), 0, None]]\n'1190 '(3, 0): [[((0, 0), (3, 0)), (1, 0), 0, None]]\n'1191 '(3, 2): [[((1, 4), (3, 2)), (1, -1), 0, None]]\n'1192 '(3, 4): [[((1, 4), (3, 4)), (1, 0), 0, None]]\n'1193 '(3, 5): [[((0, 2), (3, 5)), (1, 1), 0, None]]\n'1194 '(3, 6): [[((1, 4), (3, 6)), (1, 1), 0, None]]\n'1195 '(4, 1): [[((1, 4), (4, 1)), (1, -1), 0, None], [((3, 0), (4, 1)), (1, 1), 0, None]]\n'1196 '(4, 2): [[((3, 3), (4, 2)), (1, -1), 0, None]]\n'1197 '(4, 4): [[((1, 4), (4, 4)), (1, 0), 1, (4, 4)], [((3, 3), (4, 4)), (1, 1), 0, None]]\n'1198 '(4, 6): [[((0, 2), (4, 6)), (1, 1), 0, None]]\n'1199 '(4, 7): [[((1, 4), (4, 7)), (1, 1), 0, None]]\n'1200 '(5, 0): [[((1, 4), (5, 0)), (1, -1), 0, None]]\n'1201 '(5, 2): [[((4, 3), (5, 2)), (1, -1), 0, None]]\n'1202 '(5, 4): [[((1, 4), (5, 4)), (1, 0), 1, (4, 4)], [((4, 3), (5, 4)), (1, 1), 0, None]]\n'1203 '(5, 7): [[((0, 2), (5, 7)), (1, 1), 1, (5, 7)]]\n'1204 '(6, 4): [[((1, 4), (6, 4)), (1, 0), 2, None]]\n'1205 '(7, 4): [[((1, 4), (7, 4)), (1, 0), 2, None]]\n')12061207 input_dict = chess.gen_check_attacks()1208 givenOutput = ''1209 for key in sorted(input_dict):1210 givenOutput += '{}: '.format(key)1211 givenOutput += str(input_dict[key])1212 givenOutput += '\n'1213 1214 if (correctOutput == givenOutput):1215 print('Test 4: Correct')1216 correctCount += 11217 else:1218 print('Test 4: Incorrect')1219 print('Correct output:\n{}'.format(correctOutput))1220 print('Given output:\n{}'.format(givenOutput))1221 print()1222 1223 #Test 51224 move = 'e4d5'1225 coordinateMove = chess.notation_to_coordinate(move) 1226 chess.move_piece(coordinateMove) 1227 12281229 move = 'e2e7'1230 coordinateMove = chess.notation_to_coordinate(move) 1231 chess.move_piece(coordinateMove) 1232 1233 1234 move = 'e1e2'1235 coordinateMove = chess.notation_to_coordinate(move) 1236 chess.move_piece(coordinateMove) 1237 1238 1239 move = 'f1e2'1240 coordinateMove = chess.notation_to_coordinate(move) 1241 chess.move_piece(coordinateMove) 1242 1243 1244 move = 'a1a2'1245 coordinateMove = chess.notation_to_coordinate(move) 1246 chess.move_piece(coordinateMove) 1247 1248 1249 move = 'g1h3'1250 coordinateMove = chess.notation_to_coordinate(move) 1251 chess.move_piece(coordinateMove) 1252 1253 1254 move = 'a2a3'1255 coordinateMove = chess.notation_to_coordinate(move) 1256 chess.move_piece(coordinateMove) 1257 1258 1259 move = 'e1g1'1260 coordinateMove = chess.notation_to_coordinate(move) 1261 chess.move_piece(coordinateMove) 1262 1263 1264 move = 'a3b3'1265 coordinateMove = chess.notation_to_coordinate(move) 1266 chess.move_piece(coordinateMove) 1267 1268 1269 move = 'f1e1'1270 coordinateMove = chess.notation_to_coordinate(move) 1271 chess.move_piece(coordinateMove) 1272 1273 1274 move = 'f2f3'1275 coordinateMove = chess.notation_to_coordinate(move) 1276 chess.move_piece(coordinateMove) 1277 1278 1279 move = 'e2h5'1280 coordinateMove = chess.notation_to_coordinate(move) 1281 chess.move_piece(coordinateMove) 1282 1283 1284 correctOutput = ('(0, 1): [[((0, 0), (0, 1)), (0, 1), 0, None]]\n'1285 '(0, 2): [[((0, 4), (0, 2)), (0, -1), 0, None]]\n'1286 '(0, 3): [[((0, 4), (0, 3)), (0, -1), 0, None], [((4, 7), (0, 3)), (-1, -1), 0, None]]\n'1287 '(0, 5): [[((0, 4), (0, 5)), (0, 1), 0, None], [((0, 6), (0, 5)), (0, -1), 0, None]]\n'1288 '(0, 6): [[((0, 4), (0, 6)), (0, 1), 0, None], [((2, 7), (0, 6)), (-2, -1), 0, None]]\n'1289 '(0, 7): [[((0, 6), (0, 7)), (0, 1), 0, None]]\n'1290 '(1, 0): [[((0, 0), (1, 0)), (1, 0), 0, None]]\n'1291 '(1, 1): [[((0, 2), (1, 1)), (1, -1), 0, None]]\n'1292 '(1, 3): [[((0, 1), (1, 3)), (1, 2), 0, None], [((0, 2), (1, 3)), (1, 1), 0, None]]\n'1293 '(1, 4): [[((0, 4), (1, 4)), (1, 0), 0, None], [((4, 7), (1, 4)), (-1, -1), 0, None]]\n'1294 '(1, 5): [[((0, 6), (1, 5)), (1, -1), 0, None], [((2, 7), (1, 5)), (-1, -2), 0, None]]\n'1295 '(1, 6): [[((0, 6), (1, 6)), (1, 0), 0, None]]\n'1296 '(1, 7): [[((0, 6), (1, 7)), (1, 1), 0, None]]\n'1297 '(2, 0): [[((0, 0), (2, 0)), (1, 0), 0, None], [((0, 1), (2, 0)), (2, -1), 0, None], [((1, 1), (2, 0)), (1, -1), 0, None]]\n'1298 '(2, 1): [[((1, 2), (2, 1)), (1, -1), 0, None]]\n'1299 '(2, 2): [[((0, 1), (2, 2)), (2, 1), 0, None], [((1, 1), (2, 2)), (1, 1), 0, None]]\n'1300 '(2, 3): [[((1, 2), (2, 3)), (1, 1), 0, None]]\n'1301 '(2, 4): [[((0, 2), (2, 4)), (1, 1), 0, None], [((0, 4), (2, 4)), (1, 0), 0, None], [((1, 5), (2, 4)), (1, -1), 0, None]]\n'1302 '(2, 5): [[((1, 6), (2, 5)), (1, -1), 0, None], [((4, 7), (2, 5)), (-1, -1), 0, None]]\n'1303 '(2, 6): [[((1, 5), (2, 6)), (1, 1), 0, None], [((1, 7), (2, 6)), (1, -1), 0, None]]\n'1304 '(2, 7): [[((1, 6), (2, 7)), (1, 1), 0, None]]\n'1305 '(3, 0): [[((0, 0), (3, 0)), (1, 0), 0, None]]\n'1306 '(3, 4): [[((0, 4), (3, 4)), (1, 0), 0, None]]\n'1307 '(3, 5): [[((0, 2), (3, 5)), (1, 1), 0, None], [((2, 7), (3, 5)), (1, -2), 0, None]]\n'1308 '(3, 6): [[((4, 7), (3, 6)), (-1, -1), 0, None]]\n'1309 '(4, 1): [[((3, 0), (4, 1)), (1, 1), 0, None]]\n'1310 '(4, 4): [[((0, 4), (4, 4)), (1, 0), 0, None]]\n'1311 '(4, 6): [[((0, 2), (4, 6)), (1, 1), 0, None], [((2, 7), (4, 6)), (2, -1), 0, None]]\n'1312 '(5, 2): [[((4, 3), (5, 2)), (1, -1), 0, None]]\n'1313 '(5, 4): [[((0, 4), (5, 4)), (1, 0), 0, None], [((4, 3), (5, 4)), (1, 1), 0, None]]\n'1314 '(5, 6): [[((4, 7), (5, 6)), (1, -1), 0, None]]\n'1315 '(5, 7): [[((0, 2), (5, 7)), (1, 1), 1, (5, 7)]]\n'1316 '(6, 4): [[((0, 4), (6, 4)), (1, 0), 0, None]]\n'1317 '(6, 5): [[((4, 7), (6, 5)), (1, -1), 0, None]]\n'1318 '(7, 4): [[((0, 4), (7, 4)), (1, 0), 0, None], [((4, 7), (7, 4)), (1, -1), 0, None]]\n')13191320 input_dict = chess.gen_check_attacks()1321 givenOutput = ''1322 for key in sorted(input_dict):1323 givenOutput += '{}: '.format(key)1324 givenOutput += str(input_dict[key])1325 givenOutput += '\n'1326 1327 if (correctOutput == givenOutput):1328 print('Test 5: Correct')1329 correctCount += 11330 else:1331 print('Test 5: Incorrect')1332 print('Correct output:\n{}'.format(correctOutput))1333 print('Given output:\n{}'.format(givenOutput))1334 print() 1335 1336 #Test 61337 move = 'c1e3'1338 coordinateMove = chess.notation_to_coordinate(move) 1339 chess.move_piece(coordinateMove) 1340 13411342 move = 'h5e2'1343 coordinateMove = chess.notation_to_coordinate(move) 1344 chess.move_piece(coordinateMove) 1345 1346 1347 move = 'e2e1'1348 coordinateMove = chess.notation_to_coordinate(move) 1349 chess.move_piece(coordinateMove) 1350 13511352 move = 'a1a3'1353 coordinateMove = chess.notation_to_coordinate(move) 1354 chess.move_piece(coordinateMove) 1355 1356 1357 move = 'e3c1'1358 coordinateMove = chess.notation_to_coordinate(move) 1359 chess.move_piece(coordinateMove) 1360 13611362 move = 'e2h5'1363 coordinateMove = chess.notation_to_coordinate(move) 1364 chess.move_piece(coordinateMove) 1365 1366 1367 correctOutput = ('(0, 0): [[((2, 0), (0, 0)), (-1, 0), 0, None]]\n'1368 '(0, 2): [[((0, 4), (0, 2)), (0, -1), 0, None]]\n'1369 '(0, 3): [[((0, 4), (0, 3)), (0, -1), 0, None], [((4, 7), (0, 3)), (-1, -1), 0, None]]\n'1370 '(0, 5): [[((0, 4), (0, 5)), (0, 1), 0, None], [((0, 6), (0, 5)), (0, -1), 0, None]]\n'1371 '(0, 6): [[((0, 4), (0, 6)), (0, 1), 0, None], [((2, 7), (0, 6)), (-2, -1), 0, None]]\n'1372 '(0, 7): [[((0, 6), (0, 7)), (0, 1), 0, None]]\n'1373 '(1, 0): [[((2, 0), (1, 0)), (-1, 0), 0, None]]\n'1374 '(1, 1): [[((0, 2), (1, 1)), (1, -1), 0, None]]\n'1375 '(1, 3): [[((0, 1), (1, 3)), (1, 2), 0, None], [((0, 2), (1, 3)), (1, 1), 0, None]]\n'1376 '(1, 4): [[((0, 4), (1, 4)), (1, 0), 0, None], [((4, 7), (1, 4)), (-1, -1), 0, None]]\n'1377 '(1, 5): [[((0, 6), (1, 5)), (1, -1), 0, None], [((2, 7), (1, 5)), (-1, -2), 0, None]]\n'1378 '(1, 6): [[((0, 6), (1, 6)), (1, 0), 0, None]]\n'1379 '(1, 7): [[((0, 6), (1, 7)), (1, 1), 0, None]]\n'1380 '(2, 0): [[((0, 1), (2, 0)), (2, -1), 0, None], [((1, 1), (2, 0)), (1, -1), 0, None]]\n'1381 '(2, 1): [[((1, 2), (2, 1)), (1, -1), 0, None], [((2, 0), (2, 1)), (0, 1), 0, None]]\n'1382 '(2, 2): [[((0, 1), (2, 2)), (2, 1), 0, None], [((1, 1), (2, 2)), (1, 1), 0, None], [((2, 0), (2, 2)), (0, 1), 0, None]]\n'1383 '(2, 3): [[((1, 2), (2, 3)), (1, 1), 0, None], [((2, 0), (2, 3)), (0, 1), 0, None]]\n'1384 '(2, 4): [[((0, 2), (2, 4)), (1, 1), 0, None], [((0, 4), (2, 4)), (1, 0), 0, None], [((1, 5), (2, 4)), (1, -1), 0, None], [((2, 0), (2, 4)), (0, 1), 0, None]]\n'1385 '(2, 5): [[((1, 6), (2, 5)), (1, -1), 0, None], [((2, 0), (2, 5)), (0, 1), 0, None], [((4, 7), (2, 5)), (-1, -1), 0, None]]\n'1386 '(2, 6): [[((1, 5), (2, 6)), (1, 1), 0, None], [((1, 7), (2, 6)), (1, -1), 0, None], [((2, 0), (2, 6)), (0, 1), 0, None]]\n'1387 '(2, 7): [[((1, 6), (2, 7)), (1, 1), 0, None], [((2, 0), (2, 7)), (0, 1), 0, None]]\n'1388 '(3, 0): [[((2, 0), (3, 0)), (1, 0), 0, None]]\n'1389 '(3, 4): [[((0, 4), (3, 4)), (1, 0), 0, None]]\n'1390 '(3, 5): [[((0, 2), (3, 5)), (1, 1), 0, None], [((2, 7), (3, 5)), (1, -2), 0, None]]\n'1391 '(3, 6): [[((4, 7), (3, 6)), (-1, -1), 0, None]]\n'1392 '(4, 1): [[((3, 0), (4, 1)), (1, 1), 0, None]]\n'1393 '(4, 4): [[((0, 4), (4, 4)), (1, 0), 0, None]]\n'1394 '(4, 6): [[((0, 2), (4, 6)), (1, 1), 0, None], [((2, 7), (4, 6)), (2, -1), 0, None]]\n'1395 '(5, 2): [[((4, 3), (5, 2)), (1, -1), 0, None]]\n'1396 '(5, 4): [[((0, 4), (5, 4)), (1, 0), 0, None], [((4, 3), (5, 4)), (1, 1), 0, None]]\n'1397 '(5, 6): [[((4, 7), (5, 6)), (1, -1), 0, None]]\n'1398 '(5, 7): [[((0, 2), (5, 7)), (1, 1), 1, (5, 7)]]\n'1399 '(6, 4): [[((0, 4), (6, 4)), (1, 0), 0, None]]\n'1400 '(6, 5): [[((4, 7), (6, 5)), (1, -1), 0, None]]\n'1401 '(7, 4): [[((0, 4), (7, 4)), (1, 0), 0, None], [((4, 7), (7, 4)), (1, -1), 0, None]]\n')14021403 input_dict = chess.gen_check_attacks()1404 givenOutput = ''1405 for key in sorted(input_dict):1406 givenOutput += '{}: '.format(key)1407 givenOutput += str(input_dict[key])1408 givenOutput += '\n'1409 1410 if (correctOutput == givenOutput):1411 print('Test 6: Correct')1412 correctCount += 11413 else:1414 print('Test 6: Incorrect')1415 print('Correct output:\n{}'.format(correctOutput))1416 print('Given output:\n{}'.format(givenOutput))1417 print() 1418 1419 print('{} correct tests out of 6'.format(correctCount))1420 print()1421 1422 #Testing king in check1423 def test_king_in_check():1424 chess = Chess()1425 1426 correctCount = 01427 print('Testing the king_in_check() function')1428 1429 #Test 11430 chess.state.opponent_attack_dict = chess.gen_check_attacks()1431 move = 'e2e4'1432 coordinateMove = chess.notation_to_coordinate(move)1433 correctOutput = False1434 givenOutput = chess.king_in_check(coordinateMove) 1435 if (correctOutput == givenOutput):1436 print('Test 1: Correct')1437 correctCount += 11438 else:1439 print('Test 1: Incorrect')1440 print('Correct output:\n{}'.format(correctOutput))1441 print('Given output:\n{}'.format(givenOutput))1442 print() 1443 1444 #Test 21445 move = 'e2e4'1446 coordinateMove = chess.notation_to_coordinate(move) 1447 chess.move_piece(coordinateMove) 1448 1449 1450 move = 'd2d4'1451 coordinateMove = chess.notation_to_coordinate(move) 1452 chess.move_piece(coordinateMove) 1453 1454 1455 chess.state.opponent_attack_dict = chess.gen_check_attacks()1456 move = 'e1e2'1457 coordinateMove = chess.notation_to_coordinate(move)1458 correctOutput = False1459 givenOutput = chess.king_in_check(coordinateMove) 1460 if (correctOutput == givenOutput):1461 print('Test 2: Correct')1462 correctCount += 11463 else:1464 print('Test 2: Incorrect')1465 print('Correct output:\n{}'.format(correctOutput))1466 print('Given output:\n{}'.format(givenOutput))1467 print()1468 1469 #Test 31470 move = 'f2f3'1471 coordinateMove = chess.notation_to_coordinate(move) 1472 chess.move_piece(coordinateMove) 1473 1474 1475 move = 'c1g5'1476 coordinateMove = chess.notation_to_coordinate(move) 1477 chess.move_piece(coordinateMove) 1478 1479 1480 chess.state.opponent_attack_dict = chess.gen_check_attacks()1481 move = 'e1e2'1482 coordinateMove = chess.notation_to_coordinate(move) 1483 correctOutput = False1484 givenOutput = chess.king_in_check(coordinateMove) 1485 if (correctOutput == givenOutput):1486 print('Test 3: Correct')1487 correctCount += 11488 else:1489 print('Test 3: Incorrect')1490 print('Correct output:\n{}'.format(correctOutput))1491 print('Given output:\n{}'.format(givenOutput))1492 print()1493 1494 #Test 41495 move = 'f3f2'1496 coordinateMove = chess.notation_to_coordinate(move) 1497 chess.move_piece(coordinateMove) 1498 1499 1500 move = 'e2e4'1501 coordinateMove = chess.notation_to_coordinate(move) 1502 chess.move_piece(coordinateMove) 1503 1504 1505 chess.state.opponent_attack_dict = chess.gen_check_attacks()1506 move = 'e1e2' 1507 coordinateMove = chess.notation_to_coordinate(move)1508 correctOutput = True1509 givenOutput = chess.king_in_check(coordinateMove) 1510 if (correctOutput == givenOutput):1511 print('Test 4: Correct')1512 correctCount += 11513 else:1514 print('Test 4: Incorrect')1515 print('Correct output:\n{}'.format(correctOutput))1516 print('Given output:\n{}'.format(givenOutput))1517 print()1518 1519 #Test 51520 move = 'd2d4'1521 coordinateMove = chess.notation_to_coordinate(move) 1522 chess.move_piece(coordinateMove) 1523 1524 1525 move = 'g5c1'1526 coordinateMove = chess.notation_to_coordinate(move) 1527 chess.move_piece(coordinateMove) 1528 1529 1530 move = 'c2c3'1531 coordinateMove = chess.notation_to_coordinate(move) 1532 chess.move_piece(coordinateMove) 1533 1534 1535 move = 'f1b5' 1536 coordinateMove = chess.notation_to_coordinate(move) 1537 chess.move_piece(coordinateMove) 1538 1539 1540 chess.state.opponent_attack_dict = chess.gen_check_attacks()1541 move = 'g1h3' 1542 coordinateMove = chess.notation_to_coordinate(move)1543 correctOutput = False1544 givenOutput = chess.king_in_check(coordinateMove) 1545 if (correctOutput == givenOutput):1546 print('Test 5: Correct')1547 correctCount += 11548 else:1549 print('Test 5: Incorrect')1550 print('Correct output:\n{}'.format(correctOutput))1551 print('Given output:\n{}'.format(givenOutput))1552 print()1553 1554 #Test 61555 chess.state.opponent_attack_dict = chess.gen_check_attacks()1556 move = 'e1e2' 1557 coordinateMove = chess.notation_to_coordinate(move)1558 correctOutput = False1559 givenOutput = chess.king_in_check(coordinateMove) 1560 if (correctOutput == givenOutput):1561 print('Test 6: Correct')1562 correctCount += 11563 else:1564 print('Test 6: Incorrect')1565 print('Correct output:\n{}'.format(correctOutput))1566 print('Given output:\n{}'.format(givenOutput))1567 print()1568 1569 #Test 71570 chess.state.opponent_attack_dict = chess.gen_check_attacks()1571 move = 'e1d2' 1572 coordinateMove = chess.notation_to_coordinate(move)1573 correctOutput = False1574 givenOutput = chess.king_in_check(coordinateMove) 1575 if (correctOutput == givenOutput):1576 print('Test 7: Correct')1577 correctCount += 11578 else:1579 print('Test 7: Incorrect')1580 print('Correct output:\n{}'.format(correctOutput))1581 print('Given output:\n{}'.format(givenOutput))1582 print()1583 1584 #Test 81585 move = 'g1h3'1586 coordinateMove = chess.notation_to_coordinate(move) 1587 chess.move_piece(coordinateMove) 1588 1589 1590 move = 'd1b4' 1591 coordinateMove = chess.notation_to_coordinate(move) 1592 chess.move_piece(coordinateMove) 1593 1594 1595 chess.state.opponent_attack_dict = chess.gen_check_attacks()1596 move = 'e1e2' 1597 coordinateMove = chess.notation_to_coordinate(move)1598 correctOutput = True1599 givenOutput = chess.king_in_check(coordinateMove) 1600 if (correctOutput == givenOutput):1601 print('Test 8: Correct')1602 correctCount += 11603 else:1604 print('Test 8: Incorrect')1605 print('Correct output:\n{}'.format(correctOutput))1606 print('Given output:\n{}'.format(givenOutput))1607 print()1608 1609 #Test 91610 move = 'h3g1'1611 coordinateMove = chess.notation_to_coordinate(move) 1612 chess.move_piece(coordinateMove) 1613 1614 1615 move = 'b5f1' 1616 coordinateMove = chess.notation_to_coordinate(move) 1617 chess.move_piece(coordinateMove) 1618 1619 1620 move = 'g1h3' 1621 coordinateMove = chess.notation_to_coordinate(move) 1622 chess.move_piece(coordinateMove) 1623 1624 1625 move = 'b4a4' 1626 coordinateMove = chess.notation_to_coordinate(move) 1627 chess.move_piece(coordinateMove) 1628 1629 1630 move = 'c3b4'1631 chess.state.opponent_attack_dict = chess.gen_check_attacks() 1632 coordinateMove = chess.notation_to_coordinate(move)1633 correctOutput = False1634 givenOutput = chess.king_in_check(coordinateMove) 1635 if (correctOutput == givenOutput):1636 print('Test 9: Correct')1637 correctCount += 11638 else:1639 print('Test 9: Incorrect')1640 print('Correct output:\n{}'.format(correctOutput))1641 print('Given output:\n{}'.format(givenOutput))1642 print()1643 1644 #Test 101645 chess.state.opponent_attack_dict = chess.gen_check_attacks()1646 move = 'c3c4' 1647 coordinateMove = chess.notation_to_coordinate(move)1648 correctOutput = True1649 givenOutput = chess.king_in_check(coordinateMove) 1650 if (correctOutput == givenOutput):1651 print('Test 10: Correct')1652 correctCount += 11653 else:1654 print('Test 10: Incorrect')1655 print('Correct output:\n{}'.format(correctOutput))1656 print('Given output:\n{}'.format(givenOutput))1657 print()1658 1659 #Test 11 1660 move = 'c3b4' 1661 coordinateMove = chess.notation_to_coordinate(move) 1662 chess.move_piece(coordinateMove) 1663 1664 1665 move = 'a4b5' 1666 coordinateMove = chess.notation_to_coordinate(move) 1667 chess.move_piece(coordinateMove) 1668 1669 1670 chess.state.opponent_attack_dict = chess.gen_check_attacks()1671 move = 'h3g1' 1672 coordinateMove = chess.notation_to_coordinate(move)1673 correctOutput = True1674 givenOutput = chess.king_in_check(coordinateMove) 1675 if (correctOutput == givenOutput):1676 print('Test 11: Correct')1677 correctCount += 11678 else:1679 print('Test 11: Incorrect')1680 print('Correct output:\n{}'.format(correctOutput))1681 print('Given output:\n{}'.format(givenOutput))1682 print()1683 1684 #Test 121685 1686 chess.state.opponent_attack_dict = chess.gen_check_attacks()1687 move = 'e1e2' 1688 coordinateMove = chess.notation_to_coordinate(move)1689 correctOutput = False1690 givenOutput = chess.king_in_check(coordinateMove) 1691 if (correctOutput == givenOutput):1692 print('Test 12: Correct')1693 correctCount += 11694 else:1695 print('Test 12: Incorrect')1696 print('Correct output:\n{}'.format(correctOutput))1697 print('Given output:\n{}'.format(givenOutput))1698 print() 1699 1700 #Test 13 1701 move = 'f2f3' 1702 coordinateMove = chess.notation_to_coordinate(move) 1703 chess.move_piece(coordinateMove) 1704 1705 1706 move = 'c1h4' 1707 coordinateMove = chess.notation_to_coordinate(move) 1708 chess.move_piece(coordinateMove) 1709 1710 1711 chess.state.opponent_attack_dict = chess.gen_check_attacks()1712 move = 'e1e2' 1713 coordinateMove = chess.notation_to_coordinate(move)1714 correctOutput = False1715 givenOutput = chess.king_in_check(coordinateMove) 1716 if (correctOutput == givenOutput):1717 print('Test 13: Correct')1718 correctCount += 11719 else:1720 print('Test 13: Incorrect')1721 print('Correct output:\n{}'.format(correctOutput))1722 print('Given output:\n{}'.format(givenOutput))1723 print()17241725 #Test 14 1726 move = 'f3f2' 1727 coordinateMove = chess.notation_to_coordinate(move) 1728 chess.move_piece(coordinateMove) 1729 1730 1731 move = 'b5a4' 1732 coordinateMove = chess.notation_to_coordinate(move) 1733 chess.move_piece(coordinateMove) 1734 1735 1736 chess.state.opponent_attack_dict = chess.gen_check_attacks()1737 move = 'e1e2' 1738 coordinateMove = chess.notation_to_coordinate(move)1739 correctOutput = True1740 givenOutput = chess.king_in_check(coordinateMove) 1741 if (correctOutput == givenOutput):1742 print('Test 14: Correct')1743 correctCount += 11744 else:1745 print('Test 14: Incorrect')1746 print('Correct output:\n{}'.format(correctOutput))1747 print('Given output:\n{}'.format(givenOutput))1748 print() 1749 1750 #Test 15 1751 chess.state.opponent_attack_dict = chess.gen_check_attacks()1752 move = 'b2b4' 1753 coordinateMove = chess.notation_to_coordinate(move)1754 correctOutput = False1755 givenOutput = chess.king_in_check(coordinateMove) 1756 if (correctOutput == givenOutput):1757 print('Test 15: Correct')1758 correctCount += 11759 else:1760 print('Test 15: Incorrect')1761 print('Correct output:\n{}'.format(correctOutput))1762 print('Given output:\n{}'.format(givenOutput))1763 print()17641765 #Test 16 1766 move = 'f2f3' 1767 coordinateMove = chess.notation_to_coordinate(move) 1768 chess.move_piece(coordinateMove) 1769 1770 1771 move = 'h4h5' 1772 coordinateMove = chess.notation_to_coordinate(move) 1773 chess.move_piece(coordinateMove) 1774 1775 1776 chess.state.opponent_attack_dict = chess.gen_check_attacks()1777 move = 'h3g1' 1778 coordinateMove = chess.notation_to_coordinate(move)1779 correctOutput = True1780 givenOutput = chess.king_in_check(coordinateMove) 1781 if (correctOutput == givenOutput):1782 print('Test 16: Correct')1783 correctCount += 11784 else:1785 print('Test 16: Incorrect')1786 print('Correct output:\n{}'.format(correctOutput))1787 print('Given output:\n{}'.format(givenOutput))1788 print()1789 1790 #Test 17 1791 chess.state.opponent_attack_dict = chess.gen_check_attacks()1792 move = 'e1e2' 1793 coordinateMove = chess.notation_to_coordinate(move)1794 correctOutput = False1795 givenOutput = chess.king_in_check(coordinateMove) 1796 if (correctOutput == givenOutput):1797 print('Test 17: Correct')1798 correctCount += 11799 else:1800 print('Test 17: Incorrect')1801 print('Correct output:\n{}'.format(correctOutput))1802 print('Given output:\n{}'.format(givenOutput))1803 print()1804 1805 #Test 18 1806 move = 'h3g1' 1807 coordinateMove = chess.notation_to_coordinate(move) 1808 chess.move_piece(coordinateMove) 1809 1810 1811 move = 'f1h4' 1812 coordinateMove = chess.notation_to_coordinate(move) 1813 chess.move_piece(coordinateMove) 1814 1815 1816 chess.state.opponent_attack_dict = chess.gen_check_attacks()1817 move = 'e1e2' 1818 coordinateMove = chess.notation_to_coordinate(move)1819 correctOutput = False1820 givenOutput = chess.king_in_check(coordinateMove) 1821 if (correctOutput == givenOutput):1822 print('Test 18: Correct')1823 correctCount += 11824 else:1825 print('Test 18: Incorrect')1826 print('Correct output:\n{}'.format(correctOutput))1827 print('Given output:\n{}'.format(givenOutput))1828 print()1829 1830 #Test 19 1831 chess.state.opponent_attack_dict = chess.gen_check_attacks()1832 move = 'e1f2' 1833 coordinateMove = chess.notation_to_coordinate(move)1834 correctOutput = True1835 givenOutput = chess.king_in_check(coordinateMove) 1836 if (correctOutput == givenOutput):1837 print('Test 19: Correct')1838 correctCount += 11839 else:1840 print('Test 19: Incorrect')1841 print('Correct output:\n{}'.format(correctOutput))1842 print('Given output:\n{}'.format(givenOutput))1843 print() 18441845 #Test 20 Check en passant removing 2 pieces in a line with rook attacking king 1846 chess = Chess()1847 move = 'e1a5' 1848 coordinateMove = chess.notation_to_coordinate(move)1849 chess.move_piece(coordinateMove)1850 1851 move = 'a1h4' 1852 coordinateMove = chess.notation_to_coordinate(move)1853 chess.move_piece(coordinateMove)1854 1855 move = 'e2e5' 1856 coordinateMove = chess.notation_to_coordinate(move)1857 chess.move_piece(coordinateMove)1858 1859 move = 'd2d4' 1860 coordinateMove = chess.notation_to_coordinate(move)1861 chess.move_piece(coordinateMove)1862 1863 move = 'e5d6'1864 coordinateMove = chess.notation_to_coordinate(move) 1865 chess.state.opponent_attack_dict = chess.gen_check_attacks()1866 1867 correctOutput = True1868 givenOutput = chess.king_in_check(coordinateMove) 1869 if (correctOutput == givenOutput):1870 print('Test 20: Correct')1871 correctCount += 11872 else:1873 print('Test 20: Incorrect')1874 print('Correct output:\n{}'.format(correctOutput))1875 print('Given output:\n{}'.format(givenOutput))1876 print()1877 1878 #Test 21 Check en passant not affecting king in check if pawn just moves up1879 move = 'e5e6'1880 coordinateMove = chess.notation_to_coordinate(move) 1881 chess.state.opponent_attack_dict = chess.gen_check_attacks()1882 1883 correctOutput = False1884 givenOutput = chess.king_in_check(coordinateMove) 1885 if (correctOutput == givenOutput):1886 print('Test 21: Correct')1887 correctCount += 11888 else:1889 print('Test 21: Incorrect')1890 print('Correct output:\n{}'.format(correctOutput))1891 print('Given output:\n{}'.format(givenOutput))1892 print()1893 1894 #Test 22 Check en passant removing 2 pieces in a line with rook attacking king, opponent's pawn closer1895 chess = Chess()1896 move = 'e1a5' 1897 coordinateMove = chess.notation_to_coordinate(move)1898 chess.move_piece(coordinateMove)1899 1900 move = 'a1h4' 1901 coordinateMove = chess.notation_to_coordinate(move)1902 chess.move_piece(coordinateMove)1903 1904 move = 'd2d5' 1905 coordinateMove = chess.notation_to_coordinate(move)1906 chess.move_piece(coordinateMove)1907 1908 move = 'e2e4' 1909 coordinateMove = chess.notation_to_coordinate(move)1910 chess.move_piece(coordinateMove)1911 1912 move = 'd5e6'1913 coordinateMove = chess.notation_to_coordinate(move) 1914 chess.state.opponent_attack_dict = chess.gen_check_attacks()1915 1916 correctOutput = True1917 givenOutput = chess.king_in_check(coordinateMove) 1918 if (correctOutput == givenOutput):1919 print('Test 22: Correct')1920 correctCount += 11921 else:1922 print('Test 22: Incorrect')1923 print('Correct output:\n{}'.format(correctOutput))1924 print('Given output:\n{}'.format(givenOutput))1925 print()19261927 #Test 23 Check en passant not affecting king in check if pawn just moves up1928 move = 'd5d6'1929 coordinateMove = chess.notation_to_coordinate(move) 1930 chess.state.opponent_attack_dict = chess.gen_check_attacks()1931 1932 correctOutput = False1933 givenOutput = chess.king_in_check(coordinateMove) 1934 if (correctOutput == givenOutput):1935 print('Test 23: Correct')1936 correctCount += 11937 else:1938 print('Test 23: Incorrect')1939 print('Correct output:\n{}'.format(correctOutput))1940 print('Given output:\n{}'.format(givenOutput))1941 print()1942 1943 #Test 24 Check en passant removing 2 pieces in a line with rook attacking king, opponent's pawn closer1944 chess = Chess()1945 move = 'a1a4' 1946 coordinateMove = chess.notation_to_coordinate(move)1947 chess.move_piece(coordinateMove)1948 1949 move = 'e1h5' 1950 coordinateMove = chess.notation_to_coordinate(move)1951 chess.move_piece(coordinateMove)1952 1953 move = 'a2a3' 1954 coordinateMove = chess.notation_to_coordinate(move)1955 chess.move_piece(coordinateMove)1956 1957 move = 'e2e5' 1958 coordinateMove = chess.notation_to_coordinate(move)1959 chess.move_piece(coordinateMove)1960 1961 move = 'd2d4' 1962 coordinateMove = chess.notation_to_coordinate(move)1963 chess.move_piece(coordinateMove)1964 1965 move = 'e5d6'1966 coordinateMove = chess.notation_to_coordinate(move) 1967 chess.state.opponent_attack_dict = chess.gen_check_attacks()1968 1969 correctOutput = True1970 givenOutput = chess.king_in_check(coordinateMove) 1971 if (correctOutput == givenOutput):1972 print('Test 24: Correct')1973 correctCount += 11974 else:1975 print('Test 24: Incorrect')1976 print('Correct output:\n{}'.format(correctOutput))1977 print('Given output:\n{}'.format(givenOutput))1978 print()1979 1980 #Test 25 pin_count = 0, black en passant 1981 move = 'e5e6'1982 coordinateMove = chess.notation_to_coordinate(move) 1983 chess.state.opponent_attack_dict = chess.gen_check_attacks()1984 1985 correctOutput = False1986 givenOutput = chess.king_in_check(coordinateMove) 1987 if (correctOutput == givenOutput):1988 print('Test 25: Correct')1989 correctCount += 11990 else:1991 print('Test 25: Incorrect')1992 print('Correct output:\n{}'.format(correctOutput))1993 print('Given output:\n{}'.format(givenOutput))1994 print()1995 1996 #Test 26 Check en passant removing 2 pieces in a line with rook attacking king, opponent's pawn closer1997 chess = Chess()1998 move = 'a1a4' 1999 coordinateMove = chess.notation_to_coordinate(move)2000 chess.move_piece(coordinateMove)2001 2002 move = 'e1h5' 2003 coordinateMove = chess.notation_to_coordinate(move)2004 chess.move_piece(coordinateMove)2005 2006 move = 'a2a3' 2007 coordinateMove = chess.notation_to_coordinate(move)2008 chess.move_piece(coordinateMove)2009 2010 move = 'e2e5' 2011 coordinateMove = chess.notation_to_coordinate(move)2012 chess.move_piece(coordinateMove)2013 2014 move = 'f2f4' 2015 coordinateMove = chess.notation_to_coordinate(move)2016 chess.move_piece(coordinateMove)2017 2018 move = 'e5f6'2019 coordinateMove = chess.notation_to_coordinate(move) 2020 chess.state.opponent_attack_dict = chess.gen_check_attacks()2021 2022 correctOutput = True2023 givenOutput = chess.king_in_check(coordinateMove) 2024 if (correctOutput == givenOutput):2025 print('Test 26: Correct')2026 correctCount += 12027 else:2028 print('Test 26: Incorrect')2029 print('Correct output:\n{}'.format(correctOutput))2030 print('Given output:\n{}'.format(givenOutput))2031 print()2032 2033 #Test 27 Check en passant removing 2 pieces in a line with rook attacking king, opponent's pawn closer2034 chess = Chess() 2035 move = 'e5e6'2036 coordinateMove = chess.notation_to_coordinate(move) 2037 chess.state.opponent_attack_dict = chess.gen_check_attacks()2038 2039 correctOutput = False2040 givenOutput = chess.king_in_check(coordinateMove) 2041 if (correctOutput == givenOutput):2042 print('Test 27: Correct')2043 correctCount += 12044 else:2045 print('Test 27: Incorrect')2046 print('Correct output:\n{}'.format(correctOutput))2047 print('Given output:\n{}'.format(givenOutput))2048 print()2049 2050 #Test 28 Check en passant double check2051 chess = Chess()2052 2053 move = 'e2e5' 2054 coordinateMove = chess.notation_to_coordinate(move)2055 chess.move_piece(coordinateMove)2056 2057 move = 'd1e3' 2058 coordinateMove = chess.notation_to_coordinate(move)2059 chess.move_piece(coordinateMove)2060 2061 move = 'a2a3' 2062 coordinateMove = chess.notation_to_coordinate(move)2063 chess.move_piece(coordinateMove)2064 2065 move = 'd2d4' 2066 coordinateMove = chess.notation_to_coordinate(move)2067 chess.move_piece(coordinateMove)2068 2069 move = 'e5d6'2070 coordinateMove = chess.notation_to_coordinate(move) 2071 chess.state.opponent_attack_dict = chess.gen_check_attacks()2072 2073 correctOutput = True2074 givenOutput = chess.king_in_check(coordinateMove) 2075 if (correctOutput == givenOutput):2076 print('Test 28: Correct')2077 correctCount += 12078 else:2079 print('Test 28: Incorrect')2080 print('Correct output:\n{}'.format(correctOutput))2081 print('Given output:\n{}'.format(givenOutput))2082 print()2083 2084 #Test 29 Check en passant double check2085 chess = Chess()2086 2087 move = 'e2e5' 2088 coordinateMove = chess.notation_to_coordinate(move)2089 chess.move_piece(coordinateMove)2090 2091 move = 'd1e3' 2092 coordinateMove = chess.notation_to_coordinate(move)2093 chess.move_piece(coordinateMove)2094 2095 move = 'e1e4' 2096 coordinateMove = chess.notation_to_coordinate(move)2097 chess.move_piece(coordinateMove)2098 2099 move = 'd2d4' 2100 coordinateMove = chess.notation_to_coordinate(move)2101 chess.move_piece(coordinateMove)2102 2103 move = 'e5d6'2104 coordinateMove = chess.notation_to_coordinate(move) 2105 chess.state.opponent_attack_dict = chess.gen_check_attacks()2106 2107 correctOutput = True2108 givenOutput = chess.king_in_check(coordinateMove) 2109 if (correctOutput == givenOutput):2110 print('Test 29: Correct')2111 correctCount += 12112 else:2113 print('Test 29: Incorrect')2114 print('Correct output:\n{}'.format(correctOutput))2115 print('Given output:\n{}'.format(givenOutput))2116 print()2117 2118 #Test 30: Using the new input state function, determine if checkmate from a blocking piece moving to block another piece2119 chess = Chess()2120 2121 state_dict = {} 2122 state_dict['board'] = [['r', '·', '·', '·', '·', '·', 'k', '·'],2123 ['p', 'p', 'p', '·', '·', 'p', '·', '·'],2124 ['·', '·', '·', '·', '·', '·', '·', 'p'],2125 ['·', '·', '·', '·', '·', 'P', 'p', '·'],2126 ['·', '·', 'q', 'B', 'K', '·', '·', '·'],2127 ['·', '·', 'P', '·', 'n', '·', 'r', 'P'],2128 ['·', '·', '·', '·', '·', 'R', '·', '·'],2129 ['·', '·', '·', '·', '·', '·', 'Q', '·']]2130 2131 state_dict['board'].reverse()2132 state_dict['turn'] = 'black'2133 state_dict['current_move'] = None2134 state_dict['white_king_loc'] = (3, 4)2135 state_dict['black_king_loc'] = (7, 6)2136 state_dict['white_castle'] = [False, False]2137 state_dict['black_castle'] = [False, False]2138 state_dict['en_passant'] = []2139 state_dict['en_passant_loc'] = []2140 2141 #Opponent attack dictionary and legal move list2142 state_dict['opponent_attack_dict'] = {}2143 state_dict['legal_move_list'] = {}2144 2145 #Value Hueristic2146 state_dict['white_value'] = 02147 state_dict['black_value'] = 02148 state_dict['value'] = 02149 2150 chess.input_state(state_dict)2151 2152 move = 'a1e1' 2153 coordinateMove = chess.notation_to_coordinate(move)2154 chess.move_piece(coordinateMove) 2155 2156 move = 'd4e5' 2157 coordinateMove = chess.notation_to_coordinate(move)2158 chess.state.opponent_attack_dict = chess.gen_check_attacks()2159 2160 correctOutput = True2161 givenOutput = chess.king_in_check(coordinateMove) 2162 if (correctOutput == givenOutput):2163 print('Test 30: Correct')2164 correctCount += 12165 else:2166 print('Test 30: Incorrect')2167 print('Correct output:\n{}'.format(correctOutput))2168 print('Given output:\n{}'.format(givenOutput))2169 print()2170 2171 #Test 31: En_passant revealing check2172 chess = Chess()2173 2174 state_dict = {} 2175 state_dict['board'] = [['r', '·', '·', '·', '·', '·', 'k', '·'],2176 ['p', 'q', 'p', '·', '·', 'p', '·', '·'],2177 ['·', '·', '·', '·', '·', '·', '·', 'p'],2178 ['·', 'P', '·', '·', '·', 'P', 'p', '·'],2179 ['·', 'K', 'P', 'B', '·', '·', '·', '·'],2180 ['·', '·', 'P', '·', '·', '·', 'r', 'P'],2181 ['·', '·', '·', '·', '·', 'R', '·', '·'],2182 ['·', '·', '·', '·', '·', '·', 'Q', '·']]2183 2184 state_dict['board'].reverse()2185 state_dict['turn'] = 'black'2186 state_dict['current_move'] = None2187 state_dict['white_king_loc'] = (3, 1)2188 state_dict['black_king_loc'] = (7, 6)2189 state_dict['white_castle'] = [False, False]2190 state_dict['black_castle'] = [False, False]2191 state_dict['en_passant'] = []2192 state_dict['en_passant_loc'] = []2193 2194 #Opponent attack dictionary and legal move list2195 state_dict['opponent_attack_dict'] = {}2196 state_dict['legal_move_list'] = {}2197 2198 #Value Hueristic2199 state_dict['white_value'] = 02200 state_dict['black_value'] = 02201 state_dict['value'] = 02202 2203 chess.input_state(state_dict)2204 2205 move = 'c2c4' 2206 coordinateMove = chess.notation_to_coordinate(move)2207 chess.move_piece(coordinateMove) 2208 2209 move = 'b5c6' 2210 coordinateMove = chess.notation_to_coordinate(move)2211 chess.state.opponent_attack_dict = chess.gen_check_attacks()2212 2213 correctOutput = True2214 givenOutput = chess.king_in_check(coordinateMove) 2215 if (correctOutput == givenOutput):2216 print('Test 31: Correct')2217 correctCount += 12218 else:2219 print('Test 31: Incorrect')2220 print('Correct output:\n{}'.format(correctOutput))2221 print('Given output:\n{}'.format(givenOutput))2222 print()2223 2224 print('{} correct tests out of 31'.format(correctCount))2225 print() 2226 2227 #Testing the legal_moves() function2228 def test_legal_moves():2229 chess = Chess()2230 2231 correctCount = 02232 print('Testing the legal_moves() function')2233 2234 #Test 12235 legal_moves = chess.legal_moves()2236 correctOutput = ('((6, 0), (5, 0))\n'2237 '((6, 0), (4, 0))\n'2238 '((6, 1), (5, 1))\n'2239 '((6, 1), (4, 1))\n'2240 '((6, 2), (5, 2))\n'2241 '((6, 2), (4, 2))\n'2242 '((6, 3), (5, 3))\n'2243 '((6, 3), (4, 3))\n'2244 '((6, 4), (5, 4))\n'2245 '((6, 4), (4, 4))\n'2246 '((6, 5), (5, 5))\n'2247 '((6, 5), (4, 5))\n'2248 '((6, 6), (5, 6))\n'2249 '((6, 6), (4, 6))\n'2250 '((6, 7), (5, 7))\n'2251 '((6, 7), (4, 7))\n'2252 '((7, 1), (5, 2))\n'2253 '((7, 1), (5, 0))\n'2254 '((7, 6), (5, 7))\n'2255 '((7, 6), (5, 5))\n')2256 givenOutput = ''2257 for move in legal_moves:2258 givenOutput += str(move)2259 givenOutput += '\n'2260 if (correctOutput == givenOutput):2261 print('Test 1: Correct')2262 correctCount += 12263 else:2264 print('Test 1: Incorrect')2265 print('Correct output:\n{}'.format(correctOutput))2266 print('Given output:\n{}'.format(givenOutput))2267 print()2268 2269 2270 #Test 22271 move = 'e2e4'2272 coordinateMove = chess.notation_to_coordinate(move) 2273 chess.move_piece(coordinateMove) 2274 2275 2276 move = 'd2d4'2277 coordinateMove = chess.notation_to_coordinate(move) 2278 chess.move_piece(coordinateMove) 2279 2280 2281 legal_moves = chess.legal_moves()2282 correctOutput = ('((4, 4), (3, 4))\n'2283 '((4, 4), (3, 3))\n'2284 '((6, 0), (5, 0))\n'2285 '((6, 0), (4, 0))\n'2286 '((6, 1), (5, 1))\n'2287 '((6, 1), (4, 1))\n'2288 '((6, 2), (5, 2))\n'2289 '((6, 2), (4, 2))\n'2290 '((6, 3), (5, 3))\n'2291 '((6, 3), (4, 3))\n'2292 '((6, 5), (5, 5))\n'2293 '((6, 5), (4, 5))\n'2294 '((6, 6), (5, 6))\n'2295 '((6, 6), (4, 6))\n'2296 '((6, 7), (5, 7))\n'2297 '((6, 7), (4, 7))\n'2298 '((7, 1), (5, 2))\n'2299 '((7, 1), (5, 0))\n'2300 '((7, 3), (6, 4))\n'2301 '((7, 3), (5, 5))\n'2302 '((7, 3), (4, 6))\n'2303 '((7, 3), (3, 7))\n'2304 '((7, 4), (6, 4))\n'2305 '((7, 5), (6, 4))\n'2306 '((7, 5), (5, 3))\n'2307 '((7, 5), (4, 2))\n'2308 '((7, 5), (3, 1))\n'2309 '((7, 5), (2, 0))\n'2310 '((7, 6), (5, 7))\n'2311 '((7, 6), (6, 4))\n'2312 '((7, 6), (5, 5))\n')2313 givenOutput = ''2314 for move in legal_moves:2315 givenOutput += str(move)2316 givenOutput += '\n'2317 if (correctOutput == givenOutput):2318 print('Test 2: Correct')2319 correctCount += 12320 else:2321 print('Test 2: Incorrect')2322 print('Correct output:\n{}'.format(correctOutput))2323 print('Given output:\n{}'.format(givenOutput))2324 print()2325 2326 #Test 32327 move = 'e4d5'2328 coordinateMove = chess.notation_to_coordinate(move) 2329 chess.move_piece(coordinateMove) 2330 2331 2332 move = 'd1d4'2333 coordinateMove = chess.notation_to_coordinate(move) 2334 chess.move_piece(coordinateMove) 2335 2336 2337 move = 'd2d3'2338 coordinateMove = chess.notation_to_coordinate(move) 2339 chess.move_piece(coordinateMove) 2340 2341 2342 move = 'd4e4'2343 coordinateMove = chess.notation_to_coordinate(move) 2344 chess.move_piece(coordinateMove) 2345 2346 2347 legal_moves = chess.legal_moves()2348 correctOutput = ('((7, 2), (5, 4))\n'2349 '((7, 3), (6, 4))\n'2350 '((7, 4), (6, 3))\n'2351 '((7, 5), (6, 4))\n'2352 '((7, 6), (6, 4))\n')2353 givenOutput = ''2354 for move in legal_moves:2355 givenOutput += str(move)2356 givenOutput += '\n'2357 if (correctOutput == givenOutput):2358 print('Test 3: Correct')2359 correctCount += 12360 else:2361 print('Test 3: Incorrect')2362 print('Correct output:\n{}'.format(correctOutput))2363 print('Given output:\n{}'.format(givenOutput))2364 print()2365 2366 #Test 42367 move = 'e1d2'2368 coordinateMove = chess.notation_to_coordinate(move) 2369 chess.move_piece(coordinateMove) 2370 2371 2372 move = 'e4e7'2373 coordinateMove = chess.notation_to_coordinate(move) 2374 chess.move_piece(coordinateMove) 2375 2376 2377 legal_moves = chess.legal_moves()2378 correctOutput = ('((6, 3), (6, 4))\n'2379 '((6, 3), (5, 2))\n' 2380 '((7, 3), (6, 4))\n'2381 '((7, 5), (6, 4))\n'2382 '((7, 6), (6, 4))\n')2383 givenOutput = ''2384 for move in legal_moves:2385 givenOutput += str(move)2386 givenOutput += '\n'2387 if (correctOutput == givenOutput):2388 print('Test 4: Correct')2389 correctCount += 12390 else:2391 print('Test 4: Incorrect')2392 print('Correct output:\n{}'.format(correctOutput))2393 print('Given output:\n{}'.format(givenOutput))2394 print()2395 2396 #Test 52397 chess = Chess()2398 2399 move = 'b1a3'2400 coordinateMove = chess.notation_to_coordinate(move) 2401 chess.move_piece(coordinateMove) 2402 2403 2404 move = 'a1e4'2405 coordinateMove = chess.notation_to_coordinate(move) 2406 chess.move_piece(coordinateMove) 2407 2408 2409 move = 'c1a4'2410 coordinateMove = chess.notation_to_coordinate(move) 2411 chess.move_piece(coordinateMove) 2412 2413 2414 move = 'h1d4'2415 coordinateMove = chess.notation_to_coordinate(move) 2416 chess.move_piece(coordinateMove) 2417 2418 2419 move = 'd1a5'2420 coordinateMove = chess.notation_to_coordinate(move) 2421 chess.move_piece(coordinateMove) 2422 2423 2424 move = 'c2c3'2425 coordinateMove = chess.notation_to_coordinate(move) 2426 chess.move_piece(coordinateMove) 2427 2428 2429 move = 'g1h3'2430 coordinateMove = chess.notation_to_coordinate(move) 2431 chess.move_piece(coordinateMove) 2432 2433 2434 move = 'f2f3'2435 coordinateMove = chess.notation_to_coordinate(move) 2436 chess.move_piece(coordinateMove) 2437 2438 2439 move = 'f1h4'2440 coordinateMove = chess.notation_to_coordinate(move) 2441 chess.move_piece(coordinateMove) 2442 2443 2444 move = 'a2a3'2445 coordinateMove = chess.notation_to_coordinate(move) 2446 chess.move_piece(coordinateMove) 2447 2448 2449 legal_moves = chess.legal_moves()2450 correctOutput = ('((3, 0), (2, 0))\n'2451 '((3, 0), (3, 1))\n'2452 '((3, 0), (3, 2))\n'2453 '((3, 0), (3, 3))\n'2454 '((3, 0), (2, 1))\n'2455 '((3, 0), (1, 2))\n'2456 '((3, 0), (0, 3))\n'2457 '((3, 0), (4, 1))\n'2458 '((3, 0), (5, 2))\n'2459 '((4, 0), (3, 1))\n'2460 '((4, 0), (2, 2))\n'2461 '((4, 0), (5, 1))\n'2462 '((4, 7), (5, 6))\n'2463 '((4, 7), (3, 6))\n'2464 '((4, 7), (2, 5))\n'2465 '((5, 0), (3, 1))\n'2466 '((5, 0), (4, 2))\n'2467 '((5, 0), (7, 1))\n'2468 '((5, 7), (7, 6))\n'2469 '((5, 7), (4, 5))\n'2470 '((5, 7), (3, 6))\n'2471 '((6, 1), (5, 1))\n'2472 '((6, 1), (4, 1))\n'2473 '((6, 2), (5, 2))\n'2474 '((6, 2), (4, 2))\n'2475 '((6, 3), (5, 3))\n'2476 '((6, 3), (4, 3))\n'2477 '((6, 4), (5, 4))\n'2478 '((6, 4), (4, 4))\n'2479 '((6, 5), (5, 5))\n'2480 '((6, 5), (4, 5))\n'2481 '((6, 6), (5, 6))\n'2482 '((6, 6), (4, 6))\n'2483 '((7, 0), (7, 1))\n'2484 '((7, 0), (7, 2))\n'2485 '((7, 0), (7, 3))\n'2486 '((7, 4), (7, 2))\n'2487 '((7, 4), (7, 5))\n'2488 '((7, 4), (7, 3))\n'2489 '((7, 7), (7, 6))\n'2490 '((7, 7), (7, 5))\n'2491 '((7, 4), (7, 6))\n')2492 givenOutput = ''2493 for move in legal_moves:2494 givenOutput += str(move)2495 givenOutput += '\n'2496 if (correctOutput == givenOutput):2497 print('Test 5: Correct')2498 correctCount += 12499 else:2500 print('Test 5: Incorrect')2501 print('Correct output:\n{}'.format(correctOutput))2502 print('Given output:\n{}'.format(givenOutput))2503 print()25042505 #Test 6 2506 move = 'e2h5'2507 coordinateMove = chess.notation_to_coordinate(move) 2508 chess.move_piece(coordinateMove) 2509 2510 2511 move = 'b2b3'2512 coordinateMove = chess.notation_to_coordinate(move) 2513 chess.move_piece(coordinateMove) 2514 2515 2516 legal_moves = chess.legal_moves()2517 correctOutput = ('((7, 4), (7, 5))\n'2518 '((7, 4), (7, 3))\n')2519 givenOutput = ''2520 for move in legal_moves:2521 givenOutput += str(move)2522 givenOutput += '\n'2523 if (correctOutput == givenOutput):2524 print('Test 6: Correct')2525 correctCount += 12526 else:2527 print('Test 6: Incorrect')2528 print('Correct output:\n{}'.format(correctOutput))2529 print('Given output:\n{}'.format(givenOutput))2530 print()2531 2532 #Test 7 2533 move = 'd2h6'2534 coordinateMove = chess.notation_to_coordinate(move) 2535 chess.move_piece(coordinateMove) 2536 2537 2538 move = 'e4f4'2539 coordinateMove = chess.notation_to_coordinate(move) 2540 chess.move_piece(coordinateMove) 2541 2542 2543 legal_moves = chess.legal_moves()2544 correctOutput = ('((2, 7), (1, 6))\n'2545 '((3, 0), (2, 0))\n'2546 '((3, 0), (3, 1))\n'2547 '((3, 0), (3, 2))\n'2548 '((3, 0), (3, 3))\n'2549 '((3, 0), (2, 1))\n'2550 '((3, 0), (4, 1))\n'2551 '((3, 0), (5, 2))\n'2552 '((3, 0), (6, 3))\n'2553 '((4, 0), (3, 1))\n'2554 '((4, 0), (2, 2))\n'2555 '((4, 0), (5, 1))\n'2556 '((4, 7), (5, 6))\n'2557 '((4, 7), (3, 6))\n'2558 '((4, 7), (2, 5))\n'2559 '((5, 0), (3, 1))\n'2560 '((5, 0), (4, 2))\n'2561 '((5, 0), (7, 1))\n'2562 '((5, 7), (7, 6))\n'2563 '((5, 7), (4, 5))\n'2564 '((5, 7), (3, 6))\n'2565 '((6, 1), (5, 1))\n'2566 '((6, 1), (4, 1))\n'2567 '((6, 2), (5, 2))\n'2568 '((6, 2), (4, 2))\n'2569 '((6, 5), (5, 5))\n'2570 '((6, 5), (4, 5))\n'2571 '((6, 6), (5, 6))\n'2572 '((6, 6), (4, 6))\n'2573 '((7, 0), (7, 1))\n'2574 '((7, 0), (7, 2))\n'2575 '((7, 0), (7, 3))\n'2576 '((7, 4), (6, 4))\n'2577 '((7, 4), (7, 5))\n'2578 '((7, 7), (7, 6))\n'2579 '((7, 7), (7, 5))\n'2580 '((7, 4), (7, 6))\n')2581 givenOutput = ''2582 for move in legal_moves:2583 givenOutput += str(move)2584 givenOutput += '\n'2585 if (correctOutput == givenOutput):2586 print('Test 7: Correct')2587 correctCount += 12588 else:2589 print('Test 7: Incorrect')2590 print('Correct output:\n{}'.format(correctOutput))2591 print('Given output:\n{}'.format(givenOutput))2592 print()2593 2594 #Test 8 2595 move = 'f2a7'2596 coordinateMove = chess.notation_to_coordinate(move) 2597 chess.move_piece(coordinateMove) 2598 2599 2600 move = 'd4c4'2601 coordinateMove = chess.notation_to_coordinate(move) 2602 chess.move_piece(coordinateMove) 2603 26042605 move = 'g2a8'2606 coordinateMove = chess.notation_to_coordinate(move) 2607 chess.move_piece(coordinateMove) 2608 2609 2610 move = 'g2g3'2611 coordinateMove = chess.notation_to_coordinate(move) 2612 chess.move_piece(coordinateMove) 2613 2614 2615 move = 'c2h8'2616 coordinateMove = chess.notation_to_coordinate(move) 2617 chess.move_piece(coordinateMove) 2618 2619 2620 move = 'd2d3'2621 coordinateMove = chess.notation_to_coordinate(move) 2622 chess.move_piece(coordinateMove) 2623 2624 2625 legal_moves = chess.legal_moves()2626 correctOutput = ('((0, 0), (0, 1))\n'2627 '((0, 0), (1, 1))\n'2628 '((0, 0), (2, 2))\n'2629 '((0, 7), (1, 7))\n'2630 '((0, 7), (0, 6))\n'2631 '((0, 7), (1, 6))\n'2632 '((0, 7), (2, 5))\n'2633 '((1, 0), (0, 1))\n'2634 '((3, 0), (2, 0))\n'2635 '((3, 0), (3, 1))\n'2636 '((3, 0), (3, 2))\n'2637 '((3, 0), (2, 1))\n'2638 '((3, 0), (4, 1))\n'2639 '((3, 0), (5, 2))\n'2640 '((3, 0), (6, 3))\n'2641 '((3, 7), (2, 6))\n'2642 '((4, 0), (3, 1))\n'2643 '((4, 0), (2, 2))\n'2644 '((4, 0), (5, 1))\n'2645 '((4, 0), (6, 2))\n'2646 '((4, 0), (7, 3))\n'2647 '((4, 7), (5, 6))\n'2648 '((4, 7), (6, 5))\n'2649 '((4, 7), (3, 6))\n'2650 '((4, 7), (2, 5))\n'2651 '((5, 0), (3, 1))\n'2652 '((5, 0), (4, 2))\n'2653 '((5, 0), (6, 2))\n'2654 '((5, 0), (7, 1))\n'2655 '((5, 7), (7, 6))\n'2656 '((5, 7), (6, 5))\n'2657 '((5, 7), (4, 5))\n'2658 '((5, 7), (3, 6))\n'2659 '((6, 1), (5, 1))\n'2660 '((6, 1), (4, 1))\n'2661 '((7, 0), (7, 1))\n'2662 '((7, 0), (7, 2))\n'2663 '((7, 0), (7, 3))\n'2664 '((7, 4), (6, 4))\n'2665 '((7, 4), (7, 3))\n'2666 '((7, 4), (6, 3))\n'2667 '((7, 7), (7, 6))\n'2668 '((7, 7), (7, 5))\n')2669 givenOutput = ''2670 for move in legal_moves:2671 givenOutput += str(move)2672 givenOutput += '\n'2673 if (correctOutput == givenOutput):2674 print('Test 8: Correct')2675 correctCount += 12676 else:2677 print('Test 8: Incorrect')2678 print('Correct output:\n{}'.format(correctOutput))2679 print('Given output:\n{}'.format(givenOutput))2680 print()2681 2682 #Test 9 2683 move = 'b2b3'2684 coordinateMove = chess.notation_to_coordinate(move) 2685 chess.move_piece(coordinateMove) 2686 2687 2688 move = 'f4g4'2689 coordinateMove = chess.notation_to_coordinate(move) 2690 chess.move_piece(coordinateMove) 2691 2692 2693 legal_moves = chess.legal_moves()2694 correctOutput = ('((0, 0), (0, 1))\n'2695 '((0, 0), (1, 1))\n'2696 '((0, 0), (2, 2))\n'2697 '((0, 7), (1, 7))\n'2698 '((0, 7), (0, 6))\n'2699 '((0, 7), (1, 6))\n'2700 '((0, 7), (2, 5))\n'2701 '((1, 0), (0, 1))\n'2702 '((3, 0), (2, 0))\n'2703 '((3, 0), (3, 1))\n'2704 '((3, 0), (3, 2))\n'2705 '((3, 0), (2, 1))\n'2706 '((3, 0), (4, 1))\n'2707 '((3, 0), (5, 2))\n'2708 '((3, 0), (6, 3))\n'2709 '((3, 7), (2, 6))\n'2710 '((4, 0), (3, 1))\n'2711 '((4, 0), (2, 2))\n'2712 '((4, 7), (5, 6))\n'2713 '((4, 7), (6, 5))\n'2714 '((4, 7), (3, 6))\n'2715 '((5, 0), (3, 1))\n'2716 '((5, 0), (4, 2))\n'2717 '((5, 0), (6, 2))\n'2718 '((5, 0), (7, 1))\n'2719 '((5, 1), (4, 1))\n'2720 '((5, 7), (7, 6))\n'2721 '((5, 7), (6, 5))\n'2722 '((5, 7), (4, 5))\n'2723 '((5, 7), (3, 6))\n'2724 '((7, 0), (7, 1))\n'2725 '((7, 0), (7, 2))\n'2726 '((7, 0), (7, 3))\n'2727 '((7, 4), (6, 4))\n'2728 '((7, 4), (7, 5))\n'2729 '((7, 4), (7, 3))\n'2730 '((7, 4), (6, 5))\n'2731 '((7, 4), (6, 3))\n'2732 '((7, 7), (7, 6))\n'2733 '((7, 7), (7, 5))\n')2734 2735 givenOutput = ''2736 for move in legal_moves:2737 givenOutput += str(move)2738 givenOutput += '\n'2739 if (correctOutput == givenOutput):2740 print('Test 9: Correct')2741 correctCount += 12742 else:2743 print('Test 9: Incorrect')2744 print('Correct output:\n{}'.format(correctOutput))2745 print('Given output:\n{}'.format(givenOutput))2746 print()2747 2748 #Test 10 Checkmate2749 chess = Chess()2750 2751 move = 'e2e4' 2752 coordinateMove = chess.notation_to_coordinate(move) 2753 chess.move_piece(coordinateMove) 2754 2755 2756 move = 'a2a4' 2757 coordinateMove = chess.notation_to_coordinate(move) 2758 chess.move_piece(coordinateMove) 2759 2760 2761 move = 'f1c4' 2762 coordinateMove = chess.notation_to_coordinate(move) 2763 chess.move_piece(coordinateMove) 2764 2765 2766 move = 'h2h4' 2767 coordinateMove = chess.notation_to_coordinate(move) 2768 chess.move_piece(coordinateMove) 2769 2770 2771 move = 'd1f3' 2772 coordinateMove = chess.notation_to_coordinate(move) 2773 chess.move_piece(coordinateMove) 2774 2775 2776 move = 'a4a5' 2777 coordinateMove = chess.notation_to_coordinate(move) 2778 chess.move_piece(coordinateMove) 2779 2780 2781 move = 'f3f7' 2782 coordinateMove = chess.notation_to_coordinate(move) 2783 chess.move_piece(coordinateMove) 2784 2785 2786 legal_moves = chess.legal_moves()2787 correctOutput = ''2788 givenOutput = ''2789 for move in legal_moves:2790 givenOutput += str(move)2791 givenOutput += '\n' 2792 if (correctOutput == givenOutput):2793 print('Test 10: Correct')2794 correctCount += 12795 else:2796 print('Test 10: Incorrect')2797 print('Correct output:\n{}'.format(correctOutput))2798 print('Given output:\n{}'.format(givenOutput))2799 print() 2800 2801 #Test 11 Bug response: Take knight while knight is checking king2802 chess = Chess()2803 2804 move = 'b1c3' 2805 coordinateMove = chess.notation_to_coordinate(move) 2806 chess.move_piece(coordinateMove) 2807 2808 move = 'b1c3' 2809 coordinateMove = chess.notation_to_coordinate(move) 2810 chess.move_piece(coordinateMove)28112812 move = 'c3d5' 2813 coordinateMove = chess.notation_to_coordinate(move) 2814 chess.move_piece(coordinateMove)28152816 move = 'c3b1' 2817 coordinateMove = chess.notation_to_coordinate(move) 2818 chess.move_piece(coordinateMove)2819 2820 move = 'd5f6' 2821 coordinateMove = chess.notation_to_coordinate(move) 2822 chess.move_piece(coordinateMove)2823 2824 legal_moves = chess.legal_moves()2825 correctOutput = ('((6, 4), (5, 5))\n'2826 '((6, 6), (5, 5))\n'2827 '((7, 6), (5, 5))\n')2828 givenOutput = ''2829 for move in legal_moves:2830 givenOutput += str(move)2831 givenOutput += '\n' 2832 if (correctOutput == givenOutput):2833 print('Test 11: Correct')2834 correctCount += 12835 else:2836 print('Test 11: Incorrect')2837 print('Correct output:\n{}'.format(correctOutput))2838 print('Given output:\n{}'.format(givenOutput))2839 print() 28402841 print('{} correct tests out of 11'.format(correctCount))2842 print()2843 2844 #Testing king in check after a move2845 def test_king_ray_check():2846 chess = Chess()2847 2848 correctCount = 02849 print('Testing the king_ray_check() function') 2850 2851 #Test 1 2852 move = 'e2e4' 2853 coordinateMove = chess.notation_to_coordinate(move) 2854 chess.move_piece(coordinateMove) 2855 2856 givenOutput = chess.king_ray_check()2857 correctOutput = False2858 if (correctOutput == givenOutput):2859 print('Test 1: Correct')2860 correctCount += 12861 else:2862 print('Test 1: Incorrect')2863 print('Correct output:\n{}'.format(correctOutput))2864 print('Given output:\n{}'.format(givenOutput))2865 print()2866 2867 #Test 22868 chess = Chess()2869 move = 'e2e4' 2870 coordinateMove = chess.notation_to_coordinate(move) 2871 chess.move_piece(coordinateMove) 2872 2873 2874 move = 'e2e4' 2875 coordinateMove = chess.notation_to_coordinate(move) 2876 chess.move_piece(coordinateMove) 2877 2878 2879 move = 'a1e5' 2880 coordinateMove = chess.notation_to_coordinate(move) 2881 chess.move_piece(coordinateMove) 2882 2883 2884 givenOutput = chess.king_ray_check()2885 correctOutput = True2886 if (correctOutput == givenOutput):2887 print('Test 2: Correct')2888 correctCount += 12889 else:2890 print('Test 2: Incorrect')2891 print('Correct output:\n{}'.format(correctOutput))2892 print('Given output:\n{}'.format(givenOutput))2893 print()2894 2895 #Test 3 2896 chess = Chess()2897 2898 move = 'e2e4' 2899 coordinateMove = chess.notation_to_coordinate(move) 2900 chess.move_piece(coordinateMove) 2901 2902 2903 move = 'd2d4' 2904 coordinateMove = chess.notation_to_coordinate(move) 2905 chess.move_piece(coordinateMove) 2906 2907 2908 move = 'c1a4' 2909 coordinateMove = chess.notation_to_coordinate(move) 2910 chess.move_piece(coordinateMove) 2911 2912 2913 givenOutput = chess.king_ray_check()2914 correctOutput = True2915 if (correctOutput == givenOutput):2916 print('Test 3: Correct')2917 correctCount += 12918 else:2919 print('Test 3: Incorrect')2920 print('Correct output:\n{}'.format(correctOutput))2921 print('Given output:\n{}'.format(givenOutput))2922 print()2923 2924 #Test 4 2925 chess = Chess()2926 2927 move = 'e2e4' 2928 coordinateMove = chess.notation_to_coordinate(move) 2929 chess.move_piece(coordinateMove) 2930 2931 2932 move = 'f2f4' 2933 coordinateMove = chess.notation_to_coordinate(move) 2934 chess.move_piece(coordinateMove) 2935 2936 2937 move = 'd1h5' 2938 coordinateMove = chess.notation_to_coordinate(move) 2939 chess.move_piece(coordinateMove) 2940 2941 2942 givenOutput = chess.king_ray_check()2943 correctOutput = True2944 if (correctOutput == givenOutput):2945 print('Test 4: Correct')2946 correctCount += 12947 else:2948 print('Test 4: Incorrect')2949 print('Correct output:\n{}'.format(correctOutput))2950 print('Given output:\n{}'.format(givenOutput))2951 print()2952 2953 #Test 5 2954 chess = Chess()2955 2956 move = 'g1f6' 2957 coordinateMove = chess.notation_to_coordinate(move) 2958 chess.move_piece(coordinateMove) 2959 2960 givenOutput = chess.king_ray_check()2961 correctOutput = True2962 if (correctOutput == givenOutput):2963 print('Test 5: Correct')2964 correctCount += 12965 else:2966 print('Test 5: Incorrect')2967 print('Correct output:\n{}'.format(correctOutput))2968 print('Given output:\n{}'.format(givenOutput))2969 print()2970 2971 #Test 6 2972 chess = Chess()2973 2974 move = 'e2e4' 2975 coordinateMove = chess.notation_to_coordinate(move) 2976 chess.move_piece(coordinateMove) 2977 2978 2979 move = 'f2f4' 2980 coordinateMove = chess.notation_to_coordinate(move) 2981 chess.move_piece(coordinateMove) 2982 2983 2984 move = 'e4f7' 2985 coordinateMove = chess.notation_to_coordinate(move) 2986 chess.move_piece(coordinateMove) 2987 2988 2989 givenOutput = chess.king_ray_check()2990 correctOutput = True2991 if (correctOutput == givenOutput):2992 print('Test 6: Correct')2993 correctCount += 12994 else:2995 print('Test 6: Incorrect')2996 print('Correct output:\n{}'.format(correctOutput))2997 print('Given output:\n{}'.format(givenOutput))2998 print()2999 3000 #Test 7 3001 chess = Chess()3002 3003 move = 'e2e4' 3004 coordinateMove = chess.notation_to_coordinate(move) 3005 chess.move_piece(coordinateMove) 3006 3007 3008 move = 'd2d4' 3009 coordinateMove = chess.notation_to_coordinate(move) 3010 chess.move_piece(coordinateMove) 3011 3012 3013 move = 'a2d7' 3014 coordinateMove = chess.notation_to_coordinate(move) 3015 chess.move_piece(coordinateMove) 3016 3017 3018 givenOutput = chess.king_ray_check()3019 correctOutput = True3020 if (correctOutput == givenOutput):3021 print('Test 7: Correct')3022 correctCount += 13023 else:3024 print('Test 7: Incorrect')3025 print('Correct output:\n{}'.format(correctOutput))3026 print('Given output:\n{}'.format(givenOutput))3027 print()3028 3029 #Test 8 3030 chess = Chess()3031 3032 move = 'e2e4' 3033 coordinateMove = chess.notation_to_coordinate(move) 3034 chess.move_piece(coordinateMove) 3035 3036 3037 move = 'd2d4' 3038 coordinateMove = chess.notation_to_coordinate(move) 3039 chess.move_piece(coordinateMove) 3040 3041 3042 move = 'a2c6' 3043 coordinateMove = chess.notation_to_coordinate(move) 3044 chess.move_piece(coordinateMove) 3045 3046 3047 givenOutput = chess.king_ray_check()3048 correctOutput = False3049 if (correctOutput == givenOutput):3050 print('Test 8: Correct')3051 correctCount += 13052 else:3053 print('Test 8: Incorrect')3054 print('Correct output:\n{}'.format(correctOutput))3055 print('Given output:\n{}'.format(givenOutput))3056 print()3057 3058 #Test 9 3059 chess = Chess()3060 3061 move = 'e2e4' 3062 coordinateMove = chess.notation_to_coordinate(move) 3063 chess.move_piece(coordinateMove) 3064 3065 3066 move = 'f2f4' 3067 coordinateMove = chess.notation_to_coordinate(move) 3068 chess.move_piece(coordinateMove) 3069 3070 3071 move = 'e4g6' 3072 coordinateMove = chess.notation_to_coordinate(move) 3073 chess.move_piece(coordinateMove) 3074 3075 3076 givenOutput = chess.king_ray_check()3077 correctOutput = False3078 if (correctOutput == givenOutput):3079 print('Test 9: Correct')3080 correctCount += 13081 else:3082 print('Test 9: Incorrect')3083 print('Correct output:\n{}'.format(correctOutput))3084 print('Given output:\n{}'.format(givenOutput))3085 print()3086 3087 #Test 10 3088 chess = Chess()3089 3090 state_dict = {} 3091 state_dict['board'] = [['r', '·', 'b', '·', '·', '·', '·', 'Q'],3092 ['p', 'p', 'p', 'k', 'P', '·', '·', 'p'],3093 ['q', '·', 'n', '·', '·', '·', '·', '·'],3094 ['·', '·', '·', '·', '·', 'r', '·', '·'],3095 ['·', '·', 'P', '·', '·', '·', '·', '·'],3096 ['·', 'P', '·', '·', 'R', '·', '·', '·'],3097 ['·', 'P', '·', 'N', 'K', '·', 'N', '·'],3098 ['·', '·', '·', '·', '·', '·', '·', '·']]3099 3100 state_dict['board']3101 state_dict['turn'] = 'white'3102 state_dict['current_move'] = None3103 state_dict['white_king_loc'] = (6, 4)3104 state_dict['black_king_loc'] = (1, 3)3105 state_dict['white_castle'] = [False, False]3106 state_dict['black_castle'] = [False, False]3107 state_dict['en_passant'] = []3108 state_dict['en_passant_loc'] = []3109 3110 #Opponent attack dictionary and legal move list3111 state_dict['opponent_attack_dict'] = {}3112 state_dict['legal_move_list'] = {}3113 3114 #Value Hueristic3115 state_dict['white_value'] = 03116 state_dict['black_value'] = 03117 state_dict['value'] = 03118 3119 chess.input_state(state_dict)3120 3121 move = 'e7e8' 3122 coordinateMove = chess.notation_to_coordinate(move)3123 chess.move_piece(coordinateMove)3124 3125 move = 'd2d3' 3126 coordinateMove = chess.notation_to_coordinate(move)3127 chess.move_piece(coordinateMove)3128 3129 move = 'd2e4' 3130 coordinateMove = chess.notation_to_coordinate(move)3131 chess.move_piece(coordinateMove)3132 3133 correctOutput = True3134 givenOutput = chess.king_ray_check() 3135 if (correctOutput == givenOutput):3136 print('Test 10: Correct')3137 correctCount += 13138 else:3139 print('Test 10: Incorrect')3140 print('Correct output:\n{}'.format(correctOutput))3141 print('Given output:\n{}'.format(givenOutput))3142 print()3143 3144 print('{} correct tests out of 10'.format(correctCount))3145 print() 3146 3147 3148 #Test the formatting of moves3149 def test_format_move():3150 chess = Chess()3151 3152 correctCount = 03153 print('Testing the format_move() function')3154 3155 #Test 13156 move = 'e2e45'3157 print('Test 1 Correct output:')3158 print('Input move in the form such as: e2e4')3159 print('Given output:')3160 chess.format_move(move)3161 3162 print()3163 3164 #Test 23165 move = 'k2e4'3166 print('Test 2 Correct output:')3167 print('Input move in the form such as: e2e4')3168 print('Given output:')3169 chess.format_move(move)3170 3171 print()3172 3173 #Test 33174 move = 'e2z4'3175 print('Test 3 Correct output:')3176 print('Input move in the form such as: e2e4')3177 print('Given output:')3178 chess.format_move(move)3179 3180 print()3181 3182 #Test 43183 move = 'e9e4'3184 print('Test 4 Correct output:')3185 print('Input move in the form such as: e2e4')3186 print('Given output:')3187 chess.format_move(move)3188 3189 print()3190 3191 #Test 53192 move = 'e2e9'3193 print('Test 5 Correct output:')3194 print('Input move in the form such as: e2e4')3195 print('Given output:')3196 chess.format_move(move)3197 3198 print()3199 3200 #Test 63201 move = 'e2e4'3202 correctOutput = '((6, 4), (4, 4))'3203 givenOutput = str(chess.format_move(move))3204 3205 if (correctOutput == givenOutput):3206 print('Test 6: Correct')3207 correctCount += 13208 else:3209 print('Test 6: Incorrect')3210 print('Correct output:\n{}'.format(correctOutput))3211 print('Given output:\n{}'.format(givenOutput))3212 print()3213 3214 print()3215 3216 #Testing the move function3217 def test_move():3218 chess = Chess()3219 3220 correctCount = 03221 print('Testing the move() function')3222 3223 #Test 13224 move = 'e2e4'3225 chess.move(move)3226 correctOutput = ('RNBQKBNR\n'3227 'PPPP·PPP\n'3228 '········\n'3229 '····P···\n'3230 '········\n'3231 '········\n'3232 'pppppppp\n'3233 'rnbqkbnr\n')3234 givenOutput = Test.boardString(chess) 3235 if (correctOutput == givenOutput):3236 print('Test 1: Correct')3237 correctCount += 13238 else:3239 print('Test 1: Incorrect')3240 print('Correct output:\n{}'.format(correctOutput))3241 print('Given output:\n{}'.format(givenOutput))3242 print()3243 3244 print()32453246 #Test 23247 move = 'e2e45'3248 print('Test 2 Correct output:')3249 print('Input move in the form such as: e2e4')3250 print('Given output:')3251 chess.move(move)3252 3253 print()3254 3255 #Test 33256 move = 'e2e5'3257 print('Test 3 Correct output:')3258 print('Not a valid move')3259 print('Given output:')3260 chess.move(move)32613262 print()3263 3264 #Test 43265 move = 'e2e4'3266 chess.move(move)3267 correctOutput = ('rnbqkbnr\n'3268 'pppp·ppp\n'3269 '········\n'3270 '····p···\n'3271 '····P···\n'3272 '········\n'3273 'PPPP·PPP\n'3274 'RNBQKBNR\n')3275 givenOutput = Test.boardString(chess) 3276 if (correctOutput == givenOutput):3277 print('Test 4: Correct')3278 correctCount += 13279 else:3280 print('Test 4: Incorrect')3281 print('Correct output:\n{}'.format(correctOutput))3282 print('Given output:\n{}'.format(givenOutput))3283 print()3284 3285 print()3286 3287 #Test 53288 move = 'f1c4'3289 chess.move(move)3290 3291 move = 'b1c3'3292 chess.move(move)3293 3294 move = 'd1f3'3295 chess.move(move)3296 3297 move = 'd2d3'3298 chess.move(move)3299 3300 move = 'f3f7'3301 chess.move(move) 3302 correctOutput = ('RNB·K·NR\n'3303 'PPPP·PPP\n'3304 '········\n'3305 '··B·P···\n'3306 '····p···\n'3307 '··np····\n'3308 'ppp··Qpp\n'3309 'r·bqkbnr\n')3310 givenOutput = Test.boardString(chess) 3311 if (correctOutput == givenOutput):3312 print('Test 5: Correct')3313 correctCount += 13314 else:3315 print('Test 5: Incorrect')3316 print('Correct output:\n{}'.format(correctOutput))3317 print('Given output:\n{}'.format(givenOutput))3318 print()3319 3320 print() 33213322 #Test 63323 move = 'e1e2'3324 print('Test 6 Correct output:')3325 print('Not a valid move')3326 print('Given output:')3327 chess.move(move)33283329 print()3330 3331 #Testing the undo function3332 def test_undo_move():3333 chess = Chess()3334 3335 correctCount = 03336 print('Testing the undo_move() function')3337 3338 #Test 13339 move = 'e2e4' 3340 chess.move(move) 3341 correctOutput = ('RNBQKBNR\n'3342 'PPPP·PPP\n'3343 '········\n'3344 '····P···\n'3345 '········\n'3346 '········\n'3347 'pppppppp\n'3348 'rnbqkbnr\n')3349 3350 givenOutput = Test.boardString(chess)3351 if (correctOutput == givenOutput):3352 print('Test 1: Correct')3353 correctCount += 13354 else:3355 print('Test 1: Incorrect')3356 print('Correct output:\n{}'.format(correctOutput))3357 print('Given output:\n{}'.format(givenOutput))3358 print()3359 3360 #Test 23361 move = 'e2e4' 3362 chess.move(move)3363 chess.undo_move()3364 correctOutput = ('RNBQKBNR\n'3365 'PPPP·PPP\n'3366 '········\n'3367 '····P···\n'3368 '········\n'3369 '········\n'3370 'pppppppp\n'3371 'rnbqkbnr\n')3372 3373 givenOutput = Test.boardString(chess)3374 if (correctOutput == givenOutput):3375 print('Test 2: Correct')3376 correctCount += 13377 else:3378 print('Test 2: Incorrect')3379 print('Correct output:\n{}'.format(correctOutput))3380 print('Given output:\n{}'.format(givenOutput))3381 print()3382 3383 #Test 33384 move = 'c2c4' 3385 chess.move(move)3386 correctOutput = ('rnbqkbnr\n'3387 'pp·ppppp\n'3388 '········\n'3389 '··p·····\n'3390 '····P···\n'3391 '········\n'3392 'PPPP·PPP\n'3393 'RNBQKBNR\n')3394 givenOutput = Test.boardString(chess)3395 if (correctOutput == givenOutput):3396 print('Test 3: Correct')3397 correctCount += 13398 else:3399 print('Test 3: Incorrect')3400 print('Correct output:\n{}'.format(correctOutput))3401 print('Given output:\n{}'.format(givenOutput))3402 print() 3403 3404 #Test 43405 previous_state = chess.states[len(chess.states)-2]3406 correctOutput = str(previous_state.en_passant)3407 chess.undo_move()3408 givenOutput = str(chess.state.en_passant)3409 if (correctOutput == givenOutput):3410 print('Test 4: Correct')3411 correctCount += 13412 else:3413 print('Test 4: Incorrect')3414 print('Correct output:\n{}'.format(correctOutput))3415 print('Given output:\n{}'.format(givenOutput))3416 print()3417 3418 #Test 5 3419 move = 'g1f3' 3420 chess.move(move)3421 move = 'b1c3' 3422 chess.move(move)3423 move = 'f3e5' 3424 chess.move(move)3425 move = 'c3e4' 3426 chess.move(move)3427 correctOutput = ('R·BQKBNR\n'3428 'PPPP·PPP\n'3429 '········\n'3430 '····N···\n'3431 '········\n'3432 '········\n'3433 'pppppppp\n'3434 'rnbqkb·r\n')3435 3436 givenOutput = Test.boardString(chess)3437 if (correctOutput == givenOutput):3438 print('Test 5: Correct')3439 correctCount += 13440 else:3441 print('Test 5: Incorrect')3442 print('Correct output:\n{}'.format(correctOutput))3443 print('Given output:\n{}'.format(givenOutput))3444 print() 3445 3446 #Test 6 3447 chess.undo_move()3448 correctOutput = ('rnbqkb·r\n'3449 'pppppppp\n'3450 '········\n'3451 '········\n'3452 '····n···\n'3453 '··N·····\n'3454 'PPPP·PPP\n'3455 'R·BQKBNR\n')3456 givenOutput = Test.boardString(chess)3457 if (correctOutput == givenOutput):3458 print('Test 6: Correct')3459 correctCount += 13460 else:3461 print('Test 6: Incorrect')3462 print('Correct output:\n{}'.format(correctOutput))3463 print('Given output:\n{}'.format(givenOutput))3464 print()3465 3466 #Test 7 3467 chess.undo_move()3468 correctOutput = ('R·BQKBNR\n'3469 'PPPP·PPP\n'3470 '··N·····\n'3471 '····P···\n'3472 '········\n'3473 '·····n··\n'3474 'pppppppp\n'3475 'rnbqkb·r\n')3476 3477 givenOutput = Test.boardString(chess)3478 if (correctOutput == givenOutput):3479 print('Test 7: Correct')3480 correctCount += 13481 else:3482 print('Test 7: Incorrect')3483 print('Correct output:\n{}'.format(correctOutput))3484 print('Given output:\n{}'.format(givenOutput))3485 print()3486 3487 #Test 83488 chess = Chess()3489 3490 move = 'e2e4' 3491 chess.move(move)3492 move = 'e2e4' 3493 chess.move(move)3494 move = 'f1c4' 3495 chess.move(move)3496 move = 'b1c3' 3497 chess.move(move)3498 move = 'd1f3' 3499 chess.move(move)3500 move = 'd2d3' 3501 chess.move(move)3502 move = 'f3f7' 3503 chess.move(move)3504 3505 3506 correctOutput = ('RNB·K·NR\n'3507 'PPPP·PPP\n'3508 '········\n'3509 '··B·P···\n'3510 '····p···\n'3511 '··np····\n'3512 'ppp··Qpp\n'3513 'r·bqkbnr\n')3514 givenOutput = Test.boardString(chess)3515 if (correctOutput == givenOutput):3516 print('Test 8: Correct')3517 correctCount += 13518 else:3519 print('Test 8: Incorrect')3520 print('Correct output:\n{}'.format(correctOutput))3521 print('Given output:\n{}'.format(givenOutput))3522 print()3523 3524 #Test 93525 chess.undo_move()3526 correctOutput = ('r·bqkbnr\n'3527 'ppp··ppp\n'3528 '··np····\n'3529 '····p···\n'3530 '··B·P···\n'3531 '·····Q··\n'3532 'PPPP·PPP\n'3533 'RNB·K·NR\n')3534 givenOutput = Test.boardString(chess)3535 if (correctOutput == givenOutput):3536 print('Test 9: Correct')3537 correctCount += 13538 else:3539 print('Test 9: Incorrect')3540 print('Correct output:\n{}'.format(correctOutput))3541 print('Given output:\n{}'.format(givenOutput))3542 print()3543 3544 #Test 103545 move = 'h2h4'3546 chess.move(move)3547 move = 'd1d2'3548 chess.move(move)3549 correctOutput = ('r·b·kbnr\n'3550 'pppq·ppp\n'3551 '··np····\n'3552 '····p···\n'3553 '··B·P··P\n'3554 '·····Q··\n'3555 'PPPP·PP·\n'3556 'RNB·K·NR\n')3557 givenOutput = Test.boardString(chess)3558 if (correctOutput == givenOutput):3559 print('Test 10: Correct')3560 correctCount += 13561 else:3562 print('Test 10: Incorrect')3563 print('Correct output:\n{}'.format(correctOutput))3564 print('Given output:\n{}'.format(givenOutput))3565 print()3566 3567 #Test 113568 move = 'f3f7'3569 chess.move(move)3570 move = 'd2f2'3571 chess.move(move)3572 correctOutput = ('r·b·kbnr\n'3573 'ppp··qpp\n'3574 '··np····\n'3575 '····p···\n'3576 '··B·P··P\n'3577 '········\n'3578 'PPPP·PP·\n'3579 'RNB·K·NR\n')3580 givenOutput = Test.boardString(chess)3581 if (correctOutput == givenOutput):3582 print('Test 11: Correct')3583 correctCount += 13584 else:3585 print('Test 11: Incorrect')3586 print('Correct output:\n{}'.format(correctOutput))3587 print('Given output:\n{}'.format(givenOutput))3588 print()3589 3590 #Test 123591 chess.undo_move()3592 correctOutput = ('RNB·K·NR\n'3593 'PPPP·PP·\n'3594 '········\n'3595 '··B·P··P\n'3596 '····p···\n'3597 '··np····\n'3598 'pppq·Qpp\n'3599 'r·b·kbnr\n')3600 givenOutput = Test.boardString(chess)3601 if (correctOutput == givenOutput):3602 print('Test 12: Correct')3603 correctCount += 13604 else:3605 print('Test 12: Incorrect')3606 print('Correct output:\n{}'.format(correctOutput))3607 print('Given output:\n{}'.format(givenOutput))3608 print()3609 3610 #Test 133611 chess.undo_move()3612 chess.undo_move()3613 chess.undo_move()3614 correctOutput = ('r·bqkbnr\n'3615 'ppp··ppp\n'3616 '··np····\n'3617 '····p···\n'3618 '··B·P···\n'3619 '·····Q··\n'3620 'PPPP·PPP\n'3621 'RNB·K·NR\n')3622 givenOutput = Test.boardString(chess)3623 if (correctOutput == givenOutput):3624 print('Test 13: Correct')3625 correctCount += 13626 else:3627 print('Test 13: Incorrect')3628 print('Correct output:\n{}'.format(correctOutput))3629 print('Given output:\n{}'.format(givenOutput))3630 print()3631 3632 #Test 143633 move = 'g1h3'3634 chess.move(move)3635 correctOutput = ('RNB·K··R\n'3636 'PPPP·PPP\n'3637 '·····Q·N\n'3638 '··B·P···\n'3639 '····p···\n'3640 '··np····\n'3641 'ppp··ppp\n'3642 'r·bqkbnr\n')3643 givenOutput = Test.boardString(chess)3644 if (correctOutput == givenOutput):3645 print('Test 14: Correct')3646 correctCount += 13647 else:3648 print('Test 14: Incorrect')3649 print('Correct output:\n{}'.format(correctOutput))3650 print('Given output:\n{}'.format(givenOutput))3651 print()3652 3653 print('{} correct tests out of 14'.format(correctCount))3654 print() 3655 3656 #Creates a simple representation of the given chess board3657 def boardString(chess):3658 correctOutput = ''3659 for row in chess.state.board:3660 for tile in row:3661 correctOutput += tile3662 correctOutput += '\n'3663 3664 return(correctOutput)3665 3666def main():36673668 #Testing setup and move calculation 3669 test = Test36703671 test.test_Chess() 3672 test.test_move_piece()3673 test.test_value()3674 test.test_gen_moves()3675 test.test_gen_check_attacks() 3676 3677 #Testing check detection3678 test.test_king_in_check()3679 test.test_legal_moves()3680 test.test_king_ray_check()3681 3682 #Testing gameplay3683 test.test_format_move()3684 test.test_move()3685 test.test_undo_move() 3686 3687main()
...
test_networking_topology.py
Source:test_networking_topology.py
1# Copyright (c) 2015-2016 OpenStack Foundation2# All Rights Reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License"); you may5# not use this file except in compliance with the License. You may obtain6# a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13# License for the specific language governing permissions and limitations14# under the License.15from os import path16import mock17from oslo_log import log18from oslo_serialization import jsonutils19import requests20from neutron.common import constants as n_constants21from neutron.extensions import portbindings22from neutron.plugins.common import constants23from neutron.plugins.ml2 import driver_api24from neutron.plugins.ml2 import driver_context25from networking_odl.common import cache26from networking_odl.ml2 import mech_driver27from networking_odl.ml2 import mech_driver_v228from networking_odl.ml2 import network_topology29from networking_odl.tests import base30LOG = log.getLogger(__name__)31class TestNetworkTopologyManager(base.DietTestCase):32 # pylint: disable=protected-access33 # given valid and invalid segments34 valid_segment = {35 driver_api.ID: 'API_ID',36 driver_api.NETWORK_TYPE: constants.TYPE_LOCAL,37 driver_api.SEGMENTATION_ID: 'API_SEGMENTATION_ID',38 driver_api.PHYSICAL_NETWORK: 'API_PHYSICAL_NETWORK'}39 invalid_segment = {40 driver_api.ID: 'API_ID',41 driver_api.NETWORK_TYPE: constants.TYPE_NONE,42 driver_api.SEGMENTATION_ID: 'API_SEGMENTATION_ID',43 driver_api.PHYSICAL_NETWORK: 'API_PHYSICAL_NETWORK'}44 segments_to_bind = [valid_segment, invalid_segment]45 def setUp(self):46 super(TestNetworkTopologyManager, self).setUp()47 self.patch(network_topology.LOG, 'isEnabledFor', lambda level: True)48 # patch given configuration49 self.cfg = mocked_cfg = self.patch(network_topology.client, 'cfg')50 mocked_cfg.CONF.ml2_odl.url =\51 'http://localhost:8181/controller/nb/v2/neutron'52 mocked_cfg.CONF.ml2_odl.username = 'admin'53 mocked_cfg.CONF.ml2_odl.password = 'admin'54 mocked_cfg.CONF.ml2_odl.timeout = 555 @mock.patch.object(cache, 'LOG')56 @mock.patch.object(network_topology, 'LOG')57 def test_fetch_elements_by_host_with_no_entry(58 self, network_topology_logger, cache_logger):59 given_client = self.mock_client('ovs_topology.json')60 self.mock_get_addresses_by_name(['127.0.0.1', '192.168.0.1'])61 given_network_topology = network_topology.NetworkTopologyManager(62 client=given_client)63 try:64 next(given_network_topology._fetch_elements_by_host(65 'some_host_name'))66 except ValueError as error:67 cache_logger.warning.assert_called_once_with(68 'Error fetching values for keys: %r',69 "'some_host_name', '127.0.0.1', '192.168.0.1'",70 exc_info=(ValueError, error, mock.ANY))71 network_topology_logger.exception.assert_called_once_with(72 'No such network topology elements for given host '73 '%(host_name)r and given IPs: %(ip_addresses)s.',74 {'ip_addresses': '127.0.0.1, 192.168.0.1',75 'host_name': 'some_host_name'})76 else:77 self.fail('Expected ValueError being raised.')78 def test_fetch_element_with_ovs_entry(self):79 given_client = self.mock_client('ovs_topology.json')80 self.mock_get_addresses_by_name(['127.0.0.1', '10.237.214.247'])81 given_network_topology = network_topology.NetworkTopologyManager(82 client=given_client)83 elements = given_network_topology._fetch_elements_by_host(84 'some_host_name.')85 self.assertEqual([86 {'class':87 'networking_odl.ml2.ovsdb_topology.OvsdbNetworkTopologyElement',88 'has_datapath_type_netdev': False,89 'host_addresses': ['10.237.214.247'],90 'support_vhost_user': False,91 'uuid': 'c4ad780f-8f91-4fa4-804e-dd16beb191e2',92 'valid_vif_types': [portbindings.VIF_TYPE_OVS]}],93 [e.to_dict() for e in elements])94 def test_fetch_elements_with_vhost_user_entry(self):95 given_client = self.mock_client('vhostuser_topology.json')96 self.mock_get_addresses_by_name(['127.0.0.1', '192.168.66.1'])97 given_network_topology = network_topology.NetworkTopologyManager(98 client=given_client)99 elements = given_network_topology._fetch_elements_by_host(100 'some_host_name.')101 self.assertEqual([102 {'class':103 'networking_odl.ml2.ovsdb_topology.OvsdbNetworkTopologyElement',104 'has_datapath_type_netdev': True,105 'host_addresses': ['192.168.66.1'],106 'support_vhost_user': True,107 'uuid': 'c805d82d-a5d8-419d-bc89-6e3713ff9f6c',108 'valid_vif_types': [portbindings.VIF_TYPE_VHOST_USER,109 portbindings.VIF_TYPE_OVS],110 'port_prefix': 'vhu',111 'vhostuser_socket_dir': '/var/run/openvswitch'}],112 [e.to_dict() for e in elements])113 def mock_get_addresses_by_name(self, ips):114 utils = self.patch(115 network_topology, 'utils',116 mock.Mock(117 get_addresses_by_name=mock.Mock(return_value=tuple(ips))))118 return utils.get_addresses_by_name119 def mock_client(self, topology_name=None):120 mocked_client = mock.NonCallableMock(121 specs=network_topology.NetworkTopologyClient)122 if topology_name:123 cached_file_path = path.join(path.dirname(__file__), topology_name)124 with open(cached_file_path, 'rt') as fd:125 topology = jsonutils.loads(str(fd.read()), encoding='utf-8')126 mocked_client.get().json.return_value = topology127 return mocked_client128 def test_bind_port_from_mech_driver_with_ovs(self):129 given_client = self.mock_client('ovs_topology.json')130 self.mock_get_addresses_by_name(['127.0.0.1', '10.237.214.247'])131 given_network_topology = network_topology.NetworkTopologyManager(132 vif_details={'some': 'detail'},133 client=given_client)134 self.patch(135 network_topology, 'NetworkTopologyManager',136 return_value=given_network_topology)137 given_driver = mech_driver.OpenDaylightMechanismDriver()138 given_driver.odl_drv = mech_driver.OpenDaylightDriver()139 given_port_context = self.given_port_context()140 # when port is bound141 given_driver.bind_port(given_port_context)142 # then context binding is setup with returned vif_type and valid143 # segment api ID144 given_port_context.set_binding.assert_called_once_with(145 self.valid_segment[driver_api.ID], portbindings.VIF_TYPE_OVS,146 {'some': 'detail'}, status=n_constants.PORT_STATUS_ACTIVE)147 def test_bind_port_from_mech_driver_with_vhostuser(self):148 given_client = self.mock_client('vhostuser_topology.json')149 self.mock_get_addresses_by_name(['127.0.0.1', '192.168.66.1'])150 given_network_topology = network_topology.NetworkTopologyManager(151 vif_details={'some': 'detail'},152 client=given_client)153 self.patch(154 network_topology, 'NetworkTopologyManager',155 return_value=given_network_topology)156 given_driver = mech_driver.OpenDaylightMechanismDriver()157 given_driver.odl_drv = mech_driver.OpenDaylightDriver()158 given_port_context = self.given_port_context()159 # when port is bound160 given_driver.bind_port(given_port_context)161 expected_vif_details = {162 'vhostuser_socket': '/var/run/openvswitch/vhuCURRENT_CON',163 'vhostuser_ovs_plug': True,164 'some': 'detail',165 'vhostuser_mode': 'client'}166 # then context binding is setup with returned vif_type and valid167 # segment api ID168 given_port_context.set_binding.assert_called_once_with(169 self.valid_segment[driver_api.ID],170 portbindings.VIF_TYPE_VHOST_USER,171 expected_vif_details, status=n_constants.PORT_STATUS_ACTIVE)172 def test_bind_port_from_mech_driver_v2_with_ovs(self):173 given_client = self.mock_client('ovs_topology.json')174 self.mock_get_addresses_by_name(['127.0.0.1', '10.237.214.247'])175 given_network_topology = network_topology.NetworkTopologyManager(176 vif_details={'some': 'detail'},177 client=given_client)178 given_driver = mech_driver_v2.OpenDaylightMechanismDriver()179 given_driver._network_topology = given_network_topology180 given_port_context = self.given_port_context()181 # when port is bound182 given_driver.bind_port(given_port_context)183 # then context binding is setup with returned vif_type and valid184 # segment api ID185 given_port_context.set_binding.assert_called_once_with(186 self.valid_segment[driver_api.ID], portbindings.VIF_TYPE_OVS,187 {'some': 'detail'}, status=n_constants.PORT_STATUS_ACTIVE)188 def test_bind_port_from_mech_driver_v2_with_vhostuser(self):189 given_client = self.mock_client('vhostuser_topology.json')190 self.mock_get_addresses_by_name(['127.0.0.1', '192.168.66.1'])191 given_network_topology = network_topology.NetworkTopologyManager(192 vif_details={'some': 'detail'},193 client=given_client)194 self.patch(195 network_topology, 'NetworkTopologyManager',196 return_value=given_network_topology)197 given_driver = mech_driver_v2.OpenDaylightMechanismDriver()198 given_driver._network_topology = given_network_topology199 given_port_context = self.given_port_context()200 # when port is bound201 given_driver.bind_port(given_port_context)202 expected_vif_details = {203 'vhostuser_socket': '/var/run/openvswitch/vhuCURRENT_CON',204 'vhostuser_ovs_plug': True,205 'some': 'detail',206 'vhostuser_mode': 'client'}207 # then context binding is setup with returned vif_type and valid208 # segment api ID209 given_port_context.set_binding.assert_called_once_with(210 self.valid_segment[driver_api.ID],211 portbindings.VIF_TYPE_VHOST_USER,212 expected_vif_details, status=n_constants.PORT_STATUS_ACTIVE)213 def test_bind_port_with_vif_type_ovs(self):214 given_topology = self._mock_network_topology(215 'ovs_topology.json', vif_details={'much': 'details'})216 given_port_context = self.given_port_context()217 # when port is bound218 given_topology.bind_port(given_port_context)219 # then context binding is setup wit returned vif_type and valid220 # segment api ID221 given_port_context.set_binding.assert_called_once_with(222 self.valid_segment[driver_api.ID], portbindings.VIF_TYPE_OVS,223 {'much': 'details'}, status=n_constants.PORT_STATUS_ACTIVE)224 def test_bind_port_with_vif_type_vhost_user(self):225 given_topology = self._mock_network_topology(226 'vhostuser_topology.json', vif_details={'much': 'details'})227 given_port_context = self.given_port_context()228 # when port is bound229 given_topology.bind_port(given_port_context)230 # then context binding is setup wit returned vif_type and valid231 # segment api ID232 given_port_context.set_binding.assert_called_once_with(233 self.valid_segment[driver_api.ID],234 portbindings.VIF_TYPE_VHOST_USER,235 {'vhostuser_socket': '/var/run/openvswitch/vhuCURRENT_CON',236 'vhostuser_ovs_plug': True, 'vhostuser_mode': 'client',237 'much': 'details'},238 status=n_constants.PORT_STATUS_ACTIVE)239 @mock.patch.object(network_topology, 'LOG')240 def test_bind_port_without_valid_segment(self, logger):241 given_topology = self._mock_network_topology('ovs_topology.json')242 given_port_context = self.given_port_context(243 given_segments=[self.invalid_segment])244 # when port is bound245 given_topology.bind_port(given_port_context)246 self.assertFalse(given_port_context.set_binding.called)247 logger.exception.assert_called_once_with(248 'Network topology element has failed binding port:\n%(element)s',249 {'element': mock.ANY})250 logger.error.assert_called_once_with(251 'Unable to bind port element for given host and valid VIF types:\n'252 '\thostname: %(host_name)s\n'253 '\tvalid VIF types: %(valid_vif_types)s',254 {'host_name': 'some_host', 'valid_vif_types': 'vhostuser, ovs'})255 def _mock_network_topology(self, given_topology, vif_details=None):256 self.mock_get_addresses_by_name(257 ['127.0.0.1', '10.237.214.247', '192.168.66.1'])258 return network_topology.NetworkTopologyManager(259 client=self.mock_client(given_topology),260 vif_details=vif_details)261 def given_port_context(self, given_segments=None):262 # given NetworkContext263 network = mock.MagicMock(spec=driver_api.NetworkContext)264 if given_segments is None:265 given_segments = self.segments_to_bind266 # given port context267 return mock.MagicMock(268 spec=driver_context.PortContext,269 current={'id': 'CURRENT_CONTEXT_ID'},270 host='some_host',271 segments_to_bind=given_segments,272 network=network)273 NETOWORK_TOPOLOGY_URL =\274 'http://localhost:8181/'\275 'restconf/operational/network-topology:network-topology/'276 def mock_request_network_topology(self, file_name):277 cached_file_path = path.join(278 path.dirname(__file__), file_name + '.json')279 if path.isfile(cached_file_path):280 LOG.debug('Loading topology from file: %r', cached_file_path)281 with open(cached_file_path, 'rt') as fd:282 topology = jsonutils.loads(str(fd.read()), encoding='utf-8')283 else:284 LOG.debug(285 'Getting topology from ODL: %r', self.NETOWORK_TOPOLOGY_URL)286 request = requests.get(287 self.NETOWORK_TOPOLOGY_URL, auth=('admin', 'admin'),288 headers={'Content-Type': 'application/json'})289 request.raise_for_status()290 with open(cached_file_path, 'wt') as fd:291 LOG.debug('Saving topology to file: %r', cached_file_path)292 topology = request.json()293 jsonutils.dump(294 topology, fd, sort_keys=True, indent=4,295 separators=(',', ': '))296 mocked_request = self.patch(297 mech_driver.odl_client.requests, 'request',298 return_value=mock.MagicMock(299 spec=requests.Response,300 json=mock.MagicMock(return_value=topology)))301 return mocked_request302class TestNetworkTopologyClient(base.DietTestCase):303 given_host = 'given.host'304 given_port = 1234305 given_url_with_port = 'http://{}:{}/'.format(306 given_host, given_port)307 given_url_without_port = 'http://{}/'.format(given_host)308 given_username = 'GIVEN_USERNAME'309 given_password = 'GIVEN_PASSWORD'310 given_timeout = 20311 def given_client(312 self, url=None, username=None, password=None, timeout=None):313 return network_topology.NetworkTopologyClient(314 url=url or self.given_url_with_port,315 username=username or self.given_username,316 password=password or self.given_password,317 timeout=timeout or self.given_timeout)318 def test_constructor(self):319 # When client is created320 rest_client = network_topology.NetworkTopologyClient(321 url=self.given_url_with_port,322 username=self.given_username,323 password=self.given_password,324 timeout=self.given_timeout)325 self.assertEqual(326 self.given_url_with_port +327 'restconf/operational/network-topology:network-topology',328 rest_client.url)329 self.assertEqual(330 (self.given_username, self.given_password), rest_client.auth)331 self.assertEqual(self.given_timeout, rest_client.timeout)332 def test_request_with_port(self):333 # Given rest client and used 'requests' module334 given_client = self.given_client()335 mocked_requests_module = self.mocked_requests()336 # When a request is performed337 result = given_client.request(338 'GIVEN_METHOD', 'given/path', 'GIVEN_DATA')339 # Then request method is called340 mocked_requests_module.request.assert_called_once_with(341 'GIVEN_METHOD',342 url='http://given.host:1234/restconf/operational/' +343 'network-topology:network-topology/given/path',344 auth=(self.given_username, self.given_password),345 data='GIVEN_DATA', headers={'Content-Type': 'application/json'},346 timeout=self.given_timeout)347 # Then request method result is returned348 self.assertIs(mocked_requests_module.request.return_value, result)349 def test_request_without_port(self):350 # Given rest client and used 'requests' module351 given_client = self.given_client(url=self.given_url_without_port)352 mocked_requests_module = self.mocked_requests()353 # When a request is performed354 result = given_client.request(355 'GIVEN_METHOD', 'given/path', 'GIVEN_DATA')356 # Then request method is called357 mocked_requests_module.request.assert_called_once_with(358 'GIVEN_METHOD',359 url='http://given.host/restconf/operational/' +360 'network-topology:network-topology/given/path',361 auth=(self.given_username, self.given_password),362 data='GIVEN_DATA', headers={'Content-Type': 'application/json'},363 timeout=self.given_timeout)364 # Then request method result is returned365 self.assertIs(mocked_requests_module.request.return_value, result)366 def test_get(self):367 # Given rest client and used 'requests' module368 given_client = self.given_client()369 mocked_requests_module = self.mocked_requests()370 # When a request is performed371 result = given_client.get('given/path', 'GIVEN_DATA')372 # Then request method is called373 mocked_requests_module.request.assert_called_once_with(374 'get',375 url='http://given.host:1234/restconf/operational/' +376 'network-topology:network-topology/given/path',377 auth=(self.given_username, self.given_password),378 data='GIVEN_DATA', headers={'Content-Type': 'application/json'},379 timeout=self.given_timeout)380 # Then request method result is returned381 self.assertIs(mocked_requests_module.request.return_value, result)382 def mocked_requests(self):...
boundary.py
Source:boundary.py
1from __future__ import division2import numpy as np3import pandas as pd4import math5from collections import Counter6import mmap7from time import time8import random910start_time = time()1112#total number of lines in a file13def get_num_lines(file_path):14 fp = open(file_path, "r+")15 buf = mmap.mmap(fp.fileno(), 0)16 lines = 017 while buf.readline():18 lines += 119 return lines2021#linear address22from operator import mul23def get_lin_add(d,M): #d={d_1,d_2,...,d_N}24 sum = 025 for i in range(len(d)):26 sum += X[i]*d[i]27 return sum28def get_mul_list(M):29 x = []30 for i in range(len(M) - 1):31 x.append(reduce(mul, M[i + 1:], 1))32 x.append(1)33 return x3435M = np.array([6,6,6,6,6])36filename = 'train_shuf.txt' #training data37filename_val = 'val_shuf.txt'3839X = get_mul_list(M)4041att = len(M) #number of attributes42k = 2 #number of classes43p_c0_given = 0.4 #prior probability for class 044p_c1_given = 0.6 #prior probability for class 145e = np.array([[1,-1],[-2,3]]) #economic gain matrix464748##########49#TRAINING#50##########5152names = ['d0','d1','d2','d3','d4','c']53data = pd.read_csv(filename, delim_whitespace=True, names=names)54print 'training data loaded'5556#find c0(#class 0) and c1 (#class 1)57c_counts = data.groupby('c').size()58c0 = c_counts[0]59c1 = c_counts[1]60#find number of datapoints in the training data61count = get_num_lines(filename)6263p_c0 = c0/count64p_c1 = c1/count65possible = reduce(mul,M,1)66all_bins = []67L = M.tolist()68columns = data.columns.tolist()[:-1]69for i,item in enumerate(columns):70 index_new = 071 next = int(math.ceil(float(count) / L[0]))72 bins = []73 for j in range(1,L[i]):74 index_new += next75 #shift back the even indices for uniformity76 if (j%2==0):77 index_new = index_new - 178 boundary = data[item].sort_values().values[index_new]79 bins.append(boundary)80 all_bins.append(bins)81print 'bin boundaries set for quantization'8283############84#VALIDATION#85############8687names = ['d0','d1','d2','d3','d4','c']88data_val = pd.read_csv(filename_val, delim_whitespace=True, names=names)89print 'validation data loaded'9091#find c0(#class 0) and c1 (#class 1)92c_counts_val = data_val.groupby('c').size()93c0_val = c_counts_val[0]94c1_val = c_counts_val[1]95#find number of datapoints in the training data96count_val = get_num_lines(filename_val)9798p_c0_val = c0_val/count_val99p_c1_val = c1_val/count_val100101102#################################103#################################104###FIND OPTIMUM BIN BOUNDARIES###105#################################106#################################107print all_bins #bins before starting perturbations108#randomly pick a boundary and optimize till convergence109max_exp_gain = -float('Inf')110max_temp = -float('Inf')111patience = 100112countdown = patience113random.seed(1234)114while(countdown > 0):115 dim = random.randrange(len(all_bins))116 index_boundary = random.randrange(len(all_bins[dim]))117 #find previous boundary118 if index_boundary == 0:119 prev_boundary = 0120 else:121 prev_boundary = all_bins[dim][index_boundary-1]122 #find next boundary123 if index_boundary == (len(all_bins[dim])-1):124 next_boundary = 1125 else:126 next_boundary = all_bins[dim][index_boundary+1]127 flag = False128 already_boundary = all_bins[dim][index_boundary]129 mid_picked = 100 #lol, just assigning a number130 while (mid_picked == 100 or mid_picked == prev_boundary or mid_picked == next_boundary):131 mid_picked = random.uniform(prev_boundary, next_boundary)132 all_bins[dim][index_boundary] = mid_picked133 # for i_delta in range(11):134 # all_bins[dim][index_boundary] = start_boundary +(i_delta*delta)135 ##########136 #TRAINING#137 ##########138 #quantize training data139 for i,item in enumerate(names[:-1]):140 dq = pd.np.digitize(data[item], bins=all_bins[i],right=True)141 data['{}_quantized'.format(item)] = dq142 # print 'training data quantized'143 #calculate frequency of d,c144 freq = np.array([[0, 0]]*possible)145 counter0 = Counter(tuple(a[1:]) for a in data.values[:,5:11] if a[0]==0)146 counter1 = Counter(tuple(a[1:]) for a in data.values[:,5:11] if a[0]==1)147 for key in counter0.keys():148 freq[int(get_lin_add(key, X))][0] = counter0[key]149 for key in counter1.keys():150 freq[int(get_lin_add(key, X))][1] = counter1[key]151 #calculate P(d,c)152 p_d_c = freq/count153 #calculate P(d|c)154 p_d_given_c = freq/count #just initialize155 for row in range(possible):156 p_d_given_c[row][0] = p_d_given_c[row][0]/p_c0157 p_d_given_c[row][1] = p_d_given_c[row][1]/p_c1158 #calculate P(c|d) (uses p_c0_given and p_c1_given)159 p_c_given_d = freq/count #just initialize160 for row in range(possible):161 denominator = (p_d_given_c[row][0]*p_c0_given) + (p_d_given_c[row][1]*p_c1_given)162 if (denominator!=0):163 p_c_given_d[row][0] = (p_d_given_c[row][0]*p_c0_given)/denominator164 p_c_given_d[row][1] = (p_d_given_c[row][1]*p_c1_given)/denominator165 #calculate P(c,d): to be used (**not same as P(d,c) calculated before)166 #(uses p_c0_given and p_c1_given)167 p_c_d = freq/count #just initialize168 for row in range(possible):169 p_c_d[row][0] = p_d_given_c[row][0]*p_c0_given170 p_c_d[row][1] = p_d_given_c[row][1]*p_c1_given171 #calculate fd(c)172 fd = np.array([[0,0]]*possible)173 for row in range(possible):174 sum0 = p_c_d[row][0]*e[0,0]+p_c_d[row][1]*e[1,0]175 sum1 = p_c_d[row][0]*e[0,1]+p_c_d[row][1]*e[1,1]176 if sum0 > sum1:177 fd[row][0] = 1178 else:179 fd[row][1] = 1180 ############181 #VALIDATION#182 ############183 #quantize validation data184 for i,item in enumerate(names[:-1]):185 dq = pd.np.digitize(data_val[item], bins=all_bins[i])186 data_val['{}_quantized'.format(item)] = dq187 # print 'validation data quantized'188 #calculate frequency of d,c189 freq_val = np.array([[0, 0]]*possible)190 counter0_val = Counter(tuple(a[1:]) for a in data_val.values[:,5:11] if a[0]==0)191 counter1_val = Counter(tuple(a[1:]) for a in data_val.values[:,5:11] if a[0]==1)192 for key in counter0_val.keys():193 freq_val[int(get_lin_add(key, X))][0] = counter0_val[key]194 for key in counter1_val.keys():195 freq_val[int(get_lin_add(key, X))][1] = counter1_val[key]196 #calculate P(d,c)197 p_d_c_val = freq_val/count_val198 #calculate confusion matrix199 conf_mat = np.array([[0,0],[0,0]], dtype=float) #initialize200 for tr in range(k):201 for assigned in range(k):202 sum = 0203 for i in range(possible):204 sum = sum + p_d_c_val[i,tr]*fd[i,assigned] #p_c_d_val changed to p_d_c_val205 conf_mat[tr,assigned] = sum206 #calculate economic gain207 exp_gain = (e*conf_mat).sum()208 if exp_gain > max_exp_gain:209 flag = True210 max_exp_gain = exp_gain211 # optimal_i = i_delta212 print 'sum =', conf_mat.sum(), 'Exp gain = ', exp_gain, 'max Exp gain =', max_exp_gain, countdown213214 if (flag==False):215 all_bins[dim][index_boundary] = already_boundary216217 if (max_exp_gain == max_temp):218 countdown = countdown - 1219 else:220 countdown = patience221 max_temp = max_exp_gain222223 #sequential check224 if (countdown == 0):225 flag_sequential = True226 for dim_seq in range(len(all_bins)):227 if (not flag_sequential):228 break229 for index_boundary_seq in range(len(all_bins[dim_seq])):230 if (not flag_sequential):231 break232 # find previous boundary233 if index_boundary_seq == 0:234 prev_boundary_seq = 0235 else:236 prev_boundary_seq = all_bins[dim_seq][index_boundary_seq - 1]237 # find next boundary238 if index_boundary_seq == (len(all_bins[dim_seq]) - 1):239 next_boundary_seq = 1240 else:241 next_boundary_seq = all_bins[dim_seq][index_boundary_seq + 1]242 # find delta243 delta_seq = float(244 (0.5 * (next_boundary_seq - prev_boundary_seq)) / (10)) # 11 new boundaries to be covered for every boundary245 # max_exp_gain = -float('Inf')246 start_boundary_seq = ((all_bins[dim_seq][index_boundary_seq] + prev_boundary_seq) / float(2))247 # flag = False248 already_boundary_seq = all_bins[dim_seq][index_boundary_seq]249 for i_delta_seq in range(11):250 all_bins[dim_seq][index_boundary_seq] = start_boundary_seq + (i_delta_seq * delta_seq)251 ##########252 #TRAINING#253 ##########254 # quantize training data255 for i, item in enumerate(names[:-1]):256 dq = pd.np.digitize(data[item], bins=all_bins[i], right=True)257 data['{}_quantized'.format(item)] = dq258 # print 'training data quantized'259 # calculate frequency of d,c260 freq = np.array([[0, 0]] * possible)261 counter0 = Counter(tuple(a[1:]) for a in data.values[:, 5:11] if a[0] == 0)262 counter1 = Counter(tuple(a[1:]) for a in data.values[:, 5:11] if a[0] == 1)263 for key in counter0.keys():264 freq[int(get_lin_add(key, X))][0] = counter0[key]265 for key in counter1.keys():266 freq[int(get_lin_add(key, X))][1] = counter1[key]267 # calculate P(d,c)268 p_d_c = freq / count269 # calculate P(d|c)270 p_d_given_c = freq / count # just initialize271 for row in range(possible):272 p_d_given_c[row][0] = p_d_given_c[row][0] / p_c0273 p_d_given_c[row][1] = p_d_given_c[row][1] / p_c1274 # calculate P(c|d) (uses p_c0_given and p_c1_given)275 p_c_given_d = freq / count # just initialize276 for row in range(possible):277 denominator = (p_d_given_c[row][0] * p_c0_given) + (p_d_given_c[row][1] * p_c1_given)278 if (denominator != 0):279 p_c_given_d[row][0] = (p_d_given_c[row][0] * p_c0_given) / denominator280 p_c_given_d[row][1] = (p_d_given_c[row][1] * p_c1_given) / denominator281 # calculate P(c,d): to be used (**not same as P(d,c) calculated before)282 # (uses p_c0_given and p_c1_given)283 p_c_d = freq / count # just initialize284 for row in range(possible):285 p_c_d[row][0] = p_d_given_c[row][0] * p_c0_given286 p_c_d[row][1] = p_d_given_c[row][1] * p_c1_given287 # calculate fd(c)288 fd = np.array([[0, 0]] * possible)289 for row in range(possible):290 sum0 = p_c_d[row][0] * e[0, 0] + p_c_d[row][1] * e[1, 0]291 sum1 = p_c_d[row][0] * e[0, 1] + p_c_d[row][1] * e[1, 1]292 if sum0 > sum1:293 fd[row][0] = 1294 else:295 fd[row][1] = 1296 ############297 #VALIDATION#298 ############299 # quantize validation data300 for i, item in enumerate(names[:-1]):301 dq = pd.np.digitize(data_val[item], bins=all_bins[i])302 data_val['{}_quantized'.format(item)] = dq303 # print 'validation data quantized'304 # calculate frequency of d,c305 freq_val = np.array([[0, 0]] * possible)306 counter0_val = Counter(tuple(a[1:]) for a in data_val.values[:, 5:11] if a[0] == 0)307 counter1_val = Counter(tuple(a[1:]) for a in data_val.values[:, 5:11] if a[0] == 1)308 for key in counter0_val.keys():309 freq_val[int(get_lin_add(key, X))][0] = counter0_val[key]310 for key in counter1_val.keys():311 freq_val[int(get_lin_add(key, X))][1] = counter1_val[key]312 # calculate P(d,c)313 p_d_c_val = freq_val / count_val314 # calculate confusion matrix315 conf_mat = np.array([[0, 0], [0, 0]], dtype=float) # initialize316 for tr in range(k):317 for assigned in range(k):318 sum = 0319 for i in range(possible):320 sum = sum + p_d_c_val[i, tr] * fd[i, assigned] #p_c_d_val changed to p_d_c_val321 conf_mat[tr, assigned] = sum322 # calculate economic gain323 exp_gain = (e * conf_mat).sum()324 if exp_gain > max_exp_gain:325 # flag = True326 max_exp_gain = exp_gain327 max_temp = max_exp_gain328 optimal_i_seq = i_delta_seq329 all_bins[dim_seq][index_boundary_seq] = start_boundary_seq + (optimal_i_seq * delta_seq)330 countdown = patience331 print 'sum =', conf_mat.sum(), 'Exp gain = ', exp_gain, 'max Exp gain =', max_exp_gain, countdown332 print all_bins333 flag_sequential = False334 break335 else:336 all_bins[dim_seq][index_boundary_seq] = already_boundary_seq337 print 'checking if convergence is successful..'338339340##################################341##################################342###OPTIMUM BIN BOUNDARIES FOUND###343##################################344##################################345346347print M348print e349350print freq351print p_d_c352print p_d_given_c353print p_c_given_d354print p_c_d355print fd356print conf_mat357print exp_gain358print max_exp_gain359print all_bins360361print '\n'
...
integrands.py
Source:integrands.py
1import numpy as np2# import COLD GASS functions3import schechter4import models5def integrand_SFR1(M, SFR, m_step, log_sigma, params, gsmf_params):6 # parameters inferred from emcee7 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params8 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params9 # probabilities10 phi_Mstar_double = schechter.double_schechter_peak(M, m_step, gsmf_params, log_sigma)11 fpass = models.f_passive(M, alpha, beta, zeta)12 # P_SFR_given_passive13 y_passive = r1*M + r214 P_SFR_given_Mstar_red = models.Gaussian_Conditional_Probability(SFR, y_passive, lnr)15 # P_SFR_given_sforming16 y_sforming = (b1*M*M) + (b2*M) + b317 P_SFR_given_Mstar_blue = models.Gaussian_Conditional_Probability(SFR, y_sforming, lnb)18 # P_SFR_total19 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red + (1-fpass)*P_SFR_given_Mstar_blue20 # return phi_SFR21 return phi_Mstar_double*P_SFR_given_Mstar_total22def integrand_SFR_Saintonge16(M, SFR, params, gsmf_params):23 # parameters inferred from emcee24 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params25 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params26 # probabilities27 phi_Mstar_double = schechter.double_schechter(M, gsmf_params)28 fpass = models.f_passive(M, alpha, beta, zeta)29 # P_SFR_given_passive30 # y_passive = r1*M + r231 # P_SFR_given_Mstar_red = models.Gaussian_Conditional_Probability(SFR, y_passive, lnr)32 # P_SFR_given_sforming33 y_sforming = models.Saintonge16_MS(M)34 P_SFR_given_Mstar_blue = models.Gaussian_Conditional_Probability(SFR, y_sforming, lnb)35 # P_SFR_total36 P_SFR_given_Mstar_total = (1-fpass)*P_SFR_given_Mstar_blue37 # return phi_SFR38 return phi_Mstar_double*P_SFR_given_Mstar_total39def integrand_SFR_blue1(M, SFR, params, gsmf_params):40 # parameters inferred from emcee41 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params42 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params43 # probabilities44 phi_Mstar_double = schechter.double_schechter(M, gsmf_params)45 fpass = models.f_passive(M, alpha, beta, zeta)46 # P_SFR_given_blue47 y_sforming = (b1*M*M) + (b2*M) + b348 # y_sforming = models.first_order(M, 1.037, - 0.077 - 10)49 # y_sforming = models.Saintonge16_MS(M)50 P_SFR_given_Mstar_blue = models.Gaussian_Conditional_Probability(SFR, y_sforming, -0.94)51 P_SFR_given_Mstar_total = (1-fpass)*P_SFR_given_Mstar_blue52 # return phi_SFR53 return phi_Mstar_double*P_SFR_given_Mstar_total54def integrand_SFR_red1(M, SFR, params, gsmf_params):55 # parameters inferred from emcee56 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params57 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params58 # probabilities59 phi_Mstar_double = schechter.double_schechter(M, gsmf_params)60 fpass = models.f_passive(M, alpha, beta, zeta)61 # P_SFR_given_passive62 y_passive = r1*M + r263 P_SFR_given_Mstar_red = models.Gaussian_Conditional_Probability(SFR, y_passive, lnr)64 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red65 # return phi_SFR66 return phi_Mstar_double*P_SFR_given_Mstar_total67def integrand_SFR1c(SFR, M, params):68 # parameters inferred from emcee69 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params70 # probabilities71 fpass = models.f_passive(M, alpha, beta, zeta)72 # P_SFR_given_passive73 y_passive = r1*M + r274 P_SFR_given_Mstar_red = models.Gaussian_Conditional_Probability(SFR, y_passive, lnr)75 # P_SFR_given_sforming76 y_sforming = (b1*M*M) + (b2*M) + b377 P_SFR_given_Mstar_blue = models.Gaussian_Conditional_Probability(SFR, y_sforming, lnb)78 # P_SFR_total79 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red + (1-fpass)*P_SFR_given_Mstar_blue80 # return phi_SFR81 return P_SFR_given_Mstar_total82def integrand_SFR1b(M, SFR, params, gsmf_params):83 # parameters inferred from emcee84 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params85 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params86 # probabilities87 phi_Mstar_double = schechter.double_schechter(M, gsmf_params)88 fpass = models.f_passive(M, alpha, beta, zeta)89 # P_SFR_given_passive90 y_passive = r1*M + r291 P_SFR_given_Mstar_red = models.Gaussian_Conditional_Probability(SFR, y_passive, lnr)92 # P_SFR_given_sforming93 y_sforming = (b1*M*M) + (b2*M) + b394 # y_sforming = models.first_order(M, 1.037, - 0.077 - 10)95 # y_sforming = models.Saintonge16_MS(M)96 P_SFR_given_Mstar_blue = models.Gaussian_Conditional_Probability(SFR, y_sforming, -0.94)97 # P_SFR_total98 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red + (1-fpass)*P_SFR_given_Mstar_blue99 # return phi_SFR100 return phi_Mstar_double*P_SFR_given_Mstar_total101def integrand_SFR2(M, SFR, params, gsmf_params):102 # parameters inferred from emcee103 b1, b2, b3, lnb, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params104 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params105 # probabilities106 phi_Mstar_double = schechter.double_schechter(M, gsmf_params)107 fpass = models.f_passive(M, alpha, beta, zeta)108 # P_SFR_given_passive109 y_passive = (b1*M*M) + (b2*M) + b3 + r2110 P_SFR_given_Mstar_red = (1/np.sqrt(2*np.pi*np.power(np.exp(lnr),2)))*np.exp((-1/(2*np.power(np.exp(lnr),2)))*np.power((SFR-y_passive),2))111 # P_SFR_given_sforming112 y_sforming = (b1*M*M) + (b2*M) + b3113 P_SFR_given_Mstar_blue = (1/np.sqrt(2*np.pi*np.power(np.exp(lnb),2)))*np.exp((-1/(2*np.power(np.exp(lnb),2)))*np.power((SFR-y_sforming),2))114 # P_SFR_total115 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red + (1-fpass)*P_SFR_given_Mstar_blue116 # return phi_SFR117 return phi_Mstar_double*P_SFR_given_Mstar_total118def integrand_MHI_direct(M, MHI, *params):119 # parameters inferred from emcee120 a1, a2, lna = params121 Mstar = 10.78122 phistar1 = 2.93E-3123 phistar2 = 0.63E-3124 alpha1 = - 0.62125 alpha2 = - 1.50126 # probabilities127 phi_Mstar_double = np.log(10) * np.exp(-np.power(10,M-Mstar)) * (phistar1*np.power(10,(alpha1+1)*(M-Mstar)) + phistar2*np.power(10,(alpha2+1)*(M-Mstar)))128 P_MHI_given_Mstar = (1/np.sqrt(2*np.pi*np.power(np.exp(lna),2)))*np.exp((-1/(2*np.power(np.exp(lna),2)))*np.power((MHI - ((a1*M) + a2)),2))129 # P_SFR_total130 return phi_Mstar_double*P_MHI_given_Mstar131def integrand_SFR_blue2(M, SFR, params, gsmf_params):132 # parameters inferred from emcee133 b1, b2, b3, lnb, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params134 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params135 # probabilities136 phi_Mstar_double = np.log(10) * np.exp(-np.power(10,M-Mstar)) * (phistar1*np.power(10,(alpha1+1)*(M-Mstar)) + phistar2*np.power(10,(alpha2+1)*(M-Mstar)))137 fpass = models.f_passive(M, alpha, beta, zeta)138 y_sforming = (b1*M*M) + (b2*M) + b3139 P_SFR_given_Mstar_blue = (1/np.sqrt(2*np.pi*np.power(np.exp(lnb),2)))*np.exp((-1/(2*np.power(np.exp(lnb),2)))*np.power((SFR-y_sforming),2))140 # P_SFR_total141 P_SFR_given_Mstar_total = (1-fpass)*P_SFR_given_Mstar_blue142 # return phi_SFR143 return phi_Mstar_double*P_SFR_given_Mstar_total144def integrand_SFR_red2(M, SFR, params, gsmf_params):145 # parameters inferred from emcee146 b1, b2, b3, lnb, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params147 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params148 # probabilities149 phi_Mstar_double = np.log(10) * np.exp(-np.power(10,M-Mstar)) * (phistar1*np.power(10,(alpha1+1)*(M-Mstar)) + phistar2*np.power(10,(alpha2+1)*(M-Mstar)))150 fpass = models.f_passive(M, alpha, beta, zeta)151 # P_SFR_given_passive152 y_passive = (b1*M*M) + (b2*M) + b3 + r2153 P_SFR_given_Mstar_red = (1/np.sqrt(2*np.pi*np.power(np.exp(lnr),2)))*np.exp((-1/(2*np.power(np.exp(lnr),2)))*np.power((SFR-y_passive),2))154 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red155 # return phi_SFR156 return phi_Mstar_double*P_SFR_given_Mstar_total157def integrand_MHI_blue(M, SFR, MHI, *params):158 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params159 lnh160 Mstar, phistar1, alpha1 = 10.72, 0.71E-3, -1.45161 phi_Mstar_double = np.log(10) * np.exp(-np.power(10,M-Mstar)) * (phistar1*np.power(10,(alpha1+1)*(M-Mstar)))162 f = (b1*M*M) + (b2*M) + b3163 P_SFR_given_Mstar = (1/np.sqrt(2*np.pi*np.power(np.exp(lnb),2)))*np.exp((-1/(2*np.power(np.exp(lnb),2)))*np.power((SFR-f),2))164 f2 = (h1*SFR) + h2165 P_MHI_given_SFR = (1/np.sqrt(2*np.pi*np.power(np.exp(lnh),2)))*np.exp((-1/(2*np.power(np.exp(lnh),2)))*np.power((MHI-f2),2))166 return phi_Mstar_double*P_SFR_given_Mstar*P_MHI_given_SFR167def integrand_MHI_total(M, SFR, MHI, params, gsmf_params):168 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params169 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params170 # probabilities171 phi_Mstar_double = np.log(10) * np.exp(-np.power(10,M-Mstar)) * (phistar1*np.power(10,(alpha1+1)*(M-Mstar)) + phistar2*np.power(10,(alpha2+1)*(M-Mstar)))172 fpass = models.f_passive(M, alpha, beta, zeta)173 # P_SFR_given_passive174 y_passive = r1*M + r2175 P_SFR_given_Mstar_red = (1/np.sqrt(2*np.pi*np.power(np.exp(lnr),2)))*np.exp((-1/(2*np.power(np.exp(lnr),2)))*np.power((SFR-y_passive),2))176 # P_SFR_given_sforming177 y_sforming = (b1*M*M) + (b2*M) + b3178 P_SFR_given_Mstar_blue = (1/np.sqrt(2*np.pi*np.power(np.exp(lnb),2)))*np.exp((-1/(2*np.power(np.exp(lnb),2)))*np.power((SFR-y_sforming),2))179 # P_SFR_total180 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red + (1-fpass)*P_SFR_given_Mstar_blue181 # P_MHI_given_SFR182 f2 = (h1*SFR) + h2183 P_MHI_given_SFR = (1/np.sqrt(2*np.pi*np.power(np.exp(lnh),2)))*np.exp((-1/(2*np.power(np.exp(lnh),2)))*np.power((MHI-f2),2))184 return phi_Mstar_double*P_SFR_given_Mstar_total*P_MHI_given_SFR185def integrand_MHI_blue(M, SFR, MHI, params, gsmf_params):186 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params187 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params188 # probabilities189 phi_Mstar_double = np.log(10) * np.exp(-np.power(10,M-Mstar)) * (phistar1*np.power(10,(alpha1+1)*(M-Mstar)) + phistar2*np.power(10,(alpha2+1)*(M-Mstar)))190 fpass = models.f_passive(M, alpha, beta, zeta)191 # P_SFR_given_sforming192 y_sforming = (b1*M*M) + (b2*M) + b3193 P_SFR_given_Mstar_blue = (1/np.sqrt(2*np.pi*np.power(np.exp(lnb),2)))*np.exp((-1/(2*np.power(np.exp(lnb),2)))*np.power((SFR-y_sforming),2))194 # P_SFR_total195 P_SFR_given_Mstar_total = (1-fpass)*P_SFR_given_Mstar_blue196 # P_MHI_given_SFR197 f2 = (h1*SFR) + h2198 P_MHI_given_SFR = (1/np.sqrt(2*np.pi*np.power(np.exp(lnh),2)))*np.exp((-1/(2*np.power(np.exp(lnh),2)))*np.power((MHI-f2),2))199 return phi_Mstar_double*P_SFR_given_Mstar_total*P_MHI_given_SFR200def integrand_MHI_red(M, SFR, MHI, params, gsmf_params):201 b1, b2, b3, lnb, r1, r2, lnr, alpha, beta, zeta, h1, h2, lnh = params202 Mstar, phistar1, phistar2, alpha1, alpha2 = gsmf_params203 # probabilities204 phi_Mstar_double = np.log(10) * np.exp(-np.power(10,M-Mstar)) * (phistar1*np.power(10,(alpha1+1)*(M-Mstar)) + phistar2*np.power(10,(alpha2+1)*(M-Mstar)))205 fpass = models.f_passive(M, alpha, beta, zeta)206 # P_SFR_given_passive207 y_passive = r1*M + r2208 P_SFR_given_Mstar_red = (1/np.sqrt(2*np.pi*np.power(np.exp(lnr),2)))*np.exp((-1/(2*np.power(np.exp(lnr),2)))*np.power((SFR-y_passive),2))209 # P_SFR_total210 P_SFR_given_Mstar_total = fpass*P_SFR_given_Mstar_red211 # P_MHI_given_SFR212 f2 = (h1*SFR) + h2213 P_MHI_given_SFR = (1/np.sqrt(2*np.pi*np.power(np.exp(lnh),2)))*np.exp((-1/(2*np.power(np.exp(lnh),2)))*np.power((MHI-f2),2))...
smoothing.py
Source:smoothing.py
1from __future__ import division2import numpy as np3import pandas as pd4from collections import Counter5import mmap67#total number of lines in a file8def get_num_lines(file_path):9 fp = open(file_path, "r+")10 buf = mmap.mmap(fp.fileno(), 0)11 lines = 012 while buf.readline():13 lines += 114 return lines1516#linear address17from operator import mul18def get_lin_add(d,M): #d={d_1,d_2,...,d_N}19 sum = 020 for i in range(len(d)):21 sum += X[i]*d[i]22 return sum23def get_mul_list(M):24 x = []25 for i in range(len(M) - 1):26 x.append(reduce(mul, M[i + 1:], 1))27 x.append(1)28 return x2930#find volume of bin in a given linear address31def get_volume(lin_address):32 prod = 133 for i in range(len(L)):34 tuple_quantized_value = tuples_[lin_address][i]35 if (tuple_quantized_value == (L[i] - 1)):36 b_ = 137 else:38 b_ = all_bins[i][tuple_quantized_value]39 if (tuple_quantized_value == 0):40 a_ = 041 else:42 a_ = all_bins[i][tuple_quantized_value - 1]43 length = b_ - a_44 prod = prod * length45 return prod46#find list of adjacent hypercubes given linear address47def get_adjacents(lin_address):48 adj = []49 for i in range(len(L)):50 tuple_quantized_value = tuples_[lin_address][i]51 if (tuple_quantized_value != (L[i] - 1)):52 current_tuple = []53 for j in range(len(L)):54 current_tuple.append(tuples_[lin_address][j])55 # current_tuple = tuples_[lin_address]56 oneplus = tuple_quantized_value+157 current_tuple[i] = oneplus58 adj.append(get_lin_add(current_tuple, X))59 if (tuple_quantized_value != 0):60 current_tuple = []61 for j in range(len(L)):62 current_tuple.append(tuples_[lin_address][j])63 # current_tuple = tuples_[lin_address]64 oneminus = tuple_quantized_value-165 current_tuple[i] = oneminus66 adj.append(get_lin_add(current_tuple, X))67 return adj6869k_smoothing = 0 #k smoothing parameter70M = np.array([6,6,6,6,6])71filename = 'train_shuf.txt' #training data72filename_val = 'testset_shuf.txt' #validation data(to find expected gain on test dataset,73 #use test dataset filename here)7475X = get_mul_list(M)7677att = len(M) #number of attributes78k = 2 #number of classes79p_c0_given = 0.480p_c1_given = 0.681e = np.array([[1,-1],[-2,3]]) #economic gain matrix828384##########85#TRAINING#86##########8788names = ['d0','d1','d2','d3','d4','c']89data = pd.read_csv(filename, delim_whitespace=True, names=names)90print 'training data loaded'9192#find c0(#class 0) and c1 (#class 1)93c_counts = data.groupby('c').size()94c0 = c_counts[0]95c1 = c_counts[1]96#find number of datapoints in the training data97count = get_num_lines(filename)9899p_c0 = c0/count100p_c1 = c1/count101possible = reduce(mul,M,1)102freq = np.array([[0,0]]*possible)103#assign quantization boundaries104105#website106# all_bins = [[0.02037, 0.18117, 0.56374, 0.90676, 0.98718],107# [0.47436, 0.49150, 0.53603, 0.58948, 0.62023],108# [0.08321, 0.15193, 0.24154, 0.60653, 0.94493],109# [0.02697, 0.22574, 0.25494, 0.32456, 0.85316],110# [0.06348, 0.10362, 0.19162, 0.51352, 0.60375]]111112#obtained113all_bins = [[0.020396230352061586, 0.18112093576230517, 0.56371108997429864, 0.90573194987351546, 0.98713552434720719], [0.47740305825561957, 0.49158230891229621, 0.53604530753654833, 0.58945797857319193, 0.62133588387997052], [0.083527517494396325, 0.15043785729425685, 0.24212870105257039, 0.60883725653314369, 0.94429274843755207], [0.027062732204467147, 0.22586873166582544, 0.25495747557281101, 0.32423799658245084, 0.85452868021262018], [0.10338670244319639, 0.18964591655552912, 0.51164305299824786, 0.60293289381089343, 0.7600441109968824]]114115L = M.tolist()116print 'bin boundaries set for quantization'117#quantize training data118for i,item in enumerate(names[:-1]):119 dq = pd.np.digitize(data[item], bins=all_bins[i],right=True)120 data['{}_quantized'.format(item)] = dq121print 'training data quantized'122#calculate frequency of d,c123counter0 = Counter(tuple(a[1:]) for a in data.values[:,5:11] if a[0]==0)124counter1 = Counter(tuple(a[1:]) for a in data.values[:,5:11] if a[0]==1)125for key in counter0.keys():126 freq[int(get_lin_add(key, X))][0] = counter0[key]127for key in counter1.keys():128 freq[int(get_lin_add(key, X))][1] = counter1[key]129130131##################132##################133### SMOOTHING ###134##################135##################136137tuples_ = np.array([[0]*len(L)]*possible) #stores the tuples138row = 0139for i in range(L[0]):140 for j in range(L[1]):141 for k_ in range(L[2]):142 for l in range(L[3]):143 for m in range(L[4]):144 tuples_[row] = i,j,k_,l,m145 row = row + 1146147pm = np.array([[0, 0]] * possible, dtype=float)148#calculate pm for class 0149for row in range(possible):150 #find v151 v = get_volume(row)152 #find b and v1153 b = freq[row][0]154 v1 = v155 if (b < k_smoothing):156 adjacents = get_adjacents(row) #get_adjacents(row) should return a list of linear addresses157 for liad in adjacents:158 b = b + freq[liad][0]159 v1 = v1 + get_volume(liad)160 if (b >= k_smoothing):161 break162 #find pm[row][0]163 pm[row][0] = (float(b)*v)/v1164165166#normalize167pm_sum0 = pm[:,0].sum()168for row in range(possible):169 if pm_sum0 != 0:170 pm[row][0] = pm[row][0]/pm_sum0171172173#calculate pm for class 1174for row in range(possible):175 #find v176 v = get_volume(row)177 #find b and v1178 b = freq[row][1]179 v1 = v180 if (b < k_smoothing):181 adjacents = get_adjacents(row) #get_adjacents(row) should return a list of linear addresses182 for liad in adjacents:183 b = b + freq[liad][1]184 v1 = v1 + get_volume(liad)185 if (b >= k_smoothing):186 break187188 #find pm[row][1]189 pm[row][1] = (float(b)*v)/v1190#normalize191pm_sum1 = pm[:,1].sum()192for row in range(possible):193 if pm_sum1 != 0:194 pm[row][1] = pm[row][1]/pm_sum1195print 'smoothing done'196197#calculate P(d,c)198p_d_c = freq/count199#calculate P(d|c)200p_d_given_c_prev = freq/count #just initialize201for row in range(possible):202 p_d_given_c_prev[row][0] = p_d_given_c_prev[row][0]/p_c0203 p_d_given_c_prev[row][1] = p_d_given_c_prev[row][1]/p_c1204#calculate P(d|c) (NOW USING SMOOTHING)205p_d_given_c = pm206#calculate P(c|d) (uses p_c0_given and p_c1_given)207# p_c_given_d = freq/count #just initialize208p_c_given_d = np.array([[0,0]]*possible, dtype=float)209for row in range(possible):210 denominator = (p_d_given_c[row][0]*p_c0_given) + (p_d_given_c[row][1]*p_c1_given)211 if (denominator!=0):212 p_c_given_d[row][0] = (p_d_given_c[row][0]*p_c0_given)/denominator213 p_c_given_d[row][1] = (p_d_given_c[row][1]*p_c1_given)/denominator214#calculate P(c,d): to be used (**not same as P(d,c) calculated before)215#(uses p_c0_given and p_c1_given)216p_c_d = freq/count #just initialize217# p_c_d = np.array([[0,0]]*possible, dtype=float)218for row in range(possible):219 p_c_d[row][0] = p_d_given_c[row][0]*p_c0_given220 p_c_d[row][1] = p_d_given_c[row][1]*p_c1_given221222##find p_c_given_d_another using p_c_d##223p_c_given_d_another = np.array([[0,0]]*possible, dtype=float)224for row in range(possible):225 deno = p_c_d[row][0] + p_c_d[row][1]226 if deno!=0:227 p_c_given_d_another[row][0] = p_c_d[row][0]/deno228 p_c_given_d_another[row][1] = p_c_d[row][1]/deno229##230231#calculate fd(c)232fd = np.array([[0,0]]*possible)233for row in range(possible):234 sum0 = p_c_d[row][0]*e[0,0]+p_c_d[row][1]*e[1,0]235 sum1 = p_c_d[row][0]*e[0,1]+p_c_d[row][1]*e[1,1]236237 if sum0 > sum1:238 fd[row][0] = 1239 else:240 fd[row][1] = 1241print 'decision rule built'242243244############245#VALIDATION#246############247248names = ['d0','d1','d2','d3','d4','c']249data_val = pd.read_csv(filename_val, delim_whitespace=True, names=names)250print 'validation data loaded'251252#find c0(#class 0) and c1 (#class 1)253c_counts_val = data_val.groupby('c').size()254c0_val = c_counts_val[0]255c1_val = c_counts_val[1]256#find number of datapoints in the training data257count_val = get_num_lines(filename_val)258259p_c0_val = c0_val/count_val260p_c1_val = c1_val/count_val261freq_val = np.array([[0,0]]*possible)262#quantize validation data263for i,item in enumerate(names[:-1]):264 dq = pd.np.digitize(data_val[item], bins=all_bins[i])265 data_val['{}_quantized'.format(item)] = dq266print 'validation data quantized'267#calculate frequency of d,c268counter0_val = Counter(tuple(a[1:]) for a in data_val.values[:,5:11] if a[0]==0)269counter1_val = Counter(tuple(a[1:]) for a in data_val.values[:,5:11] if a[0]==1)270for key in counter0_val.keys():271 freq_val[int(get_lin_add(key, X))][0] = counter0_val[key]272for key in counter1_val.keys():273 freq_val[int(get_lin_add(key, X))][1] = counter1_val[key]274275#calculate P(d,c)276p_d_c_val = freq_val/count_val277#calculate P(d|c)278p_d_given_c_val = freq_val/count_val #just initialize279for row in range(possible):280 p_d_given_c_val[row][0] = p_d_given_c_val[row][0]/p_c0_val281 p_d_given_c_val[row][1] = p_d_given_c_val[row][1]/p_c1_val282#calculate P(c|d) (uses p_c0_given and p_c1_given)283p_c_given_d_val = freq_val/count_val #just initialize284for row in range(possible):285 denominator = (p_d_given_c_val[row][0]*p_c0_given) + (p_d_given_c_val[row][1]*p_c1_given)286 if (denominator!=0):287 p_c_given_d_val[row][0] = (p_d_given_c_val[row][0]*p_c0_given)/denominator288 p_c_given_d_val[row][1] = (p_d_given_c_val[row][1]*p_c1_given)/denominator289#calculate P(c,d): to be used (**not same as P(d,c) calculated before)290#(uses p_c0_given and p_c1_given)291p_c_d_val = freq_val/count_val #just initialize292for row in range(possible):293 p_c_d_val[row][0] = p_d_given_c_val[row][0]*p_c0_given294 p_c_d_val[row][1] = p_d_given_c_val[row][1]*p_c1_given295296#calculate confusion matrix297conf_mat = np.array([[0,0],[0,0]], dtype=float) #initialize298for tr in range(k):299 for assigned in range(k):300 sum = 0301 for i in range(possible):302 sum = sum + p_d_c_val[i,tr]*fd[i,assigned] #p_c_d_val changed to p_d_c_val303 conf_mat[tr,assigned] = sum304#calculate economic gain305exp_gain = (e*conf_mat).sum()306307print M308print e309310print freq311print p_d_c312print p_d_given_c313print p_c_given_d314print p_c_d315print fd316print conf_mat317print exp_gain318
...
TestCaptureGivenAuth.py
Source:TestCaptureGivenAuth.py
1#Copyright (c) 2017 Vantiv eCommerce2#3#Permission is hereby granted, free of charge, to any person4#obtaining a copy of this software and associated documentation5#files (the "Software"), to deal in the Software without6#restriction, including without limitation the rights to use,7#copy, modify, merge, publish, distribute, sublicense, and/or sell8#copies of the Software, and to permit persons to whom the9#Software is furnished to do so, subject to the following10#conditions:11#12#The above copyright notice and this permission notice shall be13#included in all copies or substantial portions of the Software.14#15#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,16#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES17#OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND18#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT19#HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,20#WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING21#FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR22#OTHER DEALINGS IN THE SOFTWARE.23import os, sys24lib_path = os.path.abspath('../all')25sys.path.append(lib_path)26from SetupTest import *27import unittest28import pyxb29class TestCaptureGivenAuth(unittest.TestCase):30 31 def testSimpleCaptureGivenAuth(self):32 CaptureGivenAuth = litleXmlFields.captureGivenAuth()33 CaptureGivenAuth.amount = 10634 CaptureGivenAuth.orderId = "12344"35 AuthInfo = litleXmlFields.authInformation()36 date = pyxb.binding.datatypes.date(2002, 10, 20)37 AuthInfo.authDate = date38 AuthInfo.authCode = "543216"39 AuthInfo.authAmount = 1234540 CaptureGivenAuth.authInformation = AuthInfo41 CaptureGivenAuth.orderSource = "ecommerce"42 Card = litleXmlFields.cardType()43 Card.number = "4100000000000000"44 Card.expDate = "1210"45 Card.type = 'VI'46 Card.cardValidationNum = '1210'47 CaptureGivenAuth.card = Card48 litleXml = litleOnlineRequest(config)49 response = litleXml.sendRequest(CaptureGivenAuth)50 self.assertEquals("Approved",response.message)51 52 def testSimpleCaptureGivenAuthWithToken(self):53 CaptureGivenAuth = litleXmlFields.captureGivenAuth()54 CaptureGivenAuth.amount = 10655 CaptureGivenAuth.orderId = "12344"56 AuthInfo = litleXmlFields.authInformation()57 date = pyxb.binding.datatypes.date(2002, 10, 9)58 AuthInfo.authDate = date59 AuthInfo.authCode = "543216"60 AuthInfo.authAmount = 1234561 CaptureGivenAuth.authInformation = AuthInfo62 CaptureGivenAuth.orderSource = "ecommerce"63 Token = litleXmlFields.cardTokenType()64 Token.litleToken = "123456789101112"65 Token.expDate = "1210"66 Token.type = 'VI'67 Token.cardValidationNum = '555'68 CaptureGivenAuth.token = Token69 litleXml = litleOnlineRequest(config)70 response = litleXml.sendRequest(CaptureGivenAuth)71 self.assertEquals("Approved",response.message)72 73 def testComplexCaptureGivenAuth(self):74 CaptureGivenAuth = litleXmlFields.captureGivenAuth()75 CaptureGivenAuth.amount = 10676 CaptureGivenAuth.secondaryAmount = 1077 CaptureGivenAuth.orderId = "12344"78 AuthInfo = litleXmlFields.authInformation()79 date = pyxb.binding.datatypes.date(2002, 10, 9)80 AuthInfo.authDate = date81 AuthInfo.authCode = "543216"82 AuthInfo.authAmount = 1234583 CaptureGivenAuth.authInformation = AuthInfo84 Contact = litleXmlFields.contact();85 Contact.name="Bob"86 Contact.city="lowell"87 Contact.state="MA"88 Contact.email="litle.com"89 CaptureGivenAuth.billToAddress = Contact90 ProcessingInstruct = litleXmlFields.processingInstructions()91 ProcessingInstruct.bypassVelocityCheck = True92 CaptureGivenAuth.processingInstructions = ProcessingInstruct93 CaptureGivenAuth.orderSource = "ecommerce"94 Card = litleXmlFields.cardType()95 Card.number = "4100000000000000"96 Card.expDate = "1210"97 Card.type = 'VI'98 Card.cardValidationNum = '1210'99 CaptureGivenAuth.card = Card100 litleXml = litleOnlineRequest(config)101 response = litleXml.sendRequest(CaptureGivenAuth)102 self.assertEquals("Approved",response.message)103 104 105 def testAuthInfo(self):106 CaptureGivenAuth = litleXmlFields.captureGivenAuth()107 CaptureGivenAuth.amount = 106108 CaptureGivenAuth.orderId = "12344"109 AuthInfo = litleXmlFields.authInformation()110 date = pyxb.binding.datatypes.date(2002, 10, 9)111 AuthInfo.authDate = date112 AuthInfo.authCode = "543216"113 AuthInfo.authAmount = 12345114 FraudResult = litleXmlFields.fraudResult()115 FraudResult.avsResult = "12"116 FraudResult.cardValidationResult = "123"117 FraudResult.authenticationResult = "1"118 FraudResult.advancedAvsResult = "123"119 AuthInfo.fraudResult = FraudResult120 CaptureGivenAuth.authInformation = AuthInfo121 CaptureGivenAuth.orderSource = "ecommerce"122 Card = litleXmlFields.cardType()123 Card.number = "4100000000000000"124 Card.expDate = "1210"125 Card.type = 'VI'126 Card.cardValidationNum = '555'127 CaptureGivenAuth.card = Card128 litleXml = litleOnlineRequest(config)129 response = litleXml.sendRequest(CaptureGivenAuth)130 self.assertEquals("Approved",response.message)131 132def suite():133 suite = unittest.TestSuite()134 suite = unittest.TestLoader().loadTestsFromTestCase(TestCaptureGivenAuth)135 return suite136if __name__ =='__main__':...
breakword.py
Source:breakword.py
1"""2Problem Statement3=================4Given a string and a dictionary, split the string in to multiple words so that each word belongs to the dictionary.5Video6-----7* https://youtu.be/WepWFGxiwRs8Analysis9--------10* word_break_recursive: Exponential11* word_break_dp : O(n^3)12Solution13--------14if input[i..j] belongs in a dictionary:15 DP[i][j] = True16else:17 DP[i][j] = True if DP[i][k-1] and DP[k][j] for any k between i to j.18Multiple different implementations are given below.19"""20def word_break_recursive(given_string, dictionary):21 """"Returns None if the given string cannot be broken into words, otherwise returns space separate words."""22 given_string_length = len(given_string)23 if given_string_length == 0:24 return ""25 string = ""26 for i in range(given_string_length):27 string += given_string[i]28 if string in dictionary:29 r = word_break_recursive(given_string[i + 1:], dictionary)30 if r is not None:31 string += " " + r32 return string33 return None34def word_break_dp(given_string, dictionary):35 """Returns None if the given string cannot be broken into words, otherwise returns space separated words."""36 given_string_length = len(given_string)37 # -1 indicates the word cannot be split.38 DP = [[-1 for _ in range(given_string_length)] for _ in range(given_string_length)]39 for substring_length in range(1, given_string_length + 1):40 for start in range(0, given_string_length - substring_length + 1):41 end = start + substring_length - 142 substring = given_string[start: end + 1]43 if substring in dictionary:44 DP[start][end] = start45 continue46 for split in range(start + 1, end + 1):47 if DP[start][split - 1] != -1 and DP[split][end] != -1:48 DP[start][end] = split49 break50 if DP[0][-1] == -1:51 return None52 words = []53 start_index = 054 end_index = given_string_length - 155 while start_index < given_string_length:56 split_index = DP[start_index][end_index]57 if start_index == split_index:58 words.append(given_string[start_index: end_index + 1])59 break60 else:61 words.append(given_string[start_index: split_index])62 start_index = split_index63 return " ".join(words)64def is_word_break_possible(given_string, dictionary):65 """Returns if any word break is possible amongst the multiple word breaks in the sentence."""66 DP = dict()67 max_word_length = len(max(dictionary, key=len))68 return is_word_break_possible_recursive_helper(given_string, dictionary, 0, max_word_length, DP)69def is_word_break_possible_recursive_helper(given_string, dictionary, start, max_word_length, DP):70 if start == len(given_string):71 return True72 if start in DP:73 return DP[start]74 for i in range(start, start + max_word_length):75 if i < len(given_string):76 new_word = given_string[start: i + 1]77 if new_word in dictionary:78 continue79 if is_word_break_possible_recursive_helper(given_string, dictionary, i + 1, max_word_length, DP):80 DP[start] = True81 return True82 DP[start] = False83 return False84def all_possible_word_break_helper(given_string, dictionary, start, max_word_length, DP):85 """"Returns all possible word breaks in a given sentence."""86 if start == len(given_string):87 return [""]88 if start in DP:89 return DP[start]90 words = []91 for i in range(start, start + max_word_length):92 if i < len(given_string):93 new_word = given_string[start: i + 1]94 if new_word not in dictionary:95 continue96 sub_words = all_possible_word_break_helper(given_string, dictionary, i + 1, max_word_length, DP)97 for word in sub_words:98 extra_space = "" if len(word) == 0 else " "99 words.append(new_word + extra_space + word)100 DP[start] = words101 return words102def all_possible_word_breaks(given_string, dictionary):103 DP = dict()104 max_word_length = len(max(dictionary, key=len))105 return all_possible_word_break_helper(given_string, dictionary, 0, max_word_length, DP)106if __name__ == '__main__':107 dictionary = {"joy", "likes", "to", "play"}108 given_string = "joylikestoplay"109 assert True == is_word_break_possible(given_string, dictionary)110 assert "joy likes to play " == word_break_recursive(given_string, dictionary)111 assert "joy likes to play" == word_break_dp(given_string, dictionary)112 dictionary = {"pea", "nut", "peanut", "butter"}113 given_string = "peanutbutter"...
index_test.py
Source:index_test.py
1from datetime import datetime, timedelta2import index as i3def test_parse_compliance_status():4 expiration_past = datetime.now() - timedelta(days=2)5 expiration_future = datetime.now() + timedelta(days=2)6 records = [7 {8 'id': 'i-0c9d6b554167f2bea',9 'tags': [{'Key': 'environment', 'Value': 'stage'}]10 },11 {12 'id': 'i-064529d714f511dbb',13 'tags': [{'Key': 'expiration', 'Value': expiration_past.strftime("%Y-%m-%d %H:%M:%S")}]14 },15 {16 'id': 'i-03f4std714f511dbb',17 'tags': [{18 'Key': 'expiration', 'Value': expiration_future.strftime("%Y-%m-%d %H:%M:%S")19 }]20 },21 {22 'id': 'i-sdf098345kjsdf'23 }24 ]25 expected = {26 'terminate': ['i-064529d714f511dbb'],27 'terminate_soon': ['i-03f4std714f511dbb'],28 'set_expiration': ['i-0c9d6b554167f2bea', 'i-sdf098345kjsdf']29 }30 assert i.parse_compliance_status(records) == expected31def test_validate_tag_keys():32 given_tags = ['environment', 'owner']33 required_tags = ['environment', 'owner']34 assert i.validate_tag_keys(given_tags, required_tags) is True35def test_validate_tag_keys_different():36 given_tags = ['environment']37 required_tags = ['environment', 'owner']38 assert i.validate_tag_keys(given_tags, required_tags) is False39def test_validate_tag_keys_when_has_extras():40 given_tags = ['environment', 'extra']41 required_tags = ['environment']42 assert i.validate_tag_keys(given_tags, required_tags) is True43def test_validate_tag_value():44 given_value = "dev"45 accepted_values = ["dev", "prod", "stage"]46 assert i.validate_tag_value(given_value, accepted_values) is True47def test_audit_tag_value_not_accepted():48 given_value = "whatever"49 accepted_values = ["dev", "stage"]50 assert i.validate_tag_value(given_value, accepted_values) is False51def test_audit_tag_wildcard():52 given_value = "anything"53 accepted_values = ["*"]54 assert i.validate_tag_value(given_value, accepted_values) is True55def test_audit_tag_partial_match():56 given_value = "person@gmail.com"57 accepted_values = ["*@gmail.com"]58 assert i.validate_tag_value(given_value, accepted_values) is True59def test_audit_tag_partial_match_order():60 given_value = "person@gmail.com"61 accepted_values = ["person@*", "whatever", "*@gmail.com"]62 assert i.validate_tag_value(given_value, accepted_values) is True63def test_audit_tags():64 given_tags = [65 {'Value': 'dev', 'Key': 'environment'},66 {'Value': 'person', 'Key': 'owner'}67 ]68 required_tags = {69 'environment': [70 'dev',71 'prod',72 'stage'73 ],74 'owner': ['*']75 }76 assert i.audit_tags(given_tags, required_tags) is True77def test_audit_tags_no_tags():78 given_tags = []79 required_tags = {80 'environment': ['*']81 }82 assert i.audit_tags(given_tags, required_tags) is False83def test_audit_tags_more_then_required():84 given_tags = [85 {'Value': 'dev', 'Key': 'environment'},86 {'Value': 'person', 'Key': 'owner'}87 ]88 required_tags = {89 'environment': ['dev', 'stage']90 }91 assert i.audit_tags(given_tags, required_tags) is True92def test_audit_tags_lots_of_wildcards():93 given_tags = [94 {'Value': 'dev', 'Key': 'environment'},95 {'Value': 'Whatever Name', 'Key': 'person'},96 {'Value': 'person@gmail.com', 'Key': 'email'},97 {'Value': '10930', 'Key': 'costCenter'}98 ]99 required_tags = {100 'environment': ['dev', 'stage'],101 'person': ['Whatever*'],102 'email': ['*@gmail.com']103 }104 assert i.audit_tags(given_tags, required_tags) is True105def test_is_node_first_offense():106 given_tags = ['environment', 'owner']107 assert i.node_first_offense(given_tags) is True108def test_is_node_second_offense():109 given_tags = ['environment', 'owner', 'expiration']110 assert i.node_first_offense(given_tags) is False111def test_node_past_due():112 expiration_date = datetime.now() - timedelta(days=2)113 assert i.node_past_due(...
Using AI Code Generation
1const {Pact} = require('@pact-foundation/pact');2const {somethingLike} = require('@pact-foundation/pact/dsl/matchers');3const {eachLike} = require('@pact-foundation/pact/dsl/matchers');4const {term} = require('@pact-foundation/pact/dsl/matchers');5const {like} = require('@pact-foundation/pact/dsl/matchers');6const {term} = require('@pact-foundation/pact/dsl/matchers');7const {term} = require('@pact-foundation/pact/dsl/matchers');8const {term} = require('@pact-foundation/pact/dsl/matchers');9const {term} = require('@pact-foundation/pact/dsl/matchers');10const {term} = require('@pact-foundation/pact/dsl/matchers');11const {term} = require('@pact-foundation/pact/dsl/matchers');12const {term} = require('@pact-foundation/pact/dsl/matchers');13const {term} = require('@pact-foundation/pact/dsl/matchers');14const {term} = require('@pact-foundation/pact/dsl/matchers');15const {term} = require('@pact-foundation/pact/dsl/matchers');16const {term} = require('@pact-foundation/pact/dsl/matchers');17const {term} = require('@pact-foundation/pact/dsl/matchers');18const {term} = require('@pact-foundation/pact/dsl/matchers');19const {term} = require('@pact-foundation/pact/dsl/matchers');20const {term} = require('@pact-foundation/pact/dsl/matchers');21const {term} = require('@pact-foundation/pact/dsl/matchers');22const {term} = require('@pact-foundation/pact/dsl/matchers');23const {term} = require('@pact-foundation/pact/dsl/matchers');24const {Pact, Matchers} = require('@pact-foundation/pact');25const {somethingLike} = require('@pact-foundation/pact/dsl/matchers');26const {eachLike} = require('@pact-foundation/pact/dsl/matchers');27const {term} =
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!!