nim-json-rpc/tests/testhttp.nim

69 lines
2.1 KiB
Nim
Raw Normal View History

# json-rpc
# Copyright (c) 2019-2023 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
import unittest2
import ../json_rpc/[rpcserver, rpcclient]
2018-07-14 10:51:54 +03:00
2021-11-22 10:09:13 -03:00
const TestsCount = 100
2018-07-14 10:51:54 +03:00
2021-11-22 10:09:13 -03:00
proc simpleTest(address: string, port: Port): Future[bool] {.async.} =
var client = newRpcHttpClient()
await client.connect(address, port, secure = false)
2021-11-22 10:09:13 -03:00
var r = await client.call("noParamsProc", %[])
if r.string == "\"Hello world\"":
2021-11-22 10:09:13 -03:00
result = true
2018-07-14 10:51:54 +03:00
proc continuousTest(address: string, port: Port): Future[int] {.async.} =
var client = newRpcHttpClient()
result = 0
for i in 0..<TestsCount:
await client.connect(address, port, secure = false)
2018-07-14 10:51:54 +03:00
var r = await client.call("myProc", %[%"abc", %[1, 2, 3, i]])
if r.string == "\"Hello abc data: [1, 2, 3, " & $i & "]\"":
2018-07-14 10:51:54 +03:00
result += 1
2019-06-17 19:56:19 +03:00
await client.close()
2018-07-14 10:51:54 +03:00
2021-11-22 10:09:13 -03:00
proc invalidTest(address: string, port: Port): Future[bool] {.async.} =
var client = newRpcHttpClient()
await client.connect(address, port, secure = false)
2021-11-22 10:09:13 -03:00
var invalidA, invalidB: bool
try:
var r = await client.call("invalidProcA", %[])
discard r
except JsonRpcError:
2021-11-22 10:09:13 -03:00
invalidA = true
try:
var r = await client.call("invalidProcB", %[1, 2, 3])
discard r
except JsonRpcError:
2021-11-22 10:09:13 -03:00
invalidB = true
if invalidA and invalidB:
result = true
2018-07-14 10:51:54 +03:00
var httpsrv = newRpcHttpServer(["127.0.0.1:8545"])
2018-07-14 10:51:54 +03:00
# Create RPC on server
httpsrv.rpc("myProc") do(input: string, data: array[0..3, int]):
result = %("Hello " & input & " data: " & $data)
httpsrv.rpc("noParamsProc") do():
result = %("Hello world")
2018-07-14 10:51:54 +03:00
httpsrv.start()
2021-11-22 10:09:13 -03:00
suite "JSON-RPC test suite":
test "Simple RPC call":
check waitFor(simpleTest("127.0.0.1", Port(8545))) == true
2018-07-14 10:51:54 +03:00
test "Continuous RPC calls (" & $TestsCount & " messages)":
check waitFor(continuousTest("127.0.0.1", Port(8545))) == TestsCount
2021-11-22 10:09:13 -03:00
test "Invalid RPC calls":
check waitFor(invalidTest("127.0.0.1", Port(8545))) == true
2018-07-14 10:51:54 +03:00
2021-11-22 10:09:13 -03:00
waitFor httpsrv.stop()
2018-09-13 18:06:54 +01:00
waitFor httpsrv.closeWait()