選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Test.ts 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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 cb2: Function
  155. let client: RPCSocket
  156. let server: RPCServer<{topic: string}>
  157. before(async() => {
  158. server = new RPCServer<{ topic: string }>(21010, [{
  159. name: "test",
  160. exportRPCs: () => [{
  161. name: 'subscribe',
  162. hook: async(callback):Promise<SubscriptionResponse<{topic:string}>> => {
  163. cb = <Function> callback
  164. return {
  165. result: "Success",
  166. uuid: uuidv4(),
  167. topic: "test"
  168. }
  169. }
  170. },
  171. {
  172. name: 'subscribeWithParam',
  173. hook: async(param, callback):Promise<SubscriptionResponse<{topic:string}>> => {
  174. if(param != "OK"){
  175. console.log("param was"+ param);
  176. return {
  177. result: "Success",
  178. uuid: "no",
  179. topic: "test"
  180. }
  181. }
  182. cb2 = <Function> callback
  183. return {
  184. result: "Success",
  185. uuid: "OK",
  186. topic: "test"
  187. }
  188. }
  189. },
  190. function checkCandy():string { cb(candy); return candy },
  191. function stealCandy():string { candy = "_OK"; cb(candy); cb = () => {}; return candy }
  192. ]
  193. }],{
  194. connectionHandler: (socket) => { },
  195. closeHandler: (socket) => { },
  196. errorHandler: (socket, err) => { throw err }
  197. })
  198. client = new RPCSocket(21010, "localhost")
  199. return await client.connect()
  200. })
  201. after(() => {
  202. client.destroy()
  203. server.destroy()
  204. })
  205. it('Subscribe with param', (done) => {
  206. client['test'].subscribeWithParam("OK", c => {}).then( async (res: SubscriptionResponse) => {
  207. if(res.uuid === "OK"){
  208. done()
  209. }else
  210. done(new Error("Results did not match "+res.uuid))
  211. })
  212. })
  213. it('Unhook+unsubscribe should stop callbacks', (done) => {
  214. client['test'].subscribe(c => {}).then( async (res: SubscriptionResponse) => {
  215. const r1 = await client['test'].checkCandy()
  216. const r3 = await client['test'].stealCandy()
  217. client.unhook(res.uuid)
  218. const r2 = await client['test'].checkCandy()
  219. const r4 = await client['test'].checkCandy()
  220. if(r1 === "OK" && r3 === "_OK" && r2 === "_OK" && r4 === "_OK")
  221. done()
  222. else
  223. done(new Error("Results did not match: "+[r1,r2,r3,r4]))
  224. })
  225. })
  226. })
  227. type SesameTestIfc = {
  228. test: {
  229. checkCandy: ()=>Promise<string>
  230. subscribe: (callback) => Promise<SubscriptionResponse<{ topic: string; }>>
  231. }
  232. }
  233. describe('Sesame should unlock the socket', () => {
  234. let candy = "OK"
  235. let client: RPCSocket & SesameTestIfc
  236. let server: RPCServer
  237. let cb = (...args) => {}
  238. before((done) => {
  239. server = new RPCServer(21004, [{
  240. name: "test",
  241. exportRPCs: () => [
  242. {
  243. name: 'subscribe',
  244. hook: async(callback) => {
  245. cb = callback
  246. return <SubscriptionResponse>{
  247. result: "Success",
  248. uuid: uuidv4(),
  249. topic: 'test'
  250. }
  251. }
  252. },
  253. async function checkCandy():Promise<string> { cb(candy); cb=()=>{}; return candy },
  254. async function manyParams(a,b,c,d) {return [a,b,c,d]}
  255. ]}
  256. ],{
  257. sesame: (_sesame) => _sesame === 'sesame!'
  258. })
  259. const sock = new RPCSocket(21004, "localhost")
  260. sock.connect<SesameTestIfc>('sesame!').then(cli => {
  261. client = cli
  262. done()
  263. })
  264. })
  265. after(() => {
  266. client.destroy()
  267. server.destroy()
  268. })
  269. it('should work with sesame', (done) => {
  270. client.test.checkCandy().then(c => done())
  271. })
  272. it('should work with multiple params', (done) => {
  273. client.test['manyParams']('a','b','c','d').then(c => {
  274. if(c[0] == 'a' && c[1] === 'b' && c[2] === 'c' && c[3] === 'd')
  275. done()
  276. })
  277. })
  278. it('should not work without sesame', (done) => {
  279. const sock = new RPCSocket(21004, "localhost")
  280. sock.connect<SesameTestIfc>( /* no sesame */).then(async (cli) => {
  281. cli.test.checkCandy().then(d => {
  282. done(d)
  283. }).catch(e => {
  284. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  285. done()
  286. }).finally(() => {
  287. cli.destroy()
  288. sock.destroy()
  289. })
  290. })
  291. })
  292. it('should fail with wrong sesame', (done) => {
  293. const sock = new RPCSocket(21004, "localhost")
  294. sock.connect<SesameTestIfc>('abasd').then(async (cli) => {
  295. cli.test.checkCandy().then(d => {
  296. done("should not be able to get candy")
  297. }).catch(e => {
  298. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  299. done()
  300. }).finally(() => {
  301. sock.destroy()
  302. cli.destroy()
  303. })
  304. })
  305. })
  306. it('callback should work with sesame', (done) => {
  307. client.test.subscribe((c) => {
  308. if(c === candy){
  309. done()
  310. }
  311. }).then(d => {
  312. if(d.result !== 'Success')
  313. done('unexpected valid response')
  314. client.test.checkCandy()
  315. })
  316. })
  317. it('callback should not work without sesame', (done) => {
  318. const sock = new RPCSocket(21004, "localhost")
  319. sock.connect<SesameTestIfc>( /* no sesame */).then(async (cli) => {
  320. cli.test.subscribe((c) => {
  321. console.log("CALLBACK TRIGGERED UNEXPECTED");
  322. if(c === candy)
  323. done("super not")
  324. }).then(async d => {
  325. await client.test.checkCandy()
  326. if(d == null){
  327. done()
  328. }else
  329. done('unexpected valid response '+(d) )
  330. }).finally(() => {
  331. sock.destroy()
  332. })
  333. })
  334. })
  335. })
  336. describe('Error handling', ()=>{
  337. let createUser = async( user: {a:any,b:any}) => {
  338. throw new Error("BAD BAD BAD")
  339. }
  340. it("RPC throws on client without handler", (done)=>{
  341. let server = new RPCServer(21004, [ {
  342. name: 'createUser' as 'createUser',
  343. exportRPCs: () => [{
  344. name: 'createUser' as 'createUser',
  345. call: createUser
  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. //console.log("EXPECTED CLIENT EXCEPTION", String(e));
  360. done()
  361. })
  362. .finally(() => {
  363. cli.destroy()
  364. sock.destroy()
  365. server.destroy()
  366. })
  367. })
  368. })
  369. it("RPC throws on server with handler", (done)=>{
  370. let server = new RPCServer(21004, [ {
  371. name: 'createUser' as 'createUser',
  372. exportRPCs: () => [{
  373. name: 'createUser' as 'createUser',
  374. call: createUser
  375. }]}], {
  376. errorHandler: (socket, e, rpcName, args) => {
  377. done()
  378. }
  379. })
  380. let sock = new RPCSocket(21004, 'localhost')
  381. sock.connect().then((cli) => {
  382. cli["createUser"]["createUser"]({
  383. a:'a',
  384. b:'b'
  385. })
  386. .then(r => {
  387. if(r != null)
  388. done("UNEXPECTED RESULT " + r)
  389. })
  390. .catch((e) => {
  391. done("UNEXPECTED CLIENT ERROR " + e)
  392. done(e)
  393. })
  394. .finally(() => {
  395. cli.destroy()
  396. sock.destroy()
  397. server.destroy()
  398. })
  399. })
  400. })
  401. })
  402. describe("Errorhandler functionality", ()=>{
  403. let createUser = async( user: {a:any,b:any}) => {
  404. throw new Error("BAD BAD BAD")
  405. }
  406. it("correct values are passed to the handler", (done)=>{
  407. let server = new RPCServer(21004, [ {
  408. name: 'createUser' as 'createUser',
  409. exportRPCs: () => [{
  410. name: 'createUser' as 'createUser',
  411. call: createUser
  412. }]}], {
  413. errorHandler: (socket, e, rpcName, args) => {
  414. if(e.message === "BAD BAD BAD" && rpcName === "createUser" && args[0]['a'] === 'a' && args[0]['b'] === 'b')
  415. done()
  416. }
  417. })
  418. let sock = new RPCSocket(21004, 'localhost')
  419. sock.connect().then((cli) => {
  420. cli["createUser"]["createUser"]({
  421. a:'a',
  422. b:'b'
  423. })
  424. .then(r => {
  425. if(r != null)
  426. done("UNEXPECTED RESULT " + r)
  427. })
  428. .catch((e) => {
  429. done("UNEXPECTED CLIENT ERROR " + e)
  430. done(e)
  431. })
  432. .finally(() => {
  433. cli.destroy()
  434. sock.destroy()
  435. server.destroy()
  436. })
  437. })
  438. })
  439. it("handler sees sesame", (done)=>{
  440. let sesame = "AAAAAAAAAAAAAAA"
  441. let server = new RPCServer(21004, [ {
  442. name: 'createUser' as 'createUser',
  443. exportRPCs: () => [{
  444. name: 'createUser' as 'createUser',
  445. call: createUser
  446. }]}], {
  447. sesame: sesame,
  448. errorHandler: (socket, e, rpcName, args) => {
  449. if(e.message === "BAD BAD BAD" && rpcName === "createUser" && args[0] === sesame && args[1]['a'] === 'a' && args[1]['b'] === 'b')
  450. done()
  451. }
  452. })
  453. let sock = new RPCSocket(21004, 'localhost')
  454. sock.connect(sesame).then((cli) => {
  455. cli["createUser"]["createUser"]({
  456. a:'a',
  457. b:'b'
  458. })
  459. .then(r => {
  460. if(r != null)
  461. done("UNEXPECTED RESULT " + r)
  462. })
  463. .catch((e) => {
  464. done("UNEXPECTED CLIENT ERROR " + e)
  465. done(e)
  466. })
  467. .finally(() => {
  468. cli.destroy()
  469. sock.destroy()
  470. server.destroy()
  471. })
  472. })
  473. })
  474. })
  475. type myExporterIfc = {
  476. MyExporter: {
  477. myRPC: ()=>Promise<string>
  478. }
  479. }
  480. describe("Class binding", ()=>{
  481. class MyExporter implements RPCExporter<myExporterIfc>{
  482. name = "MyExporter" as "MyExporter";
  483. exportRPCs = () => [
  484. this.myRPC
  485. ]
  486. myRPC = async () => "Hello World"
  487. }
  488. let serv: RPCServer,
  489. sock: RPCSocket & myExporterIfc,
  490. exporter: MyExporter
  491. before((done)=>{
  492. exporter = new MyExporter()
  493. serv = new RPCServer(21004, [exporter])
  494. const s = new RPCSocket(21004, 'localhost')
  495. s.connect<myExporterIfc>().then(conn => {
  496. sock = conn
  497. done()
  498. })
  499. })
  500. after(() => {
  501. sock.destroy()
  502. serv.destroy()
  503. })
  504. it("binds correctly", (done)=>{
  505. sock['MyExporter'].myRPC().then(() => {
  506. done()
  507. })
  508. })
  509. })
  510. describe("attaching handlers before connecting", ()=>{
  511. it("fires error if server is unreachable", (done)=>{
  512. const sock = new RPCSocket(21004, 'localhost')
  513. let errorHandleCount = 0
  514. sock.on('error', (err) => {
  515. //attached listener fires first
  516. if(errorHandleCount != 0){
  517. console.log("Error handler didn't fire first");
  518. }else{
  519. errorHandleCount++
  520. }
  521. })
  522. sock.connect().then(_ => {
  523. console.log("Unexpected successful connect")
  524. }).catch(e => {
  525. //catch clause fires second
  526. if(errorHandleCount != 1){
  527. console.log("catch clause didn't fire second");
  528. }else{
  529. sock.destroy()
  530. done()
  531. }
  532. })
  533. })
  534. it("fires error if call is unknown", (done)=>{
  535. const serv = new RPCServer(21004)
  536. const sock = new RPCSocket(21004, 'localhost')
  537. sock.on('error', (err) => {
  538. sock.destroy()
  539. serv.destroy()
  540. done()
  541. })
  542. sock.connect().then(_ => {
  543. sock.call("unknownRPC123", "AAAAA").catch(e => { /* ignore */})
  544. }).catch(e => {
  545. console.log("unexpected connect catch clause");
  546. done(e)
  547. })
  548. })
  549. it("demands catch on method invocation if call is unknown", (done)=>{
  550. const serv = new RPCServer(21004)
  551. const sock = new RPCSocket(21004, 'localhost')
  552. sock.connect().then(_ => {
  553. sock.call("unknownRPC123", "AAAAA").catch(e => {
  554. sock.destroy()
  555. serv.destroy()
  556. done()
  557. })
  558. }).catch(e => {
  559. console.log("unexpected connect catch clause");
  560. done(e)
  561. })
  562. })
  563. })