Files
knowledge-governance/internal/releaseadapter/v071/formal_es_fault_test.go
T
姚章浩 8febe12d7d test(library): 隔离数据契约与 r11 身份自然键矩阵
真实本机 PG/ES/MinIO:v071 目录镜像 10 模式、结构引用/游标 15 模式、
8 表×2 外部范围身份矩阵、13 模式自然键(含软删除与合法同 parent 正例)、
备份期间三注入、收尾故障与授权撤销两个真实治理 PG 用例。

需隔离服务的用例在 test-scope.json 显式声明:普通 CI 跳过不算通过。
2026-11-01 11:35:09 +08:00

82 lines
2.6 KiB
Go

package v071
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
)
// This is only a faulting wire: every response, commit and CAS originates in
// the real isolated ES. Successful bodies are recorded, then one is withheld.
func formalElasticFaultProxy(t *testing.T, root, upstream, fault string) string {
t.Helper()
var mu sync.Mutex
dropped := false
events := []map[string]any{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, e := io.ReadAll(r.Body)
if e != nil {
http.Error(w, "read failed", 500)
return
}
request, e := http.NewRequestWithContext(r.Context(), r.Method, upstream+r.URL.RequestURI(), bytes.NewReader(raw))
if e != nil {
http.Error(w, "request failed", 500)
return
}
request.Header = r.Header.Clone()
response, e := http.DefaultClient.Do(request)
if e != nil {
http.Error(w, "upstream failed", 502)
return
}
body, e := io.ReadAll(response.Body)
response.Body.Close()
if e != nil {
http.Error(w, "upstream body failed", 502)
return
}
mutating := r.Method == "PUT" || r.Method == "DELETE" || strings.Contains(r.URL.Path, "_bulk")
mu.Lock()
selected := fault == "apply-clean" && strings.HasSuffix(r.URL.Path, "/_doc/chunk-src") && !bytes.Contains(raw, []byte(indexClaimPrefix))
selected = selected || (fault == "restore-write" && strings.HasSuffix(r.URL.Path, "/_create/chunk-target"))
selected = selected || (fault == "restore-clean" && r.Method == http.MethodPut && strings.HasSuffix(r.URL.Path, "/_doc/chunk-target") && !bytes.Contains(raw, []byte(indexRestoreClaimPrefix)))
drop := !dropped && selected && response.StatusCode >= 200 && response.StatusCode < 300
if mutating {
events = append(events, map[string]any{"method": r.Method, "path": r.URL.RequestURI(), "request": string(raw), "response": string(body), "status": response.StatusCode, "dropped": drop})
encoded, _ := json.MarshalIndent(events, "", " ")
_ = os.WriteFile(filepath.Join(root, "es-wire.json"), encoded, 0600)
}
if drop {
dropped = true
_ = os.WriteFile(filepath.Join(root, "es-response-dropped"), []byte(fault), 0600)
}
mu.Unlock()
if drop {
if hijacker, ok := w.(http.Hijacker); ok {
connection, _, err := hijacker.Hijack()
if err == nil {
connection.Close()
}
}
return
}
for k, values := range response.Header {
for _, v := range values {
w.Header().Add(k, v)
}
}
w.WriteHeader(response.StatusCode)
_, _ = w.Write(body)
}))
t.Cleanup(server.Close)
return server.URL
}