Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Do not use WeakRef on mocks. #1290

Merged
merged 3 commits into from Mar 18, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 11 additions & 2 deletions lib/mock/mock-agent.js
Expand Up @@ -18,7 +18,16 @@ const MockPool = require('./mock-pool')
const { matchValue, buildMockOptions } = require('./mock-utils')
const { InvalidArgumentError } = require('../core/errors')
const Dispatcher = require('../dispatcher')
const { WeakRef } = require('../compat/dispatcher-weakref')()

class FakeWeakRef {
constructor (value) {
this.value = value
}

deref () {
return this.value
}
}

class MockAgent extends Dispatcher {
constructor (opts) {
Expand Down Expand Up @@ -86,7 +95,7 @@ class MockAgent extends Dispatcher {
}

[kMockAgentSet] (origin, dispatcher) {
this[kClients].set(origin, new WeakRef(dispatcher))
this[kClients].set(origin, new FakeWeakRef(dispatcher))
}

[kFactory] (origin) {
Expand Down
47 changes: 47 additions & 0 deletions test/mock-agent.js
Expand Up @@ -2349,3 +2349,50 @@ test('MockAgent - headers function interceptor', async (t) => {
t.equal(statusCode, 200)
}
})

test('MockAgent - clients are not garbage collected', async (t) => {
const samples = 250
t.plan(2)

const server = createServer((req, res) => {
t.fail('should not be called')
t.end()
res.end('should not be called')
})
t.teardown(server.close.bind(server))

await promisify(server.listen.bind(server))(0)

const baseUrl = `http://localhost:${server.address().port}`

// Create the dispatcher and isable net connect so we can make sure it matches properly
const dispatcher = new MockAgent()
dispatcher.disableNetConnect()

// Purposely create the pool inside a function so that the reference is lost
function intercept () {
// Create the pool and add a lot of intercepts
const pool = dispatcher.get(baseUrl)

for (let i = 0; i < samples; i++) {
pool.intercept({
path: `/foo/${i}`,
method: 'GET'
}).reply(200, Buffer.alloc(1024 * 1024))
}
}

intercept()

const results = new Set()
for (let i = 0; i < samples; i++) {
// Let's make some time pass to allow garbage collection to happen
await require('timers/promises').setTimeout(10)

const { statusCode } = await request(`${baseUrl}/foo/${i}`, { method: 'GET', dispatcher })
results.add(statusCode)
}

t.equal(results.size, 1)
t.ok(results.has(200))
})