[Frisby]Can't report correctly if test is fail - jasmine-node

I wrote RestAPI TEST with frisby.js.
If Test result is True, There is no probrem.
But If Test result is False, Frisby doesn't report correctly on Linux.(report correctly on windows)
following are sample codes:
const frisby = require('frisby');
const Joi = frisby.Joi;
describe('TEST', () => {
it ('should return a status of 200', (done) =>{
frisby
.get('https://jsonfeed.org/feed.json')
.expect('status', 400) //deliberately error
.done(done);
});
});
If this spec.js run on Windows, result is below
> jasmine-node .
F
Failures:
1) TEST should return a status of 200
Message:
Expected 'AssertionError: HTTP status 400 !== 200
at FrisbySpec.status ([mydirpath]\expects.js:25:12)
(snip)
But, If spec.js run on Linux(Ubuntu), result is below
(node:28704) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: HTTP status 400 !== 200
at FrisbySpec.status (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/expects.js:25:12)
at FrisbySpec._addExpect.response (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/spec.js:368:23)
at FrisbySpec._runExpects (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/spec.js:260:24)
at _fetch.fetch.then.then.responseBody (/home/nsco/jen_work/frisby/node_modules/frisby/src/frisby/spec.js:139:14)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:28704) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:28704) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
F
Failures:
1) TEST should return a status of 200
Message:
timeout: timed out after 5000 msec waiting for spec to complete
Stacktrace:
undefined
"Failures:" section is displayed as "Timeout".
(On windows, displayed as "Expected 'AssertionError: HTTP status 400 !== 200".It is correct.)
Environments:
frisby#2.0.11
jasmine-node#1.14.5
node/9.4.0
Ubuntu16.04

Related

for a grpc client `listen` function to the stream not working same as `await for (...)`

I have a golang server which streams data and a dart client. I put the following code which seems to be working fine
var response = stub.streamMusic(RequestMusicId(musicId: musicId));
await for(var v in response) {
print(v);
}
but when i tried to listen to the stream using this
var response = stub.streamMusic(RequestMusicId(musicId: musicId));
response.listen((value) {
print(value);
});
i get the following error, even though the server is running.
Connecting to VM Service at http://127.0.0.1:55936/l3_uHzU_qIw=/
Unhandled exception:
gRPC Error (code: 14, codeName: UNAVAILABLE, message: Error connecting: Connection shutting down., details: null, rawResponse: null, trailers: {})
Exited (255)

Error: EVP_PKEY_sign_init:operation not supported for this keytype

With jsonwebtoken 8.2.0, the following code signs a payload with RS256:
const jwt = require('jsonwebtoken');
const token = jwt.sign( //<<==sign throw error below
{
uid: this.id, //<<==payload
},
key, //<<==RSA private key of 2048bit
{
expiresIn: (parseInt(process.env.jwt_token_expire_days) * 24).toString() + 'h',
algorithm: 'RS256'
}
);
The sign throws error:
(node:6528) UnhandledPromiseRejectionWarning: Error: error:0608D096:digital envelope routines:EVP_PKEY_sign_init:operation not supported for this keytype
at Sign.sign (internal/crypto/sig.js:110:29)
at Object.sign (C:\d\code\js\xyz\node_modules\jwa\index.js:152:45)
at Object.jwsSign [as sign] (C:\d\code\js\xyz\node_modules\jws\lib\sign-stream.js:32:24)
at Object.module.exports [as sign] (C:\d\code\js\xyz\node_modules\jsonwebtoken\sign.js:204:16)
at Viewer.RSAAuthToken (C:\d\code\js\xyz\models\viewer.js:162:21)
at C:\d\code\js\xyz\routes\viewers.js:184:41
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6528) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6528) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Viewer verification status update failed TypeError: res.setheader is not a function
at C:\d\code\js\xyz\routes\viewers.js:203:17
at processTicksAndRejections (internal/process/task_queues.js:93:5)
The RSA private key (2048bit) looks like below:
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAtBwLxqZEirr0uhtMTThmVDu3XKFVgE+qQqQ6oi6P/cvnTBHc
zlnmgqYNpufUbnIgGSZ9RzL29gVq6o/Dc4Sf1C0sEdkU1A5weFEegpeQTfEU1XI9
.....
0q6yoDXSl7JC+y5BWaz75xFX+tb4hKVTD27BvNDYRuvRsFeiKnn7vDmVS1/CoSnd
bv9Y1DrudRU2PkgAUPqbxDzuCNY9VW8IAP/DCw0oJBJP+wzdH9uvhg==
-----END RSA PRIVATE KEY-----
What is wrong here?
It is probably because your RSA key is actually an RSA-PSS one with restrictions on used padding, usage, algorithms, digests, or any combination of those. You can confirm this hypothesis by executing
const { createPrivateKey } = require('crypto')
const pk = createPrivateKey(pem)
console.log(pk.asymmetricKeyType)
If you get rsa-pss logged, then your key is restricting the operations that can be executed with it.

Class variable is undefined... despite being defined

I have a class called RouteBinder that looks like this:
class RouteBinder
constructor: (#server, #pool) ->
bindRoute: (name, fn, method = "post", useDb = true) ->
#server[method]("/api/accounts/v1/" + name, (req, res, next) ->
client = await #pool.connect() if useDb?
await fn req, res, next, client
await #pool.release() if useDb?
)
I declare it and call it like this:
binder = new RouteBinder server, pool
binder.bindRoute "login", controllers.login
(Pool is node-postgres's Pool and is declared and tested earlier like this)
pool = new Pool
[...]
try
client = await pool.connect()
await client.query 'SELECT 1=1'
catch e
console.fatal "Could not connect to database: #{e}"
return
finally
try client.release() if client?
catch e
console.fatal "Couldn't release client: #{e}"
return
console.info 'Database is OK!'
When running this, I get this error:
02/14 18:44:34 error (node:11855) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'connect' of undefined
at _callee2$ (/home/vi/[redacted]_accounts/main.js:136:38)
at tryCatch (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:45:40)
at Generator.invoke [as _invoke] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:271:22)
at Generator.prototype.(anonymous function) [as next] (/home/vi/[redacted]_accounts/node_modules/regenerator-runtime/runtime.js:97:21)
at asyncGeneratorStep (/home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:3:24)
at _next (/home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:25:9)
at /home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:32:7
at new Promise (<anonymous>)
at /home/vi/[redacted]_accounts/node_modules/#babel/runtime/helpers/asyncToGenerator.js:21:12
at /home/vi/[redacted]_accounts/main.js:166:26
02/14 18:44:34 error (node:11855) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
02/14 18:44:34 error (node:11855) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I'm using CoffeeScript compiled transpiled with Babel. My .babelrc looks like this:
{
"presets": ["#babel/env"],
"plugins": [
["#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}
Sorry if it's a rookie question, I'm still learning and would love all the advice I can get.
I figured out my mistake. Both #pool and #server were defined, however, the inline function (handler) for #server[method] was running in the context of that function.
The solution was to bind it to the RouteBinder instance using .bind(#) (or .bind(this), if you prefer)
bindRoute: (name, fn, method = "post", useDb = true) ->
#server[method]("/api/accounts/v1/" + name, ((req, res, next) ->
console.log "pool", #pool
client = await #pool.connect() if useDb?
await fn req, res, next, client
await #pool.release() if useDb?
).bind(#))

How to handle idle_in_transaction_session_timeout?

When we set idle_in_transaction_session_timeout, the database will terminate connections that are idle for some time.
This works as expected, but I wonder how we should deal with this situation in the aplication code.
We are using pg-promise 10.3.1.
Details of the test:
we set the connection pool size to 1, so that we only have a single session
we set the for the idle-transaction-session-timeout to 2.5 sec:
SET idle_in_transaction_session_timeout TO 2500
now the active transaction will be in state idle in transaction:
see What can cause “idle in transaction” for “BEGIN” statements
now we start a transaction and sleep for 5 seconds
after 2.5sec the database will terminate the session and send an error to the client:
pgp-error error: terminating connection due to idle-in-transaction timeout
after another 2.5sec the transactional code tries to send a query (via the already terminated session), and this fails as expected:
dbIdle failed Error: Client has encountered a connection error and is not queryable
then pg-promise will try to rollback the transaction which will also fail (also expected, I guess)
But now we start a new query and also this query fails with
dbCall failed Client has encountered a connection error and is not queryable
is this expected? I was hoping that pg-promise can somehow remove the "broken" connection from the pool and that we could get a new one
obvously this is not the case, so how should we deal with this situation: i.e. how to recover, so that we can send new queries to the database?
Code example:
import pgPromise, { IMain } from "pg-promise";
import * as dbConfig from "./db-config.json";
import { IConnectionParameters } from "pg-promise/typescript/pg-subset";
const cll = "pg";
console.time(cll);
const pgp: IMain = pgPromise({
query(e) {
console.timeLog(cll,`> ${e.query}`);
},
error(e, ctx) {
console.timeLog(cll,"pgp-error", e);
}
});
const connectParams: IConnectionParameters = {
...dbConfig,
application_name: "pg-test",
max: 1
};
const db = pgp(connectParams);
/**
* #param timeoutMs 0 is no timeout
*/
async function setDbIdleInTxTimeout(timeoutMs: number = 0) {
await db.any("SET idle_in_transaction_session_timeout TO $1;", timeoutMs);
}
async function dbIdle(sleepTimeSec: number) {
console.timeLog(cll, `starting db idle ${sleepTimeSec}`);
const result = await db.tx(async t => {
await new Promise(resolve => setTimeout(resolve, sleepTimeSec * 1000));
return t.one("Select $1 as sleep_sec", sleepTimeSec);
});
console.timeLog(cll, result);
}
async function main() {
await setDbIdleInTxTimeout(2500);
try {
await dbIdle(5);
} catch (e) {
console.timeLog(cll, "dbIdle failed", e);
}
try {
await db.one("Select 1+1 as res");
} catch (e) {
console.timeLog(cll, "dbCall failed", e);
}
}
main().finally(() => {
pgp.end();
});
Console output (removed some useless lines):
"C:\Program Files\nodejs\node.exe" D:\dev_no_backup\pg-promise-tx\dist\index.js
pg: 23.959ms > SET idle_in_transaction_session_timeout TO 2500;
pg: 28.696ms starting db idle 5
pg: 29.705ms > begin
pg: 2531.247ms pgp-error error: terminating connection due to idle-in-transaction timeout
at TCP.onStreamRead (internal/stream_base_commons.js:182:23) {
name: 'error',
severity: 'FATAL',
code: '25P03',
}
pg: 2533.569ms pgp-error Error: Connection terminated unexpectedly
pg: 5031.091ms > Select 5 as sleep_sec
pg: 5031.323ms pgp-error Error: Client has encountered a connection error and is not queryable
pg: 5031.489ms > rollback
pg: 5031.570ms pgp-error Error: Client has encountered a connection error and is not queryable
pg: 5031.953ms dbIdle failed Error: Client has encountered a connection error and is not queryable
pg: 5032.094ms > Select 1+1 as res
pg: 5032.164ms pgp-error Error: Client has encountered a connection error and is not queryable
pg: 5032.303ms dbCall failed Error: Client has encountered a connection error and is not queryable
Process finished with exit code 0
This issue #680 has been fixed in pg-promise 10.3.5

Handling Http errors in coffeescript

I am trying to handle a http request in coffeescript, but in case the server is down the app just dies with error below, and I can't find the right solution.
Code:
http.get "http://localhost:8080/health", (res) ->
status = res.statusCode
value = if status == 200 then 1 else 0
console.log value
server.push_metric metricPrefix , value
res.on 'error', () ->
colsone.log "Tomcat Disconected"
error:
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:770:11)
at Object.afterConnect [as oncomplete] (net.js:761:19)
I think you have to actively listen for the error in a separate event handler. Right now, you're attaching an event handler to the response (res), but it needs to be attached to the request object itself. See the docs.
req = http.get "http://localhost:8080/health", (res) ->
status = res.statusCode
value = if status == 200 then 1 else 0
console.log value
server.push_metric metricPrefix , value
req.on 'error', ->
console.log "Tomcat Disconected"
Also, you have a typo in your current error handler: colsone.log