def basicUnitTest(): client = Protocol.ForgotPasswordClientProtocol() server = Protocol.ForgotPasswordServerProtocol() cTransport, sTransport = MockTransportToProtocol.CreateTransportPair( client, server) server.connection_made(sTransport) client.connection_made(cTransport) # client.send_initial_message() packet1 = Packets.RequestForgotPasswordPacket() packet1.userId = 'ehsia1' packet1Bytes = packet1.__serialize__() sResponse1 = server.data_received(packet1Bytes) assert isinstance(sResponse1, Packets.SecurityQuestionPacket) packet2 = Packets.SecurityQuestionPacket() packet2.securityQuestion = 'What was your hometown?' packet2Bytes = packet2.__serialize__() cResponse1 = client.data_received(packet2Bytes) cResponse1 = PacketType.Deserialize(cResponse1) assert isinstance(cResponse1, Packets.SecurityAnswerPacket) packet3 = Packets.SecurityAnswerPacket() packet3.securityAnswer = 'Windsor, CT' packet3Bytes = packet3.__serialize__() sResponse2 = server.data_received(packet3Bytes) assert isinstance(sResponse2, Packets.ForgotPasswordTokenPacket) packet3.securityAnswer = 'Windsor' packet3Bytes = packet3.__serialize__() sResponse2 = server.data_received(packet3Bytes) assert sResponse2 == "Invalid" packet4 = Packets.ForgotPasswordTokenPacket() packet4.token = 'asdf2313241SqwerXq' packet4Bytes = packet4.__serialize__() cResponse2 = client.data_received(packet4Bytes) cResponse2 = PacketType.Deserialize(cResponse2) assert isinstance(cResponse2, Packets.ResetPasswordInputPacket) packet5 = Packets.ResetPasswordInputPacket() packet5.newPassword = '******' packet5.passwordConfirmation = 'gronkgronkgronk' packet5Bytes = packet5.__serialize__() sResponse3 = server.data_received(packet5Bytes) assert isinstance(sResponse3, Packets.PasswordResetPacket) assert sResponse3.verification == True packet5.newPassword = '******' packet5.passwordConfirmation = 'gronkgronkgronk' packet5Bytes = packet5.__serialize__() sResponse3 = server.data_received(packet5Bytes) assert isinstance(sResponse3, Packets.PasswordResetPacket) assert sResponse3.verification == False print("Protocol completed! All tests passed!")
def UnitTest_RequestConnect(testNum, iD): packet1 = RequestConnect() packet1.testNum = testNum packet1.iD = iD packet1Bytes = packet1.__serialize__() packet1a = PacketType.Deserialize(packet1Bytes) assert packet1 == packet1a
def UnitTest_VerifyAnswer(iD, answer): packet3 = VerifyAnswer() packet3.iD = iD packet3.answer = answer packet3Bytes = packet3.__serialize__() packet3a = PacketType.Deserialize(packet3Bytes) assert packet3 == packet3a
def UnitTest_ConnectResult(iD, result): packet4 = ConnectResult() packet4.iD = iD packet4.result = result packet4Bytes = packet4.__serialize__() packet4a = PacketType.Deserialize(packet4Bytes) assert packet4 == packet4a
def test1(self): flipPacket = RequestFlip() flipPacket.headOrTail = True flipPacket.numFlips = 10 packetBytes = flipPacket.__serialize__() flipPacketDes = PacketType.Deserialize(packetBytes) assert flipPacket == flipPacketDes
def UnitTest_VerifyQuestion(iD, question): packet2 = VerifyQuestion() packet2.iD = iD packet2.question = question packet2Bytes = packet2.__serialize__() packet2a = PacketType.Deserialize(packet2Bytes) assert packet2 == packet2a
def data_received(self, data): pkt = PacketType.Deserialize(data) if isinstance(pkt, ResponsePacket): clientPrint("LTP " + str(pkt.code) + " " + LtpCode[pkt.code] + ", server message: " + pkt.message) self.responseCount += 1 if self.responseCount == self.pktCount: # All request completed self.transport.close()
def basicUnitTest2(): packet3 = OperationRequestPacket() packet3.sessionID = "wwz1234" packet3.operation1 = 1 packet3.data1 = b"hello" packet3.data2 = b"world" pkyBytes = packet3.__serialize__() packet3check = PacketType.Deserialize(pkyBytes) if packet3check == packet3: print("These two packages are the same!")
def handlePacket(self, protocol, pkt): pkt = PacketType.Deserialize(pkt) version = pkt.DEFINITION_VERSION versionMajorString, versionMinorString = version.split(".") versionMajor = int(versionMajorString) versionMinor = int(versionMinorString) pktHandlerVersions = self.__packetHandlers.get(pkt.__class__, None) if not pktHandlerVersions: return False pktHandlerSpecificVersions = pktHandlerVersions.get(versionMajor, None) if not pktHandlerSpecificVersions: return False handler = pktHandlerSpecificVersions.get(versionMinor, None) if not handler: otherVersions = pktHandlerSpecificVersions.keys() otherVersions.append(versionMinor) otherVersions.sort() myIndex = otherVersions.index(versionMinor) if myIndex < len(otherVersions) - 1: nextHighestVersion = otherVersions[myIndex + 1] handler = pktHandlerSpecificVersions[nextHighestVersion] if handler: # TODO: Put log packet here about handling one version with another pass if not handler: return False try: handler(protocol, pkt) except Exception as e: print(traceback.format_exc()) raise PacketHandlerFailure( "Handler %s failed to handle %s %s (%s)" % (handler, protocol, pkt, e)) return True
def basicUnitTest(): p = PacketType() class TestPacket1(PacketType): DEFINITION_IDENTIFIER = "packettype.basicunittest.TestPacket1" DEFINITION_VERSION = "1.0" class SubFields(PacketFields): FIELDS = [("subfield1",Uint({Bits:16})), ("subfield2",Uint({Bits:16}))] FIELDS = [ ("ls", ListFieldType(ComplexFieldType(SubFields))) ] packet = TestPacket1() packet.ls = [] subFields = TestPacket1.SubFields(); subFields.subfield1 = 21 subFields.subfield2 = 45 packet.ls.append(subFields) serializedData = packet.__serialize__() restoredPacket = PacketType.Deserialize(serializedData) print("Success!")
# return super(RIPPPacket, self).__repr__() + \ # ". Type: " + str(self.Type) + \ # ". SeqNo: " + str(self.SeqNo) + \ # ". AckNo: " + str(self.AckNo) + \ # ". Data: " + str(self.Data) + \ # ". CRC: " + str(self.CRC) if __name__ == "__main__": packet1 = RIPPPacket() packet1.Type = 1 packet1.SeqNo = 1 packet1.AckNo = 100 packet1.CRC = b'5000' packet1.Data = b'Kandarp Khandwala' packetBytes = packet1.__serialize__() packet2 = PacketType.Deserialize(packetBytes) if packet1 == packet2: print("These two packets are the same! {} {}".format(packet1, packet2)) else: print("Mismatched packets {} {}".format(packet1, packet2)) pkt3 = RIPPPacket().syn_packet(1) pkt4 = RIPPPacket().ack_packet(2, 3) pkt5 = RIPPPacket().syn_ack_packet(1, 2) pkt6 = RIPPPacket().data_packet(1, b'abc') print(pkt3, pkt4, pkt5, pkt6)
def basicUnitTest(): # Modified from lab1b PDF unlockPacket1 = UnlockPacket() unlockPacket1.password = 000 unlockPacketBytes = unlockPacket1.__serialize__() unlockPacket2 = PacketType.Deserialize(unlockPacketBytes) if unlockPacket1 == unlockPacket2: print("These two unlock packets are the same!") changePasswordPacket1 = ChangePasswordPacket() changePasswordPacket1.password = 000 changePasswordPacket2 = ChangePasswordPacket() changePasswordPacket2.password = 000 if changePasswordPacket1 == changePasswordPacket2: print("These two change password packets are the same!") changePasswordPacket2.password = 111 if changePasswordPacket1 != changePasswordPacket2: print("After editing, these two change password packets are not the same.") # Missed Google foo.bar by searching "python try except" and clicking on the first result immediately -_- lockPacket1 = LockPacket() lockPacket1.password = 222 lockPacketBytes = lockPacket1.__serialize__() lockPacket2 = PacketType.Deserialize(lockPacketBytes) print("Lock packet 1 password is: " + str(lockPacket1.password)) try: print("Lock packet 2 password is: " + str(lockPacket2.password)) except AttributeError: print("Exception on accessing invalid password field of deserialized lock packet 2.") try: responsePacket0 = ResponsePacket() responsePacket0.code = -418 except Exception: print("Exception on setting negative value to a UINT32 field of response packet.") responsePacket1 = ResponsePacket() responsePacket1.code = 200 responsePacket1.message = "Success" responsePacket2 = ResponsePacket() responsePacket2.code = 400 responsePacket2.message = "Bad Request" responsePacket3 = ResponsePacket() responsePacket3.code = 403 responsePacket3.message = "Forbidden" pktBytes = responsePacket1.__serialize__() + responsePacket2.__serialize__() + responsePacket3.__serialize__() deserializer = PacketType.Deserializer() print("Starting with {} bytes of data".format(len(pktBytes))) packetCount = 0; while len(pktBytes) > 0: # let’s take one byte chunk, pktBytes = pktBytes[:1], pktBytes[1:] deserializer.update(chunk) packetCount += 1 for packet in deserializer.nextPackets(): print("Got a packet end at byte " + str(packetCount) + "!") if packet == responsePacket1: print("It’s response packet 1!") elif packet == responsePacket2: print("It’s response packet 2!") elif packet == responsePacket3: print("It’s response packet 3!") testOptionalListPacket1 = TestOptionalListPacket() testOptionalListPacketBytes1 = testOptionalListPacket1.__serialize__() print("Optional field can be left unset!") testOptionalListPacket1.testlist = ["Hello Playground!"] testOptionalListPacketBytes2 = testOptionalListPacket1.__serialize__() testOptionalListPacket2 = PacketType.Deserialize(testOptionalListPacketBytes2) if testOptionalListPacket1 == testOptionalListPacket2: print("These two optional list packets are the same!") else: print(list(testOptionalListPacket1.testlist)) print(list(testOptionalListPacket2.testlist)) if list(testOptionalListPacket1.testlist) == list(testOptionalListPacket2.testlist): print("Though cannot be compared at packet level, these two list fields are the same!")
def basicUnitTest(): print("~~~Welcome to Jukebox!~~~") Genre = input( "Please Enter the genre you would like to listen to! Available options - Rock/Pop/Classical/Jazz \n" ) Genre = Genre.upper() print(Genre) AuthToken = input("Enter your authentication token - 3 digit\n") if int(AuthToken) > 0: # Packet 1 - Client Hello ClientHello1 = ClientHello() ClientHello1.UserAuthToken = AuthToken ClientHello1.Genre = str(Genre) # Sending the packet packetBytes = ClientHello1.__serialize__() deserializer_ClientHello = PacketType.Deserialize(packetBytes) if deserializer_ClientHello == ClientHello1: print( "\nClient Hello has been successfully serialized and deserialized \n" ) else: print("\nHouston, we have a problem! \n") return # Genres GenreList = ["ROCK", "POP", "CLASSICAL", "JAZZ"] # AuthTokens # UserTokens = [123,345,567,789,901] print("==Server processing Client Hello==") # Generating Random Session IDs SessionID_Random = random.randint(1, 100) # Packet 2 - Server Hello ServerHello1 = ServerHello() ServerHello1.SessionID = SessionID_Random # Keeping track of all ongoing sessions # SessionID_Random_List = [] # SessionID_Random_List.insert(0,SessionID_Random) # Authentication token at this moment can be any 3 digit number if re.match("^\d\d\d$", str(deserializer_ClientHello.UserAuthToken)): ServerHello1.AuthResponse = 1 ServerHello1.RequestBitRate = "Enter the bit rate at which you would like to listen to your music" if deserializer_ClientHello.Genre in GenreList: ServerHello1.GenreAvailable = 1 else: ServerHello1.GenreAvailable = 0 else: ServerHello1.AuthResponse = 0 ServerHello1.GenreAvailable = 0 ServerHello1.RequestBitRate = "NULL" # Sending out the Server response packetBytes1 = ServerHello1.__serialize__() deserializer1 = PacketType.Deserialize(packetBytes1) if (deserializer1.GenreAvailable == True and deserializer1.AuthResponse == 1): print("Your requested Genre is available!") else: print("SERVER SIDE ERROR: Error with Genre or Username") # Packet 3 - Client Request ClientRequest1 = ClientRequest() ClientRequest1.SessionID = deserializer1.SessionID # print (ClientRequest1.SessionID) ClientRequest1.ACKofServerHello = 1 if (deserializer1.AuthResponse == 1 and deserializer1.GenreAvailable == 1): print("Authentication Succeeded") # ClientRequest1.BitRate = ["320Kbps","123Kbps"] else: print("Authentication Failed :( ") # ClientRequest1.BitRate = ["0"] return (basicUnitTest()) ClientRequest1_serialize = ClientRequest1.__serialize__() ClientRequest1_deserailze = PacketType.Deserialize( ClientRequest1_serialize) assert ClientRequest1_deserailze == ClientRequest1 # Packet 4 - Server Stream ServerStream1 = ServerStream() ServerStream1.SessionID = deserializer1.SessionID if deserializer_ClientHello.Genre == "ROCK": ServerStream1.Linktomusic = "https://www.youtube.com/watch?v=3_5RbI9goz4" elif deserializer_ClientHello.Genre == "POP": ServerStream1.Linktomusic = "https://www.youtube.com/watch?v=2VncTzuXhu0&list=PLMAV5w57ey1rYKkjhUwVpdLn3wCUTurGC" elif deserializer_ClientHello.Genre == "CLASSICAL": ServerStream1.Linktomusic = "https://www.youtube.com/watch?v=a-b6JgQa3EY&list=PLauX1OLju8VgJ1-oBaBDGKZeAiFav-mAE" elif deserializer_ClientHello.Genre == "JAZZ": ServerStream1.Linktomusic = "https://www.youtube.com/watch?v=2o4NyCE8-Zs&list=PLjBo9Ev93QFXo9_14jtlHGEir4G_omx34" else: ServerStream1.Linktomusic == "Unexpected error" ServerStream1_serializer = ServerStream1.__serialize__() # Deserializing the final response from the server. deserializer1 = PacketType.Deserializer() while len(ServerStream1_serializer) > 0: chunk, ServerStream1_serializer = ServerStream1_serializer[: 10], ServerStream1_serializer[ 10:] deserializer1.update(chunk) for packet in deserializer1.nextPackets(): if packet == ServerStream1: print(str(packet.Linktomusic)) else: print("Packet lost in transmission!") else: print("Incorrect Auth Token. Value should be anything above 0") return (basicUnitTest())
def test3(self): winnerPacket = CurrentWinner() packetBytesWinner = winnerPacket.__serialize__() winnerPacketDes = PacketType.Deserialize(packetBytesWinner) assert winnerPacket == winnerPacketDes
def basicUnitTest(): from playground.network.packet import FIELD_NOT_SET rng_request1 = RequestRandomNumberPacket() rng_request1_bytes = rng_request1.__serialize__() rng_request1_deserialzed = RequestRandomNumberPacket.Deserialize(rng_request1_bytes) assert rng_request1 == rng_request1_deserialzed rng_problem1 = RandomNumberProblemPacket(min_range=0, max_range=10, game_id=0) rng_problem2 = RandomNumberProblemPacket(min_range=0, max_range=11) assert rng_problem1.min_range == 0 assert rng_problem1.max_range == 10 assert rng_problem1.game_id == 0 assert rng_problem2.min_range == 0 assert rng_problem2.max_range == 11 assert rng_problem2.game_id == FIELD_NOT_SET rng_problem2.max_range = rng_problem1.max_range assert rng_problem2.max_range == rng_problem1.max_range rng_problem2.game_id = 1 assert rng_problem2.game_id-1 == rng_problem1.game_id deserializer = RandomNumberProblemPacket.Deserializer() deserializer.update(rng_problem1.__serialize__()) deserializer.update(rng_problem2.__serialize__()) packets = list(deserializer.nextPackets()) assert packets[0] == rng_problem1 and packets[1] == rng_problem2 guess_packet1 = GuessPacket(guess=9) assert guess_packet1.game_id == FIELD_NOT_SET guess_packet1.game_id=3 assert guess_packet1.guess == 9 guess_packet2 = GuessPacket(guess=9, game_id=4) assert guess_packet1 != guess_packet2 guess_packet1_des = PacketType.Deserialize(guess_packet1.__serialize__()) assert guess_packet1_des == guess_packet1 correctness_packet1 = CorrectnessPacket(game_id=2) assert correctness_packet1.correct == FIELD_NOT_SET correctness_packet1.correct = False assert correctness_packet1.correct == False correctness_packet2 = CorrectnessPacket(game_id=5, correct=True) assert correctness_packet2.correct == True serialized_data = correctness_packet2.__serialize__() + correctness_packet1.__serialize__() + correctness_packet2.__serialize__() packets = [] deserializer = CorrectnessPacket.Deserializer() while serialized_data: chunk, serialized_data = serialized_data[:10], serialized_data[10:] deserializer.update(chunk) for p in deserializer.nextPackets(): packets.append(p) assert packets[0] == correctness_packet2 and packets[1] == correctness_packet1 and packets[2] == correctness_packet2