Skip to content

Commit 7774e29

Browse files
committed
Add codersdk function + test
1 parent 9cc7e94 commit 7774e29

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

coderd/users_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,33 @@ func TestOrganizationsByUser(t *testing.T) {
119119
require.Len(t, orgs, 1)
120120
}
121121

122+
func TestPostAPIKey(t *testing.T) {
123+
t.Parallel()
124+
t.Run("InvalidUser", func(t *testing.T) {
125+
t.Parallel()
126+
client := coderdtest.New(t)
127+
_ = coderdtest.CreateInitialUser(t, client)
128+
129+
// Clear session token
130+
client.SessionToken = ""
131+
// ...and request an API key
132+
_, err := client.CreateApiKey(context.Background())
133+
var apiErr *codersdk.Error
134+
require.ErrorAs(t, err, &apiErr)
135+
require.Equal(t, http.StatusUnauthorized, apiErr.StatusCode())
136+
})
137+
138+
t.Run("Success", func(t *testing.T) {
139+
t.Parallel()
140+
client := coderdtest.New(t)
141+
_ = coderdtest.CreateInitialUser(t, client)
142+
apiKey, err := client.CreateApiKey(context.Background())
143+
require.NotNil(t, apiKey)
144+
require.GreaterOrEqual(t, len(apiKey.Key), 2)
145+
require.NoError(t, err)
146+
})
147+
}
148+
122149
func TestPostLogin(t *testing.T) {
123150
t.Parallel()
124151
t.Run("InvalidUser", func(t *testing.T) {

codersdk/users.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,20 @@ func (c *Client) CreateUser(ctx context.Context, req coderd.CreateUserRequest) (
5656
return user, json.NewDecoder(res.Body).Decode(&user)
5757
}
5858

59+
// CreateApiKey calls the /api-key API
60+
func (c *Client) CreateApiKey(ctx context.Context) (*coderd.GenerateAPIKeyResponse, error) {
61+
res, err := c.request(ctx, http.MethodPost, fmt.Sprintf("/api/v2/api-keys"), nil)
62+
if err != nil {
63+
return nil, err
64+
}
65+
defer res.Body.Close()
66+
if res.StatusCode > http.StatusCreated {
67+
return nil, readBodyAsError(res)
68+
}
69+
apiKey := &coderd.GenerateAPIKeyResponse{}
70+
return apiKey, json.NewDecoder(res.Body).Decode(apiKey)
71+
}
72+
5973
// LoginWithPassword creates a session token authenticating with an email and password.
6074
// Call `SetSessionToken()` to apply the newly acquired token to the client.
6175
func (c *Client) LoginWithPassword(ctx context.Context, req coderd.LoginWithPasswordRequest) (coderd.LoginWithPasswordResponse, error) {

0 commit comments

Comments
 (0)