|
4 | 4 | "context" |
5 | 5 | "encoding/json" |
6 | 6 | "fmt" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
7 | 9 | "strings" |
8 | 10 | "testing" |
9 | 11 | "time" |
@@ -101,3 +103,52 @@ func ExampleConfig_DeviceAuth() { |
101 | 103 | } |
102 | 104 | fmt.Println(token) |
103 | 105 | } |
| 106 | + |
| 107 | +func TestDeviceAuthTokenRetrieveError(t *testing.T) { |
| 108 | + runner := func(responseFun func(w http.ResponseWriter)) func(t *testing.T) { |
| 109 | + return func(t *testing.T) { |
| 110 | + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 111 | + if r.URL.String() != "/device" { |
| 112 | + t.Errorf("Unexpected device auth request URL, %v is found.", r.URL) |
| 113 | + } |
| 114 | + responseFun(w) |
| 115 | + })) |
| 116 | + defer ts.Close() |
| 117 | + conf := newConf(ts.URL) |
| 118 | + _, err := conf.DeviceAuth(context.Background()) |
| 119 | + if err == nil { |
| 120 | + t.Fatalf("got no error, expected one") |
| 121 | + } |
| 122 | + re, ok := err.(*RetrieveError) |
| 123 | + if !ok { |
| 124 | + t.Fatalf("got %T error, expected *RetrieveError; error was: %v", err, err) |
| 125 | + } |
| 126 | + expected := `oauth2: "invalid_grant" "sometext"` |
| 127 | + if errStr := err.Error(); errStr != expected { |
| 128 | + t.Fatalf("got %#v, expected %#v", errStr, expected) |
| 129 | + } |
| 130 | + expected = "invalid_grant" |
| 131 | + if re.ErrorCode != expected { |
| 132 | + t.Fatalf("got %#v, expected %#v", re.ErrorCode, expected) |
| 133 | + } |
| 134 | + expected = "sometext" |
| 135 | + if re.ErrorDescription != expected { |
| 136 | + t.Fatalf("got %#v, expected %#v", re.ErrorDescription, expected) |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + t.Run("UrlEncoding", runner(func(w http.ResponseWriter) { |
| 142 | + w.Header().Set("Content-type", "application/x-www-form-urlencoded") |
| 143 | + // "The authorization server responds with an HTTP 400 (Bad Request)" https://www.rfc-editor.org/rfc/rfc6749#section-5.2 |
| 144 | + w.WriteHeader(http.StatusBadRequest) |
| 145 | + w.Write([]byte(`error=invalid_grant&error_description=sometext`)) |
| 146 | + })) |
| 147 | + |
| 148 | + t.Run("JSON", runner(func(w http.ResponseWriter) { |
| 149 | + w.Header().Set("Content-type", "application/json") |
| 150 | + // "The authorization server responds with an HTTP 400 (Bad Request)" https://www.rfc-editor.org/rfc/rfc6749#section-5.2 |
| 151 | + w.WriteHeader(http.StatusBadRequest) |
| 152 | + w.Write([]byte(`{"error": "invalid_grant", "error_description": "sometext"}`)) |
| 153 | + })) |
| 154 | +} |
0 commit comments