package bearer
import (
"errors"
"fmt"
"net/http"
"testing"
"github.com/stretchr/testify/assert"
)
func TestStatusForKeepsTheUnreachableDaemonOutOfThe401(t *testing.T) {
// The arm the whole table exists for: a token service that cannot be
// reached must not read as a bad credential.
assert.Equal(t, http.StatusServiceUnavailable, StatusFor(ErrUnavailable))
assert.Equal(t, http.StatusServiceUnavailable,
StatusFor(fmt.Errorf("ask tokens.sr.ht: %w", ErrUnavailable)),
"a wrapped one too — services wrap before returning")
assert.Equal(t, http.StatusForbidden, StatusFor(ErrForbidden))
assert.Equal(t, http.StatusForbidden,
StatusFor(fmt.Errorf("check the grant: %w", ErrForbidden)))
// The three the caller is responsible for answer alike, on purpose.
for _, err := range []error{ErrInvalid, ErrRevoked, ErrNotOurs} {
assert.Equal(t, http.StatusUnauthorized, StatusFor(err), "%v", err)
}
assert.Equal(t, http.StatusOK, StatusFor(nil))
assert.Equal(t, http.StatusUnauthorized, StatusFor(errors.New("something new")),
"an unrecognised failure refuses the request rather than declaring the service unwell")
}
func TestChallengeNamesTheServiceAndQuotesIt(t *testing.T) {
assert.Equal(t, `Bearer realm="bench.sr.ht"`, Challenge("bench.sr.ht"))
assert.Equal(t, `Bearer realm="dolt.sr.ht"`, Challenge("dolt.sr.ht"))
// A quote in the realm would end the parameter early if it were pasted in.
assert.Equal(t, `Bearer realm="a\"b"`, Challenge(`a"b`))
}