Files
go-fa-api/sfw_test.go
2026-05-25 22:27:18 +02:00

109 lines
3.0 KiB
Go

package fa
import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
// TestSFW_CookieOnOutboundRequest sets up an httptest server that records
// the Cookie header it received, then asserts each SFW mode produces the
// expected `sfw=…` cookie value (or none, for SFWAuto).
func TestSFW_CookieOnOutboundRequest(t *testing.T) {
cases := []struct {
name string
mode SFWMode
wantSFW string // "" = expect no sfw cookie at all
}{
{"auto omits cookie", SFWAuto, ""},
{"on sets sfw=1", SFWOn, "1"},
{"off sets sfw=0", SFWOff, "0"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
var seen string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie("sfw"); err == nil {
seen = c.Value
}
w.Header().Set("Content-Type", "text/html")
_, _ = w.Write([]byte(`<html><body>
<div class="submission-title"><h2>OK</h2></div>
<div class="submission-description-artist">
<a href="/user/x/"><img class="submission-user-icon avatar" src="/a.png"/></a>
<div>
<div class="submission-title"><h2>OK</h2></div>
<div><span class="c-usernameBlockSimple__displayName" title="x">x</span></div>
</div>
</div>
<img id="submissionImg" src="/file.png" data-fullview-src="/file.png" data-preview-src="/thumb.png"/>
</body></html>`))
}))
defer srv.Close()
target, _ := url.Parse(srv.URL)
hc := &http.Client{
Transport: &rewritingRT{target: target, base: http.DefaultTransport},
Timeout: 5 * time.Second,
}
client := New(
WithHTTPClient(hc),
WithRateLimit(time.Microsecond, 16),
WithMaxRetries(0),
WithSFW(tc.mode),
)
if _, err := client.GetSubmission(context.Background(), 1); err != nil {
t.Fatalf("GetSubmission: %v", err)
}
if seen != tc.wantSFW {
t.Errorf("sfw cookie sent = %q; want %q", seen, tc.wantSFW)
}
})
}
}
// TestSFW_CookieDoesNotClobberAuth confirms that enabling SFW does not
// wipe out the a/b session cookies on the same jar both should ride on
// the same request.
func TestSFW_CookieDoesNotClobberAuth(t *testing.T) {
var got string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Get("Cookie")
_, _ = w.Write([]byte(`<html><body>
<div class="submission-description-artist">
<div><div class="submission-title"><h2>T</h2></div></div>
</div></body></html>`))
}))
defer srv.Close()
target, _ := url.Parse(srv.URL)
hc := &http.Client{
Transport: &rewritingRT{target: target, base: http.DefaultTransport},
Timeout: 5 * time.Second,
}
client := New(
WithHTTPClient(hc),
WithRateLimit(time.Microsecond, 16),
WithMaxRetries(0),
WithCookies(Cookies{A: "aaa", B: "bbb"}),
WithSFW(SFWOn),
)
if _, err := client.GetSubmission(context.Background(), 1); err != nil {
t.Fatalf("GetSubmission: %v", err)
}
for _, want := range []string{"a=aaa", "b=bbb", "sfw=1"} {
if !strings.Contains(got, want) {
t.Errorf("Cookie header %q missing %q", got, want)
}
}
}