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: call fs.createReadStream lazily #2357

Merged
merged 6 commits into from
Feb 26, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
17 changes: 5 additions & 12 deletions lib/interceptor.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,10 +198,12 @@ module.exports = class Interceptor {
if (!fs) {
throw new Error('No fs')
}
const readStream = fs.createReadStream(filePath)
readStream.pause()
this.filePath = filePath
return this.reply(statusCode, readStream, headers)
return this.reply(statusCode, () => {
const readStream = fs.createReadStream(filePath)
readStream.pause()
return readStream
}, headers)
Uzlopak marked this conversation as resolved.
Show resolved Hide resolved
}

// Also match request headers
Expand Down Expand Up @@ -453,15 +455,6 @@ module.exports = class Interceptor {
markConsumed() {
this.interceptionCounter++

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) {
Expand Down
35 changes: 35 additions & 0 deletions tests/got/test_reply_with_file.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,29 @@ describe('`replyWithFile()`', () => {
scope.done()
})

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

const scope = nock('http://example.test')
.persist()
.get('/')
.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 All @@ -79,4 +102,16 @@ describe('`replyWithFile()`', () => {
).to.throw(Error, 'No fs')
})
})

it('does not create ReadStream eagerly', async () => {
sinon.spy(fs)

nock('http://example.test')
.get('/')
.replyWithFile(200, binaryFilePath, {
'content-encoding': 'gzip',
})
Uzlopak marked this conversation as resolved.
Show resolved Hide resolved

expect(fs.createReadStream.callCount).to.equal(0)
})
})