From 0a61c5e7428a4b42d7a43ca94a1671927e10cf5f Mon Sep 17 00:00:00 2001 From: Daniel Bruce Date: Thu, 15 Oct 2026 20:54:42 +0000 Subject: [PATCH 1/4] test: remove --proxyquire-shim from logging and pubsub packages --- handwritten/logging-bunyan/package.json | 2 +- handwritten/logging-bunyan/test/index.ts | 2 +- .../test/middleware/test-express.ts | 2 +- handwritten/logging-bunyan/test/proxyquire.ts | 115 ++++++++++++++++++ handwritten/logging-winston/package.json | 2 +- handwritten/logging-winston/test/common.ts | 2 +- handwritten/logging-winston/test/index.ts | 2 +- .../test/middleware/express.ts | 2 +- .../logging-winston/test/proxyquire.ts | 115 ++++++++++++++++++ .../test/stackdriver-trace-integration.ts | 2 +- handwritten/logging/package.json | 2 +- handwritten/logging/test/entry.ts | 34 +++--- handwritten/logging/test/index.ts | 66 +++++----- handwritten/logging/test/log.ts | 98 +++++++-------- .../express/test-make-middleware.ts | 6 +- handwritten/logging/test/proxyquire.ts | 115 ++++++++++++++++++ handwritten/logging/test/sink.ts | 16 +-- handwritten/logging/test/utils/metadata.ts | 6 +- handwritten/pubsub/package.json | 2 +- handwritten/pubsub/test/iam.ts | 2 +- handwritten/pubsub/test/lease-manager.ts | 17 +-- handwritten/pubsub/test/message-stream.ts | 2 +- handwritten/pubsub/test/proxyquire.ts | 115 ++++++++++++++++++ handwritten/pubsub/test/publisher/index.ts | 2 +- .../pubsub/test/publisher/message-queues.ts | 9 +- handwritten/pubsub/test/pubsub.ts | 4 +- handwritten/pubsub/test/snapshot.ts | 2 +- handwritten/pubsub/test/subscriber.ts | 2 +- handwritten/pubsub/test/subscription.ts | 2 +- handwritten/pubsub/test/topic.ts | 2 +- 30 files changed, 601 insertions(+), 149 deletions(-) create mode 100644 handwritten/logging-bunyan/test/proxyquire.ts create mode 100644 handwritten/logging-winston/test/proxyquire.ts create mode 100644 handwritten/logging/test/proxyquire.ts create mode 100644 handwritten/pubsub/test/proxyquire.ts diff --git a/handwritten/logging-bunyan/package.json b/handwritten/logging-bunyan/package.json index 3358325c6cce..4bd8a2581106 100644 --- a/handwritten/logging-bunyan/package.json +++ b/handwritten/logging-bunyan/package.json @@ -42,7 +42,7 @@ "presystem-test": "pnpm run compile", "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", "system-test": "node ../../bin/run-test.cjs build/system-test --timeout 600000", - "test": "cross-env NODE_OPTIONS='--no-deprecation' node ../../bin/run-test.cjs --proxyquire-shim build/test", + "test": "cross-env NODE_OPTIONS='--no-deprecation' node ../../bin/run-test.cjs build/test", "clean": "gts clean", "compile": "tsc -p .", "postcompile": "cpy \"src/types/*\" build/src/types", diff --git a/handwritten/logging-bunyan/test/index.ts b/handwritten/logging-bunyan/test/index.ts index 9e91fe2665fe..0c82b56d35f5 100644 --- a/handwritten/logging-bunyan/test/index.ts +++ b/handwritten/logging-bunyan/test/index.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; import {describe, it, beforeEach, afterEach} from 'mocha'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import {inspect} from 'util'; import {LoggingBunyan} from '../src'; diff --git a/handwritten/logging-bunyan/test/middleware/test-express.ts b/handwritten/logging-bunyan/test/middleware/test-express.ts index 99920c4ca522..ba5f651c6e8d 100644 --- a/handwritten/logging-bunyan/test/middleware/test-express.ts +++ b/handwritten/logging-bunyan/test/middleware/test-express.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import {GCPEnv} from 'google-auth-library'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from '../proxyquire'; // types-only import. Actual require is done through proxyquire below. import {MiddlewareOptions} from '../../src/middleware/express'; diff --git a/handwritten/logging-bunyan/test/proxyquire.ts b/handwritten/logging-bunyan/test/proxyquire.ts new file mode 100644 index 000000000000..44ff9f689c12 --- /dev/null +++ b/handwritten/logging-bunyan/test/proxyquire.ts @@ -0,0 +1,115 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as Module from 'module'; +import * as path from 'path'; + +delete require.cache[require.resolve(__filename)]; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Stubs = Record; +const mod = Module as unknown as { + prototype: {require: NodeRequire}; + _resolveFilename: (request: string, parent: NodeModule) => string; +}; +const {hasOwnProperty} = Object.prototype; +const hasOwn = (o: unknown, k: string) => + Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isGlobal = (s: unknown) => + hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); +const resolveFrom = (base: string, req: string) => { + try { + return require.resolve(req, {paths: [path.dirname(base)]}); + } catch { + return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; + } +}; + +const parent = module.parent || module; +let skipCallThru = false; +let keepCache = true; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function proxyquire(request: string, stubs: Stubs = {}): T { + const sut = mod._resolveFilename(request, parent); + const resolved: Stubs = {}; + let global = false; + for (const [k, v] of Object.entries(stubs)) { + if (isGlobal(v)) global = true; + resolved[resolveFrom(sut, k)] = v; + } + const cache = require.cache; + const keys = global + ? Object.keys(cache).filter(id => !id.endsWith('.node')) + : [sut]; + const saved = keys.map(id => [id, cache[id]] as const); + for (const id of keys) delete cache[id]; + const prev = mod.prototype.require; + const req = function (this: NodeModule, id: string) { + const isSut = this?.filename === sut; + if (this?.filename && (isSut || global)) { + const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); + const rId = hit ? '' : resolveFrom(this.filename, id); + if (hit || hasOwn(resolved, rId)) { + const stub = hit ? stubs[id] : resolved[rId]; + if (isSut || isGlobal(stub)) { + if (stub === null) { + const e = new Error(`Cannot find module '${id}'`); + throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); + } + const skip = hasOwn(stub, '@noCallThru') + ? stub['@noCallThru'] + : skipCallThru; + if (!skip && stub && ['object', 'function'].includes(typeof stub)) { + try { + const real = prev.call(this, id); + if (real && ['object', 'function'].includes(typeof real)) { + for (const k of Object.keys(real)) { + if (!(k in stub)) stub[k] = real[k]; + } + } + } catch { + // ignore + } + } + return stub; + } + } + } + return prev.call(this, id); + }; + mod.prototype.require = Object.assign(req, prev); + try { + return prev.call(parent, request); + } finally { + mod.prototype.require = prev; + for (const id of global ? Object.keys(cache) : [sut]) { + if (!id.endsWith('.node')) delete cache[id]; + } + for (const [id, m] of saved) { + if (m && (keepCache || id !== sut)) cache[id] = m; + } + } +} + +// eslint-disable-next-line @typescript-eslint/no-namespace +namespace proxyquire { + export const load = proxyquire; + export const noCallThru = () => ((skipCallThru = true), proxyquire); + export const callThru = () => ((skipCallThru = false), proxyquire); + export const noPreserveCache = () => ((keepCache = false), proxyquire); + export const preserveCache = () => ((keepCache = true), proxyquire); +} + +export = proxyquire; diff --git a/handwritten/logging-winston/package.json b/handwritten/logging-winston/package.json index aaf7cd1b0af5..810054027251 100644 --- a/handwritten/logging-winston/package.json +++ b/handwritten/logging-winston/package.json @@ -42,7 +42,7 @@ "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", "presystem-test": "pnpm run pretest", "system-test": "node ../../bin/run-test.cjs build/system-test --timeout 600000", - "test": "cross-env NODE_OPTIONS='--no-deprecation' node ../../bin/run-test.cjs --proxyquire-shim build/test", + "test": "cross-env NODE_OPTIONS='--no-deprecation' node ../../bin/run-test.cjs build/test", "clean": "gts clean", "compile": "tsc -p .", "fix": "gts fix", diff --git a/handwritten/logging-winston/test/common.ts b/handwritten/logging-winston/test/common.ts index 39401702c6ee..f3fb4011a6dc 100644 --- a/handwritten/logging-winston/test/common.ts +++ b/handwritten/logging-winston/test/common.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import * as nodeutil from 'util'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import {Options} from '../src'; import {Entry, Logging, LogSync, Log} from '@google-cloud/logging'; import * as instrumentation from '@google-cloud/logging/build/src/utils/instrumentation'; diff --git a/handwritten/logging-winston/test/index.ts b/handwritten/logging-winston/test/index.ts index 13412aa4e742..1af6b8881636 100644 --- a/handwritten/logging-winston/test/index.ts +++ b/handwritten/logging-winston/test/index.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import * as TransportStream from 'winston-transport'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import {Options} from '../src'; describe('logging-winston', () => { diff --git a/handwritten/logging-winston/test/middleware/express.ts b/handwritten/logging-winston/test/middleware/express.ts index 40a1853601dc..b8ec33cc8f9c 100644 --- a/handwritten/logging-winston/test/middleware/express.ts +++ b/handwritten/logging-winston/test/middleware/express.ts @@ -18,7 +18,7 @@ import {GCPEnv} from 'google-auth-library'; import {LogEntry} from 'winston'; import * as TransportStream from 'winston-transport'; import * as winston from 'winston'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from '../proxyquire'; import {Options} from '../../src'; // types-only import. Actual require is done through proxyquire below. diff --git a/handwritten/logging-winston/test/proxyquire.ts b/handwritten/logging-winston/test/proxyquire.ts new file mode 100644 index 000000000000..44ff9f689c12 --- /dev/null +++ b/handwritten/logging-winston/test/proxyquire.ts @@ -0,0 +1,115 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as Module from 'module'; +import * as path from 'path'; + +delete require.cache[require.resolve(__filename)]; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Stubs = Record; +const mod = Module as unknown as { + prototype: {require: NodeRequire}; + _resolveFilename: (request: string, parent: NodeModule) => string; +}; +const {hasOwnProperty} = Object.prototype; +const hasOwn = (o: unknown, k: string) => + Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isGlobal = (s: unknown) => + hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); +const resolveFrom = (base: string, req: string) => { + try { + return require.resolve(req, {paths: [path.dirname(base)]}); + } catch { + return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; + } +}; + +const parent = module.parent || module; +let skipCallThru = false; +let keepCache = true; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function proxyquire(request: string, stubs: Stubs = {}): T { + const sut = mod._resolveFilename(request, parent); + const resolved: Stubs = {}; + let global = false; + for (const [k, v] of Object.entries(stubs)) { + if (isGlobal(v)) global = true; + resolved[resolveFrom(sut, k)] = v; + } + const cache = require.cache; + const keys = global + ? Object.keys(cache).filter(id => !id.endsWith('.node')) + : [sut]; + const saved = keys.map(id => [id, cache[id]] as const); + for (const id of keys) delete cache[id]; + const prev = mod.prototype.require; + const req = function (this: NodeModule, id: string) { + const isSut = this?.filename === sut; + if (this?.filename && (isSut || global)) { + const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); + const rId = hit ? '' : resolveFrom(this.filename, id); + if (hit || hasOwn(resolved, rId)) { + const stub = hit ? stubs[id] : resolved[rId]; + if (isSut || isGlobal(stub)) { + if (stub === null) { + const e = new Error(`Cannot find module '${id}'`); + throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); + } + const skip = hasOwn(stub, '@noCallThru') + ? stub['@noCallThru'] + : skipCallThru; + if (!skip && stub && ['object', 'function'].includes(typeof stub)) { + try { + const real = prev.call(this, id); + if (real && ['object', 'function'].includes(typeof real)) { + for (const k of Object.keys(real)) { + if (!(k in stub)) stub[k] = real[k]; + } + } + } catch { + // ignore + } + } + return stub; + } + } + } + return prev.call(this, id); + }; + mod.prototype.require = Object.assign(req, prev); + try { + return prev.call(parent, request); + } finally { + mod.prototype.require = prev; + for (const id of global ? Object.keys(cache) : [sut]) { + if (!id.endsWith('.node')) delete cache[id]; + } + for (const [id, m] of saved) { + if (m && (keepCache || id !== sut)) cache[id] = m; + } + } +} + +// eslint-disable-next-line @typescript-eslint/no-namespace +namespace proxyquire { + export const load = proxyquire; + export const noCallThru = () => ((skipCallThru = true), proxyquire); + export const callThru = () => ((skipCallThru = false), proxyquire); + export const noPreserveCache = () => ((keepCache = false), proxyquire); + export const preserveCache = () => ((keepCache = true), proxyquire); +} + +export = proxyquire; diff --git a/handwritten/logging-winston/test/stackdriver-trace-integration.ts b/handwritten/logging-winston/test/stackdriver-trace-integration.ts index ed0e668c4bbb..9e62c33575e0 100644 --- a/handwritten/logging-winston/test/stackdriver-trace-integration.ts +++ b/handwritten/logging-winston/test/stackdriver-trace-integration.ts @@ -14,7 +14,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, after} from 'mocha'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as winston from 'winston'; import * as loggingWinstonLibTypes from '../src/index'; diff --git a/handwritten/logging/package.json b/handwritten/logging/package.json index 63a3d3261513..06363bb21952 100644 --- a/handwritten/logging/package.json +++ b/handwritten/logging/package.json @@ -40,7 +40,7 @@ "presystem-test": "pnpm run compile", "system-test": "node ../../bin/run-test.cjs build/system-test --timeout 600000", "pretest": "pnpm run compile", - "test": "cross-env NODE_OPTIONS='--no-deprecation' node ../../bin/run-test.cjs --proxyquire-shim build/test", + "test": "cross-env NODE_OPTIONS='--no-deprecation' node ../../bin/run-test.cjs build/test", "precompile": "gts clean", "postpublish": "./.kokoro/publish-min.sh" }, diff --git a/handwritten/logging/test/entry.ts b/handwritten/logging/test/entry.ts index d17976edd138..d9d994a8e44d 100644 --- a/handwritten/logging/test/entry.ts +++ b/handwritten/logging/test/entry.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as entryTypes from '../src/entry'; import * as common from '../src/utils/common'; import * as http from 'http'; @@ -222,7 +222,7 @@ describe('Entry', () => { it('should pass removeCircular to objToStruct_', done => { fakeObjToStruct = ( obj: {}, - options: common.ObjectToStructConverterConfig, + options: common.ObjectToStructConverterConfig ) => { assert.strictEqual(options.removeCircular, true); done(); @@ -325,7 +325,7 @@ describe('Entry', () => { }); after(() => { - sdk.shutdown(); + return sdk.shutdown(); }); it('should detect open telemetry trace and span if open telemetry context present', () => { @@ -335,12 +335,12 @@ describe('Entry', () => { const json = entry.toJSON(); assert.strictEqual( json.trace, - `projects//traces/${span.spanContext().traceId}`, + `projects//traces/${span.spanContext().traceId}` ); assert.strictEqual(json.spanId, span.spanContext().spanId); assert.strictEqual( json.traceSampled, - (span.spanContext().traceFlags & 1) !== 0, + (span.spanContext().traceFlags & 1) !== 0 ); }); }); @@ -360,12 +360,12 @@ describe('Entry', () => { const json = entry.toJSON(); assert.strictEqual( json.trace, - `projects//traces/${span.spanContext().traceId}`, + `projects//traces/${span.spanContext().traceId}` ); assert.strictEqual(json.spanId, span.spanContext().spanId); assert.strictEqual( json.traceSampled, - (span.spanContext().traceFlags & 1) !== 0, + (span.spanContext().traceFlags & 1) !== 0 ); }); }); @@ -413,7 +413,7 @@ describe('Entry', () => { entry.data = 'this is a log'; const json = entry.toStructuredJSON(); assert( - withinExpectedTimeBoundaries(nanosAndSecondsToDate(json.timestamp!)), + withinExpectedTimeBoundaries(nanosAndSecondsToDate(json.timestamp!)) ); delete json.timestamp; const expectedJSON = { @@ -441,7 +441,7 @@ describe('Entry', () => { entry.metadata.timestamp = new Date(); const json = entry.toStructuredJSON(); assert( - withinExpectedTimeBoundaries(nanosAndSecondsToDate(json.timestamp!)), + withinExpectedTimeBoundaries(nanosAndSecondsToDate(json.timestamp!)) ); }); @@ -503,7 +503,7 @@ describe('Entry', () => { }); after(() => { - sdk.shutdown(); + return sdk.shutdown(); }); it('should detect open telemetry trace and span if open telemetry context present', () => { @@ -513,15 +513,15 @@ describe('Entry', () => { const json = entry.toStructuredJSON(); assert.strictEqual( json[entryTypes.TRACE_KEY], - `projects//traces/${span.spanContext().traceId}`, + `projects//traces/${span.spanContext().traceId}` ); assert.strictEqual( json[entryTypes.SPAN_ID_KEY], - span.spanContext().spanId, + span.spanContext().spanId ); assert.strictEqual( json[entryTypes.TRACE_SAMPLED_KEY], - (span.spanContext().traceFlags & 1) !== 0, + (span.spanContext().traceFlags & 1) !== 0 ); }); }); @@ -541,15 +541,15 @@ describe('Entry', () => { const json = entry.toStructuredJSON(); assert.strictEqual( json[entryTypes.TRACE_KEY], - `projects//traces/${span.spanContext().traceId}`, + `projects//traces/${span.spanContext().traceId}` ); assert.strictEqual( json[entryTypes.SPAN_ID_KEY], - span.spanContext().spanId, + span.spanContext().spanId ); assert.strictEqual( json[entryTypes.TRACE_SAMPLED_KEY], - (span.spanContext().traceFlags & 1) !== 0, + (span.spanContext().traceFlags & 1) !== 0 ); }); }); @@ -571,7 +571,7 @@ describe('Entry', () => { assert.strictEqual(json[entryTypes.SPAN_ID_KEY], expected.spanId); assert.strictEqual( json[entryTypes.TRACE_SAMPLED_KEY], - expected.traceSampled, + expected.traceSampled ); }); }); diff --git a/handwritten/logging/test/index.ts b/handwritten/logging/test/index.ts index 73ae9f61581a..03663ed512dc 100644 --- a/handwritten/logging/test/index.ts +++ b/handwritten/logging/test/index.ts @@ -18,7 +18,7 @@ import arrify = require('arrify'); import * as assert from 'assert'; import {describe, it, beforeEach, before} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import { Logging as LOGGING, LoggingOptions, @@ -215,8 +215,8 @@ describe('Logging', () => { libVersion: version, scopes: EXPECTED_SCOPES, }, - options, - ), + options + ) ); return fakeGoogleAuthInstance; }; @@ -245,8 +245,8 @@ describe('Logging', () => { libVersion: version, scopes: EXPECTED_SCOPES, }, - options, - ), + options + ) ); }); @@ -270,7 +270,7 @@ describe('Logging', () => { it('should throw if a name is not provided', () => { const error = new Error('A sink name must be provided.'); // eslint-disable-next-line @typescript-eslint/no-explicit-any - (logging as any).createSink().then(noop, (err: Error) => { + return (logging as any).createSink().then(noop, (err: Error) => { assert.deepStrictEqual(err, error); }); }); @@ -278,7 +278,7 @@ describe('Logging', () => { it('should throw if a config object is not provided', () => { const error = new Error('A sink configuration object must be provided.'); // eslint-disable-next-line @typescript-eslint/no-explicit-any - (logging as any).createSink(SINK_NAME).then(noop, (err: Error) => { + return (logging as any).createSink(SINK_NAME).then(noop, (err: Error) => { assert.deepStrictEqual(err, error); }); }); @@ -354,7 +354,7 @@ describe('Logging', () => { logging.configService.createSink = async ( // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts: any, - gaxOpts: {}, + gaxOpts: {} ) => { const expectedParent = 'projects/' + logging.projectId; assert.strictEqual(reqOpts.parent, expectedParent); @@ -376,11 +376,11 @@ describe('Logging', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts: any, // eslint-disable-next-line @typescript-eslint/no-unused-vars - gaxOpts: {}, + gaxOpts: {} ) => { assert.strictEqual( reqOpts.uniqueWriterIdentity, - config.uniqueWriterIdentity, + config.uniqueWriterIdentity ); assert.strictEqual(reqOpts.sink.uniqueWriterIdentity, undefined); return [{}]; @@ -399,7 +399,7 @@ describe('Logging', () => { logging.configService.createSink = async ( // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts: any, - gaxOpts: {}, + gaxOpts: {} ) => { assert.strictEqual(reqOpts.sink.gaxOptions, undefined); assert.strictEqual(gaxOpts, config.gaxOptions); @@ -424,7 +424,7 @@ describe('Logging', () => { throw error; }; - logging + return logging .createSink(SINK_NAME, {} as CreateSinkRequest) .then(noop, (err: Error) => assert.deepStrictEqual(err, error)); }); @@ -455,7 +455,7 @@ describe('Logging', () => { const [sink_, apiResponse_] = await logging.createSink( SINK_NAME, - {} as CreateSinkRequest, + {} as CreateSinkRequest ); assert.strictEqual(sink_, sink); assert.strictEqual(sink_.metadata, apiResponse); @@ -487,7 +487,7 @@ describe('Logging', () => { logging.loggingService.listLogEntries = async ( // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts: any, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(reqOpts, { filter: reqOpts?.filter, @@ -512,7 +512,7 @@ describe('Logging', () => { logging.loggingService.listLogEntries = async ( // eslint-disable-next-line @typescript-eslint/no-explicit-any - reqOpts: any, + reqOpts: any ) => { assert.deepStrictEqual(reqOpts.resourceNames, resourceNames); return [[]]; @@ -526,7 +526,7 @@ describe('Logging', () => { logging.loggingService.listLogEntries = async ( reqOpts: {}, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual( reqOpts, @@ -534,7 +534,7 @@ describe('Logging', () => { filter: 'timestamp > "2020-11-11T15:01:23.045123456Z"', orderBy: 'timestamp desc', resourceNames: ['projects/' + logging.projectId], - }), + }) ); assert.deepStrictEqual(gaxOpts, { @@ -552,7 +552,7 @@ describe('Logging', () => { logging.loggingService.listLogEntries = async ( // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts: any, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual( reqOpts, @@ -560,7 +560,7 @@ describe('Logging', () => { filter: reqOpts?.filter, orderBy: 'timestamp desc', resourceNames: ['projects/' + logging.projectId], - }), + }) ); assert.deepStrictEqual(gaxOpts, { autoPaginate: undefined, @@ -614,7 +614,7 @@ describe('Logging', () => { logging.loggingService.listLogEntries = async ( // eslint-disable-next-line @typescript-eslint/no-explicit-any reqOpts: any, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(reqOpts, { a: 'b', @@ -643,7 +643,9 @@ describe('Logging', () => { }); it('should reject promise with error', () => { - logging.getEntries().then(noop, err => assert.strictEqual(err, error)); + return logging + .getEntries() + .then(noop, err => assert.strictEqual(err, error)); }); }); @@ -692,7 +694,7 @@ describe('Logging', () => { it('should make request once reading', done => { logging.loggingService.listLogEntriesStream = ( reqOpts: {}, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(reqOpts, { resourceNames: ['projects/' + logging.projectId], @@ -721,7 +723,7 @@ describe('Logging', () => { logging = new LOGGING({projectId: PROJECT_ID}); logging.loggingService.listLogEntriesStream = ( reqOpts: {}, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(reqOpts, { resourceNames: ['projects/' + logging.projectId], @@ -758,12 +760,12 @@ describe('Logging', () => { { filter: 'custom filter', }, - OPTIONS, + OPTIONS ); logging = new LOGGING({projectId: PROJECT_ID}); logging.loggingService.listLogEntriesStream = ( reqOpts: {}, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(reqOpts, { resourceNames: ['projects/' + logging.projectId], @@ -908,7 +910,7 @@ describe('Logging', () => { logging.loggingService.listLogs = async () => { throw error; }; - logging + return logging .getLogs(OPTIONS) .then(noop, err => assert.strictEqual(err, error)); }); @@ -1079,7 +1081,7 @@ describe('Logging', () => { logging.configService.listSinks = async () => { throw error; }; - logging + return logging .getSinks(OPTIONS) .then(noop, err => assert.strictEqual(err, error)); }); @@ -1561,7 +1563,7 @@ describe('Logging', () => { }); it('should return error', () => { - logging + return logging .setAclForBucket_(CONFIG) .then(noop, err => assert.deepStrictEqual(err, error)); }); @@ -1610,7 +1612,7 @@ describe('Logging', () => { }); it('should reject with error', () => { - logging + return logging .setAclForDataset_(CONFIG) .then(noop, err => assert.deepStrictEqual(err, error)); }); @@ -1658,7 +1660,7 @@ describe('Logging', () => { }); it('should reject with error', () => { - logging + return logging .setAclForDataset_(CONFIG) .then(noop, err => assert.deepStrictEqual(err, error)); }); @@ -1717,7 +1719,7 @@ describe('Logging', () => { }); it('should throw error', () => { - logging + return logging .setAclForTopic_(CONFIG) .then(noop, err => assert.deepStrictEqual(err, error)); }); @@ -1764,7 +1766,7 @@ describe('Logging', () => { }); it('should throw error', () => { - logging + return logging .setAclForTopic_(CONFIG) .then(noop, err => assert.deepStrictEqual(err, error)); }); diff --git a/handwritten/logging/test/log.ts b/handwritten/logging/test/log.ts index e535e739b694..3efb9dfbf2ae 100644 --- a/handwritten/logging/test/log.ts +++ b/handwritten/logging/test/log.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import {Entry, Logging} from '../src'; import {Log as LOG, LogOptions, WriteOptions} from '../src/log'; @@ -123,8 +123,8 @@ describe('Log', () => { assert( callbackifyFake.callbackifyAll.calledWithExactly( Log, - sinon.match({exclude: ['entry', 'getEntriesStream']}), - ), + sinon.match({exclude: ['entry', 'getEntriesStream']}) + ) ); }); @@ -140,7 +140,7 @@ describe('Log', () => { const log = new Log(LOGGING, LOG_NAME); assert.strictEqual( log.formattedName_, - logCommon.formatLogName('{{project-id}}', LOG_NAME), + logCommon.formatLogName('{{project-id}}', LOG_NAME) ); }); @@ -172,8 +172,8 @@ describe('Log', () => { logName: log.formattedName_, }, undefined, - undefined, - ), + undefined + ) ); }); @@ -186,8 +186,8 @@ describe('Log', () => { logName: log.formattedName_, }, undefined, - log.defaultWriteDeleteCallback, - ), + log.defaultWriteDeleteCallback + ) ); log.defaultWriteDeleteCallback = undefined; }); @@ -195,7 +195,7 @@ describe('Log', () => { it('should accept gaxOptions', async () => { await log.delete({}); assert( - log.logging.loggingService.deleteLog.calledWith(sinon.match.any, {}), + log.logging.loggingService.deleteLog.calledWith(sinon.match.any, {}) ); }); }); @@ -235,7 +235,7 @@ describe('Log', () => { assert( log.logging.getEntries.calledWithExactly({ filter: `logName="${LOG_NAME_FORMATTED}"`, - }), + }) ); }); @@ -273,7 +273,7 @@ describe('Log', () => { assert( log.logging.getEntriesStream.calledWithExactly({ log: LOG_NAME_ENCODED, - }), + }) ); }); @@ -292,9 +292,9 @@ describe('Log', () => { { log: LOG_NAME_ENCODED, }, - options, - ), - ), + options + ) + ) ); }); }); @@ -312,7 +312,7 @@ describe('Log', () => { assert( log.logging.tailEntries.calledWithExactly({ log: LOG_NAME_ENCODED, - }), + }) ); }); @@ -331,9 +331,9 @@ describe('Log', () => { { log: LOG_NAME_ENCODED, }, - options, - ), - ), + options + ) + ) ); }); }); @@ -388,8 +388,8 @@ describe('Log', () => { }, }, undefined, - undefined, - ), + undefined + ) ); }); @@ -424,8 +424,8 @@ describe('Log', () => { log.logging.loggingService.writeLogEntries.calledOnceWith( sinon.match({ resource: reusableDetectedResource, - }), - ), + }) + ) ); }); @@ -454,8 +454,8 @@ describe('Log', () => { resource: EXPECTED_RESOURCE, }, undefined, - undefined, - ), + undefined + ) ); }); @@ -470,8 +470,8 @@ describe('Log', () => { resource: FAKE_RESOURCE, }, undefined, - undefined, - ), + undefined + ) ); }); @@ -487,8 +487,8 @@ describe('Log', () => { resource: FAKE_RESOURCE, }, undefined, - log.defaultWriteDeleteCallback, - ), + log.defaultWriteDeleteCallback + ) ); log.defaultWriteDeleteCallback = undefined; }); @@ -503,8 +503,8 @@ describe('Log', () => { log.logging.loggingService.writeLogEntries.calledOnceWith( sinon.match({ entries: 'decorated entries', - }), - ), + }) + ) ); }); @@ -517,8 +517,8 @@ describe('Log', () => { log.logging.loggingService.writeLogEntries.calledOnceWith( sinon.match({ entries: arrifiedEntries, - }), - ), + }) + ) ); }); @@ -530,8 +530,8 @@ describe('Log', () => { log.logging.loggingService.writeLogEntries.calledOnceWith( sinon.match({ entries: ENTRIES, - }), - ), + }) + ) ); }); @@ -541,8 +541,8 @@ describe('Log', () => { log.logging.loggingService.writeLogEntries.calledOnceWith( sinon.match({ partialSuccess: true, - }), - ), + }) + ) ); }); @@ -553,8 +553,8 @@ describe('Log', () => { sinon.match({ dryRun: true, partialSuccess: false, - }), - ), + }) + ) ); }); @@ -567,8 +567,8 @@ describe('Log', () => { log.logging.loggingService.writeLogEntries.calledOnceWith( sinon.match({ partialSuccess: true, - }), - ), + }) + ) ); instrumentation.setInstrumentationStatus(true); }); @@ -582,8 +582,8 @@ describe('Log', () => { log.logging.loggingService.writeLogEntries.calledOnceWith( sinon.match({ partialSuccess: true, - }), - ), + }) + ) ); }); @@ -597,8 +597,8 @@ describe('Log', () => { { maxRetries: 1, }, - sinon.match.any, - ), + sinon.match.any + ) ); log.logging.loggingService.writeLogEntries.reset(); await log.write(ENTRIES, {gaxOptions: {maxRetries: 10}}); @@ -608,8 +608,8 @@ describe('Log', () => { { maxRetries: 10, }, - sinon.match.any, - ), + sinon.match.any + ) ); }); }); @@ -656,7 +656,7 @@ describe('Log', () => { .returns({} as EntryJson); log.decorateEntries([entry]); assert( - localJSONStub.calledWithExactly({removeCircular: true}, PROJECT_ID), + localJSONStub.calledWithExactly({removeCircular: true}, PROJECT_ID) ); }); @@ -749,11 +749,11 @@ describe('Log', () => { assert.ok(log.jsonFieldsToTruncate.length > 1); assert.ok(log.jsonFieldsToTruncate[0] === TRUNCATE_FIELD); const notExists = log.jsonFieldsToTruncate.filter( - (str: string) => str === INVALID_TRUNCATE_FIELD, + (str: string) => str === INVALID_TRUNCATE_FIELD ); assert.strictEqual(notExists.length, 0); const existOnce = log.jsonFieldsToTruncate.filter( - (str: string) => str === TRUNCATE_FIELD, + (str: string) => str === TRUNCATE_FIELD ); assert.strictEqual(existOnce.length, 1); }); diff --git a/handwritten/logging/test/middleware/express/test-make-middleware.ts b/handwritten/logging/test/middleware/express/test-make-middleware.ts index 47740b2ad306..5444e2fc698e 100644 --- a/handwritten/logging/test/middleware/express/test-make-middleware.ts +++ b/handwritten/logging/test/middleware/express/test-make-middleware.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import * as EventEmitter from 'events'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from '../../proxyquire'; const FAKE_PROJECT_ID = 'project-🦄'; @@ -45,7 +45,7 @@ describe('middleware/express/make-middleware', () => { '../../../src/middleware/express/make-middleware', { '../../../src/utils/context': FAKE_CONTEXT, - }, + } ); it('should return a function accepting 3 arguments', () => { @@ -133,7 +133,7 @@ describe('middleware/express/make-middleware', () => { const middleware = makeMiddleware( FAKE_PROJECT_ID, () => {}, - emitRequestLog, + emitRequestLog ); middleware(fakeRequest, fakeResponse, () => {}); diff --git a/handwritten/logging/test/proxyquire.ts b/handwritten/logging/test/proxyquire.ts new file mode 100644 index 000000000000..44ff9f689c12 --- /dev/null +++ b/handwritten/logging/test/proxyquire.ts @@ -0,0 +1,115 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as Module from 'module'; +import * as path from 'path'; + +delete require.cache[require.resolve(__filename)]; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Stubs = Record; +const mod = Module as unknown as { + prototype: {require: NodeRequire}; + _resolveFilename: (request: string, parent: NodeModule) => string; +}; +const {hasOwnProperty} = Object.prototype; +const hasOwn = (o: unknown, k: string) => + Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isGlobal = (s: unknown) => + hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); +const resolveFrom = (base: string, req: string) => { + try { + return require.resolve(req, {paths: [path.dirname(base)]}); + } catch { + return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; + } +}; + +const parent = module.parent || module; +let skipCallThru = false; +let keepCache = true; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function proxyquire(request: string, stubs: Stubs = {}): T { + const sut = mod._resolveFilename(request, parent); + const resolved: Stubs = {}; + let global = false; + for (const [k, v] of Object.entries(stubs)) { + if (isGlobal(v)) global = true; + resolved[resolveFrom(sut, k)] = v; + } + const cache = require.cache; + const keys = global + ? Object.keys(cache).filter(id => !id.endsWith('.node')) + : [sut]; + const saved = keys.map(id => [id, cache[id]] as const); + for (const id of keys) delete cache[id]; + const prev = mod.prototype.require; + const req = function (this: NodeModule, id: string) { + const isSut = this?.filename === sut; + if (this?.filename && (isSut || global)) { + const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); + const rId = hit ? '' : resolveFrom(this.filename, id); + if (hit || hasOwn(resolved, rId)) { + const stub = hit ? stubs[id] : resolved[rId]; + if (isSut || isGlobal(stub)) { + if (stub === null) { + const e = new Error(`Cannot find module '${id}'`); + throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); + } + const skip = hasOwn(stub, '@noCallThru') + ? stub['@noCallThru'] + : skipCallThru; + if (!skip && stub && ['object', 'function'].includes(typeof stub)) { + try { + const real = prev.call(this, id); + if (real && ['object', 'function'].includes(typeof real)) { + for (const k of Object.keys(real)) { + if (!(k in stub)) stub[k] = real[k]; + } + } + } catch { + // ignore + } + } + return stub; + } + } + } + return prev.call(this, id); + }; + mod.prototype.require = Object.assign(req, prev); + try { + return prev.call(parent, request); + } finally { + mod.prototype.require = prev; + for (const id of global ? Object.keys(cache) : [sut]) { + if (!id.endsWith('.node')) delete cache[id]; + } + for (const [id, m] of saved) { + if (m && (keepCache || id !== sut)) cache[id] = m; + } + } +} + +// eslint-disable-next-line @typescript-eslint/no-namespace +namespace proxyquire { + export const load = proxyquire; + export const noCallThru = () => ((skipCallThru = true), proxyquire); + export const callThru = () => ((skipCallThru = false), proxyquire); + export const noPreserveCache = () => ((keepCache = false), proxyquire); + export const preserveCache = () => ((keepCache = true), proxyquire); +} + +export = proxyquire; diff --git a/handwritten/logging/test/sink.ts b/handwritten/logging/test/sink.ts index 598e63c70bf7..f5a6c747bb2e 100644 --- a/handwritten/logging/test/sink.ts +++ b/handwritten/logging/test/sink.ts @@ -16,7 +16,7 @@ import * as callbackify from '@google-cloud/promisify'; import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import {Sink as SINK} from '../src/sink'; import {Logging, CreateSinkRequest, LogSink} from '../src/index'; @@ -75,7 +75,7 @@ describe('Sink', () => { it('should localize the formatted name', () => { assert.strictEqual( sink.formattedName_, - 'projects/' + LOGGING.projectId + '/sinks/' + SINK_NAME, + 'projects/' + LOGGING.projectId + '/sinks/' + SINK_NAME ); }); }); @@ -98,7 +98,7 @@ describe('Sink', () => { sink.logging.auth.getProjectId = async () => PROJECT_ID; sink.logging.configService.deleteSink = async ( reqOpts: {}, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(reqOpts, { sinkName: sink.formattedName_, @@ -113,7 +113,7 @@ describe('Sink', () => { const gaxOptions = {}; sink.logging.configService.deleteSink = async ( reqOpts: {}, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(gaxOpts, gaxOptions); }; @@ -201,9 +201,9 @@ describe('Sink', () => { sink.getMetadata = async () => { throw error; }; - sink.setMetadata(METADATA).then( - () => {}, - err => assert.strictEqual(err, error), + return sink.setMetadata(METADATA).then( + () => null, + err => assert.strictEqual(err, error) ); }); @@ -213,7 +213,7 @@ describe('Sink', () => { sink.getMetadata = async () => [currentMetadata] as any; sink.logging.configService.updateSink = async ( reqOpts: {}, - gaxOpts: {}, + gaxOpts: {} ) => { assert.deepStrictEqual(reqOpts, { sinkName: sink.formattedName_, diff --git a/handwritten/logging/test/utils/metadata.ts b/handwritten/logging/test/utils/metadata.ts index 9425f8ff5436..0e32e59f2853 100644 --- a/handwritten/logging/test/utils/metadata.ts +++ b/handwritten/logging/test/utils/metadata.ts @@ -17,7 +17,7 @@ import {describe, it, beforeEach, before, after, afterEach} from 'mocha'; import BigNumber from 'bignumber.js'; import * as extend from 'extend'; import {GCPEnv} from 'google-auth-library'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from '../proxyquire'; let instanceOverride: {} | null; const fakeGcpMetadata = { @@ -298,7 +298,7 @@ describe('metadata', () => { }; await assert.rejects( metadata.getGKEDescriptor(), - (err: Error) => err === FAKE_ERROR, + (err: Error) => err === FAKE_ERROR ); }); @@ -306,7 +306,7 @@ describe('metadata', () => { readFileShouldError = true; await assert.doesNotReject(metadata.getGKEDescriptor(), (err: Error) => - err.message.includes(FAKE_READFILE_ERROR_MESSAGE), + err.message.includes(FAKE_READFILE_ERROR_MESSAGE) ); }); }); diff --git a/handwritten/pubsub/package.json b/handwritten/pubsub/package.json index 866f3c601933..4f5993ad4447 100644 --- a/handwritten/pubsub/package.json +++ b/handwritten/pubsub/package.json @@ -35,7 +35,7 @@ "system-test": "node ../../bin/run-test.cjs build/system-test --timeout 600000", "samples-test": "pnpm run link-samples && pnpm test && cd ../", "link-samples": "cd samples/ && pnpm link ../ && pnpm install", - "test": "node ../../bin/run-test.cjs --proxyquire-shim build/test", + "test": "node ../../bin/run-test.cjs build/test", "lint": "gts check", "predocs": "pnpm run compile", "docs": "jsdoc -c .jsdoc.js", diff --git a/handwritten/pubsub/test/iam.ts b/handwritten/pubsub/test/iam.ts index a1f73f8bf35d..6232a51e37ac 100644 --- a/handwritten/pubsub/test/iam.ts +++ b/handwritten/pubsub/test/iam.ts @@ -14,7 +14,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach} from 'mocha'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as iamTypes from '../src/iam'; import {PubSub, RequestConfig} from '../src/pubsub'; diff --git a/handwritten/pubsub/test/lease-manager.ts b/handwritten/pubsub/test/lease-manager.ts index d7fc2d8a2cfd..a5088a5d1813 100644 --- a/handwritten/pubsub/test/lease-manager.ts +++ b/handwritten/pubsub/test/lease-manager.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import * as defer from 'p-defer'; @@ -208,10 +208,7 @@ describe('LeaseManager', () => { subscriber.on('message', () => { assert.strictEqual(fakeLog!.called, true); - assert.strictEqual( - fakeLog!.fields!.severity, - 'INFO', - ); + assert.strictEqual(fakeLog!.fields!.severity, 'INFO'); assert.strictEqual(fakeLog!.args![1] as string, 'a'); assert.strictEqual(fakeLog!.args![2] as string, 'b'); done(); @@ -241,10 +238,7 @@ describe('LeaseManager', () => { await deferred.promise; assert.strictEqual(fakeLog.called, true); - assert.strictEqual( - fakeLog.fields!.severity, - 'ERROR', - ); + assert.strictEqual(fakeLog.fields!.severity, 'ERROR'); assert.strictEqual( (fakeLog.args![0] as string).includes('exception'), true, @@ -402,10 +396,7 @@ describe('LeaseManager', () => { // make sure the expired messages were forgotten assert.strictEqual(removeStub.callCount, badMessages.length); - assert.strictEqual( - fakeLog.fields!.severity, - 'WARNING', - ); + assert.strictEqual(fakeLog.fields!.severity, 'WARNING'); assert.strictEqual(fakeLog.called, true); badMessages.forEach((fakeMessage, i) => { diff --git a/handwritten/pubsub/test/message-stream.ts b/handwritten/pubsub/test/message-stream.ts index e9a0a5a1fad2..0d921e038ba8 100644 --- a/handwritten/pubsub/test/message-stream.ts +++ b/handwritten/pubsub/test/message-stream.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {grpc} from 'google-gax'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import {Duplex, PassThrough} from 'stream'; import * as defer from 'p-defer'; diff --git a/handwritten/pubsub/test/proxyquire.ts b/handwritten/pubsub/test/proxyquire.ts new file mode 100644 index 000000000000..44ff9f689c12 --- /dev/null +++ b/handwritten/pubsub/test/proxyquire.ts @@ -0,0 +1,115 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import * as Module from 'module'; +import * as path from 'path'; + +delete require.cache[require.resolve(__filename)]; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Stubs = Record; +const mod = Module as unknown as { + prototype: {require: NodeRequire}; + _resolveFilename: (request: string, parent: NodeModule) => string; +}; +const {hasOwnProperty} = Object.prototype; +const hasOwn = (o: unknown, k: string) => + Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isGlobal = (s: unknown) => + hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); +const resolveFrom = (base: string, req: string) => { + try { + return require.resolve(req, {paths: [path.dirname(base)]}); + } catch { + return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; + } +}; + +const parent = module.parent || module; +let skipCallThru = false; +let keepCache = true; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function proxyquire(request: string, stubs: Stubs = {}): T { + const sut = mod._resolveFilename(request, parent); + const resolved: Stubs = {}; + let global = false; + for (const [k, v] of Object.entries(stubs)) { + if (isGlobal(v)) global = true; + resolved[resolveFrom(sut, k)] = v; + } + const cache = require.cache; + const keys = global + ? Object.keys(cache).filter(id => !id.endsWith('.node')) + : [sut]; + const saved = keys.map(id => [id, cache[id]] as const); + for (const id of keys) delete cache[id]; + const prev = mod.prototype.require; + const req = function (this: NodeModule, id: string) { + const isSut = this?.filename === sut; + if (this?.filename && (isSut || global)) { + const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); + const rId = hit ? '' : resolveFrom(this.filename, id); + if (hit || hasOwn(resolved, rId)) { + const stub = hit ? stubs[id] : resolved[rId]; + if (isSut || isGlobal(stub)) { + if (stub === null) { + const e = new Error(`Cannot find module '${id}'`); + throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); + } + const skip = hasOwn(stub, '@noCallThru') + ? stub['@noCallThru'] + : skipCallThru; + if (!skip && stub && ['object', 'function'].includes(typeof stub)) { + try { + const real = prev.call(this, id); + if (real && ['object', 'function'].includes(typeof real)) { + for (const k of Object.keys(real)) { + if (!(k in stub)) stub[k] = real[k]; + } + } + } catch { + // ignore + } + } + return stub; + } + } + } + return prev.call(this, id); + }; + mod.prototype.require = Object.assign(req, prev); + try { + return prev.call(parent, request); + } finally { + mod.prototype.require = prev; + for (const id of global ? Object.keys(cache) : [sut]) { + if (!id.endsWith('.node')) delete cache[id]; + } + for (const [id, m] of saved) { + if (m && (keepCache || id !== sut)) cache[id] = m; + } + } +} + +// eslint-disable-next-line @typescript-eslint/no-namespace +namespace proxyquire { + export const load = proxyquire; + export const noCallThru = () => ((skipCallThru = true), proxyquire); + export const callThru = () => ((skipCallThru = false), proxyquire); + export const noPreserveCache = () => ((keepCache = false), proxyquire); + export const preserveCache = () => ((keepCache = true), proxyquire); +} + +export = proxyquire; diff --git a/handwritten/pubsub/test/publisher/index.ts b/handwritten/pubsub/test/publisher/index.ts index 6930b3baa67e..f4fa95908ba2 100644 --- a/handwritten/pubsub/test/publisher/index.ts +++ b/handwritten/pubsub/test/publisher/index.ts @@ -18,7 +18,7 @@ import * as pfy from '@google-cloud/promisify'; import * as assert from 'assert'; import {describe, it, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from '../proxyquire'; import * as sinon from 'sinon'; import * as opentelemetry from '@opentelemetry/api'; import {Topic} from '../../src'; diff --git a/handwritten/pubsub/test/publisher/message-queues.ts b/handwritten/pubsub/test/publisher/message-queues.ts index c6d0b3309987..343906dd6833 100644 --- a/handwritten/pubsub/test/publisher/message-queues.ts +++ b/handwritten/pubsub/test/publisher/message-queues.ts @@ -18,7 +18,7 @@ import {loggingUtils, ServiceError} from 'google-gax'; import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from '../proxyquire'; import * as sinon from 'sinon'; import {RequestConfig, RequestCallback} from '../../src/pubsub'; @@ -187,10 +187,7 @@ describe('Message Queues', () => { fakeLog.remove(); assert.strictEqual(fakeLog.called, true); - assert.strictEqual( - fakeLog.fields!.severity, - 'INFO', - ); + assert.strictEqual(fakeLog.fields!.severity, 'INFO'); assert.strictEqual(fakeLog.args![1] as string, 'test'); }); @@ -394,6 +391,7 @@ describe('Message Queues', () => { queue.batch = new FakeMessageBatch(); queue.batch.messages = fakeMessages; queue.batch.callbacks = spies; + // eslint-disable-next-line promise/always-return void queue.publishDrain().then(() => { process.nextTick(() => { assert.strictEqual(stub.callCount, 2); @@ -429,6 +427,7 @@ describe('Message Queues', () => { sandbox.stub(queue, '_publish').callsFake(async () => {}); queue.on('drain', spy); + // eslint-disable-next-line promise/always-return void queue.publish('test').then(() => { process.nextTick(() => { assert.strictEqual(spy.callCount, 1); diff --git a/handwritten/pubsub/test/pubsub.ts b/handwritten/pubsub/test/pubsub.ts index b2ecbfa7d29f..06f4547a09eb 100644 --- a/handwritten/pubsub/test/pubsub.ts +++ b/handwritten/pubsub/test/pubsub.ts @@ -17,7 +17,7 @@ import arrify = require('arrify'); import * as assert from 'assert'; import {describe, it, before, beforeEach, after, afterEach} from 'mocha'; import * as gax from 'google-gax'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import defer = require('p-defer'); @@ -196,7 +196,7 @@ describe('PubSub', () => { './snapshot': {Snapshot: FakeSnapshot}, './subscription': {Subscription}, './topic': {Topic: FakeTopic}, - './index': {v1:v1Override}, + './index': {v1: v1Override}, './util': fakeUtil, }).PubSub; }); diff --git a/handwritten/pubsub/test/snapshot.ts b/handwritten/pubsub/test/snapshot.ts index 5e5da3efec7a..cd781fe09e8d 100644 --- a/handwritten/pubsub/test/snapshot.ts +++ b/handwritten/pubsub/test/snapshot.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {ServiceError} from 'google-gax'; import {describe, it, beforeEach, before, after, afterEach} from 'mocha'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import {PubSub, RequestConfig} from '../src/pubsub'; diff --git a/handwritten/pubsub/test/subscriber.ts b/handwritten/pubsub/test/subscriber.ts index a0c4b0336b96..a6051a7aa459 100644 --- a/handwritten/pubsub/test/subscriber.ts +++ b/handwritten/pubsub/test/subscriber.ts @@ -19,7 +19,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; import {common as protobuf} from 'protobufjs'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import {PassThrough} from 'stream'; import * as opentelemetry from '@opentelemetry/api'; diff --git a/handwritten/pubsub/test/subscription.ts b/handwritten/pubsub/test/subscription.ts index 4855ec9217a5..5577c6b0e794 100644 --- a/handwritten/pubsub/test/subscription.ts +++ b/handwritten/pubsub/test/subscription.ts @@ -16,7 +16,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; import {ServiceError} from 'google-gax'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import {PubSub, RequestConfig} from '../src/pubsub'; diff --git a/handwritten/pubsub/test/topic.ts b/handwritten/pubsub/test/topic.ts index c918b21c64e9..4e2f736e48b1 100644 --- a/handwritten/pubsub/test/topic.ts +++ b/handwritten/pubsub/test/topic.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {CallOptions, ServiceError} from 'google-gax'; -import * as proxyquire from 'proxyquire'; +import * as proxyquire from './proxyquire'; import * as sinon from 'sinon'; import {google} from '../protos/protos'; From 1b74f20040cd32307a433ae55b96fde9542b69ed Mon Sep 17 00:00:00 2001 From: Daniel Bruce Date: Mon, 19 Oct 2026 14:43:47 +0000 Subject: [PATCH 2/4] [Address CI errors] test: support function stubs and guard read-only properties in proxyquire helper --- handwritten/logging-bunyan/test/proxyquire.ts | 13 ++++++++++--- handwritten/logging-winston/test/proxyquire.ts | 13 ++++++++++--- handwritten/logging/test/proxyquire.ts | 13 ++++++++++--- handwritten/pubsub/test/proxyquire.ts | 13 ++++++++++--- 4 files changed, 40 insertions(+), 12 deletions(-) diff --git a/handwritten/logging-bunyan/test/proxyquire.ts b/handwritten/logging-bunyan/test/proxyquire.ts index 44ff9f689c12..5d344ba47dad 100644 --- a/handwritten/logging-bunyan/test/proxyquire.ts +++ b/handwritten/logging-bunyan/test/proxyquire.ts @@ -24,8 +24,9 @@ const mod = Module as unknown as { _resolveFilename: (request: string, parent: NodeModule) => string; }; const {hasOwnProperty} = Object.prototype; -const hasOwn = (o: unknown, k: string) => - Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isObj = (o: unknown) => + Boolean(o && (typeof o === 'object' || typeof o === 'function')); +const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); const isGlobal = (s: unknown) => hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); const resolveFrom = (base: string, req: string) => { @@ -76,7 +77,13 @@ function proxyquire(request: string, stubs: Stubs = {}): T { const real = prev.call(this, id); if (real && ['object', 'function'].includes(typeof real)) { for (const k of Object.keys(real)) { - if (!(k in stub)) stub[k] = real[k]; + if (!(k in stub)) { + try { + stub[k] = real[k]; + } catch { + // ignore + } + } } } } catch { diff --git a/handwritten/logging-winston/test/proxyquire.ts b/handwritten/logging-winston/test/proxyquire.ts index 44ff9f689c12..5d344ba47dad 100644 --- a/handwritten/logging-winston/test/proxyquire.ts +++ b/handwritten/logging-winston/test/proxyquire.ts @@ -24,8 +24,9 @@ const mod = Module as unknown as { _resolveFilename: (request: string, parent: NodeModule) => string; }; const {hasOwnProperty} = Object.prototype; -const hasOwn = (o: unknown, k: string) => - Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isObj = (o: unknown) => + Boolean(o && (typeof o === 'object' || typeof o === 'function')); +const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); const isGlobal = (s: unknown) => hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); const resolveFrom = (base: string, req: string) => { @@ -76,7 +77,13 @@ function proxyquire(request: string, stubs: Stubs = {}): T { const real = prev.call(this, id); if (real && ['object', 'function'].includes(typeof real)) { for (const k of Object.keys(real)) { - if (!(k in stub)) stub[k] = real[k]; + if (!(k in stub)) { + try { + stub[k] = real[k]; + } catch { + // ignore + } + } } } } catch { diff --git a/handwritten/logging/test/proxyquire.ts b/handwritten/logging/test/proxyquire.ts index 44ff9f689c12..5d344ba47dad 100644 --- a/handwritten/logging/test/proxyquire.ts +++ b/handwritten/logging/test/proxyquire.ts @@ -24,8 +24,9 @@ const mod = Module as unknown as { _resolveFilename: (request: string, parent: NodeModule) => string; }; const {hasOwnProperty} = Object.prototype; -const hasOwn = (o: unknown, k: string) => - Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isObj = (o: unknown) => + Boolean(o && (typeof o === 'object' || typeof o === 'function')); +const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); const isGlobal = (s: unknown) => hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); const resolveFrom = (base: string, req: string) => { @@ -76,7 +77,13 @@ function proxyquire(request: string, stubs: Stubs = {}): T { const real = prev.call(this, id); if (real && ['object', 'function'].includes(typeof real)) { for (const k of Object.keys(real)) { - if (!(k in stub)) stub[k] = real[k]; + if (!(k in stub)) { + try { + stub[k] = real[k]; + } catch { + // ignore + } + } } } } catch { diff --git a/handwritten/pubsub/test/proxyquire.ts b/handwritten/pubsub/test/proxyquire.ts index 44ff9f689c12..5d344ba47dad 100644 --- a/handwritten/pubsub/test/proxyquire.ts +++ b/handwritten/pubsub/test/proxyquire.ts @@ -24,8 +24,9 @@ const mod = Module as unknown as { _resolveFilename: (request: string, parent: NodeModule) => string; }; const {hasOwnProperty} = Object.prototype; -const hasOwn = (o: unknown, k: string) => - Boolean(o && typeof o === 'object' && hasOwnProperty.call(o, k)); +const isObj = (o: unknown) => + Boolean(o && (typeof o === 'object' || typeof o === 'function')); +const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); const isGlobal = (s: unknown) => hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); const resolveFrom = (base: string, req: string) => { @@ -76,7 +77,13 @@ function proxyquire(request: string, stubs: Stubs = {}): T { const real = prev.call(this, id); if (real && ['object', 'function'].includes(typeof real)) { for (const k of Object.keys(real)) { - if (!(k in stub)) stub[k] = real[k]; + if (!(k in stub)) { + try { + stub[k] = real[k]; + } catch { + // ignore + } + } } } } catch { From 3ab82400b83395f3510de173ece49f0ed60c6f71 Mon Sep 17 00:00:00 2001 From: Daniel Bruce Date: Mon, 19 Oct 2026 16:02:11 +0000 Subject: [PATCH 3/4] [Address review comments] test(logging): use assert.rejects for promise rejection assertions --- handwritten/logging/test/index.ts | 47 +++++++++---------------------- handwritten/logging/test/sink.ts | 5 +--- 2 files changed, 15 insertions(+), 37 deletions(-) diff --git a/handwritten/logging/test/index.ts b/handwritten/logging/test/index.ts index 03663ed512dc..2bbdc411e914 100644 --- a/handwritten/logging/test/index.ts +++ b/handwritten/logging/test/index.ts @@ -270,17 +270,13 @@ describe('Logging', () => { it('should throw if a name is not provided', () => { const error = new Error('A sink name must be provided.'); // eslint-disable-next-line @typescript-eslint/no-explicit-any - return (logging as any).createSink().then(noop, (err: Error) => { - assert.deepStrictEqual(err, error); - }); + return assert.rejects((logging as any).createSink(), error); }); it('should throw if a config object is not provided', () => { const error = new Error('A sink configuration object must be provided.'); // eslint-disable-next-line @typescript-eslint/no-explicit-any - return (logging as any).createSink(SINK_NAME).then(noop, (err: Error) => { - assert.deepStrictEqual(err, error); - }); + return assert.rejects((logging as any).createSink(SINK_NAME), error); }); it('should set acls for a Dataset destination', async () => { @@ -424,9 +420,10 @@ describe('Logging', () => { throw error; }; - return logging - .createSink(SINK_NAME, {} as CreateSinkRequest) - .then(noop, (err: Error) => assert.deepStrictEqual(err, error)); + return assert.rejects( + logging.createSink(SINK_NAME, {} as CreateSinkRequest), + error + ); }); }); @@ -643,9 +640,7 @@ describe('Logging', () => { }); it('should reject promise with error', () => { - return logging - .getEntries() - .then(noop, err => assert.strictEqual(err, error)); + return assert.rejects(logging.getEntries(), error); }); }); @@ -910,9 +905,7 @@ describe('Logging', () => { logging.loggingService.listLogs = async () => { throw error; }; - return logging - .getLogs(OPTIONS) - .then(noop, err => assert.strictEqual(err, error)); + return assert.rejects(logging.getLogs(OPTIONS), error); }); }); @@ -1081,9 +1074,7 @@ describe('Logging', () => { logging.configService.listSinks = async () => { throw error; }; - return logging - .getSinks(OPTIONS) - .then(noop, err => assert.strictEqual(err, error)); + return assert.rejects(logging.getSinks(OPTIONS), error); }); }); @@ -1563,9 +1554,7 @@ describe('Logging', () => { }); it('should return error', () => { - return logging - .setAclForBucket_(CONFIG) - .then(noop, err => assert.deepStrictEqual(err, error)); + return assert.rejects(logging.setAclForBucket_(CONFIG), error); }); }); @@ -1612,9 +1601,7 @@ describe('Logging', () => { }); it('should reject with error', () => { - return logging - .setAclForDataset_(CONFIG) - .then(noop, err => assert.deepStrictEqual(err, error)); + return assert.rejects(logging.setAclForDataset_(CONFIG), error); }); }); @@ -1660,9 +1647,7 @@ describe('Logging', () => { }); it('should reject with error', () => { - return logging - .setAclForDataset_(CONFIG) - .then(noop, err => assert.deepStrictEqual(err, error)); + return assert.rejects(logging.setAclForDataset_(CONFIG), error); }); }); @@ -1719,9 +1704,7 @@ describe('Logging', () => { }); it('should throw error', () => { - return logging - .setAclForTopic_(CONFIG) - .then(noop, err => assert.deepStrictEqual(err, error)); + return assert.rejects(logging.setAclForTopic_(CONFIG), error); }); }); @@ -1766,9 +1749,7 @@ describe('Logging', () => { }); it('should throw error', () => { - return logging - .setAclForTopic_(CONFIG) - .then(noop, err => assert.deepStrictEqual(err, error)); + return assert.rejects(logging.setAclForTopic_(CONFIG), error); }); }); diff --git a/handwritten/logging/test/sink.ts b/handwritten/logging/test/sink.ts index f5a6c747bb2e..303e14f8c80b 100644 --- a/handwritten/logging/test/sink.ts +++ b/handwritten/logging/test/sink.ts @@ -201,10 +201,7 @@ describe('Sink', () => { sink.getMetadata = async () => { throw error; }; - return sink.setMetadata(METADATA).then( - () => null, - err => assert.strictEqual(err, error) - ); + return assert.rejects(sink.setMetadata(METADATA), error); }); it('should execute gax method', async () => { From dd814a5e29850fe213fb1b636f630bea3b096283 Mon Sep 17 00:00:00 2001 From: Daniel Bruce Date: Tue, 20 Oct 2026 19:09:44 +0000 Subject: [PATCH 4/4] refactor(logging,pubsub): use centralized proxyquire from google-test-utils (Path 1B) --- handwritten/logging-bunyan/cloudbuild.yaml | 2 +- handwritten/logging-bunyan/package.json | 1 + handwritten/logging-bunyan/test/index.ts | 2 +- .../test/middleware/test-express.ts | 2 +- handwritten/logging-bunyan/test/proxyquire.ts | 122 ------------------ handwritten/logging-winston/cloudbuild.yaml | 2 +- handwritten/logging-winston/package.json | 1 + handwritten/logging-winston/test/common.ts | 2 +- handwritten/logging-winston/test/index.ts | 2 +- .../test/middleware/express.ts | 2 +- .../logging-winston/test/proxyquire.ts | 122 ------------------ .../test/stackdriver-trace-integration.ts | 2 +- handwritten/logging/cloudbuild.yaml | 2 +- handwritten/logging/package.json | 1 + handwritten/logging/test/entry.ts | 2 +- handwritten/logging/test/index.ts | 2 +- handwritten/logging/test/log.ts | 2 +- .../express/test-make-middleware.ts | 2 +- handwritten/logging/test/proxyquire.ts | 122 ------------------ handwritten/logging/test/sink.ts | 2 +- handwritten/logging/test/utils/metadata.ts | 2 +- handwritten/pubsub/cloudbuild.yaml | 2 +- handwritten/pubsub/package.json | 2 +- handwritten/pubsub/test/iam.ts | 2 +- handwritten/pubsub/test/lease-manager.ts | 2 +- handwritten/pubsub/test/message-stream.ts | 2 +- handwritten/pubsub/test/proxyquire.ts | 122 ------------------ handwritten/pubsub/test/publisher/index.ts | 2 +- .../pubsub/test/publisher/message-queues.ts | 2 +- handwritten/pubsub/test/pubsub.ts | 2 +- handwritten/pubsub/test/snapshot.ts | 2 +- handwritten/pubsub/test/subscriber.ts | 2 +- handwritten/pubsub/test/subscription.ts | 2 +- handwritten/pubsub/test/topic.ts | 2 +- pnpm-lock.yaml | 25 ++-- 35 files changed, 47 insertions(+), 523 deletions(-) delete mode 100644 handwritten/logging-bunyan/test/proxyquire.ts delete mode 100644 handwritten/logging-winston/test/proxyquire.ts delete mode 100644 handwritten/logging/test/proxyquire.ts delete mode 100644 handwritten/pubsub/test/proxyquire.ts diff --git a/handwritten/logging-bunyan/cloudbuild.yaml b/handwritten/logging-bunyan/cloudbuild.yaml index 26d13e851393..59558f4a9289 100644 --- a/handwritten/logging-bunyan/cloudbuild.yaml +++ b/handwritten/logging-bunyan/cloudbuild.yaml @@ -5,7 +5,7 @@ steps: args: - '-c' - | - cd ../.. && corepack enable pnpm && pnpm install --filter "...{./handwritten/logging-bunyan}" + cd ../.. && corepack enable pnpm && pnpm install --filter "./core/test-utils" --filter "...{./handwritten/logging-bunyan}" --ignore-scripts && pnpm --dir core/test-utils run compile && node -e "require('./bin/run-test.cjs').ensureWorkspacePackagesLinked()" && pnpm --filter "...{./handwritten/logging-bunyan}" run prepare --if-present dir: 'handwritten/logging-bunyan' id: 'install-dependencies' diff --git a/handwritten/logging-bunyan/package.json b/handwritten/logging-bunyan/package.json index 4bd8a2581106..f064b1d888c5 100644 --- a/handwritten/logging-bunyan/package.json +++ b/handwritten/logging-bunyan/package.json @@ -70,6 +70,7 @@ "cross-env": "^7.0.3", "delay": "^5.0.0", "express": "^4.16.3", + "google-test-utils": "^0.3.0", "gts": "^6.0.2", "jsdoc": "^4.0.0", "jsdoc-fresh": "^6.0.0", diff --git a/handwritten/logging-bunyan/test/index.ts b/handwritten/logging-bunyan/test/index.ts index 0c82b56d35f5..2f39cc7a58f9 100644 --- a/handwritten/logging-bunyan/test/index.ts +++ b/handwritten/logging-bunyan/test/index.ts @@ -13,7 +13,7 @@ // limitations under the License. import * as assert from 'assert'; import {describe, it, beforeEach, afterEach} from 'mocha'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import {inspect} from 'util'; import {LoggingBunyan} from '../src'; diff --git a/handwritten/logging-bunyan/test/middleware/test-express.ts b/handwritten/logging-bunyan/test/middleware/test-express.ts index ba5f651c6e8d..b96fd0f4857d 100644 --- a/handwritten/logging-bunyan/test/middleware/test-express.ts +++ b/handwritten/logging-bunyan/test/middleware/test-express.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import {GCPEnv} from 'google-auth-library'; -import * as proxyquire from '../proxyquire'; +import {proxyquire} from 'google-test-utils'; // types-only import. Actual require is done through proxyquire below. import {MiddlewareOptions} from '../../src/middleware/express'; diff --git a/handwritten/logging-bunyan/test/proxyquire.ts b/handwritten/logging-bunyan/test/proxyquire.ts deleted file mode 100644 index 5d344ba47dad..000000000000 --- a/handwritten/logging-bunyan/test/proxyquire.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2026 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import * as Module from 'module'; -import * as path from 'path'; - -delete require.cache[require.resolve(__filename)]; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type Stubs = Record; -const mod = Module as unknown as { - prototype: {require: NodeRequire}; - _resolveFilename: (request: string, parent: NodeModule) => string; -}; -const {hasOwnProperty} = Object.prototype; -const isObj = (o: unknown) => - Boolean(o && (typeof o === 'object' || typeof o === 'function')); -const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); -const isGlobal = (s: unknown) => - hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); -const resolveFrom = (base: string, req: string) => { - try { - return require.resolve(req, {paths: [path.dirname(base)]}); - } catch { - return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; - } -}; - -const parent = module.parent || module; -let skipCallThru = false; -let keepCache = true; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function proxyquire(request: string, stubs: Stubs = {}): T { - const sut = mod._resolveFilename(request, parent); - const resolved: Stubs = {}; - let global = false; - for (const [k, v] of Object.entries(stubs)) { - if (isGlobal(v)) global = true; - resolved[resolveFrom(sut, k)] = v; - } - const cache = require.cache; - const keys = global - ? Object.keys(cache).filter(id => !id.endsWith('.node')) - : [sut]; - const saved = keys.map(id => [id, cache[id]] as const); - for (const id of keys) delete cache[id]; - const prev = mod.prototype.require; - const req = function (this: NodeModule, id: string) { - const isSut = this?.filename === sut; - if (this?.filename && (isSut || global)) { - const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); - const rId = hit ? '' : resolveFrom(this.filename, id); - if (hit || hasOwn(resolved, rId)) { - const stub = hit ? stubs[id] : resolved[rId]; - if (isSut || isGlobal(stub)) { - if (stub === null) { - const e = new Error(`Cannot find module '${id}'`); - throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); - } - const skip = hasOwn(stub, '@noCallThru') - ? stub['@noCallThru'] - : skipCallThru; - if (!skip && stub && ['object', 'function'].includes(typeof stub)) { - try { - const real = prev.call(this, id); - if (real && ['object', 'function'].includes(typeof real)) { - for (const k of Object.keys(real)) { - if (!(k in stub)) { - try { - stub[k] = real[k]; - } catch { - // ignore - } - } - } - } - } catch { - // ignore - } - } - return stub; - } - } - } - return prev.call(this, id); - }; - mod.prototype.require = Object.assign(req, prev); - try { - return prev.call(parent, request); - } finally { - mod.prototype.require = prev; - for (const id of global ? Object.keys(cache) : [sut]) { - if (!id.endsWith('.node')) delete cache[id]; - } - for (const [id, m] of saved) { - if (m && (keepCache || id !== sut)) cache[id] = m; - } - } -} - -// eslint-disable-next-line @typescript-eslint/no-namespace -namespace proxyquire { - export const load = proxyquire; - export const noCallThru = () => ((skipCallThru = true), proxyquire); - export const callThru = () => ((skipCallThru = false), proxyquire); - export const noPreserveCache = () => ((keepCache = false), proxyquire); - export const preserveCache = () => ((keepCache = true), proxyquire); -} - -export = proxyquire; diff --git a/handwritten/logging-winston/cloudbuild.yaml b/handwritten/logging-winston/cloudbuild.yaml index 82005cf50848..c4f4637e0823 100644 --- a/handwritten/logging-winston/cloudbuild.yaml +++ b/handwritten/logging-winston/cloudbuild.yaml @@ -5,7 +5,7 @@ steps: args: - '-c' - | - cd ../.. && corepack enable pnpm && pnpm install --filter "...{./handwritten/logging-winston}" + cd ../.. && corepack enable pnpm && pnpm install --filter "./core/test-utils" --filter "...{./handwritten/logging-winston}" --ignore-scripts && pnpm --dir core/test-utils run compile && node -e "require('./bin/run-test.cjs').ensureWorkspacePackagesLinked()" && pnpm --filter "...{./handwritten/logging-winston}" run prepare --if-present dir: 'handwritten/logging-winston' id: 'install-dependencies' diff --git a/handwritten/logging-winston/package.json b/handwritten/logging-winston/package.json index 810054027251..95f97a09dcfa 100644 --- a/handwritten/logging-winston/package.json +++ b/handwritten/logging-winston/package.json @@ -67,6 +67,7 @@ "c8": "^10.1.3", "codecov": "^3.8.3", "cross-env": "^7.0.3", + "google-test-utils": "^0.3.0", "gts": "^6.0.2", "jsdoc": "^4.0.5", "jsdoc-fresh": "^6.0.0", diff --git a/handwritten/logging-winston/test/common.ts b/handwritten/logging-winston/test/common.ts index f3fb4011a6dc..e5acd8bc7781 100644 --- a/handwritten/logging-winston/test/common.ts +++ b/handwritten/logging-winston/test/common.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import * as nodeutil from 'util'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import {Options} from '../src'; import {Entry, Logging, LogSync, Log} from '@google-cloud/logging'; import * as instrumentation from '@google-cloud/logging/build/src/utils/instrumentation'; diff --git a/handwritten/logging-winston/test/index.ts b/handwritten/logging-winston/test/index.ts index 1af6b8881636..bca6f2980aae 100644 --- a/handwritten/logging-winston/test/index.ts +++ b/handwritten/logging-winston/test/index.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import * as TransportStream from 'winston-transport'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import {Options} from '../src'; describe('logging-winston', () => { diff --git a/handwritten/logging-winston/test/middleware/express.ts b/handwritten/logging-winston/test/middleware/express.ts index b8ec33cc8f9c..ea5d747217f1 100644 --- a/handwritten/logging-winston/test/middleware/express.ts +++ b/handwritten/logging-winston/test/middleware/express.ts @@ -18,7 +18,7 @@ import {GCPEnv} from 'google-auth-library'; import {LogEntry} from 'winston'; import * as TransportStream from 'winston-transport'; import * as winston from 'winston'; -import * as proxyquire from '../proxyquire'; +import {proxyquire} from 'google-test-utils'; import {Options} from '../../src'; // types-only import. Actual require is done through proxyquire below. diff --git a/handwritten/logging-winston/test/proxyquire.ts b/handwritten/logging-winston/test/proxyquire.ts deleted file mode 100644 index 5d344ba47dad..000000000000 --- a/handwritten/logging-winston/test/proxyquire.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2026 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import * as Module from 'module'; -import * as path from 'path'; - -delete require.cache[require.resolve(__filename)]; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type Stubs = Record; -const mod = Module as unknown as { - prototype: {require: NodeRequire}; - _resolveFilename: (request: string, parent: NodeModule) => string; -}; -const {hasOwnProperty} = Object.prototype; -const isObj = (o: unknown) => - Boolean(o && (typeof o === 'object' || typeof o === 'function')); -const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); -const isGlobal = (s: unknown) => - hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); -const resolveFrom = (base: string, req: string) => { - try { - return require.resolve(req, {paths: [path.dirname(base)]}); - } catch { - return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; - } -}; - -const parent = module.parent || module; -let skipCallThru = false; -let keepCache = true; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function proxyquire(request: string, stubs: Stubs = {}): T { - const sut = mod._resolveFilename(request, parent); - const resolved: Stubs = {}; - let global = false; - for (const [k, v] of Object.entries(stubs)) { - if (isGlobal(v)) global = true; - resolved[resolveFrom(sut, k)] = v; - } - const cache = require.cache; - const keys = global - ? Object.keys(cache).filter(id => !id.endsWith('.node')) - : [sut]; - const saved = keys.map(id => [id, cache[id]] as const); - for (const id of keys) delete cache[id]; - const prev = mod.prototype.require; - const req = function (this: NodeModule, id: string) { - const isSut = this?.filename === sut; - if (this?.filename && (isSut || global)) { - const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); - const rId = hit ? '' : resolveFrom(this.filename, id); - if (hit || hasOwn(resolved, rId)) { - const stub = hit ? stubs[id] : resolved[rId]; - if (isSut || isGlobal(stub)) { - if (stub === null) { - const e = new Error(`Cannot find module '${id}'`); - throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); - } - const skip = hasOwn(stub, '@noCallThru') - ? stub['@noCallThru'] - : skipCallThru; - if (!skip && stub && ['object', 'function'].includes(typeof stub)) { - try { - const real = prev.call(this, id); - if (real && ['object', 'function'].includes(typeof real)) { - for (const k of Object.keys(real)) { - if (!(k in stub)) { - try { - stub[k] = real[k]; - } catch { - // ignore - } - } - } - } - } catch { - // ignore - } - } - return stub; - } - } - } - return prev.call(this, id); - }; - mod.prototype.require = Object.assign(req, prev); - try { - return prev.call(parent, request); - } finally { - mod.prototype.require = prev; - for (const id of global ? Object.keys(cache) : [sut]) { - if (!id.endsWith('.node')) delete cache[id]; - } - for (const [id, m] of saved) { - if (m && (keepCache || id !== sut)) cache[id] = m; - } - } -} - -// eslint-disable-next-line @typescript-eslint/no-namespace -namespace proxyquire { - export const load = proxyquire; - export const noCallThru = () => ((skipCallThru = true), proxyquire); - export const callThru = () => ((skipCallThru = false), proxyquire); - export const noPreserveCache = () => ((keepCache = false), proxyquire); - export const preserveCache = () => ((keepCache = true), proxyquire); -} - -export = proxyquire; diff --git a/handwritten/logging-winston/test/stackdriver-trace-integration.ts b/handwritten/logging-winston/test/stackdriver-trace-integration.ts index 9e62c33575e0..52142aad48df 100644 --- a/handwritten/logging-winston/test/stackdriver-trace-integration.ts +++ b/handwritten/logging-winston/test/stackdriver-trace-integration.ts @@ -14,7 +14,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, after} from 'mocha'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as winston from 'winston'; import * as loggingWinstonLibTypes from '../src/index'; diff --git a/handwritten/logging/cloudbuild.yaml b/handwritten/logging/cloudbuild.yaml index c8f34da5f96b..7043819381f5 100644 --- a/handwritten/logging/cloudbuild.yaml +++ b/handwritten/logging/cloudbuild.yaml @@ -5,7 +5,7 @@ steps: args: - '-c' - | - cd ../.. && corepack enable pnpm && pnpm install --filter "...{./handwritten/logging}" + cd ../.. && corepack enable pnpm && pnpm install --filter "./core/test-utils" --filter "...{./handwritten/logging}" --ignore-scripts && pnpm --dir core/test-utils run compile && node -e "require('./bin/run-test.cjs').ensureWorkspacePackagesLinked()" && pnpm --filter "...{./handwritten/logging}" run prepare --if-present dir: 'handwritten/logging' id: 'install-dependencies' diff --git a/handwritten/logging/package.json b/handwritten/logging/package.json index 06363bb21952..d86b8dbda7ab 100644 --- a/handwritten/logging/package.json +++ b/handwritten/logging/package.json @@ -86,6 +86,7 @@ "codecov": "^3.6.5", "cross-env": "^7.0.3", "gapic-tools": "^2.0.0", + "google-test-utils": "^0.3.0", "gts": "^5.0.0", "http2spy": "^2.0.0", "jsdoc": "^4.0.0", diff --git a/handwritten/logging/test/entry.ts b/handwritten/logging/test/entry.ts index d9d994a8e44d..d4abf0cd913b 100644 --- a/handwritten/logging/test/entry.ts +++ b/handwritten/logging/test/entry.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as entryTypes from '../src/entry'; import * as common from '../src/utils/common'; import * as http from 'http'; diff --git a/handwritten/logging/test/index.ts b/handwritten/logging/test/index.ts index 2bbdc411e914..b7d8eb98a54f 100644 --- a/handwritten/logging/test/index.ts +++ b/handwritten/logging/test/index.ts @@ -18,7 +18,7 @@ import arrify = require('arrify'); import * as assert from 'assert'; import {describe, it, beforeEach, before} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import { Logging as LOGGING, LoggingOptions, diff --git a/handwritten/logging/test/log.ts b/handwritten/logging/test/log.ts index 3efb9dfbf2ae..7dbc42c5a43d 100644 --- a/handwritten/logging/test/log.ts +++ b/handwritten/logging/test/log.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {Entry, Logging} from '../src'; import {Log as LOG, LogOptions, WriteOptions} from '../src/log'; diff --git a/handwritten/logging/test/middleware/express/test-make-middleware.ts b/handwritten/logging/test/middleware/express/test-make-middleware.ts index 5444e2fc698e..3b65cc915811 100644 --- a/handwritten/logging/test/middleware/express/test-make-middleware.ts +++ b/handwritten/logging/test/middleware/express/test-make-middleware.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach} from 'mocha'; import * as EventEmitter from 'events'; -import * as proxyquire from '../../proxyquire'; +import {proxyquire} from 'google-test-utils'; const FAKE_PROJECT_ID = 'project-🦄'; diff --git a/handwritten/logging/test/proxyquire.ts b/handwritten/logging/test/proxyquire.ts deleted file mode 100644 index 5d344ba47dad..000000000000 --- a/handwritten/logging/test/proxyquire.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2026 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import * as Module from 'module'; -import * as path from 'path'; - -delete require.cache[require.resolve(__filename)]; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type Stubs = Record; -const mod = Module as unknown as { - prototype: {require: NodeRequire}; - _resolveFilename: (request: string, parent: NodeModule) => string; -}; -const {hasOwnProperty} = Object.prototype; -const isObj = (o: unknown) => - Boolean(o && (typeof o === 'object' || typeof o === 'function')); -const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); -const isGlobal = (s: unknown) => - hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); -const resolveFrom = (base: string, req: string) => { - try { - return require.resolve(req, {paths: [path.dirname(base)]}); - } catch { - return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; - } -}; - -const parent = module.parent || module; -let skipCallThru = false; -let keepCache = true; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function proxyquire(request: string, stubs: Stubs = {}): T { - const sut = mod._resolveFilename(request, parent); - const resolved: Stubs = {}; - let global = false; - for (const [k, v] of Object.entries(stubs)) { - if (isGlobal(v)) global = true; - resolved[resolveFrom(sut, k)] = v; - } - const cache = require.cache; - const keys = global - ? Object.keys(cache).filter(id => !id.endsWith('.node')) - : [sut]; - const saved = keys.map(id => [id, cache[id]] as const); - for (const id of keys) delete cache[id]; - const prev = mod.prototype.require; - const req = function (this: NodeModule, id: string) { - const isSut = this?.filename === sut; - if (this?.filename && (isSut || global)) { - const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); - const rId = hit ? '' : resolveFrom(this.filename, id); - if (hit || hasOwn(resolved, rId)) { - const stub = hit ? stubs[id] : resolved[rId]; - if (isSut || isGlobal(stub)) { - if (stub === null) { - const e = new Error(`Cannot find module '${id}'`); - throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); - } - const skip = hasOwn(stub, '@noCallThru') - ? stub['@noCallThru'] - : skipCallThru; - if (!skip && stub && ['object', 'function'].includes(typeof stub)) { - try { - const real = prev.call(this, id); - if (real && ['object', 'function'].includes(typeof real)) { - for (const k of Object.keys(real)) { - if (!(k in stub)) { - try { - stub[k] = real[k]; - } catch { - // ignore - } - } - } - } - } catch { - // ignore - } - } - return stub; - } - } - } - return prev.call(this, id); - }; - mod.prototype.require = Object.assign(req, prev); - try { - return prev.call(parent, request); - } finally { - mod.prototype.require = prev; - for (const id of global ? Object.keys(cache) : [sut]) { - if (!id.endsWith('.node')) delete cache[id]; - } - for (const [id, m] of saved) { - if (m && (keepCache || id !== sut)) cache[id] = m; - } - } -} - -// eslint-disable-next-line @typescript-eslint/no-namespace -namespace proxyquire { - export const load = proxyquire; - export const noCallThru = () => ((skipCallThru = true), proxyquire); - export const callThru = () => ((skipCallThru = false), proxyquire); - export const noPreserveCache = () => ((keepCache = false), proxyquire); - export const preserveCache = () => ((keepCache = true), proxyquire); -} - -export = proxyquire; diff --git a/handwritten/logging/test/sink.ts b/handwritten/logging/test/sink.ts index 303e14f8c80b..ddffc2b28366 100644 --- a/handwritten/logging/test/sink.ts +++ b/handwritten/logging/test/sink.ts @@ -16,7 +16,7 @@ import * as callbackify from '@google-cloud/promisify'; import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import * as extend from 'extend'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {Sink as SINK} from '../src/sink'; import {Logging, CreateSinkRequest, LogSink} from '../src/index'; diff --git a/handwritten/logging/test/utils/metadata.ts b/handwritten/logging/test/utils/metadata.ts index 0e32e59f2853..f2184c06fa27 100644 --- a/handwritten/logging/test/utils/metadata.ts +++ b/handwritten/logging/test/utils/metadata.ts @@ -17,7 +17,7 @@ import {describe, it, beforeEach, before, after, afterEach} from 'mocha'; import BigNumber from 'bignumber.js'; import * as extend from 'extend'; import {GCPEnv} from 'google-auth-library'; -import * as proxyquire from '../proxyquire'; +import {proxyquire} from 'google-test-utils'; let instanceOverride: {} | null; const fakeGcpMetadata = { diff --git a/handwritten/pubsub/cloudbuild.yaml b/handwritten/pubsub/cloudbuild.yaml index 80a726b32a6c..b541e3e759bc 100644 --- a/handwritten/pubsub/cloudbuild.yaml +++ b/handwritten/pubsub/cloudbuild.yaml @@ -5,7 +5,7 @@ steps: args: - '-c' - | - cd ../.. && corepack enable pnpm && pnpm install --filter "...{./handwritten/pubsub}" + cd ../.. && corepack enable pnpm && pnpm install --filter "./core/test-utils" --filter "...{./handwritten/pubsub}" --ignore-scripts && pnpm --dir core/test-utils run compile && node -e "require('./bin/run-test.cjs').ensureWorkspacePackagesLinked()" && pnpm --filter "...{./handwritten/pubsub}" run prepare --if-present dir: 'handwritten/pubsub' id: 'install-dependencies' diff --git a/handwritten/pubsub/package.json b/handwritten/pubsub/package.json index 4f5993ad4447..5d41a1d4fcbe 100644 --- a/handwritten/pubsub/package.json +++ b/handwritten/pubsub/package.json @@ -88,7 +88,7 @@ "codecov": "^3.8.3", "execa": "~5.1.0", "gapic-tools": "^2.0.0", - "google-test-utils": "^0.2.0", + "google-test-utils": "^0.3.0", "gts": "^6.0.0", "jsdoc": "^4.0.4", "jsdoc-fresh": "^6.0.0", diff --git a/handwritten/pubsub/test/iam.ts b/handwritten/pubsub/test/iam.ts index 6232a51e37ac..bc20797c21ab 100644 --- a/handwritten/pubsub/test/iam.ts +++ b/handwritten/pubsub/test/iam.ts @@ -14,7 +14,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach} from 'mocha'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as iamTypes from '../src/iam'; import {PubSub, RequestConfig} from '../src/pubsub'; diff --git a/handwritten/pubsub/test/lease-manager.ts b/handwritten/pubsub/test/lease-manager.ts index a5088a5d1813..603e7015b30c 100644 --- a/handwritten/pubsub/test/lease-manager.ts +++ b/handwritten/pubsub/test/lease-manager.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import * as defer from 'p-defer'; diff --git a/handwritten/pubsub/test/message-stream.ts b/handwritten/pubsub/test/message-stream.ts index 0d921e038ba8..8c1916665e59 100644 --- a/handwritten/pubsub/test/message-stream.ts +++ b/handwritten/pubsub/test/message-stream.ts @@ -17,7 +17,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {grpc} from 'google-gax'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {Duplex, PassThrough} from 'stream'; import * as defer from 'p-defer'; diff --git a/handwritten/pubsub/test/proxyquire.ts b/handwritten/pubsub/test/proxyquire.ts deleted file mode 100644 index 5d344ba47dad..000000000000 --- a/handwritten/pubsub/test/proxyquire.ts +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2026 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import * as Module from 'module'; -import * as path from 'path'; - -delete require.cache[require.resolve(__filename)]; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type Stubs = Record; -const mod = Module as unknown as { - prototype: {require: NodeRequire}; - _resolveFilename: (request: string, parent: NodeModule) => string; -}; -const {hasOwnProperty} = Object.prototype; -const isObj = (o: unknown) => - Boolean(o && (typeof o === 'object' || typeof o === 'function')); -const hasOwn = (o: unknown, k: string) => isObj(o) && hasOwnProperty.call(o, k); -const isGlobal = (s: unknown) => - hasOwn(s, '@global') || hasOwn(s, '@runtimeGlobal'); -const resolveFrom = (base: string, req: string) => { - try { - return require.resolve(req, {paths: [path.dirname(base)]}); - } catch { - return req[0] === '.' ? path.resolve(path.dirname(base), req) : req; - } -}; - -const parent = module.parent || module; -let skipCallThru = false; -let keepCache = true; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function proxyquire(request: string, stubs: Stubs = {}): T { - const sut = mod._resolveFilename(request, parent); - const resolved: Stubs = {}; - let global = false; - for (const [k, v] of Object.entries(stubs)) { - if (isGlobal(v)) global = true; - resolved[resolveFrom(sut, k)] = v; - } - const cache = require.cache; - const keys = global - ? Object.keys(cache).filter(id => !id.endsWith('.node')) - : [sut]; - const saved = keys.map(id => [id, cache[id]] as const); - for (const id of keys) delete cache[id]; - const prev = mod.prototype.require; - const req = function (this: NodeModule, id: string) { - const isSut = this?.filename === sut; - if (this?.filename && (isSut || global)) { - const hit = (isSut || !id.startsWith('.')) && hasOwn(stubs, id); - const rId = hit ? '' : resolveFrom(this.filename, id); - if (hit || hasOwn(resolved, rId)) { - const stub = hit ? stubs[id] : resolved[rId]; - if (isSut || isGlobal(stub)) { - if (stub === null) { - const e = new Error(`Cannot find module '${id}'`); - throw Object.assign(e, {code: 'MODULE_NOT_FOUND'}); - } - const skip = hasOwn(stub, '@noCallThru') - ? stub['@noCallThru'] - : skipCallThru; - if (!skip && stub && ['object', 'function'].includes(typeof stub)) { - try { - const real = prev.call(this, id); - if (real && ['object', 'function'].includes(typeof real)) { - for (const k of Object.keys(real)) { - if (!(k in stub)) { - try { - stub[k] = real[k]; - } catch { - // ignore - } - } - } - } - } catch { - // ignore - } - } - return stub; - } - } - } - return prev.call(this, id); - }; - mod.prototype.require = Object.assign(req, prev); - try { - return prev.call(parent, request); - } finally { - mod.prototype.require = prev; - for (const id of global ? Object.keys(cache) : [sut]) { - if (!id.endsWith('.node')) delete cache[id]; - } - for (const [id, m] of saved) { - if (m && (keepCache || id !== sut)) cache[id] = m; - } - } -} - -// eslint-disable-next-line @typescript-eslint/no-namespace -namespace proxyquire { - export const load = proxyquire; - export const noCallThru = () => ((skipCallThru = true), proxyquire); - export const callThru = () => ((skipCallThru = false), proxyquire); - export const noPreserveCache = () => ((keepCache = false), proxyquire); - export const preserveCache = () => ((keepCache = true), proxyquire); -} - -export = proxyquire; diff --git a/handwritten/pubsub/test/publisher/index.ts b/handwritten/pubsub/test/publisher/index.ts index f4fa95908ba2..8a6657d10975 100644 --- a/handwritten/pubsub/test/publisher/index.ts +++ b/handwritten/pubsub/test/publisher/index.ts @@ -18,7 +18,7 @@ import * as pfy from '@google-cloud/promisify'; import * as assert from 'assert'; import {describe, it, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; -import * as proxyquire from '../proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import * as opentelemetry from '@opentelemetry/api'; import {Topic} from '../../src'; diff --git a/handwritten/pubsub/test/publisher/message-queues.ts b/handwritten/pubsub/test/publisher/message-queues.ts index 343906dd6833..3b0486e6dca2 100644 --- a/handwritten/pubsub/test/publisher/message-queues.ts +++ b/handwritten/pubsub/test/publisher/message-queues.ts @@ -18,7 +18,7 @@ import {loggingUtils, ServiceError} from 'google-gax'; import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; -import * as proxyquire from '../proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {RequestConfig, RequestCallback} from '../../src/pubsub'; diff --git a/handwritten/pubsub/test/pubsub.ts b/handwritten/pubsub/test/pubsub.ts index 06f4547a09eb..4cfdb484c3d2 100644 --- a/handwritten/pubsub/test/pubsub.ts +++ b/handwritten/pubsub/test/pubsub.ts @@ -17,7 +17,7 @@ import arrify = require('arrify'); import * as assert from 'assert'; import {describe, it, before, beforeEach, after, afterEach} from 'mocha'; import * as gax from 'google-gax'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import defer = require('p-defer'); diff --git a/handwritten/pubsub/test/snapshot.ts b/handwritten/pubsub/test/snapshot.ts index cd781fe09e8d..63660a72e77f 100644 --- a/handwritten/pubsub/test/snapshot.ts +++ b/handwritten/pubsub/test/snapshot.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {ServiceError} from 'google-gax'; import {describe, it, beforeEach, before, after, afterEach} from 'mocha'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {PubSub, RequestConfig} from '../src/pubsub'; diff --git a/handwritten/pubsub/test/subscriber.ts b/handwritten/pubsub/test/subscriber.ts index a6051a7aa459..280e44698981 100644 --- a/handwritten/pubsub/test/subscriber.ts +++ b/handwritten/pubsub/test/subscriber.ts @@ -19,7 +19,7 @@ import * as assert from 'assert'; import {describe, it, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; import {common as protobuf} from 'protobufjs'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {PassThrough} from 'stream'; import * as opentelemetry from '@opentelemetry/api'; diff --git a/handwritten/pubsub/test/subscription.ts b/handwritten/pubsub/test/subscription.ts index 5577c6b0e794..b86c5a60d732 100644 --- a/handwritten/pubsub/test/subscription.ts +++ b/handwritten/pubsub/test/subscription.ts @@ -16,7 +16,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {EventEmitter} from 'events'; import {ServiceError} from 'google-gax'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {PubSub, RequestConfig} from '../src/pubsub'; diff --git a/handwritten/pubsub/test/topic.ts b/handwritten/pubsub/test/topic.ts index 4e2f736e48b1..c8e31cd3894c 100644 --- a/handwritten/pubsub/test/topic.ts +++ b/handwritten/pubsub/test/topic.ts @@ -15,7 +15,7 @@ import * as assert from 'assert'; import {describe, it, before, beforeEach, afterEach} from 'mocha'; import {CallOptions, ServiceError} from 'google-gax'; -import * as proxyquire from './proxyquire'; +import {proxyquire} from 'google-test-utils'; import * as sinon from 'sinon'; import {google} from '../protos/protos'; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3bab231f6cbc..d3e796667663 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2672,6 +2672,9 @@ importers: gapic-tools: specifier: ^2.0.0 version: 2.0.1(protobufjs@8.8.0) + google-test-utils: + specifier: ^0.3.0 + version: 0.3.0 gts: specifier: ^5.0.0 version: 5.3.1(typescript@5.9.3) @@ -2769,6 +2772,9 @@ importers: express: specifier: ^4.16.3 version: 4.22.2 + google-test-utils: + specifier: ^0.3.0 + version: 0.3.0 gts: specifier: ^6.0.2 version: 6.0.2(typescript@5.9.3) @@ -2836,6 +2842,9 @@ importers: cross-env: specifier: ^7.0.3 version: 7.0.3 + google-test-utils: + specifier: ^0.3.0 + version: 0.3.0 gts: specifier: ^6.0.2 version: 6.0.2(typescript@5.9.3) @@ -2979,8 +2988,8 @@ importers: specifier: ^2.0.0 version: 2.0.1(protobufjs@7.5.9) google-test-utils: - specifier: ^0.2.0 - version: 0.2.0 + specifier: ^0.3.0 + version: 0.3.0 gts: specifier: ^6.0.0 version: 6.0.2(typescript@5.9.3) @@ -28732,7 +28741,7 @@ snapshots: '@webpack-cli/configtest@3.0.1(webpack-cli@6.0.1)(webpack@5.109.0)': dependencies: - webpack: 5.109.0(webpack-cli@6.0.1) + webpack: 5.109.0(uglify-js@3.19.3)(webpack-cli@6.0.1) webpack-cli: 6.0.1(webpack@5.109.0) '@webpack-cli/info@2.0.2(webpack-cli@5.1.4)(webpack@5.109.0)': @@ -28742,7 +28751,7 @@ snapshots: '@webpack-cli/info@3.0.1(webpack-cli@6.0.1)(webpack@5.109.0)': dependencies: - webpack: 5.109.0(webpack-cli@6.0.1) + webpack: 5.109.0(uglify-js@3.19.3)(webpack-cli@6.0.1) webpack-cli: 6.0.1(webpack@5.109.0) '@webpack-cli/serve@2.0.5(webpack-cli@5.1.4)(webpack@5.109.0)': @@ -28752,7 +28761,7 @@ snapshots: '@webpack-cli/serve@3.0.1(webpack-cli@6.0.1)(webpack@5.109.0)': dependencies: - webpack: 5.109.0(webpack-cli@6.0.1) + webpack: 5.109.0(uglify-js@3.19.3)(webpack-cli@6.0.1) webpack-cli: 6.0.1(webpack@5.109.0) '@xtuc/ieee754@1.2.0': {} @@ -34390,7 +34399,7 @@ snapshots: dependencies: loader-utils: 2.0.4 schema-utils: 3.3.0 - webpack: 5.109.0(webpack-cli@6.0.1) + webpack: 5.109.0(uglify-js@3.19.3)(webpack-cli@6.0.1) nunjucks@3.2.4(chokidar@3.6.0): dependencies: @@ -36581,7 +36590,7 @@ snapshots: picomatch: 4.0.5 source-map: 0.7.6 typescript: 5.8.3 - webpack: 5.109.0(webpack-cli@6.0.1) + webpack: 5.109.0(uglify-js@3.19.3)(webpack-cli@6.0.1) optionalDependencies: loader-utils: 2.0.4 @@ -37069,7 +37078,7 @@ snapshots: import-local: 3.2.0 interpret: 3.1.1 rechoir: 0.8.0 - webpack: 5.109.0(webpack-cli@6.0.1) + webpack: 5.109.0(uglify-js@3.19.3)(webpack-cli@6.0.1) webpack-merge: 6.0.1 webpack-merge@4.2.2: