-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtests.py
More file actions
381 lines (315 loc) · 12 KB
/
tests.py
File metadata and controls
381 lines (315 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import traceback
import pxprpc.backend
import pxprpc.extend
import pxprpc.base
from pxprpc.base import Serializer
from pxprpc.extend import PyCallableWrap, RpcExtendClientObject, TableSerializer
import asyncio
import struct
import logging
logging.basicConfig(level=logging.INFO)
import typing
EnableWebsocketServer=False
EnableCSharpClient=False
EnableCClient=False
EnableJavaClient=False
async def testClient(rpcconn:pxprpc.extend.ClientContext,name:str='default'):
print('================'+name+'====================')
client2=pxprpc.extend.RpcExtendClient1(rpcconn)
await client2.init()
info=await rpcconn.getInfo()
print(info)
print('server name:'+str(client2.serverName))
get1234=await client2.getFunc('test1.get1234')
assert get1234!=None
print('get1234:',get1234.value)
get1234.typedecl('->o')
printString=await client2.getFunc('test1.printString')
assert printString!=None
print('printString:',printString.value)
printString.typedecl('o->')
wait1Sec=await client2.getFunc('test1.wait1Sec')
assert wait1Sec!=None
print('test1.wait1Sec:',wait1Sec.value)
wait1Sec.typedecl('->s')
print('expect 1234')
t1=await get1234()
await printString(t1)
del get1234
await asyncio.sleep(0.2)
testNone=await client2.getFunc('test1.testNone')
assert testNone!=None
print('testNone:',testNone.value)
testNone.typedecl('o->o')
print('expect None:',await testNone(None))
testPrintArg=await client2.getFunc('test1.testPrintArg')
assert testPrintArg!=None
print('testPrintArg:',testPrintArg.value)
assert testPrintArg!=None
testPrintArg.typedecl('cilfdb->il')
print('multi-result:',await testPrintArg(True,123,1122334455667788,123.5,123.123,b'bytes'))
testUnser=await client2.getFunc('test1.testUnser')
assert testUnser!=None
print('testUnser:',testUnser.value)
testUnser.typedecl('b->')
print('expect 123,1122334455667788,123.5,123.123,abcdef,bytes')
await testUnser(Serializer().prepareSerializing()\
.putInt(123).putLong(1122334455667788).putFloat(123.5).putDouble(123.123).putString('abcdef').putBytes('bytes'.encode('utf-8'))\
.build())
testTableUnser=await client2.getFunc('test1.testTableUnser')
#optional?
if testTableUnser!=None:
print('testTableUnser:',testTableUnser.value)
testTableUnser.typedecl('b->')
print('expect a table')
await testTableUnser(TableSerializer().setColumnsInfo('iscl',None).fromMapArray(\
[dict(id=1554,name='1.txt',isdir=False,filesize=12345),dict(id=1555,name='docs',isdir=True,filesize=0)])\
.build())
print('expect wait 1 second')
print('expect tick:',await wait1Sec())
raiseError1=await client2.getFunc('test1.raiseError1')
assert raiseError1!=None
raiseError1.typedecl('->s')
try:
print('expect dummy io error')
t1=await raiseError1()
except Exception as ex1:
print('exception catched: '+str(ex1))
t1=await client2.getFunc('test1.missingfunc')
assert t1==None
#builtin func test
if 'typescript' in str(client2.serverName):
jsExec=await client2.getFunc('builtin.jsExec')
assert jsExec!=None
jsExec.typedecl('so->o')
print('print a json object after 1 second')
r=await jsExec("console.log('jsExec test');return new Promise((resolve,reject)=>setTimeout(()=>resolve({a:1,b:'23'}),1000));",None)
toJson=await client2.getFunc('builtin.toJSON')
assert toJson!=None
toJson.typedecl('o->s')
print(await toJson(r))
testPollCall=await client2.getFunc('test1.testPollCall')
if testPollCall!=None:
testPollCall.typedecl('->o')
print('testPollCall test')
tickEmitter=await typing.cast(RpcExtendClientObject,await testPollCall()).asCallable()
tickEmitter.typedecl('s->s')
map(lambda x:x+1,[1,2,3])
await tickEmitter.poll(lambda exc,result:print('poll call message ',result,exc),'pxprpc-msg')
else:
print('testPollCall not found,skipped')
await asyncio.sleep(1)
print('testSignal start')
testSignalCall=await client2.getFunc('test1.testSignal')
if testSignalCall!=None:
testSignalCall.typedecl('s->')
testSignalCall.signal('signal')
await asyncio.sleep(1)
print('testSignal end')
t1=await client2.getFunc('test1.autoCloseable')
assert t1!=None
t1.typedecl('->o')
await t1()
await client2.conn.close()
print(name+' test done')
from pxprpc.extend import decorator
async def amain():
class test1:
async def get1234(self)->typing.Any:
return '1234'
async def printString(self,s:typing.Any):
print(s)
async def testUnser(self,b:bytes):
try:
ser=Serializer().prepareUnserializing(b)
print(ser.getInt(),ser.getLong(),ser.getFloat(),ser.getDouble(),ser.getString(),
ser.getBytes().decode('utf-8'),sep=',')
except Exception as ex:
traceback.print_exc()
raise ex
async def testTableUnser(self,b:bytes):
ser=TableSerializer().load(b)
print(ser.toMapArray())
@decorator.typedecl('cilfdb->il')
async def testPrintArg(self,a:bool,b:int,c:int,d:float,e:float,f:bytes):
print(a,b,c,d,e,f)
return [100,1234567890]
async def testNone(self,noneValue:typing.Any)->typing.Any:
print('expect None:',noneValue)
return None
async def autoCloseable(self)->typing.Any:
class Cls(object):
def close(self):
print('auto closable closed')
return Cls()
async def testPollCall(self)->typing.Any:
count=0
async def fn(s:str):
nonlocal count
count+=1
if count>3:
raise Exception('Stopped')
return s+str(count)
return PyCallableWrap(fn).typedecl('s->s')
async def testSignal(self,msg:str)->typing.Any:
print(msg)
pxprpc.extend.RegisteredFuncMap['test1']=test1()
async def fn()->str:
await asyncio.sleep(1)
return 'tick'
pxprpc.extend.RegisteredFuncMap['test1.wait1Sec']=fn
async def fn():
raise IOError('dummy io error')
pxprpc.extend.RegisteredFuncMap['test1.raiseError1']=fn
server1=pxprpc.backend.TcpServer('127.0.0.1',1344)
await server1.start()
client1=pxprpc.backend.TcpClient('127.0.0.1',1344)
await client1.start()
await testClient(client1.rpcconn,'python local pxprpc')
await client1.stop()
if EnableJavaClient:
client1=pxprpc.backend.TcpClient('127.0.0.1',1064)
await client1.start()
await testClient(client1.rpcconn,'java pxprpc')
await client1.stop()
await asyncio.sleep(1)
if EnableCClient:
await ctestmain();
if EnableCSharpClient:
await cstestmain()
if EnableWebsocketServer:
await test4wstunnel()
else:
await server1.stop()
print('all test done')
async def test4wstunnel():
from aiohttp import web_app
from aiohttp import web
from aiohttp import web_request
from aiohttp import web_ws
from aiohttp import http_websocket
from aiohttp import web_runner
from pxprpc.backend import WebSocketClientIo,WebSocketServerIo
async def wshandler(req:web_request.Request):
srv=pxprpc.extend.ServerContext()
srv.backend1(WebSocketServerIo(req))
await srv.serve()
return web.Response()
async def wshandlerClient(req:web_request.Request):
client1=pxprpc.extend.ClientContext()
client1.backend1(WebSocketServerIo(req))
asyncio.create_task(client1.run())
await testClient(client1,'websocketClient')
return web.Response()
app1=web_app.Application()
app1.router.add_route('*','/pxprpc',wshandler)
app1.router.add_route('*','/pxprpcClient',wshandlerClient)
await web._run_app(app1,host='127.0.0.1',port=1345)
async def ctestmain():
print('===============c test main start================')
client1=pxprpc.backend.TcpClient('127.0.0.1',1089)
await client1.start()
print('start client')
client2=pxprpc.extend.RpcExtendClient1(client1.rpcconn)
print(await client1.rpcconn.getInfo())
t1=await client2.getFunc('printString')
assert t1!=None
print('printString:',t1.value)
t1.typedecl('s->s')
print(await t1('12345'))
await t1.free()
await asyncio.sleep(1)
t1=await client2.getFunc('printSerilizedArgs')
assert t1!=None
print('fnPrintSerilizedArgs:',t1.value)
t1.typedecl('b->')
await t1(Serializer().prepareSerializing()\
.putInt(123).putLong(1122334455667788).putFloat(123.5).putDouble(123.123).putString('abcdef').putBytes('bytes'.encode('utf-8'))\
.build())
await t1.free()
await asyncio.sleep(1)
t1=await client2.getFunc('printSerilizedTable')
assert t1!=None
print('printSerilizedTable:',t1.value)
t1.typedecl('b->b')
t2=await t1(TableSerializer().setColumnsInfo('iscl',None).fromMapArray(\
[dict(id=1554,name='1.txt',isdir=False,filesize=12345),dict(id=1555,name='docs',isdir=True,filesize=0)])\
.build())
print(TableSerializer().load(t2).toMapArray())
t1=await client2.getFunc('testDummyError')
assert t1!=None
print('testDummyError:',t1.value)
t1.typedecl('->')
print('expect dummy error raised')
try:
await t1()
except Exception as ex:
print(ex)
t1=await client2.getFunc('testPoll')
assert t1!=None
print('testPoll:',t1.value)
t1.typedecl('->i')
print('expect print 1 to 3')
await t1.poll(lambda ex,val:print(val,ex))
await asyncio.sleep(2)
t1=await client2.getFunc('testEvent')
assert t1!=None
print('testEvent:',t1.value)
t1.typedecl('->o')
t2=await (await t1()).asCallable()
print('eventDispatcher',t2.value)
t2.typedecl('->s');
print('expect tick for each second')
await t2.poll(lambda ex,val:print(val,ex))
await asyncio.sleep(3)
await t2.free()
await asyncio.sleep(3)
async def cstestmain():
print('cs test main start')
client1=pxprpc.backend.TcpClient('127.0.0.1',2050)
await client1.start()
print('start client')
await testClient(client1.rpcconn,'c# test')
#runtime bridge host test
async def runtimebridge_test():
import pxprpc.extend
import pxprpc.backend
client1=pxprpc.backend.TcpClient('127.0.0.1',2048);
await client1.start()
client2=pxprpc.extend.RpcExtendClient1(client1.rpcconn)
await client2.init()
pipeConnect=await client2.getFunc('pxprpc_pipe.connect')
pipeConnect.typedecl('s->l')
ioClose=await client2.getFunc('pxprpc.io_close')
ioClose.typedecl('l->')
pipeServe=await client2.getFunc('pxprpc_pipe.serve')
pipeServe.typedecl('s->o')
pipeAccept=await client2.getFunc('pxprpc_pipe.accept')
pipeAccept.typedecl('o->l')
ioSend=await client2.getFunc('pxprpc.io_send')
ioSend.typedecl('lb->')
ioReceive=await client2.getFunc('pxprpc.io_receive')
ioReceive.typedecl('l->b')
mytest2024Server=await pipeServe('mytest2024')
async def fn():
global testconn1
testconn1=await pipeAccept(mytest2024Server)
task1=asyncio.create_task(fn())
await asyncio.sleep(0.3)
testconn2=await pipeConnect('mytest2024')
async def fn():
global testconn1
print(await ioReceive(testconn1))
task1=asyncio.create_task(fn())
await ioSend(testconn2,b'12345')
import sys
if __name__=='__main__':
if 'enable-websocket-server' in sys.argv:
EnableWebsocketServer=True
if 'enable-csharp-client' in sys.argv:
EnableCSharpClient=True
if 'enable-c-client' in sys.argv:
EnableCClient=True
if 'enable-java-client' in sys.argv:
EnableJavaClient=True
asyncio.run(amain())