blob: 7220879ac5ddf414a4b3a8c80f177f6bc0009c53 [file] [log] [blame]
zeshuai007797fe252020-05-20 15:20:07 +08001#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18#
19
20import os
21import sys
22import threading
23import unittest
24import time
25
26gen_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "gen-py")
27sys.path.append(gen_path)
28import _import_local_thrift # noqa
29from TestServer import TestServer
30from thrift.transport import TSocket, TTransport
31from thrift.protocol import TBinaryProtocol
32from thrift.server import TNonblockingServer
33
34
35class Handler:
36
37 def add_and_get_msg(self, msg):
38 return msg
39
40
41class Server:
42
43 def __init__(self):
44 handler = Handler()
45 processor = TestServer.Processor(handler)
46 transport = TSocket.TServerSocket("127.0.0.1", 30030)
47 self.server = TNonblockingServer.TNonblockingServer(processor, transport)
48
49 def start_server(self):
50 print("-------start server ------\n")
51 self.server.serve()
52 print("------stop server -----\n")
53
54 def close_server(self):
55 self.server.stop()
56 self.server.close()
57
58
59class Client:
60
61 def start_client(self):
62 transport = TSocket.TSocket("127.0.0.1", 30030)
63 trans = TTransport.TFramedTransport(transport)
64 protocol = TBinaryProtocol.TBinaryProtocol(trans)
65 client = TestServer.Client(protocol)
66 trans.open()
67 self.msg = client.add_and_get_msg("hello thrift")
68
69 def get_message(self):
70 try:
71 msg = self.msg
72 return msg
73 except AttributeError as e:
74 raise e
75 print("self.msg not exit\n")
76
77
78class TestNonblockingServer(unittest.TestCase):
79
80 def test_normalconnection(self):
81 serve = Server()
82 client = Client()
83
84 serve_thread = threading.Thread(target=serve.start_server)
85 client_thread = threading.Thread(target=client.start_client)
86 serve_thread.start()
87 time.sleep(10)
88 client_thread.start()
89 client_thread.join(0.5)
90 try:
91 msg = client.get_message()
92 self.assertEqual("hello thrift", msg)
93 except AssertionError as e:
94 raise e
95 print("assert failure")
96 finally:
97 serve.close_server()
98
99
100if __name__ == '__main__':
101 unittest.main()