Skip to content

Commit

Permalink
Add test method to test server.http()
Browse files Browse the repository at this point in the history
  • Loading branch information
ai committed Aug 28, 2024
1 parent 5dfd9cd commit 74fe94a
Show file tree
Hide file tree
Showing 5 changed files with 83 additions and 25 deletions.
51 changes: 27 additions & 24 deletions base-server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -630,31 +630,8 @@ export class BaseServer {
res.end('The server is shutting down\n')
return
}

let urlString = req.url
if (/^\/\w+%3F/.test(urlString)) {
urlString = decodeURIComponent(urlString)
}
let reqUrl = new URL(urlString, 'http://localhost')
let rule = this.httpListeners[req.method + ' ' + reqUrl.pathname]

processing += 1
if (!rule) {
let processed = false
for (let listener of this.httpAllListeners) {
let result = await listener(req, res)
if (result === true) {
processed = true
break
}
}
if (!processed) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Not found')
}
} else {
await rule(req, res)
}
await this.processHttp(req, res)
processing -= 1
if (processing === 0 && waiting) waiting()
})
Expand Down Expand Up @@ -792,6 +769,32 @@ export class BaseServer {
this.emitter.emit('processed', action, meta, latency)
}

async processHttp(req, res) {
let urlString = req.url
if (/^\/\w+%3F/.test(urlString)) {
urlString = decodeURIComponent(urlString)
}
let reqUrl = new URL(urlString, 'http://localhost')
let rule = this.httpListeners[req.method + ' ' + reqUrl.pathname]

if (!rule) {
let processed = false
for (let listener of this.httpAllListeners) {
let result = await listener(req, res)
if (result === true) {
processed = true
break
}
}
if (!processed) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Not found')
}
} else {
await rule(req, res)
}
}

rememberBadAuth(ip) {
this.authAttempts[ip] = (this.authAttempts[ip] || 0) + 1
this.setTimeout(() => {
Expand Down
8 changes: 7 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@ export default [
...loguxTsConfig,
{
rules: {
'@typescript-eslint/no-explicit-any': 'off'
'@typescript-eslint/no-explicit-any': 'off',
'n/no-unsupported-features/node-builtins': [
'error',
{
ignores: ['fetch']
}
]
}
},
{
Expand Down
21 changes: 21 additions & 0 deletions test-client/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,27 @@ it('collects received actions', async () => {
])
})

it('receives HTTP requests', async () => {
server = new TestServer()
server.http('GET', '/a', (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end(String(req.headers['x-test'] ?? 'empty'))
})

let response1 = await server.fetch('/a')
expect(response1.headers.get('Content-Type')).toEqual('text/plain')
expect(await response1.text()).toEqual('empty')

let response2 = await server.fetch('/a', { headers: [['X-Test', '1']] })
expect(await response2.text()).toEqual('1')

let response3 = await server.fetch('/b')
expect(response3.status).toEqual(404)

let response4 = await server.fetch('/a', { method: 'POST' })
expect(response4.status).toEqual(404)
})

it('destroys on fatal', () => {
server = new TestServer()
// @ts-expect-error
Expand Down
13 changes: 13 additions & 0 deletions test-server/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,19 @@ export interface TestServerOptions
export class TestServer<
Headers extends object = {}
> extends BaseServer<Headers> {
/**
* fetch() compatible API to test HTTP endpoints.
*
* ```js
* server.http('GET', '/version', (req, res) => {
* res.end('1.0.0')
* })
* let res = await server.fetch()
* expect(await res.text()).toEqual('1.0.0')
* ```
*/
fetch: typeof fetch

/**
* Server actions log, with methods to check actions inside.
*
Expand Down
15 changes: 15 additions & 0 deletions test-server/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { TestTime } from '@logux/core'
import { createServer } from 'node:http'

import { BaseServer } from '../base-server/index.js'
import { createReporter } from '../create-reporter/index.js'
Expand Down Expand Up @@ -31,6 +32,8 @@ export class TestServer extends BaseServer {
if (opts.auth !== false) this.auth(() => true)
this.testUsers = {}

this.fetch = this.fetch.bind(this)

this.on('fatal', () => {
this.destroy()
})
Expand Down Expand Up @@ -88,4 +91,16 @@ export class TestServer extends BaseServer {
}
}
}

async fetch(path, init) {
let server = createServer(async (req, res) => {
await this.processHttp(req, res)
server.close()
})
await new Promise(resolve => {
server.listen(0, resolve)
})
let { port } = server.address()
return fetch(`http://localhost:${port}${path}`, init)
}
}

0 comments on commit 74fe94a

Please sign in to comment.