From 07a5a69d56a0b2ea0f2349a72f5e11f6f6dccf8d Mon Sep 17 00:00:00 2001 From: Daniel Bruce Date: Thu, 19 Nov 2026 22:13:52 +0000 Subject: [PATCH 1/2] test(storage): isolate Sinon sandboxes and fake timers in unit tests --- handwritten/storage/test/bucket.ts | 20 ++++---- handwritten/storage/test/file.ts | 53 +++++++++++--------- handwritten/storage/test/index.ts | 6 +-- handwritten/storage/test/resumable-upload.ts | 16 ++++-- handwritten/storage/test/signer.ts | 26 ++++++---- handwritten/storage/test/transfer-manager.ts | 2 +- 6 files changed, 72 insertions(+), 51 deletions(-) diff --git a/handwritten/storage/test/bucket.ts b/handwritten/storage/test/bucket.ts index 5945804ba0a3..ec6734e0c5a1 100644 --- a/handwritten/storage/test/bucket.ts +++ b/handwritten/storage/test/bucket.ts @@ -3053,11 +3053,18 @@ describe('Bucket', () => { it('should destroy the local read stream if write stream fails', done => { const fakeFile = new File(bucket, 'file-name'); const options = {destination: fakeFile, resumable: false}; + const textfilepath = path.join( + getDirName(), + '../../../test/testdata/textfile.txt', + ); const originalCreateReadStream = fs.createReadStream; - let readStream: fs.ReadStream; - sandbox.stub(fs, 'createReadStream').callsFake((path, opts) => { - readStream = originalCreateReadStream(path, opts); - return readStream; + let readStream: fs.ReadStream | undefined; + sandbox.stub(fs, 'createReadStream').callsFake((filePath, opts) => { + const streamInstance = originalCreateReadStream(filePath, opts); + if (filePath === textfilepath) { + readStream = streamInstance; + } + return streamInstance; }); fakeFile.createWriteStream = () => { @@ -3069,11 +3076,6 @@ describe('Bucket', () => { return ws; }; - const textfilepath = path.join( - getDirName(), - '../../../test/testdata/textfile.txt', - ); - bucket.upload(textfilepath, options, (err: Error | null) => { try { assert.strictEqual(err!.message, 'write error'); diff --git a/handwritten/storage/test/file.ts b/handwritten/storage/test/file.ts index 8f9e7d170fcf..24aea8a2097a 100644 --- a/handwritten/storage/test/file.ts +++ b/handwritten/storage/test/file.ts @@ -26,7 +26,7 @@ import { StorageRequestOptions, StorageTransport, } from '../src/storage-transport.js'; -import sinon, {createSandbox, stub, spy, restore, useFakeTimers} from 'sinon'; +import sinon, {createSandbox} from 'sinon'; import {GoogleAuth} from 'google-auth-library'; import { FileExceptionMessages, @@ -1393,9 +1393,9 @@ describe('File', () => { const rawResponseStream = new PassThrough(); const gunzipStream = new PassThrough(); createGunzipOverride = () => gunzipStream; - const destroySpy = spy(rawResponseStream, 'destroy'); - const gunzipDestroySpy = spy(gunzipStream, 'destroy'); - const pipelineSpy = spy(); + const destroySpy = sandbox.spy(rawResponseStream, 'destroy'); + const gunzipDestroySpy = sandbox.spy(gunzipStream, 'destroy'); + const pipelineSpy = sandbox.spy(); pipelineOverride = pipelineSpy; proxiedFile.storageTransport.makeRequest = sandbox @@ -1426,8 +1426,8 @@ describe('File', () => { it('should destroy rawResponseStream and return early if throughStream is closed', done => { const proxiedFile = new ProxiedFile(BUCKET, FILE_NAME); const rawResponseStream = new PassThrough(); - const destroySpy = spy(rawResponseStream, 'destroy'); - const pipelineSpy = spy(); + const destroySpy = sandbox.spy(rawResponseStream, 'destroy'); + const pipelineSpy = sandbox.spy(); pipelineOverride = pipelineSpy; proxiedFile.storageTransport.makeRequest = sandbox @@ -1458,8 +1458,8 @@ describe('File', () => { it('should destroy rawResponseStream and return early if throughStream is already writableEnded', done => { const proxiedFile = new ProxiedFile(BUCKET, FILE_NAME); const rawResponseStream = new PassThrough(); - const destroySpy = spy(rawResponseStream, 'destroy'); - const pipelineSpy = spy(); + const destroySpy = sandbox.spy(rawResponseStream, 'destroy'); + const pipelineSpy = sandbox.spy(); pipelineOverride = pipelineSpy; proxiedFile.storageTransport.makeRequest = sandbox @@ -1495,8 +1495,8 @@ describe('File', () => { const rawResponseStream = new PassThrough(); const gunzipStream = new PassThrough(); createGunzipOverride = () => gunzipStream; - const destroySpy = spy(rawResponseStream, 'destroy'); - const gunzipDestroySpy = spy(gunzipStream, 'destroy'); + const destroySpy = sandbox.spy(rawResponseStream, 'destroy'); + const gunzipDestroySpy = sandbox.spy(gunzipStream, 'destroy'); pipelineOverride = (...args: unknown[]) => { const onComplete = args[args.length - 1] as ( @@ -2076,24 +2076,27 @@ describe('File', () => { idempotencyStrategy: IdempotencyStrategy.RetryConditional, }, }, - getRequestInterceptors: stub().returns([ - (reqOpts: object) => ({...reqOpts, customOption: 'custom-value'}), - ]), + getRequestInterceptors: sandbox + .stub() + .returns([ + (reqOpts: object) => ({...reqOpts, customOption: 'custom-value'}), + ]), generation: 123, encryptionKey: 'test-encryption-key', kmsKeyName: 'test-kms-key-name', userProject: 'test-user-project', instancePreconditionOpts: {ifGenerationMatch: 123}, - createResumableUpload: spy(), + createResumableUpload: sandbox.spy(), }; - resumableUploadStub = stub(); + resumableUploadStub = sandbox.stub(); // eslint-disable-next-line @typescript-eslint/no-explicit-any (global as any).resumableUpload = {createURI: resumableUploadStub}; }); afterEach(() => { - restore(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (global as any).resumableUpload; }); it('should not require options', () => { @@ -2745,7 +2748,7 @@ describe('File', () => { }; originalSetEncryptionKey = file.setEncryptionKey; - file.setEncryptionKey = stub(); + file.setEncryptionKey = sandbox.stub(); }); afterEach(() => { @@ -3470,7 +3473,7 @@ describe('File', () => { let BUCKET: any; beforeEach(() => { - fakeTimer = useFakeTimers(NOW); + fakeTimer = sandbox.useFakeTimers(NOW); CONFIG = { expires: NOW.valueOf() + 2000, }; @@ -5751,7 +5754,7 @@ describe('File', () => { }; const resumableUpload = { - upload: stub().callsFake(opts => { + upload: sandbox.stub().callsFake(opts => { const bucket = file.bucket; const storage = bucket.storage; const authClient = storage.storageTransport.authClient; @@ -5780,7 +5783,7 @@ describe('File', () => { const uploadStream = new PassThrough(); const resumableUpload = { - upload: stub().callsFake(() => { + upload: sandbox.stub().callsFake(() => { uploadStream.emit('response', resp); done(); return uploadStream; @@ -5801,7 +5804,7 @@ describe('File', () => { const metadata = {}; const uploadStream = new PassThrough(); const resumableUpload = { - upload: stub().callsFake(() => { + upload: sandbox.stub().callsFake(() => { uploadStream.emit('metadata', metadata); setImmediate(() => { assert.deepStrictEqual(file.metadata, metadata); @@ -5821,7 +5824,7 @@ describe('File', () => { dup.on('complete', done); const resumableUpload = { - upload: stub().callsFake(() => { + upload: sandbox.stub().callsFake(() => { const uploadStream = new Transform(); setImmediate(() => { uploadStream.end(); @@ -5845,7 +5848,7 @@ describe('File', () => { }; const resumableUpload = { - upload: stub().callsFake(() => { + upload: sandbox.stub().callsFake(() => { done(); return uploadStream; }), @@ -5864,7 +5867,7 @@ describe('File', () => { }); const resumableUpload = { - upload: stub().callsFake(() => { + upload: sandbox.stub().callsFake(() => { const uploadStream = new Transform(); setImmediate(() => { uploadStream.emit('progress', progress); @@ -5888,7 +5891,7 @@ describe('File', () => { }); const resumableUpload = { - upload: stub().callsFake(() => { + upload: sandbox.stub().callsFake(() => { done(); return uploadStream; }), diff --git a/handwritten/storage/test/index.ts b/handwritten/storage/test/index.ts index 03377001262c..834f8e31e16c 100644 --- a/handwritten/storage/test/index.ts +++ b/handwritten/storage/test/index.ts @@ -452,7 +452,7 @@ describe('Storage', () => { describe('hmacKey', () => { let hmacKeyCtor: sinon.SinonSpy; beforeEach(() => { - hmacKeyCtor = sinon.spy(hmacKeyModule, 'HmacKey'); + hmacKeyCtor = sandbox.spy(hmacKeyModule, 'HmacKey'); }); afterEach(() => { @@ -499,7 +499,7 @@ describe('Storage', () => { let hmacKeyCtor: sinon.SinonSpy; beforeEach(() => { - hmacKeyCtor = sinon.spy(hmacKeyModule, 'HmacKey'); + hmacKeyCtor = sandbox.spy(hmacKeyModule, 'HmacKey'); }); afterEach(() => { @@ -1210,7 +1210,7 @@ describe('Storage', () => { let hmacKeyCtor: sinon.SinonSpy; beforeEach(() => { - hmacKeyCtor = sinon.spy(hmacKeyModule, 'HmacKey'); + hmacKeyCtor = sandbox.spy(hmacKeyModule, 'HmacKey'); }); afterEach(() => { diff --git a/handwritten/storage/test/resumable-upload.ts b/handwritten/storage/test/resumable-upload.ts index 1661fd1012b5..e47f19c73499 100644 --- a/handwritten/storage/test/resumable-upload.ts +++ b/handwritten/storage/test/resumable-upload.ts @@ -3089,14 +3089,24 @@ describe('resumable-upload', () => { }); describe('exponential back off', () => { + let sandbox: sinon.SinonSandbox; let clock: sinon.SinonFakeTimers; let setTimeoutSpy: sinon.SinonSpy; beforeEach(() => { - clock = sinon.useFakeTimers({toFake: ['setTimeout']}); - setTimeoutSpy = sinon.spy(global, 'setTimeout'); + sandbox = sinon.createSandbox(); + clock = sandbox.useFakeTimers({toFake: ['setTimeout']}); + setTimeoutSpy = sandbox.spy(global, 'setTimeout'); }); afterEach(() => { - clock.restore(); + sandbox.restore(); + }); + + it('should restore global setTimeout without leaking to the default sinon sandbox', async () => { + sandbox.restore(); + sinon.restore(); + await new Promise(resolve => { + setTimeout(resolve, 1); + }); }); it('should continue uploading after retry count^2 * random', done => { diff --git a/handwritten/storage/test/signer.ts b/handwritten/storage/test/signer.ts index 7432cf193592..1a349dfedd08 100644 --- a/handwritten/storage/test/signer.ts +++ b/handwritten/storage/test/signer.ts @@ -60,7 +60,7 @@ describe('signer', () => { const NOW = new Date('2019-03-18T00:00:00.999Z'); let fakeTimers: sinon.SinonFakeTimers; - beforeEach(() => (fakeTimers = sinon.useFakeTimers(NOW))); + beforeEach(() => (fakeTimers = sandbox.useFakeTimers(NOW))); afterEach(() => fakeTimers.restore()); beforeEach(() => { @@ -813,11 +813,13 @@ describe('signer', () => { 'x-goog-content-sha256': '76af7efae0d034d1e3335ed1b90f24b6cadf2bf1', }; CONFIG.file = 'file-name.png'; - sinon.stub(signer, 'getCanonicalHeaders').returns('canonical-headers'); - sinon + sandbox + .stub(signer, 'getCanonicalHeaders') + .returns('canonical-headers'); + sandbox .stub(signer, 'getCanonicalQueryParams') .returns('canonical-query'); - const getCanonicalRequest = sinon.spy(signer, 'getCanonicalRequest'); + const getCanonicalRequest = sandbox.spy(signer, 'getCanonicalRequest'); await signer['getSignedUrlV4'](CONFIG); const args = getCanonicalRequest.getCall(0).args; @@ -831,8 +833,10 @@ describe('signer', () => { }); it('should compute SHA256 digest in hex on canonical request', async () => { - sinon.stub(signer, 'getCanonicalRequest').returns('canonical-request'); - const authClientSign = sinon + sandbox + .stub(signer, 'getCanonicalRequest') + .returns('canonical-request'); + const authClientSign = sandbox .stub(authClient, 'sign') .resolves('signature'); @@ -850,8 +854,10 @@ describe('signer', () => { it('should sign using the `signingEndpoint` when provided', async () => { const signingEndpoint = 'https://my-endpoint.com'; - sinon.stub(signer, 'getCanonicalRequest').returns('canonical-request'); - const authClientSign = sinon + sandbox + .stub(signer, 'getCanonicalRequest') + .returns('canonical-request'); + const authClientSign = sandbox .stub(authClient, 'sign') .resolves('signature'); @@ -871,7 +877,7 @@ describe('signer', () => { const credentialScope = `${datestamp}/auto/storage/goog4_request`; const dateISO = formatAsUTCISO(NOW, true); - const authClientSign = sinon + const authClientSign = sandbox .stub(authClient, 'sign') .resolves('signature'); @@ -888,7 +894,7 @@ describe('signer', () => { it('rejects with SigningError on signing Error', async () => { const err = new Error('my-err'); err.stack = 'some-stack-trace'; - sinon.stub(authClient, 'sign').rejects(err); + sandbox.stub(authClient, 'sign').rejects(err); await assert.rejects(() => signer['getSignedUrlV4'](CONFIG), { name: 'SigningError', diff --git a/handwritten/storage/test/transfer-manager.ts b/handwritten/storage/test/transfer-manager.ts index 13b25cfc4dbc..70783891c52d 100644 --- a/handwritten/storage/test/transfer-manager.ts +++ b/handwritten/storage/test/transfer-manager.ts @@ -43,7 +43,7 @@ import {DownloadResponseWithStatus, SkipReason} from '../src/file.js'; describe('Transfer Manager', () => { const BUCKET_NAME = 'test-bucket'; - const STORAGE = sinon.stub( + const STORAGE = sinon.createSandbox().stub( new Storage({ retryOptions: { autoRetry: true, From b8ff53ea3a027fb4f49a838f1bd82b8874caf67c Mon Sep 17 00:00:00 2001 From: danieljbruce Date: Thu, 19 Nov 2026 17:30:55 -0500 Subject: [PATCH 2/2] Update handwritten/storage/test/resumable-upload.ts Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> --- handwritten/storage/test/resumable-upload.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/handwritten/storage/test/resumable-upload.ts b/handwritten/storage/test/resumable-upload.ts index e47f19c73499..f03283123dd4 100644 --- a/handwritten/storage/test/resumable-upload.ts +++ b/handwritten/storage/test/resumable-upload.ts @@ -3102,11 +3102,7 @@ describe('resumable-upload', () => { }); it('should restore global setTimeout without leaking to the default sinon sandbox', async () => { - sandbox.restore(); - sinon.restore(); - await new Promise(resolve => { - setTimeout(resolve, 1); - }); +setImmediate(restoreStubs); }); it('should continue uploading after retry count^2 * random', done => {