golang.org/x/oauth2@v0.18.0/deviceauth_test.go (about) 1 package oauth2 2 3 import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "strings" 8 "testing" 9 "time" 10 11 "github.com/google/go-cmp/cmp" 12 "github.com/google/go-cmp/cmp/cmpopts" 13 ) 14 15 func TestDeviceAuthResponseMarshalJson(t *testing.T) { 16 tests := []struct { 17 name string 18 response DeviceAuthResponse 19 want string 20 }{ 21 { 22 name: "empty", 23 response: DeviceAuthResponse{}, 24 want: `{"device_code":"","user_code":"","verification_uri":""}`, 25 }, 26 { 27 name: "soon", 28 response: DeviceAuthResponse{ 29 Expiry: time.Now().Add(100*time.Second + 999*time.Millisecond), 30 }, 31 want: `{"expires_in":100,"device_code":"","user_code":"","verification_uri":""}`, 32 }, 33 } 34 for _, tc := range tests { 35 t.Run(tc.name, func(t *testing.T) { 36 begin := time.Now() 37 gotBytes, err := json.Marshal(tc.response) 38 if err != nil { 39 t.Fatal(err) 40 } 41 if strings.Contains(tc.want, "expires_in") && time.Since(begin) > 999*time.Millisecond { 42 t.Skip("test ran too slowly to compare `expires_in`") 43 } 44 got := string(gotBytes) 45 if got != tc.want { 46 t.Errorf("want=%s, got=%s", tc.want, got) 47 } 48 }) 49 } 50 } 51 52 func TestDeviceAuthResponseUnmarshalJson(t *testing.T) { 53 tests := []struct { 54 name string 55 data string 56 want DeviceAuthResponse 57 }{ 58 { 59 name: "empty", 60 data: `{}`, 61 want: DeviceAuthResponse{}, 62 }, 63 { 64 name: "soon", 65 data: `{"expires_in":100}`, 66 want: DeviceAuthResponse{Expiry: time.Now().UTC().Add(100 * time.Second)}, 67 }, 68 } 69 for _, tc := range tests { 70 t.Run(tc.name, func(t *testing.T) { 71 begin := time.Now() 72 got := DeviceAuthResponse{} 73 err := json.Unmarshal([]byte(tc.data), &got) 74 if err != nil { 75 t.Fatal(err) 76 } 77 if !cmp.Equal(got, tc.want, cmpopts.IgnoreUnexported(DeviceAuthResponse{}), cmpopts.EquateApproxTime(time.Second+time.Since(begin))) { 78 t.Errorf("want=%#v, got=%#v", tc.want, got) 79 } 80 }) 81 } 82 } 83 84 func ExampleConfig_DeviceAuth() { 85 var config Config 86 ctx := context.Background() 87 response, err := config.DeviceAuth(ctx) 88 if err != nil { 89 panic(err) 90 } 91 fmt.Printf("please enter code %s at %s\n", response.UserCode, response.VerificationURI) 92 token, err := config.DeviceAccessToken(ctx, response) 93 if err != nil { 94 panic(err) 95 } 96 fmt.Println(token) 97 }