Skip to content

Commit

Permalink
test: add testing for h2
Browse files Browse the repository at this point in the history
  • Loading branch information
metcoder95 committed Apr 21, 2023
1 parent 8639989 commit 7176963
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/core/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { kDestroyed, kBodyUsed } = require('./symbols')
const { IncomingMessage } = require('http')
const stream = require('stream')
const net = require('net')
const { InvalidArgumentError } = require('./errors')
const { InvalidArgumentError, ClientDestroyedError } = require('./errors')
const { Blob } = require('buffer')
const nodeUtil = require('util')
const { stringify } = require('querystring')
Expand Down Expand Up @@ -199,7 +199,16 @@ function destroy (stream, err) {
// See: https://github.com/nodejs/node/pull/38505/files
stream.socket = null
}
stream.destroy(err)

// HTTP/2 - It causes to throw uncaught exceptions due to the
// error passed down the socket.destroy
if (stream.alpnProtocol === 'h2' &&
Object.getPrototypeOf(err).constructor === ClientDestroyedError
) {
stream.destroy()
} else {
stream.destroy(err)
}
} else if (err) {
process.nextTick((stream, err) => {
stream.emit('error', err)
Expand Down
56 changes: 56 additions & 0 deletions test/http2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use strict'

const { createSecureServer } = require('node:http2')
const { once } = require('node:events')

const { test } = require('tap')
const pem = require('https-pem')

const { Client } = require('..')

test('Should support H2 connection', async t => {
const body = []
const server = createSecureServer(pem)

server.on('stream', (stream, headers) => {
t.equal(headers['x-my-header'], 'foo')
t.equal(headers[':method'], 'GET')
stream.respond({
'content-type': 'text/plain; charset=utf-8',
'x-custom-h2': 'hello',
':status': 200
})
stream.end('hello h2!')
})

server.listen(0)
await once(server, 'listening')

const client = new Client(`https://localhost:${server.address().port}`, {
connect: {
rejectUnauthorized: false
}
})

t.plan(6)
t.teardown(server.close.bind(server))
t.teardown(client.close.bind(client))

const response = await client.request({
path: '/',
method: 'GET',
headers: {
'x-my-header': 'foo'
}
})

response.body.on('data', chunk => {
body.push(chunk)
})

await once(response.body, 'end')
t.equal(response.statusCode, 200)
t.equal(response.headers['content-type'], 'text/plain; charset=utf-8')
t.equal(response.headers['x-custom-h2'], 'hello')
t.equal(Buffer.concat(body).toString('utf8'), 'hello h2!')
})

0 comments on commit 7176963

Please sign in to comment.