(t *testing.T)
| 182 | } |
| 183 | |
| 184 | func TestPost(t *testing.T) { |
| 185 | handler, _ := newHttpHandler() |
| 186 | defer handler.Clean() |
| 187 | // 创建一个测试用的 HTTP 服务器 |
| 188 | server := httptest.NewServer(http.HandlerFunc(handler.PostHandler)) |
| 189 | defer server.Close() |
| 190 | |
| 191 | // 构造请求 |
| 192 | reqBody := map[string]string{ |
| 193 | "key": "test_post", |
| 194 | "value": "test_post_value", |
| 195 | } |
| 196 | reqBytes, _ := json.Marshal(reqBody) |
| 197 | |
| 198 | req, _ := http.NewRequest(http.MethodPost, server.URL, bytes.NewBuffer(reqBytes)) |
| 199 | req.Header.Set("Content-Type", "application/json") |
| 200 | |
| 201 | // 发送请求 |
| 202 | resp, err := http.DefaultClient.Do(req) |
| 203 | if err != nil { |
| 204 | t.Fatalf("could not send request: %v", err) |
| 205 | } |
| 206 | defer func(Body io.ReadCloser) { |
| 207 | err := Body.Close() |
| 208 | if err != nil { |
| 209 | // 处理关闭响应主体失败的错误 |
| 210 | } |
| 211 | }(resp.Body) |
| 212 | |
| 213 | // 检查响应 |
| 214 | if resp.StatusCode != http.StatusOK { |
| 215 | t.Errorf("unexpected status code: %d", resp.StatusCode) |
| 216 | } |
| 217 | |
| 218 | body, err := io.ReadAll(resp.Body) |
| 219 | if err != nil { |
| 220 | t.Errorf("ReadAll error: %v", err) |
| 221 | } |
| 222 | if string(body) != "ok" { |
| 223 | t.Errorf("Post error: expected ok, got %s", string(body)) |
| 224 | } |
| 225 | |
| 226 | // 验证是否成功创建新资源 |
| 227 | valueByte, err := handler.Get([]byte("test_post")) |
| 228 | if err != nil { |
| 229 | t.Errorf("Get error: %v", err) |
| 230 | } |
| 231 | value := string(valueByte) |
| 232 | if value != "test_post_value" { |
| 233 | t.Errorf("Post error: expected %s, got %s", "test_value", value) |
| 234 | } else { |
| 235 | t.Logf("Post: test_value and Get: %s", value) |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | func TestGetListKeysHandler(t *testing.T) { |
| 240 | handler, _ := newHttpHandler() |
nothing calls this directly
no test coverage detected