我在这方面花了很多钱,但我不知道如何模拟@google-cloud/secret-manager。我尝试了这篇post中的解决方案,但它对我不起作用。
我设置了一个 Nodejs 应用程序来使用秘密管理器。它按预期工作。现在我需要编写笑话测试。
这是代码。
const { SecretManagerServiceClient } = require("@google-cloud/secret-manager");
const gcpMetadata = require("gcp-metadata");
const client = new SecretManagerServiceClient();
module.exports.accessSecret = async (secretName) => {
try {
const lastEnabledVersion = await getLastEnabledVersion(secretName);
if (lastEnabledVersion) {
const [version] = await client.accessSecretVersion({
name: lastEnabledVersion,
});
return version.payload.data.toString("utf8");
} else {
return null;
}
} catch (err) {
console.error("Error occurred with getting secret", err.message);
}
};
const getLastEnabledVersion = async (secretName) => {
const projectId = await gcpMetadata.project("project-id");
const [versions] = await client.listSecretVersions({
parent: `projects/${projectId}/secrets/${secretName}`,
});
// get the last enabled version
const lastEnabledVersion = versions
.filter((v) => v.state === "ENABLED")
.sort((a, b) => b.createTime.nanos - a.createTime.nanos);
return lastEnabledVersion?.length > 0 ? lastEnabledVersion[0].name : null;
};
我可以模拟 gcp-metadata,但不能模拟 @google-cloud/secret-manager
这是我的测试
const { accessSecret } = require('../../../helpers/secret-manager');
const gcpMetadata = require('gcp-metadata')
const accessResponse = {
name: 'projects/74390034/secrets/ACCESS_KEY/versions/1',
payload: { data: Buffer.from('test-secret-value', 'utf-8') },
};
const versions = [
{
name: 'projects/74390034/secrets/ACCESS_KEY/versions/2',
createTime: { seconds: '1725653856', nanos: 943110000 },
destroyTime: null,
state: 'DISABLED',
replicationStatus: { automatic: [Object], replicationStatus: 'automatic' },
etag: '"1621af4cea5129"',
clientSpecifiedPayloadChecksum: true,
scheduledDestroyTime: null,
customerManagedEncryption: null
},
{
name: 'projects/74390034/secrets/ACCESS_KEY/versions/1',
createTime: { seconds: '1709052491', nanos: 685270000 },
destroyTime: null,
state: 'ENABLED',
replicationStatus: { automatic: [Object], replicationStatus: 'automatic' },
etag: '"1621af4bd6dbbb"',
clientSpecifiedPayloadChecksum: true,
scheduledDestroyTime: null,
customerManagedEncryption: null
}
]
const mClient = {
accessSecretVersion: jest.fn(),
listSecretVersions: jest.fn()
};
jest.mock('@google-cloud/secret-manager', () => {
const mSecretManagerServiceClient = jest.fn(() => mClient);
return { SecretManagerServiceClient: mSecretManagerServiceClient };
});
jest.mock('gcp-metadata');
describe('Secret Manager', () => {
beforeEach(() => {
gcpMetadata.project = jest.fn().mockResolvedValueOnce('74390034');
mClient.listSecretVersions.mockResolvedValueOnce([versions]);
mClient.accessSecretVersion.mockResolvedValueOnce([accessResponse]);
});
test('should ', async () => {
const result = await accessSecret('ACCESS_KEY');
console.log(result)
}, 7000);
});
当我运行此测试时,这是我的输出:在此处输入图像描述
我能够解决这个问题。
const { accessSecret } = require("../../../helpers/secret-manager");
let gcpMetadata = require("gcp-metadata");
jest.mock("gcp-metadata");
const versions = [
{
name: "projects/74390034/secrets/ACCESS_KEY/versions/2",
createTime: { seconds: "1725653856", nanos: 943110000 },
state: "DISABLED",
},
{
name: "projects/74390034/secrets/ACCESS_KEY/versions/1",
createTime: { seconds: "1709052491", nanos: 685270000 },
state: "ENABLED",
},
];
jest.mock("@google-cloud/secret-manager", () => {
return {
SecretManagerServiceClient: jest.fn().mockImplementation(() => {
return {
accessSecretVersion: jest.fn().mockResolvedValue([
{
payload: { data: Buffer.from("mocked-secret") },
},
]),
listSecretVersions: jest.fn().mockResolvedValue([versions]),
};
}),
};
});
describe("Secret Manager", () => {
beforeEach(() => {
gcpMetadata.project = jest.fn().mockResolvedValueOnce("74390034");
});
afterEach(() => {
jest.clearAllMocks();
});
test("should access secret", async () => {
const secret = await accessSecret("ACCESS_KEY");
expect(secret).toEqual("mocked-secret");
});
});