all repos

onasty @ 7dbb390c92161e9e45ec8715bbc8071061f9d85a

a one-time notes service

onasty/internal/oauth/github_test.go(view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package oauth

import (
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/oauth2"
)

func TestGitHubProvider_GetAuthURL(t *testing.T) {
	provider := NewGithubProvider("client.id", "secret", "http://localhost/callback")
	url := provider.GetAuthURL("test")

	assert.Contains(t, url, "client_id=client.id")
	assert.Contains(t, url, "state=test")
	assert.Contains(t, url, "scope=user%3Aemail")
}

type mockClient func(*http.Request) (*http.Response, error)

func (m mockClient) RoundTrip(req *http.Request) (*http.Response, error) {
	return m(req)
}

func TestGitHubProvider_ExchangeCode(t *testing.T) {
	userID := "123123"
	userEmail := "test@testing.org"
	userLogin := "testing"

	resp := fmt.Sprintf(`{"id":%s, "email":"%s", "login":"%s"}`, userID, userEmail, userLogin)
	client := &http.Client{
		Transport: mockClient(func(req *http.Request) (*http.Response, error) {
			if req.Method == http.MethodPost {
				return &http.Response{
					StatusCode: http.StatusOK,
					Header:     http.Header{"Content-Type": []string{"application/json"}},
					Body: io.NopCloser(
						strings.NewReader(`{"access_token":"fake",
							"token_type":"bearer",
							"expires_in":3600}`),
					),
				}, nil
			}
			return &http.Response{
				StatusCode: http.StatusOK,
				Header:     http.Header{"Content-Type": []string{"application/json"}},
				Body:       io.NopCloser(strings.NewReader(resp)),
			}, nil
		}),
	}

	provider := NewGithubProvider("client.id", "secret", "http://localhost")
	ctx := context.WithValue(context.TODO(), oauth2.HTTPClient, client)

	info, err := provider.ExchangeCode(ctx, "")
	require.NoError(t, err)
	assert.Equal(t, "github", info.Provider)
	assert.Equal(t, userID, info.ProviderID)
	assert.Equal(t, userEmail, info.Email)
}

func TestGitHubProvider_ExchangeCode_tokenExcahnge_error(t *testing.T) {
	client := &http.Client{
		Transport: mockClient(func(req *http.Request) (*http.Response, error) {
			if req.Method == http.MethodPost {
				return &http.Response{
					StatusCode: http.StatusBadRequest,
					Body:       io.NopCloser(strings.NewReader("")),
				}, nil
			}
			return nil, errors.New("unexpected request")
		}),
	}

	provider := NewGithubProvider("client.id", "secret", "http://localhost")
	ctx := context.WithValue(context.TODO(), oauth2.HTTPClient, client)

	_, err := provider.ExchangeCode(ctx, "")
	require.Error(t, err)
}