Back to Repositories

Testing Response Writable State Management in Koa

This test suite validates the writable state management in Koa’s response handling, focusing on persistent connections and response lifecycle. It ensures proper handling of connection states and response writability across different scenarios.

Test Coverage Overview

The test suite comprehensively covers response writability states in Koa applications.

  • Persistent connection handling with multiple requests
  • Socket closure scenarios before response completion
  • Response completion state verification
  • Edge cases in connection lifecycle management

Implementation Analysis

The testing approach employs Node’s native test framework with async/await patterns for connection handling verification.

Technical implementation includes:
  • Raw TCP socket manipulation for connection testing
  • Promise-based asynchronous state verification
  • HTTP request simulation using Buffer construction
  • Connection lifecycle management with timing controls

Technical Details

Testing infrastructure utilizes:

  • Node.js net module for low-level socket operations
  • Native Node.js test runner with describe/it blocks
  • Buffer manipulation for HTTP request construction
  • Custom connection handling utilities
  • Timeout and immediate scheduling for timing control

Best Practices Demonstrated

The test suite exemplifies robust testing practices for network applications.

  • Proper cleanup of server instances after tests
  • Comprehensive error handling for network operations
  • Isolated test cases with clear scope definition
  • Effective use of async patterns for network testing
  • Structured test organization with descriptive contexts

koajs/koa

__tests__/response/writable.test.js

            
'use strict'

const { describe, it } = require('node:test')
const assert = require('assert')
const Koa = require('../../')
const net = require('net')

describe('res.writable', () => {
  describe('when continuous requests in one persistent connection', () => {
    it('should always be writable and respond to all requests', (t, done) => {
      const app = new Koa()
      let count = 0
      app.use(ctx => {
        count++
        ctx.body = 'request ' + count + ', writable: ' + ctx.writable
      })

      const server = app.listen()

      requestTwice(server, (_, datas) => {
        const responses = Buffer.concat(datas).toString()
        assert.strictEqual(/request 1, writable: true/.test(responses), true)
        assert.strictEqual(/request 2, writable: true/.test(responses), true)
        done()
        server.close()
      })

      function requestTwice (server, done) {
        const port = server.address().port
        const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
        const client = net.connect(port)
        const datas = []
        client
          .on('error', done)
          .on('data', data => datas.push(data))
          .on('end', () => done(null, datas))
        setImmediate(() => {
          client.write(buf)
          client.write(buf)
          setImmediate(() => client.end())
        })
      }
    })
  })

  describe('when socket closed before response sent', () => {
    it('should not be writable', (t, done) => {
      const app = new Koa()
      let callback
      const promise = new Promise(resolve => { callback = resolve })
      app.use(ctx => {
        promise.then(() => {
          if (ctx.writable) return done(new Error('ctx.writable should not be true'))
          done()
          server.close()
        })
      })

      const server = app.listen()

      requestClosed(server)

      function requestClosed (server) {
        const port = server.address().port
        const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
        const client = net.connect(port, () => {
          client.write(buf)
          client.end(() => setTimeout(callback))
        })
      }
    })
  })

  describe('when response finished', () => {
    function request (server) {
      const port = server.address().port
      const buf = Buffer.from('GET / HTTP/1.1\r\nHost: localhost:' + port + '\r\nConnection: keep-alive\r\n\r\n')
      const client = net.connect(port)
      setImmediate(() => {
        client.write(buf)
      })
      setTimeout(() => {
        client.end()
        server.close()
      }, 100)
    }

    it('should not be writable', (t, done) => {
      const app = new Koa()
      app.use(ctx => {
        ctx.res.end()
        if (ctx.writable) return done(new Error('ctx.writable should not be true'))
        done()
      })
      request(app.listen())
    })
  })
})