-
Notifications
You must be signed in to change notification settings - Fork 31
test:pkg/picod #97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
test:pkg/picod #97
Conversation
Signed-off-by: zhoujinyu <2319109590@qq.com>
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
Summary of ChangesHello @FAUST-BENCHOU, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request focuses on enhancing the test coverage for the Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request adds several tests for the pkg/picod package, covering file mode parsing, bootstrap key loading, and error paths for the execute handler. The tests for TestParseFileMode and TestLoadBootstrapKey are well-structured unit tests. However, TestExecuteHandler_ErrorPaths tests the handler in isolation, bypassing the authentication middleware. This could lead to a false sense of security, as a real-world request would be blocked before reaching the handler logic being tested. I've suggested refactoring this test to be a proper integration test that initializes the server and sends authenticated requests through the full HTTP stack, ensuring the entire request lifecycle is tested.
| func TestExecuteHandler_ErrorPaths(t *testing.T) { | ||
| tmpDir, err := os.MkdirTemp("", "picod_execute_test") | ||
| require.NoError(t, err) | ||
| defer os.RemoveAll(tmpDir) | ||
|
|
||
| _, bootstrapPubStr := generateRSAKeys(t) | ||
| server := NewServer(Config{ | ||
| BootstrapKey: []byte(bootstrapPubStr), | ||
| Workspace: tmpDir, | ||
| }) | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| request string | ||
| statusCode int | ||
| desc string | ||
| }{ | ||
| { | ||
| name: "Empty command", | ||
| request: `{"command": []}`, | ||
| statusCode: http.StatusBadRequest, | ||
| desc: "Should reject empty command", | ||
| }, | ||
| { | ||
| name: "Invalid JSON", | ||
| request: `{"command": invalid}`, | ||
| statusCode: http.StatusBadRequest, | ||
| desc: "Should reject invalid JSON", | ||
| }, | ||
| { | ||
| name: "Invalid timeout format", | ||
| request: `{"command": ["echo", "test"], "timeout": "invalid"}`, | ||
| statusCode: http.StatusBadRequest, | ||
| desc: "Should reject invalid timeout", | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| w := httptest.NewRecorder() | ||
| req := httptest.NewRequest("POST", "/api/execute", bytes.NewBufferString(tt.request)) | ||
| req.Header.Set("Content-Type", "application/json") | ||
|
|
||
| ctx, _ := gin.CreateTestContext(w) | ||
| ctx.Request = req | ||
|
|
||
| server.ExecuteHandler(ctx) | ||
|
|
||
| assert.Equal(t, tt.statusCode, w.Code, tt.desc) | ||
| }) | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation of TestExecuteHandler_ErrorPaths tests the handler in isolation by calling server.ExecuteHandler(ctx) directly. This bypasses the authentication middleware, which is a critical part of the request lifecycle for this endpoint.
A real request to /api/execute on an uninitialized server would be rejected by the AuthMiddleware with a 403 Forbidden status, and would never reach the handler to produce the 400 Bad Request that this test expects. This means the test could pass even if the endpoint is not correctly configured or is inaccessible.
To make this test more robust and representative of real-world usage, it should be structured as an integration test that goes through the full HTTP stack. This involves:
- Setting up a test server using
httptest.NewServer. - Initializing the server by making a request to the
/initendpoint. - Sending authenticated requests with invalid bodies to the
/api/executeendpoint.
This approach ensures that the middleware, routing, and handler logic are all tested together. I've provided a suggestion to refactor the test accordingly.
func TestExecuteHandler_ErrorPaths(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "picod_execute_test")
require.NoError(t, err)
defer os.RemoveAll(tmpDir)
bootstrapPriv, bootstrapPubStr := generateRSAKeys(t)
sessionPriv, sessionPubStr := generateRSAKeys(t)
server := NewServer(Config{
BootstrapKey: []byte(bootstrapPubStr),
Workspace: tmpDir,
})
ts := httptest.NewServer(server.engine)
defer ts.Close()
client := ts.Client()
// Initialize server to allow access to authenticated endpoints
sessionPubB64 := base64.RawStdEncoding.EncodeToString([]byte(sessionPubStr))
initClaims := jwt.MapClaims{
"session_public_key": sessionPubB64,
"iat": time.Now().Unix(),
"exp": time.Now().Add(time.Hour).Unix(),
}
initToken := createToken(t, bootstrapPriv, initClaims)
initReq, err := http.NewRequest("POST", ts.URL+"/init", nil)
require.NoError(t, err)
initReq.Header.Set("Authorization", "Bearer "+initToken)
initResp, err := client.Do(initReq)
require.NoError(t, err)
require.Equal(t, http.StatusOK, initResp.StatusCode)
initResp.Body.Close()
tests := []struct {
name string
request string
statusCode int
desc string
}{
{
name: "Empty command",
request: `{"command": []}`,
statusCode: http.StatusBadRequest,
desc: "Should reject empty command",
},
{
name: "Invalid JSON",
request: `{"command": invalid}`,
statusCode: http.StatusBadRequest,
desc: "Should reject invalid JSON",
},
{
name: "Invalid timeout format",
request: `{"command": ["echo", "test"], "timeout": "invalid"}`,
statusCode: http.StatusBadRequest,
desc: "Should reject invalid timeout",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
reqBody := []byte(tt.request)
hash := sha256.Sum256(reqBody)
claims := jwt.MapClaims{
"body_sha256": fmt.Sprintf("%x", hash),
"iat": time.Now().Unix(),
"exp": time.Now().Add(time.Hour).Unix(),
}
token := createToken(t, sessionPriv, claims)
req, err := http.NewRequest("POST", ts.URL+"/api/execute", bytes.NewBuffer(reqBody))
require.NoError(t, err)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
resp, err := client.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, tt.statusCode, resp.StatusCode, tt.desc)
})
}
}| } | ||
|
|
||
| // TestExecuteHandler_ErrorPaths tests execution pipeline error paths | ||
| func TestExecuteHandler_ErrorPaths(t *testing.T) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there no test case for the normal command?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done
Signed-off-by: zhoujinyu <2319109590@qq.com>
|
@LiZhenCheng9527 Thanks for your review, I added some other tests, and now the picod test coverage has reached 77%.🙃 |
|
Hi @LiZhenCheng9527, just wanted to check if there’s any feedback on the PR I submitted. Appreciate your time! |
Link to #88