Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Test.ts 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. import { describe, it, Func } from "mocha";
  2. import { RPCServer, RPCSocket, SubscriptionResponse, makeSubResponse } from '../Index'
  3. import * as uuidv4 from "uuid/v4"
  4. import { doesNotReject } from "assert";
  5. import { Socket } from "dgram";
  6. const add = (...args:number[]) => {return args.reduce((a,b)=>a+b, 0)}
  7. function makeServer(){
  8. let subcallback
  9. return new RPCServer<{ topic: string }>(21000, [{
  10. name: "test",
  11. exportRPCs: () => [
  12. {
  13. name: 'echo',
  14. call: async (s:string) => s,
  15. },{
  16. name: 'simpleSubscribe',
  17. hook: async(callback) => {
  18. subcallback = callback
  19. return makeSubResponse<{topic: string}>({topic: "test"})
  20. }
  21. },{
  22. name: 'subscribe',
  23. hook: async (callback) => {
  24. subcallback = callback
  25. return makeSubResponse<{topic: string}>({topic: "test"})
  26. },
  27. onClose: (res, rpc) => {
  28. console.log("onClose", rpc.name === 'subscribe' && res?"OK":"")
  29. subcallback = null
  30. },
  31. onCallback: (...args:any) => {
  32. console.log("onCallback", args[0] === "test" && args[1] === "callback"?"OK":"")
  33. }
  34. },
  35. add,
  36. function triggerCallback(...messages:any[]):number {return subcallback.apply({}, messages)},
  37. ]
  38. }],{
  39. connectionHandler: (socket) => { console.log("connectionHandler OK") },
  40. closeHandler: (socket) => { console.log("closeHandler OK") },
  41. errorHandler: (socket, err) => { console.error("errorHandler OK SO YOU SHOULDN'T SEE THIS"); throw err }
  42. })
  43. }
  44. describe('RPCServer', () => {
  45. let server: RPCServer<{ topic: string }, any>
  46. before((done) => {
  47. server = makeServer()
  48. done()
  49. })
  50. after(async() => {
  51. await server.destroy()
  52. })
  53. it('should be able to use all kinds of RPC definitions', (done) => {
  54. const echo = (x) => x
  55. const server = new RPCServer(21003, [{
  56. name: 'HelloWorldRPCGroup',
  57. exportRPCs: () => [
  58. echo, //named function variable
  59. function echof(x){ return x }, //named function
  60. {
  61. name: 'echoExplicit', //describing object
  62. call: async (x,y,z) => [x,y,z]
  63. }
  64. ]
  65. }])
  66. const client = new RPCSocket(21003, 'localhost')
  67. client.connect().then(async () => {
  68. const r0 = await client['HelloWorldRPCGroup'].echo('Hello')
  69. const r1 = await client['HelloWorldRPCGroup'].echof('World')
  70. const r2 = await client['HelloWorldRPCGroup'].echoExplicit('R','P','C!')
  71. if(r0 === 'Hello' && r1 === 'World' && r2.join('') ==='RPC!'){
  72. client.destroy()
  73. server.destroy()
  74. done()
  75. }
  76. })
  77. })
  78. it('new RPCServer() should fail on bad RPC', (done) => {
  79. try{
  80. new RPCServer(20001, [{
  81. name: "bad",
  82. exportRPCs: () => [
  83. (aaa,bbb,ccc) => { return aaa+bbb+ccc }
  84. ]
  85. }])
  86. done(new Error("Didn't fail with bad RPC"))
  87. }catch(badRPCError){
  88. done()
  89. }
  90. })
  91. })
  92. describe('RPCSocket', () => {
  93. let client: RPCSocket
  94. let server: RPCServer<{topic: string}>
  95. before(async() => {
  96. server = makeServer()
  97. client = new RPCSocket(21000, "localhost")
  98. return await client.connect()
  99. })
  100. after(() => {
  101. client.destroy()
  102. server.destroy()
  103. })
  104. it('should have rpc echo', (done) => {
  105. client['test'].echo("x").then(x => {
  106. if(x === 'x')
  107. done()
  108. else
  109. done(new Error('echo RPC response did not match'))
  110. })
  111. })
  112. it('should add up to 6', (done) => {
  113. client['test'].add(1,2,3).then(x => {
  114. if(x === 6)
  115. done()
  116. else
  117. done(new Error('add RPC response did not match'))
  118. })
  119. })
  120. it('should subscribe with success', (done) => {
  121. client['test'].simpleSubscribe(console.log).then(res => {
  122. if(res.result === 'Success'){
  123. done()
  124. }else{
  125. console.error(res)
  126. done(new Error('Subscribe did not return success'))
  127. }
  128. })
  129. })
  130. it('subscribe should call back', (done) => {
  131. client['test'].subscribe((...args: any) => {
  132. if(args[0] === "test" && args[1] === "callback")
  133. done()
  134. else
  135. done(new Error("Bad callback value "+ args))
  136. }).then( async () => {
  137. await client['test'].triggerCallback("test", "callback")
  138. })
  139. })
  140. it('simpleSubscribe should call back', (done) => {
  141. client['test'].simpleSubscribe((...args: any) => {
  142. if(args[0] === "test_" && args[1] === "callback_")
  143. done()
  144. else
  145. done(new Error("Bad callback value "+ args))
  146. }).then( async () => {
  147. await client['test'].triggerCallback("test_", "callback_")
  148. })
  149. })
  150. })
  151. describe('It should do unhook', () => {
  152. let candy = "OK"
  153. let cb: Function
  154. let client: RPCSocket
  155. let server: RPCServer<{topic: string}>
  156. before(async() => {
  157. server = new RPCServer<{ topic: string }>(21000, [{
  158. name: "test",
  159. exportRPCs: () => [{
  160. name: 'subscribe',
  161. hook: async(callback):Promise<SubscriptionResponse<{topic:string}>> => {
  162. cb = <Function> callback
  163. return {
  164. result: "Success",
  165. uuid: uuidv4(),
  166. topic: "test"
  167. }
  168. }
  169. },
  170. function checkCandy():string { cb(candy); return candy },
  171. function stealCandy():string { candy = "_OK"; cb(candy); cb = (...any) => console.log.apply(console,["Server:", ...any]); return candy }
  172. ]
  173. }],{
  174. connectionHandler: (socket) => { console.log("connectionHandler OK") },
  175. closeHandler: (socket) => { console.log("closeHandler OK") },
  176. errorHandler: (socket, err) => { console.error("errorHandler OK SO YOU SHOULDN'T SEE THIS"); throw err }
  177. })
  178. client = new RPCSocket(21000, "localhost")
  179. return await client.connect()
  180. })
  181. after(() => {
  182. client.destroy()
  183. server.destroy()
  184. })
  185. it('Unhook+unsubscribe should stop callbacks', (done) => {
  186. client['test'].subscribe(c => console.log("Client: "+c)).then( async (res: SubscriptionResponse) => {
  187. const r1 = await client['test'].checkCandy()
  188. const r3 = await client['test'].stealCandy()
  189. client.unhook(res.uuid)
  190. console.log("---- No client output below this line")
  191. const r2 = await client['test'].checkCandy()
  192. const r4 = await client['test'].checkCandy()
  193. console.log("---- More output below")
  194. if(r1 === "OK" && r3 === "_OK" && r2 === "_OK" && r4 === "_OK")
  195. done()
  196. else
  197. done(new Error("Results did not match: "+[r1,r2,r3,r4]))
  198. })
  199. })
  200. })
  201. type SesameTestIfc = {
  202. test: {
  203. checkCandy: ()=>Promise<string>
  204. subscribe: (callback) => Promise<SubscriptionResponse<{ topic: string; }>>
  205. }
  206. }
  207. describe('Sesame should unlock the socket', () => {
  208. let candy = "OK"
  209. let client: RPCSocket & SesameTestIfc
  210. let server: RPCServer
  211. let cb = (...args) => {}
  212. before(async() => {
  213. server = new RPCServer(21004, [{
  214. name: "test",
  215. exportRPCs: () => [
  216. {
  217. name: 'subscribe',
  218. hook: async(callback) => {
  219. cb = callback
  220. return <SubscriptionResponse>{
  221. result: "Success",
  222. uuid: uuidv4(),
  223. topic: 'test'
  224. }
  225. }
  226. },
  227. async function checkCandy():Promise<string> { cb(candy); cb=()=>{}; return candy },
  228. async function manyParams(a,b,c,d) {return [a,b,c,d]}
  229. ]}
  230. ],{
  231. sesame: (_sesame) => _sesame === 'sesame!'
  232. })
  233. const sock = new RPCSocket(21004, "localhost")
  234. client = await sock.connect<SesameTestIfc>('sesame!')
  235. })
  236. after(() => {
  237. client.destroy()
  238. server.destroy()
  239. })
  240. it('should work with sesame', (done) => {
  241. client.test.checkCandy().then(c => done())
  242. })
  243. it('should work with multiple params', (done) => {
  244. client.test['manyParams']('a','b','c','d').then(c => {
  245. if(c[0] == 'a' && c[1] === 'b' && c[2] === 'c' && c[3] === 'd')
  246. done()
  247. })
  248. })
  249. it('should not work without sesame', (done) => {
  250. const sock = new RPCSocket(21004, "localhost")
  251. sock.connect<SesameTestIfc>( /* no sesame */).then(async (c) => {
  252. c.test.checkCandy().then(d => {
  253. done()
  254. }).catch(e => {
  255. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  256. done()
  257. }).finally(() => {
  258. sock.destroy()
  259. })
  260. })
  261. })
  262. it('should fail with wrong sesame', (done) => {
  263. const sock = new RPCSocket(21004, "localhost")
  264. sock.connect<SesameTestIfc>('abasd').then(async (c) => {
  265. c.test.checkCandy().then(d => {
  266. done("should not be able to get candy")
  267. }).catch(e => {
  268. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  269. done()
  270. }).finally(() => {
  271. sock.destroy()
  272. })
  273. })
  274. })
  275. it('callback should work with sesame', (done) => {
  276. client.test.subscribe((c) => {
  277. if(c === candy){
  278. done()
  279. }
  280. }).then(d => {
  281. if(d.result !== 'Success')
  282. done('unexpected valid response')
  283. client.test.checkCandy()
  284. })
  285. })
  286. it('callback should not work without sesame', (done) => {
  287. const sock = new RPCSocket(21004, "localhost")
  288. sock.connect<SesameTestIfc>( /* no sesame */).then(async (c) => {
  289. c.test.subscribe((c) => {
  290. console.log("CALLBACK TRIGGERED UNEXPECTED");
  291. if(c === candy)
  292. done("super not")
  293. }).then(async d => {
  294. await client.test.checkCandy()
  295. if(d == null){
  296. done()
  297. }else
  298. done('unexpected valid response '+(d) )
  299. c.destroy()
  300. })
  301. })
  302. })
  303. })
  304. describe('Error handling', ()=>{
  305. let createUser = async( user: {a:any,b:any}) => {
  306. throw new Error("BAD BAD BAD")
  307. }
  308. it("RPC throws on client without handler", (done)=>{
  309. let server = new RPCServer(21004, [ {
  310. name: 'createUser' as 'createUser',
  311. exportRPCs: () => [{
  312. name: 'createUser' as 'createUser',
  313. call: createUser
  314. }]}], {
  315. })
  316. let sock = new RPCSocket(21004, 'localhost')
  317. sock.connect().then((cli) => {
  318. cli["createUser"]["createUser"]({
  319. a:'a',
  320. b:'b'
  321. })
  322. .then(r => {
  323. if(r != null)
  324. done("UNEXPECTED RESULT " + r)
  325. })
  326. .catch((e) => {
  327. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  328. done()
  329. })
  330. .finally(() => {
  331. sock.destroy()
  332. server.destroy()
  333. })
  334. })
  335. })
  336. it("RPC throws server with handler", (done)=>{
  337. let server = new RPCServer(21004, [ {
  338. name: 'createUser' as 'createUser',
  339. exportRPCs: () => [{
  340. name: 'createUser' as 'createUser',
  341. call: createUser
  342. }]}], {
  343. errorHandler: (socket, e) => {
  344. //console.log("EXPECTED SERVER EXCEPTION", String(e));
  345. done()
  346. }
  347. })
  348. let sock = new RPCSocket(21004, 'localhost')
  349. sock.connect().then((cli) => {
  350. cli["createUser"]["createUser"]({
  351. a:'a',
  352. b:'b'
  353. })
  354. .then(r => {
  355. if(r != null)
  356. done("UNEXPECTED RESULT " + r)
  357. })
  358. .catch((e) => {
  359. done("UNEXPECTED CLIENT ERROR " + e)
  360. done(e)
  361. })
  362. .finally(() => {
  363. sock.destroy()
  364. server.destroy()
  365. })
  366. })
  367. })
  368. })