Skip to content

Commit eba7528

Browse files
committed
refactor(test): refactor authentication tests (#176)
1 parent c529e2d commit eba7528

File tree

3 files changed

+47
-51
lines changed

3 files changed

+47
-51
lines changed

src/index.ts

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,15 @@ import * as API from '@anthropic-ai/sdk/resources/index';
88

99
export interface ClientOptions {
1010
/**
11-
* Defaults to process.env["ANTHROPIC_API_KEY"]. Set it to null if you want to send unauthenticated requests.
11+
* Defaults to process.env['ANTHROPIC_API_KEY'].
1212
*/
1313
apiKey?: string | null;
1414

15+
/**
16+
* Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].
17+
*/
18+
authToken?: string | null;
19+
1520
/**
1621
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
1722
*/
@@ -65,29 +70,27 @@ export interface ClientOptions {
6570
* param to `undefined` in request options.
6671
*/
6772
defaultQuery?: Core.DefaultQuery;
68-
69-
authToken?: string | null;
7073
}
7174

7275
/** API Client for interfacing with the Anthropic API. */
7376
export class Anthropic extends Core.APIClient {
7477
apiKey: string | null;
75-
authToken?: string | null;
78+
authToken: string | null;
7679

7780
private _options: ClientOptions;
7881

7982
/**
8083
* API Client for interfacing with the Anthropic API.
8184
*
82-
* @param {string | null} [opts.apiKey=process.env['ANTHROPIC_API_KEY']] - The API Key to send to the API.
85+
* @param {string | null} [opts.apiKey==process.env['ANTHROPIC_API_KEY'] ?? null]
86+
* @param {string | null} [opts.authToken==process.env['ANTHROPIC_AUTH_TOKEN'] ?? null]
8387
* @param {string} [opts.baseURL] - Override the default base URL for the API.
8488
* @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
8589
* @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.
8690
* @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
8791
* @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
8892
* @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.
8993
* @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.
90-
* @param {string | null} [opts.authToken]
9194
*/
9295
constructor({
9396
apiKey = Core.readEnv('ANTHROPIC_API_KEY') ?? null,
@@ -149,25 +152,27 @@ export class Anthropic extends Core.APIClient {
149152
}
150153

151154
protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
152-
const apiKeyHeader = this.apiKeyHeader(opts);
153-
if (apiKeyHeader != null && !Core.isEmptyObj(apiKeyHeader)) {
154-
return apiKeyHeader;
155+
const apiKeyAuth = this.apiKeyAuth(opts);
156+
const bearerAuth = this.bearerAuth(opts);
157+
158+
if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {
159+
return apiKeyAuth;
155160
}
156-
const authTokenBearer = this.authTokenBearer(opts);
157-
if (authTokenBearer != null && !Core.isEmptyObj(authTokenBearer)) {
158-
return authTokenBearer;
161+
162+
if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
163+
return bearerAuth;
159164
}
160165
return {};
161166
}
162167

163-
protected apiKeyHeader(opts: Core.FinalRequestOptions): Core.Headers {
168+
protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
164169
if (this.apiKey == null) {
165170
return {};
166171
}
167172
return { 'X-Api-Key': this.apiKey };
168173
}
169174

170-
protected authTokenBearer(opts: Core.FinalRequestOptions): Core.Headers {
175+
protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers {
171176
if (this.authToken == null) {
172177
return {};
173178
}

tests/api-resources/completions.test.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,8 @@ import Anthropic from '@anthropic-ai/sdk';
44
import { Response } from 'node-fetch';
55

66
const anthropic = new Anthropic({
7-
apiKey: 'something1234',
7+
apiKey: 'my-anthropic-api-key',
88
baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010',
9-
authToken: 'my-auth-token',
109
});
1110

1211
describe('resource completions', () => {

tests/index.test.ts

Lines changed: 27 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ describe('instantiate client', () => {
2323
const client = new Anthropic({
2424
baseURL: 'http://localhost:5000/',
2525
defaultHeaders: { 'X-My-Default-Header': '2' },
26-
apiKey: 'my api key',
26+
apiKey: 'my-anthropic-api-key',
2727
});
2828

2929
test('they are used in the request', () => {
@@ -55,7 +55,7 @@ describe('instantiate client', () => {
5555
const client = new Anthropic({
5656
baseURL: 'http://localhost:5000/',
5757
defaultQuery: { apiVersion: 'foo' },
58-
apiKey: 'my api key',
58+
apiKey: 'my-anthropic-api-key',
5959
});
6060
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo');
6161
});
@@ -64,7 +64,7 @@ describe('instantiate client', () => {
6464
const client = new Anthropic({
6565
baseURL: 'http://localhost:5000/',
6666
defaultQuery: { apiVersion: 'foo', hello: 'world' },
67-
apiKey: 'my api key',
67+
apiKey: 'my-anthropic-api-key',
6868
});
6969
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo&hello=world');
7070
});
@@ -73,7 +73,7 @@ describe('instantiate client', () => {
7373
const client = new Anthropic({
7474
baseURL: 'http://localhost:5000/',
7575
defaultQuery: { hello: 'world' },
76-
apiKey: 'my api key',
76+
apiKey: 'my-anthropic-api-key',
7777
});
7878
expect(client.buildURL('/foo', { hello: undefined })).toEqual('http://localhost:5000/foo');
7979
});
@@ -82,7 +82,7 @@ describe('instantiate client', () => {
8282
test('custom fetch', async () => {
8383
const client = new Anthropic({
8484
baseURL: 'http://localhost:5000/',
85-
apiKey: 'my api key',
85+
apiKey: 'my-anthropic-api-key',
8686
fetch: (url) => {
8787
return Promise.resolve(
8888
new Response(JSON.stringify({ url, custom: true }), {
@@ -99,7 +99,7 @@ describe('instantiate client', () => {
9999
test('custom signal', async () => {
100100
const client = new Anthropic({
101101
baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010',
102-
apiKey: 'my api key',
102+
apiKey: 'my-anthropic-api-key',
103103
fetch: (...args) => {
104104
return new Promise((resolve, reject) =>
105105
setTimeout(
@@ -124,56 +124,48 @@ describe('instantiate client', () => {
124124

125125
describe('baseUrl', () => {
126126
test('trailing slash', () => {
127-
const client = new Anthropic({ baseURL: 'http://localhost:5000/custom/path/', apiKey: 'my api key' });
127+
const client = new Anthropic({
128+
baseURL: 'http://localhost:5000/custom/path/',
129+
apiKey: 'my-anthropic-api-key',
130+
});
128131
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/custom/path/foo');
129132
});
130133

131134
test('no trailing slash', () => {
132-
const client = new Anthropic({ baseURL: 'http://localhost:5000/custom/path', apiKey: 'my api key' });
135+
const client = new Anthropic({
136+
baseURL: 'http://localhost:5000/custom/path',
137+
apiKey: 'my-anthropic-api-key',
138+
});
133139
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/custom/path/foo');
134140
});
135141
});
136142

137143
test('maxRetries option is correctly set', () => {
138-
const client = new Anthropic({ maxRetries: 1, apiKey: 'my api key' });
144+
const client = new Anthropic({ maxRetries: 1, apiKey: 'my-anthropic-api-key' });
139145
expect(client.maxRetries).toEqual(1);
140146

141147
// default
142-
const client2 = new Anthropic({ apiKey: 'my api key' });
148+
const client2 = new Anthropic({ apiKey: 'my-anthropic-api-key' });
143149
expect(client2.maxRetries).toEqual(2);
144150
});
145151

146-
test('with minimal arguments', () => {
147-
// set API Key via env var
148-
process.env['ANTHROPIC_API_KEY'] = 'env var api key';
152+
test('with environment variable arguments', () => {
153+
// set options via env var
154+
process.env['ANTHROPIC_API_KEY'] = 'my-anthropic-api-key';
149155
const client = new Anthropic();
150-
expect(client.apiKey).toBe('env var api key');
151-
});
152-
153-
test('with apiKey argument', () => {
154-
process.env['ANTHROPIC_API_KEY'] = 'env var api key';
155-
156-
const client = new Anthropic({ apiKey: 'another api key' });
157-
expect(client.apiKey).toBe('another api key');
158-
});
159-
160-
test('with options argument', () => {
161-
process.env['ANTHROPIC_API_KEY'] = 'env var api key';
162-
163-
// apiKey and custom options
164-
const client = new Anthropic({ apiKey: 'my api key', authToken: 'my-auth-token' });
165-
expect(client.apiKey).toBe('my api key');
156+
expect(client.apiKey).toBe('my-anthropic-api-key');
166157
});
167158

168-
test('with disabled authentication', () => {
169-
process.env['ANTHROPIC_API_KEY'] = 'env var api key';
170-
const client = new Anthropic({ apiKey: null, authToken: 'my-auth-token' });
171-
expect(client.apiKey).toBeNull();
159+
test('with overriden environment variable arguments', () => {
160+
// set options via env var
161+
process.env['ANTHROPIC_API_KEY'] = 'another my-anthropic-api-key';
162+
const client = new Anthropic({ apiKey: 'my-anthropic-api-key' });
163+
expect(client.apiKey).toBe('my-anthropic-api-key');
172164
});
173165
});
174166

175167
describe('request building', () => {
176-
const client = new Anthropic({ apiKey: 'my api key' });
168+
const client = new Anthropic({ apiKey: 'my-anthropic-api-key' });
177169

178170
describe('Content-Length', () => {
179171
test('handles multi-byte characters', () => {
@@ -199,7 +191,7 @@ describe('retries', () => {
199191
return new Response(JSON.stringify({ a: 1 }), { headers: { 'Content-Type': 'application/json' } });
200192
};
201193

202-
const client = new Anthropic({ apiKey: 'my api key', timeout: 2000, fetch: testFetch });
194+
const client = new Anthropic({ apiKey: 'my-anthropic-api-key', timeout: 2000, fetch: testFetch });
203195

204196
expect(await client.request({ path: '/foo', method: 'get' })).toEqual({ a: 1 });
205197
expect(count).toEqual(2);

0 commit comments

Comments
 (0)