package xfer
import (
"net/http"
"net/http/httptest"
"strconv"
"testing"
)
// The two refusals a sync read can get must be the same bytes for a
// private repository and for one that does not exist, in both the
// no-credential and the unresolved-Basic case.
func TestRefusalsIdenticalForPrivateAndUnknown(t *testing.T) {
f := challengeFronter(t)
cases := []struct {
name string
want int
set func(*http.Request)
}{
{"no credential", http.StatusUnauthorized, func(*http.Request) {}},
{"unresolved basic", http.StatusNotFound, func(r *http.Request) { r.SetBasicAuth("outsider", "x") }},
}
for _, c := range cases {
var got [2]*httptest.ResponseRecorder
for i, repo := range []string{"secret", "absent"} {
req := syncPost(t, repo)
c.set(req)
got[i] = httptest.NewRecorder()
f.ServeHTTP(got[i], req)
}
p, a := got[0], got[1]
if p.Code != c.want {
t.Errorf("FAIL: %s: status %d, want %d", c.name, p.Code, c.want)
}
if p.Code != a.Code {
t.Errorf("FAIL: %s: private %d, unknown %d", c.name, p.Code, a.Code)
}
for _, h := range []string{"WWW-Authenticate", "Link", "Content-Type"} {
if p.Header().Get(h) != a.Header().Get(h) {
t.Errorf("FAIL: %s: header %s differs", c.name, h)
}
}
if p.Header().Get("Link") == "" {
t.Errorf("FAIL: %s: no Link header", c.name)
}
if p.Body.String() != a.Body.String() || p.Body.Len() == 0 {
t.Errorf("FAIL: %s: bodies differ or are empty", c.name)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// A held account is told 429 with a positive whole-second Retry-After.
func TestHeldReadAnswers429WithRetryAfter(t *testing.T) {
f := challengeFronter(t)
w := httptest.NewRecorder()
f.refuseRead(w, syncPost(t, "secret"), loginState{offered: true, held: true, wait: 90e9})
if w.Code != http.StatusTooManyRequests {
t.Errorf("FAIL: status %d, want 429", w.Code)
}
if n, err := strconv.Atoi(w.Header().Get("Retry-After")); err != nil || n < 1 {
t.Errorf("FAIL: Retry-After %q is not a positive integer", w.Header().Get("Retry-After"))
}
if w.Header().Get("WWW-Authenticate") != "" {
t.Errorf("FAIL: a held answer must not invite another login")
}
if w.Body.Len() == 0 {
t.Errorf("FAIL: empty body")
}
if !t.Failed() {
t.Log("ok")
}
}