🧪 [Testing Improvement] Add unit tests for R2StorageProvider#927
🧪 [Testing Improvement] Add unit tests for R2StorageProvider#927is0692vs wants to merge 1 commit into
Conversation
Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
|
👋 Jules, reporting for duty! I'm here to lend a hand with this pull request. When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down. I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job! For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with New to Jules? Learn more at jules.google/docs. For security, I will only act on instructions from the user who triggered this task. |
|
The latest updates on your projects. Learn more about Vercel for GitHub. 1 Skipped Deployment
|
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
Warning Review limit reached
More reviews will be available in 46 minutes and 31 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more credits in the billing tab to continue. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits. 🚦 How do rate limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Code Review
This pull request introduces a comprehensive suite of unit tests for the R2StorageProvider class, covering its constructor, presigned URL generation, object uploading, deletion, and metadata retrieval. The reviewer provided valuable feedback to improve the test suite, including: using a shared mockSend Jest mock to simplify test setup and reduce repetition; avoiding direct reassignment of process.env to prevent unexpected behavior with Node's environment proxy; and ensuring that client.send is explicitly verified in the deleteObject test to prevent false positives.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| jest.mock("@aws-sdk/client-s3", () => { | ||
| return { | ||
| S3Client: jest.fn().mockImplementation(() => ({ | ||
| send: jest.fn() | ||
| })), | ||
| PutObjectCommand: jest.fn(), | ||
| GetObjectCommand: jest.fn(), | ||
| DeleteObjectCommand: jest.fn(), | ||
| HeadObjectCommand: jest.fn(), | ||
| }; | ||
| }); |
There was a problem hiding this comment.
Instead of overriding the S3Client mock implementation in every single test case using (S3Client as jest.Mock).mockImplementationOnce(...), you can define a shared mockSend Jest mock function at the top level (prefixed with mock so Jest allows it in jest.mock). This simplifies the test setup, reduces repetition, and allows you to easily assert that client.send was actually called with the correct command in all tests (including deleteObject and uploadObject where it is currently unverified).
const mockSend = jest.fn();
jest.mock("@aws-sdk/client-s3", () => {
return {
S3Client: jest.fn().mockImplementation(() => ({
send: mockSend
})),
PutObjectCommand: jest.fn(),
GetObjectCommand: jest.fn(),
DeleteObjectCommand: jest.fn(),
HeadObjectCommand: jest.fn(),
};
});| const originalEnv = process.env; | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| process.env = { ...originalEnv }; | ||
| process.env.R2_ACCOUNT_ID = "test-account"; | ||
| process.env.R2_ACCESS_KEY_ID = "test-access-key"; | ||
| process.env.R2_SECRET_ACCESS_KEY = "test-secret"; | ||
| process.env.R2_BUCKET_NAME = "test-bucket"; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| process.env = originalEnv; | ||
| }); |
There was a problem hiding this comment.
Directly reassigning process.env (e.g., process.env = { ...originalEnv }) can cause unexpected behavior in Node.js because process.env is a special proxy object rather than a plain object. Reassigning it can break environment variable resolution or fail to propagate changes correctly. A safer approach is to copy the original environment variables to a local object, and then use delete and Object.assign to reset and restore process.env without replacing the object reference.
const originalEnv = { ...process.env };
beforeEach(() => {
jest.clearAllMocks();
for (const key in process.env) {
delete process.env[key];
}
Object.assign(process.env, originalEnv);
process.env.R2_ACCOUNT_ID = "test-account";
process.env.R2_ACCESS_KEY_ID = "test-access-key";
process.env.R2_SECRET_ACCESS_KEY = "test-secret";
process.env.R2_BUCKET_NAME = "test-bucket";
});
afterEach(() => {
for (const key in process.env) {
delete process.env[key];
}
Object.assign(process.env, originalEnv);
});| it("should send DeleteObjectCommand", async () => { | ||
| const provider = new R2StorageProvider(); | ||
| await provider.deleteObject("test-key.mp3"); | ||
|
|
||
| expect(DeleteObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| }); | ||
| }); |
There was a problem hiding this comment.
The test for deleteObject currently only asserts that DeleteObjectCommand was instantiated with the correct parameters, but it does not verify that client.send was actually called with the command. If client.send were omitted from the implementation, this test would still pass. If you use the shared mockSend mock suggested above, you can assert that mockSend was called with the command to ensure the object is actually deleted.
| it("should send DeleteObjectCommand", async () => { | |
| const provider = new R2StorageProvider(); | |
| await provider.deleteObject("test-key.mp3"); | |
| expect(DeleteObjectCommand).toHaveBeenCalledWith({ | |
| Bucket: "test-bucket", | |
| Key: "test-key.mp3", | |
| }); | |
| }); | |
| describe("deleteObject", () => { | |
| it("should send DeleteObjectCommand", async () => { | |
| const provider = new R2StorageProvider(); | |
| await provider.deleteObject("test-key.mp3"); | |
| expect(DeleteObjectCommand).toHaveBeenCalledWith({ | |
| Bucket: "test-bucket", | |
| Key: "test-key.mp3", | |
| }); | |
| expect(mockSend).toHaveBeenCalledWith(expect.any(DeleteObjectCommand)); | |
| }); | |
| }); |
|
|
||
| describe("headObject", () => { | ||
| it("should return exists true and size if HeadObjectCommand succeeds", async () => { | ||
| const sendMock = jest.fn().mockResolvedValueOnce({ ContentLength: 1024 }); | ||
| (S3Client as jest.Mock).mockImplementationOnce(() => ({ send: sendMock })); | ||
|
|
||
| const provider = new R2StorageProvider(); | ||
| const result = await provider.headObject("test-key.mp3"); | ||
|
|
||
| expect(HeadObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| }); | ||
| expect(result).toEqual({ exists: true, size: 1024 }); |
There was a problem hiding this comment.
deleteObject テストで client.send の呼び出しを検証していない
DeleteObjectCommand のコンストラクタ呼び出しは確認していますが、client.send が実際に呼び出されたかどうかを検証していません。実装から await this.client.send(...) の行を削除してもこのテストはパスしてしまい、削除操作が実行されたかどうかを保証できません。sendMock を用いた headObject テスト群と同様に、send の呼び出しも明示的にアサートする必要があります。
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/web-app-vercel/lib/storage/__tests__/r2-provider.test.ts
Line: 155-168
Comment:
**`deleteObject` テストで `client.send` の呼び出しを検証していない**
`DeleteObjectCommand` のコンストラクタ呼び出しは確認していますが、`client.send` が実際に呼び出されたかどうかを検証していません。実装から `await this.client.send(...)` の行を削除してもこのテストはパスしてしまい、削除操作が実行されたかどうかを保証できません。`sendMock` を用いた `headObject` テスト群と同様に、`send` の呼び出しも明示的にアサートする必要があります。
How can I resolve this? If you propose a fix, please make it concise.| (getSignedUrl as jest.Mock).mockResolvedValueOnce("https://example.com/get"); | ||
| const provider = new R2StorageProvider(); | ||
|
|
||
| const buffer = Buffer.from("test"); | ||
| const url = await provider.uploadObject("test-key.mp3", buffer, "audio/mpeg", 3600); | ||
|
|
||
| expect(PutObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| Body: expect.any(Uint8Array), | ||
| ContentType: "audio/mpeg", | ||
| }); | ||
| expect(url).toBe("https://example.com/get"); | ||
| }); | ||
|
|
||
| it("should send PutObjectCommand and return a presigned GET URL (ArrayBuffer)", async () => { | ||
| (getSignedUrl as jest.Mock).mockResolvedValueOnce("https://example.com/get"); | ||
| const provider = new R2StorageProvider(); | ||
|
|
||
| const arrayBuffer = new ArrayBuffer(4); | ||
| const url = await provider.uploadObject("test-key.mp3", arrayBuffer, "audio/mpeg", 3600); | ||
|
|
||
| expect(PutObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| Body: expect.any(Uint8Array), | ||
| ContentType: "audio/mpeg", | ||
| }); | ||
| expect(url).toBe("https://example.com/get"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("deleteObject", () => { | ||
| it("should send DeleteObjectCommand", async () => { | ||
| const provider = new R2StorageProvider(); | ||
| await provider.deleteObject("test-key.mp3"); | ||
|
|
||
| expect(DeleteObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| }); | ||
| }); |
There was a problem hiding this comment.
uploadObject テストで client.send の呼び出しを検証していない
Buffer と ArrayBuffer の両テストケースで PutObjectCommand コンストラクタへの引数は確認していますが、client.send が実際に呼び出されたかどうかをアサートしていません。実装から await this.client.send(...) の行を丸ごと取り除いてもテストはパスするため、アップロード操作が行われたことを保証できていません。headObject テスト群と同様に、S3Client モックの sendMock を使って send の呼び出しを明示的に検証することを検討してください。
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/web-app-vercel/lib/storage/__tests__/r2-provider.test.ts
Line: 112-153
Comment:
**`uploadObject` テストで `client.send` の呼び出しを検証していない**
`Buffer` と `ArrayBuffer` の両テストケースで `PutObjectCommand` コンストラクタへの引数は確認していますが、`client.send` が実際に呼び出されたかどうかをアサートしていません。実装から `await this.client.send(...)` の行を丸ごと取り除いてもテストはパスするため、アップロード操作が行われたことを保証できていません。`headObject` テスト群と同様に、`S3Client` モックの `sendMock` を使って `send` の呼び出しを明示的に検証することを検討してください。
How can I resolve this? If you propose a fix, please make it concise.| (getSignedUrl as jest.Mock).mockResolvedValueOnce("https://example.com/get"); | ||
| const provider = new R2StorageProvider(); | ||
|
|
||
| const buffer = Buffer.from("test"); | ||
| const url = await provider.uploadObject("test-key.mp3", buffer, "audio/mpeg", 3600); | ||
|
|
||
| expect(PutObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| Body: expect.any(Uint8Array), | ||
| ContentType: "audio/mpeg", | ||
| }); | ||
| expect(url).toBe("https://example.com/get"); | ||
| }); | ||
|
|
||
| it("should send PutObjectCommand and return a presigned GET URL (ArrayBuffer)", async () => { | ||
| (getSignedUrl as jest.Mock).mockResolvedValueOnce("https://example.com/get"); | ||
| const provider = new R2StorageProvider(); | ||
|
|
||
| const arrayBuffer = new ArrayBuffer(4); | ||
| const url = await provider.uploadObject("test-key.mp3", arrayBuffer, "audio/mpeg", 3600); | ||
|
|
||
| expect(PutObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| Body: expect.any(Uint8Array), | ||
| ContentType: "audio/mpeg", | ||
| }); | ||
| expect(url).toBe("https://example.com/get"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("deleteObject", () => { | ||
| it("should send DeleteObjectCommand", async () => { | ||
| const provider = new R2StorageProvider(); | ||
| await provider.deleteObject("test-key.mp3"); | ||
|
|
||
| expect(DeleteObjectCommand).toHaveBeenCalledWith({ | ||
| Bucket: "test-bucket", | ||
| Key: "test-key.mp3", | ||
| }); | ||
| }); |
There was a problem hiding this comment.
uploadObject の Buffer / ArrayBuffer 分岐が実質的に区別されていない
テスト対象のソース実装(r2-provider.ts 58行目)では、data instanceof Buffer の両ブランチがどちらも new Uint8Array(data) を返しており、実質的に同一処理となっています。そのため Buffer テストと ArrayBuffer テストはどちらも Body: expect.any(Uint8Array) を満たしますが、この分岐ロジックが正しく動くことは検証できていません。将来ブランチが修正された際の回帰テストとして、変換後の実際のバイト値をアサートする形にすることを検討してください。
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/web-app-vercel/lib/storage/__tests__/r2-provider.test.ts
Line: 112-153
Comment:
**`uploadObject` の `Buffer` / `ArrayBuffer` 分岐が実質的に区別されていない**
テスト対象のソース実装(`r2-provider.ts` 58行目)では、`data instanceof Buffer` の両ブランチがどちらも `new Uint8Array(data)` を返しており、実質的に同一処理となっています。そのため `Buffer` テストと `ArrayBuffer` テストはどちらも `Body: expect.any(Uint8Array)` を満たしますが、この分岐ロジックが正しく動くことは検証できていません。将来ブランチが修正された際の回帰テストとして、変換後の実際のバイト値をアサートする形にすることを検討してください。
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
🎯 What: The testing gap addressed
Added unit test coverage for the R2StorageProvider class in
packages/web-app-vercel/lib/storage/r2-provider.ts.📊 Coverage: What scenarios are now tested
generatePresignedPutUrlandgeneratePresignedGetUrlmock integration withgetSignedUrland S3 commands.uploadObjectbody conversion toUint8Array.deleteObjectinvocation with correct S3 command parameters.headObjectvalid response and specific error handling (NotFound and 404 status codes).✨ Result: The improvement in test coverage
Improved statement, branch, functions, and lines coverage for
packages/web-app-vercel/lib/storage/r2-provider.ts.PR created automatically by Jules for task 776126388340527962 started by @is0692vs
Greptile Summary
packages/web-app-vercel/lib/storage/r2-provider.tsに対するユニットテストを新規追加した PR です。コンストラクタのバリデーション、各メソッドの正常系・異常系を網羅しています。getSignedUrlモックおよびsendMockを使って戻り値・エラーハンドリング(NotFound / 404)を適切に検証。PutObjectCommand/DeleteObjectCommandのコンストラクタ引数は確認しているが、client.sendが実際に呼び出されたかどうかを検証するアサーションが欠けており、I/O 操作が実行されたことを保証できていない。Confidence Score: 4/5
テストのみの変更であり、プロダクションコードには影響しない。マージ自体は安全。
追加されたテストはコンストラクタの検証・presigned URL・headObject の正常/異常系を適切にカバーしているが、uploadObject と deleteObject では実際の I/O 操作を担う client.send 呼び出しの検証が欠けており、それらのメソッドに対する回帰検知力が弱い状態になっている。
r2-provider.test.ts — uploadObject と deleteObject のテストケースで send モックのアサーションを追加することを推奨。
Important Files Changed
Sequence Diagram
%%{init: {'theme': 'neutral'}}%% sequenceDiagram participant Test as テストコード participant Provider as R2StorageProvider participant S3Mock as S3Client (mock) participant Presigner as getSignedUrl (mock) Test->>Provider: new R2StorageProvider() Provider->>S3Mock: "new S3Client({ region, endpoint, credentials })" Test->>Provider: generatePresignedPutUrl(key, expiresIn) Provider->>Provider: new PutObjectCommand(...) Provider->>Presigner: "getSignedUrl(client, command, { expiresIn })" Presigner-->>Provider: https://example.com/put Test->>Provider: generatePresignedGetUrl(key, expiresIn) Provider->>Provider: new GetObjectCommand(...) Provider->>Presigner: "getSignedUrl(client, command, { expiresIn })" Presigner-->>Provider: https://example.com/get Test->>Provider: uploadObject(key, data, contentType, expiresIn) Provider->>Provider: new Uint8Array(data) Provider->>S3Mock: send(PutObjectCommand) ← ⚠️ テストで未検証 Provider->>Presigner: getSignedUrl(...) Presigner-->>Provider: https://example.com/get Test->>Provider: deleteObject(key) Provider->>S3Mock: send(DeleteObjectCommand) ← ⚠️ テストで未検証 Test->>Provider: headObject(key) Provider->>S3Mock: send(HeadObjectCommand) S3Mock-->>Provider: "{ ContentLength: 1024 } or error" Provider-->>Test: "{ exists: true, size } / { exists: false }"%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%% sequenceDiagram participant Test as テストコード participant Provider as R2StorageProvider participant S3Mock as S3Client (mock) participant Presigner as getSignedUrl (mock) Test->>Provider: new R2StorageProvider() Provider->>S3Mock: "new S3Client({ region, endpoint, credentials })" Test->>Provider: generatePresignedPutUrl(key, expiresIn) Provider->>Provider: new PutObjectCommand(...) Provider->>Presigner: "getSignedUrl(client, command, { expiresIn })" Presigner-->>Provider: https://example.com/put Test->>Provider: generatePresignedGetUrl(key, expiresIn) Provider->>Provider: new GetObjectCommand(...) Provider->>Presigner: "getSignedUrl(client, command, { expiresIn })" Presigner-->>Provider: https://example.com/get Test->>Provider: uploadObject(key, data, contentType, expiresIn) Provider->>Provider: new Uint8Array(data) Provider->>S3Mock: send(PutObjectCommand) ← ⚠️ テストで未検証 Provider->>Presigner: getSignedUrl(...) Presigner-->>Provider: https://example.com/get Test->>Provider: deleteObject(key) Provider->>S3Mock: send(DeleteObjectCommand) ← ⚠️ テストで未検証 Test->>Provider: headObject(key) Provider->>S3Mock: send(HeadObjectCommand) S3Mock-->>Provider: "{ ContentLength: 1024 } or error" Provider-->>Test: "{ exists: true, size } / { exists: false }"Prompt To Fix All With AI
Reviews (1): Last reviewed commit: "test: add unit tests for R2StorageProvid..." | Re-trigger Greptile