From ba9fc424d5a17cbdde62745d4bdd8159331a1b8d Mon Sep 17 00:00:00 2001 From: Maxime Bargiel Date: Mon, 26 Feb 2024 16:47:03 -0500 Subject: [PATCH] fix: call `fs.createReadStream` lazily (#2357) --- lib/interceptor.js | 21 +++++++++----------- tests/got/test_reply_with_file.js | 33 +++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/lib/interceptor.js b/lib/interceptor.js index aebbdad14..00c4522f6 100644 --- a/lib/interceptor.js +++ b/lib/interceptor.js @@ -198,10 +198,16 @@ 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, + ) } // Also match request headers @@ -453,15 +459,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) { diff --git a/tests/got/test_reply_with_file.js b/tests/got/test_reply_with_file.js index 473743e7b..9c2de2016 100644 --- a/tests/got/test_reply_with_file.js +++ b/tests/got/test_reply_with_file.js @@ -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', { @@ -79,4 +102,14 @@ 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', + }) + + expect(fs.createReadStream.callCount).to.equal(0) + }) })