Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Test.ts 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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. import { RPCExporter } from "../src/Interfaces";
  7. const add = (...args:number[]) => {return args.reduce((a,b)=>a+b, 0)}
  8. function makeServer(){
  9. let subcallback
  10. return new RPCServer<{ topic: string }>(21010, [{
  11. name: "test",
  12. exportRPCs: () => [
  13. {
  14. name: 'echo',
  15. call: async (s:string) => s,
  16. },{
  17. name: 'simpleSubscribe',
  18. hook: async(callback) => {
  19. subcallback = callback
  20. return makeSubResponse<{topic: string}>({topic: "test"})
  21. }
  22. },{
  23. name: 'subscribe',
  24. hook: async (callback) => {
  25. subcallback = callback
  26. return makeSubResponse<{topic: string}>({topic: "test"})
  27. },
  28. onClose: (res, rpc) => {
  29. console.log("onClose", rpc.name === 'subscribe' && res?"OK":"")
  30. subcallback = null
  31. },
  32. onCallback: (...args:any) => {
  33. console.log("onCallback", args[0] === "test" && args[1] === "callback"?"OK":"")
  34. }
  35. },
  36. add,
  37. function triggerCallback(...messages:any[]):number {return subcallback.apply({}, messages)},
  38. ]
  39. }],{
  40. connectionHandler: (socket) => { },
  41. closeHandler: (socket) => { },
  42. errorHandler: (socket, err) => { throw err }
  43. })
  44. }
  45. describe('RPCServer', () => {
  46. let server: RPCServer<{ topic: string }, any>
  47. before(() => {
  48. server = makeServer()
  49. })
  50. after(() => {
  51. 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(21010, "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 }>(21010, [{
  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 = () => {}; return candy }
  172. ]
  173. }],{
  174. connectionHandler: (socket) => { },
  175. closeHandler: (socket) => { },
  176. errorHandler: (socket, err) => { throw err }
  177. })
  178. client = new RPCSocket(21010, "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 => {}).then( async (res: SubscriptionResponse) => {
  187. const r1 = await client['test'].checkCandy()
  188. const r3 = await client['test'].stealCandy()
  189. client.unhook(res.uuid)
  190. const r2 = await client['test'].checkCandy()
  191. const r4 = await client['test'].checkCandy()
  192. if(r1 === "OK" && r3 === "_OK" && r2 === "_OK" && r4 === "_OK")
  193. done()
  194. else
  195. done(new Error("Results did not match: "+[r1,r2,r3,r4]))
  196. })
  197. })
  198. })
  199. type SesameTestIfc = {
  200. test: {
  201. checkCandy: ()=>Promise<string>
  202. subscribe: (callback) => Promise<SubscriptionResponse<{ topic: string; }>>
  203. }
  204. }
  205. describe('Sesame should unlock the socket', () => {
  206. let candy = "OK"
  207. let client: RPCSocket & SesameTestIfc
  208. let server: RPCServer
  209. let cb = (...args) => {}
  210. before((done) => {
  211. server = new RPCServer(21004, [{
  212. name: "test",
  213. exportRPCs: () => [
  214. {
  215. name: 'subscribe',
  216. hook: async(callback) => {
  217. cb = callback
  218. return <SubscriptionResponse>{
  219. result: "Success",
  220. uuid: uuidv4(),
  221. topic: 'test'
  222. }
  223. }
  224. },
  225. async function checkCandy():Promise<string> { cb(candy); cb=()=>{}; return candy },
  226. async function manyParams(a,b,c,d) {return [a,b,c,d]}
  227. ]}
  228. ],{
  229. sesame: (_sesame) => _sesame === 'sesame!'
  230. })
  231. const sock = new RPCSocket(21004, "localhost")
  232. sock.connect<SesameTestIfc>('sesame!').then(cli => {
  233. client = cli
  234. done()
  235. })
  236. })
  237. after(() => {
  238. client.destroy()
  239. server.destroy()
  240. })
  241. it('should work with sesame', (done) => {
  242. client.test.checkCandy().then(c => done())
  243. })
  244. it('should work with multiple params', (done) => {
  245. client.test['manyParams']('a','b','c','d').then(c => {
  246. if(c[0] == 'a' && c[1] === 'b' && c[2] === 'c' && c[3] === 'd')
  247. done()
  248. })
  249. })
  250. it('should not work without sesame', (done) => {
  251. const sock = new RPCSocket(21004, "localhost")
  252. sock.connect<SesameTestIfc>( /* no sesame */).then(async (cli) => {
  253. cli.test.checkCandy().then(d => {
  254. done(d)
  255. }).catch(e => {
  256. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  257. done()
  258. }).finally(() => {
  259. cli.destroy()
  260. sock.destroy()
  261. })
  262. })
  263. })
  264. it('should fail with wrong sesame', (done) => {
  265. const sock = new RPCSocket(21004, "localhost")
  266. sock.connect<SesameTestIfc>('abasd').then(async (cli) => {
  267. cli.test.checkCandy().then(d => {
  268. done("should not be able to get candy")
  269. }).catch(e => {
  270. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  271. done()
  272. }).finally(() => {
  273. sock.destroy()
  274. cli.destroy()
  275. })
  276. })
  277. })
  278. it('callback should work with sesame', (done) => {
  279. client.test.subscribe((c) => {
  280. if(c === candy){
  281. done()
  282. }
  283. }).then(d => {
  284. if(d.result !== 'Success')
  285. done('unexpected valid response')
  286. client.test.checkCandy()
  287. })
  288. })
  289. it('callback should not work without sesame', (done) => {
  290. const sock = new RPCSocket(21004, "localhost")
  291. sock.connect<SesameTestIfc>( /* no sesame */).then(async (cli) => {
  292. cli.test.subscribe((c) => {
  293. console.log("CALLBACK TRIGGERED UNEXPECTED");
  294. if(c === candy)
  295. done("super not")
  296. }).then(async d => {
  297. await client.test.checkCandy()
  298. if(d == null){
  299. done()
  300. }else
  301. done('unexpected valid response '+(d) )
  302. }).finally(() => {
  303. sock.destroy()
  304. })
  305. })
  306. })
  307. })
  308. describe('Error handling', ()=>{
  309. let createUser = async( user: {a:any,b:any}) => {
  310. throw new Error("BAD BAD BAD")
  311. }
  312. it("RPC throws on client without handler", (done)=>{
  313. let server = new RPCServer(21004, [ {
  314. name: 'createUser' as 'createUser',
  315. exportRPCs: () => [{
  316. name: 'createUser' as 'createUser',
  317. call: createUser
  318. }]}], {
  319. })
  320. let sock = new RPCSocket(21004, 'localhost')
  321. sock.connect().then((cli) => {
  322. cli["createUser"]["createUser"]({
  323. a:'a',
  324. b:'b'
  325. })
  326. .then(r => {
  327. if(r != null)
  328. done("UNEXPECTED RESULT " + r)
  329. })
  330. .catch((e) => {
  331. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  332. done()
  333. })
  334. .finally(() => {
  335. cli.destroy()
  336. sock.destroy()
  337. server.destroy()
  338. })
  339. })
  340. })
  341. it("RPC throws on server with handler", (done)=>{
  342. let server = new RPCServer(21004, [ {
  343. name: 'createUser' as 'createUser',
  344. exportRPCs: () => [{
  345. name: 'createUser' as 'createUser',
  346. call: createUser
  347. }]}], {
  348. errorHandler: (socket, e, rpcName, args) => {
  349. done()
  350. }
  351. })
  352. let sock = new RPCSocket(21004, 'localhost')
  353. sock.connect().then((cli) => {
  354. cli["createUser"]["createUser"]({
  355. a:'a',
  356. b:'b'
  357. })
  358. .then(r => {
  359. if(r != null)
  360. done("UNEXPECTED RESULT " + r)
  361. })
  362. .catch((e) => {
  363. done("UNEXPECTED CLIENT ERROR " + e)
  364. done(e)
  365. })
  366. .finally(() => {
  367. cli.destroy()
  368. sock.destroy()
  369. server.destroy()
  370. })
  371. })
  372. })
  373. })
  374. describe("Errorhandler functionality", ()=>{
  375. let createUser = async( user: {a:any,b:any}) => {
  376. throw new Error("BAD BAD BAD")
  377. }
  378. it("correct values are passed to the handler", (done)=>{
  379. let server = new RPCServer(21004, [ {
  380. name: 'createUser' as 'createUser',
  381. exportRPCs: () => [{
  382. name: 'createUser' as 'createUser',
  383. call: createUser
  384. }]}], {
  385. errorHandler: (socket, e, rpcName, args) => {
  386. if(e.message === "BAD BAD BAD" && rpcName === "createUser" && args[0]['a'] === 'a' && args[0]['b'] === 'b')
  387. done()
  388. }
  389. })
  390. let sock = new RPCSocket(21004, 'localhost')
  391. sock.connect().then((cli) => {
  392. cli["createUser"]["createUser"]({
  393. a:'a',
  394. b:'b'
  395. })
  396. .then(r => {
  397. if(r != null)
  398. done("UNEXPECTED RESULT " + r)
  399. })
  400. .catch((e) => {
  401. done("UNEXPECTED CLIENT ERROR " + e)
  402. done(e)
  403. })
  404. .finally(() => {
  405. cli.destroy()
  406. sock.destroy()
  407. server.destroy()
  408. })
  409. })
  410. })
  411. it("handler sees sesame", (done)=>{
  412. let sesame = "AAAAAAAAAAAAAAA"
  413. let server = new RPCServer(21004, [ {
  414. name: 'createUser' as 'createUser',
  415. exportRPCs: () => [{
  416. name: 'createUser' as 'createUser',
  417. call: createUser
  418. }]}], {
  419. sesame: sesame,
  420. errorHandler: (socket, e, rpcName, args) => {
  421. if(e.message === "BAD BAD BAD" && rpcName === "createUser" && args[0] === sesame && args[1]['a'] === 'a' && args[1]['b'] === 'b')
  422. done()
  423. }
  424. })
  425. let sock = new RPCSocket(21004, 'localhost')
  426. sock.connect(sesame).then((cli) => {
  427. cli["createUser"]["createUser"]({
  428. a:'a',
  429. b:'b'
  430. })
  431. .then(r => {
  432. if(r != null)
  433. done("UNEXPECTED RESULT " + r)
  434. })
  435. .catch((e) => {
  436. done("UNEXPECTED CLIENT ERROR " + e)
  437. done(e)
  438. })
  439. .finally(() => {
  440. cli.destroy()
  441. sock.destroy()
  442. server.destroy()
  443. })
  444. })
  445. })
  446. })
  447. describe("Class binding", ()=>{
  448. class MyExporter implements RPCExporter{
  449. name = "MyExporter";
  450. exportRPCs = () => [
  451. this.myRPC
  452. ]
  453. myRPC = () => "Hello World"
  454. }
  455. it("binds correctly", (done)=>{
  456. const exporter = new MyExporter()
  457. const serv = new RPCServer(21004, [exporter])
  458. const sock = new RPCSocket(21004, 'localhost')
  459. sock.connect().then(sock => {
  460. if(sock.MyExporter && sock.MyExporter.myRPC){
  461. done()
  462. }
  463. })
  464. .catch(done)
  465. .finally(() => {
  466. sock.destroy()
  467. serv.destroy()
  468. })
  469. })
  470. })