Skip to content

test(proxy): add ut for proxy - #2432

Merged
ymc9 merged 1 commit into
devfrom
jiasheng-dev
Mar 2, 2026
Merged

ymc9 merged 1 commit into
devfrom
jiasheng-dev

Conversation

@jiashengguo

@jiashengguo jiashengguo commented Mar 2, 2026 •

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • New Features

    • Added URL-encoded data support to the CLI proxy application.
  • Tests

    • Added comprehensive test coverage for proxy schema endpoint, computed field handling, and sequential transaction operations.

@claude

claude Bot commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @jiashengguo's task —— View job


PR Review Complete ✅

I've reviewed the proxy unit test additions. Here's my comprehensive analysis:

  • Read and analyze the changed files to understand the modifications
  • Review the proxy.ts changes for code quality and potential issues
  • Review the new test file for coverage and quality
  • Provide comprehensive PR review feedback

📋 Summary

This PR adds comprehensive unit tests for the proxy functionality and extracts the createProxyApp function to make it testable. The changes are well-structured and improve test coverage for a critical component.

✅ Strengths

Code Quality & Structure

  • Good separation of concerns: Extracting createProxyApp (proxy.ts:201-220) makes the Express app creation logic testable and reusable
  • Clean test organization: Tests are well-structured with proper setup/teardown using afterEach hook
  • Comprehensive test coverage: Three key scenarios are tested:
    1. Schema endpoint functionality
    2. Computed fields omission behavior
    3. Sequential transaction handling

Test Implementation

  • Proper resource cleanup: The afterEach hook (proxy.test.ts:9-18) ensures servers are properly closed
  • Dynamic port allocation: Using app.listen(0) (proxy.test.ts:22) prevents port conflicts during concurrent test runs
  • Realistic test scenarios: Tests use actual ZModel schemas and simulate real API interactions

Security & Best Practices

  • No hardcoded credentials: Tests use test clients without exposing sensitive data
  • Proper HTTP status code validation: All tests verify expected status codes (200, 201)
  • Clean async/await usage: Proper promise handling throughout

🔍 Areas for Consideration

Minor Improvements

  1. Test isolation: Consider adding explicit cleanup of created database records, though the test client likely handles this
  2. Error handling coverage: Tests currently focus on happy paths - consider adding error scenario tests
  3. Type safety: The client.$schema usage (proxy.test.ts:38) could benefit from explicit typing

Code Organization

  • The proxy.ts changes are minimal and focused (only +7/-1 lines), which is excellent for maintainability
  • The new export createProxyApp follows existing code conventions

🚀 Performance Considerations

  • Tests use in-memory databases via createTestClient, which is appropriate for unit testing
  • Server cleanup is properly handled to prevent resource leaks
  • The dynamic port allocation approach scales well for parallel test execution

🛡️ Security Assessment

  • No security concerns identified
  • Tests don't expose credentials or sensitive data
  • Proper CORS and JSON parsing middleware usage in the proxy app

📈 Test Coverage Analysis

The tests cover:

  • ✅ Schema endpoint (/api/schema) functionality and response structure
  • ✅ Computed fields omission behavior (critical for data integrity)
  • ✅ Sequential transaction handling (important for complex operations)
  • ✅ Basic CRUD operations through the proxy API

Missing coverage (for future consideration):

  • Error scenarios (database connection failures, invalid requests)
  • Concurrent transaction handling
  • Large payload handling (the 5MB limit is configured but not tested)

🎯 Recommendation

APPROVE - This is a solid addition that improves testability and coverage without introducing risks. The code follows project conventions and includes meaningful test scenarios.


@coderabbitai

coderabbitai Bot commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The proxy module refactors app creation into a new exported createProxyApp function, enabling reusability and separation of concerns. A comprehensive test suite is introduced to validate schema serving, computed field omission, and sequential transaction handling via HTTP endpoints.

Changes

Cohort / File(s) Summary
Proxy App Refactoring
packages/cli/src/actions/proxy.ts
Introduces exported createProxyApp function that constructs and returns an Express app with CORS, JSON/URL-encoded parsing, and RPC/schema routes. Refactors startServer to delegate app creation to this new helper.
Proxy Endpoint Tests
packages/cli/test/proxy.test.ts
Adds comprehensive test suite covering /api/schema endpoint validation, computed field omission behavior, and sequential transaction handling via fetch-based HTTP requests against a temporary test server.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 Hops with glee through refactored code,
An app extracted, lighter load!
Tests bloom like clover on the ground,
With schemas served and transactions sound—
This proxy proxy now reigns supreme,
A developer's most elegant dream! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'test(proxy): add ut for proxy' accurately describes the main change - adding unit tests for the proxy module, but uses the abbreviation 'ut' which is non-standard.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jiasheng-dev

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/cli/test/proxy.test.ts`:
- Around line 9-18: The test teardown currently only closes the HTTP server
(server.close) but never disconnects Kysely clients created by
createTestClient(), which leaks DB connections; modify the test file to track
created clients (e.g., push each result of createTestClient() into a testClients
array or a known client variable) and in afterEach await
Promise.all(testClients.map(c => c.$disconnect())) (or await
client.$disconnect() if a single client), then clear the references (set to
undefined/empty array) before resolving the teardown; update afterEach alongside
the existing server.close logic to ensure all clients are properly disconnected.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f58550e and 5f2446a.

📒 Files selected for processing (2)
  • packages/cli/src/actions/proxy.ts
  • packages/cli/test/proxy.test.ts

Comment on lines +9 to +18
afterEach(async () => {
await new Promise<void>((resolve) => {
if (server) {
server.close(() => resolve());
server = undefined;
} else {
resolve();
}
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# First, check the file exists and show the afterEach block
echo "=== Lines 9-18 (afterEach) ==="
sed -n '9,18p' packages/cli/test/proxy.test.ts

echo -e "\n=== Full file structure and client creation sites ==="
rg -n 'createTestClient\(|afterEach|describe' packages/cli/test/proxy.test.ts | head -30

echo -e "\n=== Search for createTestClient calls with context ==="
rg -n -B2 -A2 'createTestClient\(' packages/cli/test/proxy.test.ts

echo -e "\n=== Search for $disconnect calls in this file ==="
rg -n '\$disconnect' packages/cli/test/proxy.test.ts || echo "No \$disconnect found"

echo -e "\n=== Repository-wide createTestClient usage ==="
rg -l 'createTestClient' packages --type=ts | head -5

echo -e "\n=== Check return type and definition of createTestClient ==="
rg -B2 -A10 'export.*createTestClient|function.*createTestClient' packages --type=ts | head -40

Repository: zenstackhq/zenstack

Length of output: 1539


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check for disconnect calls for the created clients ==="
grep -n 'disconnect' packages/cli/test/proxy.test.ts || echo "No disconnect found in file"

echo -e "\n=== Check full test file to see if clients are used and cleaned up ==="
wc -l packages/cli/test/proxy.test.ts

echo -e "\n=== Show the context around each createTestClient call ==="
sed -n '35,45p' packages/cli/test/proxy.test.ts
echo "---"
sed -n '68,80p' packages/cli/test/proxy.test.ts
echo "---"
sed -n '119,130p' packages/cli/test/proxy.test.ts

echo -e "\n=== Find createTestClient definition ==="
rg -n 'export.*createTestClient|^export function createTestClient|^function createTestClient' packages --type=ts

echo -e "\n=== Look at createTestClient export and understand return type ==="
rg -B5 -A20 'createTestClient' packages/cli/src/test-client.ts 2>/dev/null | head -60 || echo "File may not exist, searching more broadly..."
rg -B3 -A15 'export.*function.*createTestClient' packages --type=ts | head -50

Repository: zenstackhq/zenstack

Length of output: 4089


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Find ClientContract definition ==="
rg -B5 -A15 'type ClientContract|interface ClientContract' packages --type=ts | head -80

echo -e "\n=== Search for $disconnect method definition ==="
rg -B3 -A8 '\$disconnect' packages --type=ts | head -100

echo -e "\n=== Check how other tests use createTestClient and cleanup ==="
rg -B2 -A5 'createTestClient' packages --type=ts | grep -A5 'disconnect\|afterEach\|cleanup' | head -50 || echo "No disconnect pattern found in other tests"

echo -e "\n=== Check test files that import createTestClient ==="
rg -l 'createTestClient' packages --type=ts | head -10
</script>

Repository: zenstackhq/zenstack

Length of output: 6819


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Search for disconnect method ==="
rg -n 'disconnect' packages/orm --type=ts | grep -v node_modules | head -30

echo -e "\n=== Search for ClientContract type definition ==="
rg -B10 -A25 'export.*type ClientContract' packages/orm --type=ts | head -100

echo -e "\n=== Look at other test files to see pattern of client cleanup ==="
fd -e test.ts -e test.tsx packages | head -5

echo -e "\n=== Check one other test file for cleanup patterns ==="
fd -e test.ts packages | head -1 | xargs head -100

echo -e "\n=== Check if there are any other afterEach or test cleanup patterns in CLI tests ==="
find packages/cli/test -name '*.test.ts' -exec grep -l 'afterEach\|afterAll' {} \;
</script>

Repository: zenstackhq/zenstack

Length of output: 3497


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check ClientContract $disconnect method definition ==="
sed -n '200,210p' packages/orm/src/client/contract.ts

echo -e "\n=== Check client-impl disconnect implementation ==="
sed -n '334,350p' packages/orm/src/client/client-impl.ts

echo -e "\n=== Verify the three client creations are indeed at lines 37, 70, 121 ==="
sed -n '37p;70p;121p' packages/cli/test/proxy.test.ts

echo -e "\n=== Check if any client is used after creation and before test end ==="
sed -n '37,65p' packages/cli/test/proxy.test.ts | grep -E 'client\.|await|expect'

echo -e "\n=== Full context of test 1 (around line 37) ==="
sed -n '20,67p' packages/cli/test/proxy.test.ts

echo -e "\n=== Full context of test 2 (around line 70) ==="
sed -n '53,105p' packages/cli/test/proxy.test.ts

Repository: zenstackhq/zenstack

Length of output: 110


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check ClientContract disconnect method definition ==="
sed -n '200,210p' packages/orm/src/client/contract.ts

echo "=== Check client-impl disconnect implementation ==="
sed -n '334,350p' packages/orm/src/client/client-impl.ts

echo "=== Verify the three client creations ==="
sed -n '37p;70p;121p' packages/cli/test/proxy.test.ts

echo "=== Check if any client is used after creation ==="
sed -n '37,65p' packages/cli/test/proxy.test.ts

echo "=== Full context of test 1 ==="
sed -n '20,67p' packages/cli/test/proxy.test.ts

echo "=== Full context of test 2 ==="
sed -n '53,105p' packages/cli/test/proxy.test.ts

echo "=== Full context of test 3 ==="
sed -n '105,150p' packages/cli/test/proxy.test.ts

Repository: zenstackhq/zenstack

Length of output: 8178


Disconnect test clients in teardown to avoid leaked database connections.

Each test creates a client via createTestClient() at lines 37, 70, and 121, but afterEach only closes the HTTP server. The clients maintain database connections through Kysely that are never cleaned up, causing connection leaks and potential test flakiness. Call $disconnect() for each created client during teardown.

💡 Suggested fix
 describe('CLI proxy tests', () => {
     let server: http.Server | undefined;
+    let clients: Array<Awaited<ReturnType<typeof createTestClient>>> = [];

     afterEach(async () => {
         await new Promise<void>((resolve) => {
             if (server) {
                 server.close(() => resolve());
                 server = undefined;
             } else {
                 resolve();
             }
         });
+        await Promise.all(clients.map((client) => client.$disconnect()));
+        clients = [];
     });
@@
-        const client = await createTestClient(zmodel);
+        const client = await createTestClient(zmodel);
+        clients.push(client);
@@
-        const client = await createTestClient(zmodel, {
+        const client = await createTestClient(zmodel, {
             skipValidationForComputedFields: true,
             omit: { User: { postCount: true } },
         });
+        clients.push(client);
@@
-        const client = await createTestClient(zmodel);
+        const client = await createTestClient(zmodel);
+        clients.push(client);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/cli/test/proxy.test.ts` around lines 9 - 18, The test teardown
currently only closes the HTTP server (server.close) but never disconnects
Kysely clients created by createTestClient(), which leaks DB connections; modify
the test file to track created clients (e.g., push each result of
createTestClient() into a testClients array or a known client variable) and in
afterEach await Promise.all(testClients.map(c => c.$disconnect())) (or await
client.$disconnect() if a single client), then clear the references (set to
undefined/empty array) before resolving the teardown; update afterEach alongside
the existing server.close logic to ensure all clients are properly disconnected.

@ymc9
ymc9 merged commit 4629810 into dev Mar 2, 2026
10 checks passed
@ymc9
ymc9 deleted the jiasheng-dev branch March 2, 2026 06:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants