Files
yhy-mager/backend/internal/httpapi/license_restore_test.go
xiewenjun 09910db251
Some checks failed
Check / delivery-static (push) Has been cancelled
Check / api (push) Has been cancelled
Check / web (push) Has been cancelled
feat: localize license states and restore revoked licenses
Co-Authored-By: Craft Agent <agents-noreply@craft.do>
2026-10-12 16:11:09 +08:00

73 lines
2.7 KiB
Go

package httpapi
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"github.com/gin-gonic/gin"
"net/http/httptest"
"strings"
"testing"
"time"
)
type restoreDB struct {
*dashboardDB
commands []string
failAudit bool
}
func (d *restoreDB) Connect(context.Context) (driver.Conn, error) { return d, nil }
func (d *restoreDB) ExecContext(_ context.Context, q string, args []driver.NamedValue) (driver.Result, error) {
d.commands = append(d.commands, q)
if strings.Contains(q, "INSERT INTO audit_events") && d.failAudit {
return nil, errors.New("audit unavailable")
}
return driver.RowsAffected(1), nil
}
func TestRestoreLicense(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
for _, tc := range []struct {
name, status string
expiry time.Time
fail bool
want int
result string
}{
{"valid", "revoked", now.Add(time.Hour), false, 200, "active"},
{"expired", "revoked", now.Add(-time.Hour), false, 200, "expired"},
{"not revoked", "active", now.Add(time.Hour), false, 409, ""},
{"audit failure", "revoked", now.Add(time.Hour), true, 500, ""},
} {
t.Run(tc.name, func(t *testing.T) {
d := &restoreDB{dashboardDB: &dashboardDB{t: t, queries: []dashboardQuery{
{sql: licenseSelect + " WHERE l.id=? FOR UPDATE", args: []any{int64(2)}, rows: [][]driver.Value{testLicenseRow(2, tc.status, now.Add(-2*time.Hour), tc.expiry, now)}},
{sql: "SELECT id,license_id,operation,idempotency_key,request_fingerprint FROM license_operations WHERE actor_admin_id=? AND operation=? AND idempotency_key=?", args: []any{int64(1), "restore", "restore-test"}},
}}, failAudit: tc.fail}
db := sql.OpenDB(d)
defer db.Close()
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("POST", "/api/v1/licenses/2/restore", strings.NewReader("{}"))
c.Request.Header.Set("Idempotency-Key", "restore-test")
c.Params = gin.Params{{Key: "id", Value: "2"}}
c.Set("admin_id", uint64(1))
(&BusinessAPI{db: db}).operateLicense(c, "restore")
c.Writer.WriteHeaderNow()
if w.Code != tc.want || d.committed != (tc.want == 200) {
t.Fatalf("code=%d committed=%v body=%s", w.Code, d.committed, w.Body)
}
if tc.want == 200 && (!strings.Contains(w.Body.String(), `"status":"`+tc.result+`"`) || !strings.Contains(w.Body.String(), tc.expiry.Format(time.RFC3339))) {
t.Fatalf("validity changed: %s", w.Body)
}
if tc.want == 409 && len(d.commands) != 0 {
t.Fatal("invalid state mutated")
}
if tc.want == 200 && (len(d.commands) != 3 || d.commands[0] != "UPDATE licenses SET status='active',revoked_at=NULL WHERE id=?") {
t.Fatal("unexpected restore writes", d.commands)
}
})
}
}