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(interceptor): don't hang, don't leak resources #2224

Merged
merged 2 commits into from Aug 25, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 7 additions & 3 deletions lib/interceptor.js
Expand Up @@ -442,13 +442,17 @@ module.exports = class Interceptor {
markConsumed() {
this.interceptionCounter++

remove(this)

if ((this.scope.shouldPersist() || this.counter > 0) && this.filePath) {
if (
(this.scope.shouldPersist() || this.counter > 0) &&
this.interceptionCounter > 1 &&
this.filePath
) {
this.body = fs.createReadStream(this.filePath)
this.body.pause()
}

remove(this)

if (!this.scope.shouldPersist() && this.counter < 1) {
this.scope.remove(this._key, this)
}
Expand Down
25 changes: 25 additions & 0 deletions tests/test_reply_with_file.js
Expand Up @@ -2,7 +2,9 @@

// Tests for `.replyWithFile()`.

const fs = require('fs')
const path = require('path')
const sinon = require('sinon')
const { expect } = require('chai')
const proxyquire = require('proxyquire').preserveCache()
const nock = require('..')
Expand Down Expand Up @@ -39,6 +41,29 @@ describe('`replyWithFile()`', () => {
scope.done()
})

it('reply with file with repeated', async () => {
sinon.spy(fs)

const scope = nock('http://example.test')
.get('/')
.times(2)
.replyWithFile(200, binaryFilePath, {
'content-encoding': 'gzip',
})

const response1 = await got('http://example.test/')
expect(response1.statusCode).to.equal(200)
expect(response1.body).to.have.lengthOf(20)

const response2 = await got('http://example.test/')
expect(response2.statusCode).to.equal(200)
expect(response2.body).to.have.lengthOf(20)

expect(fs.createReadStream.callCount).to.equal(2)

scope.done()
})

describe('with no fs', () => {
const { Scope } = proxyquire('../lib/scope', {
'./interceptor': proxyquire('../lib/interceptor', {
Expand Down