Skip to content

Commit

Permalink
refactor(test): refactor authentication tests (#176)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot committed Oct 16, 2023
1 parent c529e2d commit eba7528
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 51 deletions.
33 changes: 19 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,15 @@ import * as API from '@anthropic-ai/sdk/resources/index';

export interface ClientOptions {
/**
* Defaults to process.env["ANTHROPIC_API_KEY"]. Set it to null if you want to send unauthenticated requests.
* Defaults to process.env['ANTHROPIC_API_KEY'].
*/
apiKey?: string | null;

/**
* Defaults to process.env['ANTHROPIC_AUTH_TOKEN'].
*/
authToken?: string | null;

/**
* Override the default base URL for the API, e.g., "https://api.example.com/v2/"
*/
Expand Down Expand Up @@ -65,29 +70,27 @@ export interface ClientOptions {
* param to `undefined` in request options.
*/
defaultQuery?: Core.DefaultQuery;

authToken?: string | null;
}

/** API Client for interfacing with the Anthropic API. */
export class Anthropic extends Core.APIClient {
apiKey: string | null;
authToken?: string | null;
authToken: string | null;

private _options: ClientOptions;

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

protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
const apiKeyHeader = this.apiKeyHeader(opts);
if (apiKeyHeader != null && !Core.isEmptyObj(apiKeyHeader)) {
return apiKeyHeader;
const apiKeyAuth = this.apiKeyAuth(opts);
const bearerAuth = this.bearerAuth(opts);

if (apiKeyAuth != null && !Core.isEmptyObj(apiKeyAuth)) {
return apiKeyAuth;
}
const authTokenBearer = this.authTokenBearer(opts);
if (authTokenBearer != null && !Core.isEmptyObj(authTokenBearer)) {
return authTokenBearer;

if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
return bearerAuth;
}
return {};
}

protected apiKeyHeader(opts: Core.FinalRequestOptions): Core.Headers {
protected apiKeyAuth(opts: Core.FinalRequestOptions): Core.Headers {
if (this.apiKey == null) {
return {};
}
return { 'X-Api-Key': this.apiKey };
}

protected authTokenBearer(opts: Core.FinalRequestOptions): Core.Headers {
protected bearerAuth(opts: Core.FinalRequestOptions): Core.Headers {
if (this.authToken == null) {
return {};
}
Expand Down
3 changes: 1 addition & 2 deletions tests/api-resources/completions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import Anthropic from '@anthropic-ai/sdk';
import { Response } from 'node-fetch';

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

describe('resource completions', () => {
Expand Down
62 changes: 27 additions & 35 deletions tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ describe('instantiate client', () => {
const client = new Anthropic({
baseURL: 'http://localhost:5000/',
defaultHeaders: { 'X-My-Default-Header': '2' },
apiKey: 'my api key',
apiKey: 'my-anthropic-api-key',
});

test('they are used in the request', () => {
Expand Down Expand Up @@ -55,7 +55,7 @@ describe('instantiate client', () => {
const client = new Anthropic({
baseURL: 'http://localhost:5000/',
defaultQuery: { apiVersion: 'foo' },
apiKey: 'my api key',
apiKey: 'my-anthropic-api-key',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo');
});
Expand All @@ -64,7 +64,7 @@ describe('instantiate client', () => {
const client = new Anthropic({
baseURL: 'http://localhost:5000/',
defaultQuery: { apiVersion: 'foo', hello: 'world' },
apiKey: 'my api key',
apiKey: 'my-anthropic-api-key',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/foo?apiVersion=foo&hello=world');
});
Expand All @@ -73,7 +73,7 @@ describe('instantiate client', () => {
const client = new Anthropic({
baseURL: 'http://localhost:5000/',
defaultQuery: { hello: 'world' },
apiKey: 'my api key',
apiKey: 'my-anthropic-api-key',
});
expect(client.buildURL('/foo', { hello: undefined })).toEqual('http://localhost:5000/foo');
});
Expand All @@ -82,7 +82,7 @@ describe('instantiate client', () => {
test('custom fetch', async () => {
const client = new Anthropic({
baseURL: 'http://localhost:5000/',
apiKey: 'my api key',
apiKey: 'my-anthropic-api-key',
fetch: (url) => {
return Promise.resolve(
new Response(JSON.stringify({ url, custom: true }), {
Expand All @@ -99,7 +99,7 @@ describe('instantiate client', () => {
test('custom signal', async () => {
const client = new Anthropic({
baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010',
apiKey: 'my api key',
apiKey: 'my-anthropic-api-key',
fetch: (...args) => {
return new Promise((resolve, reject) =>
setTimeout(
Expand All @@ -124,56 +124,48 @@ describe('instantiate client', () => {

describe('baseUrl', () => {
test('trailing slash', () => {
const client = new Anthropic({ baseURL: 'http://localhost:5000/custom/path/', apiKey: 'my api key' });
const client = new Anthropic({
baseURL: 'http://localhost:5000/custom/path/',
apiKey: 'my-anthropic-api-key',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/custom/path/foo');
});

test('no trailing slash', () => {
const client = new Anthropic({ baseURL: 'http://localhost:5000/custom/path', apiKey: 'my api key' });
const client = new Anthropic({
baseURL: 'http://localhost:5000/custom/path',
apiKey: 'my-anthropic-api-key',
});
expect(client.buildURL('/foo', null)).toEqual('http://localhost:5000/custom/path/foo');
});
});

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

// default
const client2 = new Anthropic({ apiKey: 'my api key' });
const client2 = new Anthropic({ apiKey: 'my-anthropic-api-key' });
expect(client2.maxRetries).toEqual(2);
});

test('with minimal arguments', () => {
// set API Key via env var
process.env['ANTHROPIC_API_KEY'] = 'env var api key';
test('with environment variable arguments', () => {
// set options via env var
process.env['ANTHROPIC_API_KEY'] = 'my-anthropic-api-key';
const client = new Anthropic();
expect(client.apiKey).toBe('env var api key');
});

test('with apiKey argument', () => {
process.env['ANTHROPIC_API_KEY'] = 'env var api key';

const client = new Anthropic({ apiKey: 'another api key' });
expect(client.apiKey).toBe('another api key');
});

test('with options argument', () => {
process.env['ANTHROPIC_API_KEY'] = 'env var api key';

// apiKey and custom options
const client = new Anthropic({ apiKey: 'my api key', authToken: 'my-auth-token' });
expect(client.apiKey).toBe('my api key');
expect(client.apiKey).toBe('my-anthropic-api-key');
});

test('with disabled authentication', () => {
process.env['ANTHROPIC_API_KEY'] = 'env var api key';
const client = new Anthropic({ apiKey: null, authToken: 'my-auth-token' });
expect(client.apiKey).toBeNull();
test('with overriden environment variable arguments', () => {
// set options via env var
process.env['ANTHROPIC_API_KEY'] = 'another my-anthropic-api-key';
const client = new Anthropic({ apiKey: 'my-anthropic-api-key' });
expect(client.apiKey).toBe('my-anthropic-api-key');
});
});

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

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

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

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

0 comments on commit eba7528

Please sign in to comment.