[core-rest-pipeline] Switch browser transport to fetch (#20201)

Thanks to #19530 we have a new HttpClient that uses Fetch. Currently, we can't make it the default because of recorded tests. However, we'd like folks to be able to try it out, which this PR makes possible.

The solution here is for tests that are dependent on XHR to pass in a custom HttpClient to allow the previous recordings to be used until we can migrate those packages to the new recorder.
This commit is contained in:
Jeff Fisher 2022-02-10 15:08:00 -08:00 коммит произвёл GitHub
Родитель a6a534cb1e
Коммит 9afbe3fc46
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
36 изменённых файлов: 418 добавлений и 135 удалений

Просмотреть файл

@ -12578,7 +12578,7 @@ packages:
dev: false
file:projects/communication-chat.tgz:
resolution: {integrity: sha512-hAsX/useFCAtpCEUcF5W9QJhMk4bKlvJxPZCcQun8gU0CfnNlEAWIIBIimCO0vaEqLBkWT533C/i39l7IvrdjA==, tarball: file:projects/communication-chat.tgz}
resolution: {integrity: sha512-oZDdYdSoVSS2yJpAUgYO/VXraUzDbQyrp+curzNMMAoXaQbiVSEaYzSG1E08daCx89RKfbCU2rmgwoSfMUhsGw==, tarball: file:projects/communication-chat.tgz}
name: '@rush-temp/communication-chat'
version: 0.0.0
dependencies:
@ -12921,7 +12921,7 @@ packages:
dev: false
file:projects/confidential-ledger.tgz:
resolution: {integrity: sha512-HNeIndkzUiVhjrAuyjKpWvZq7LFFUbqNbWUXTmG/ZCtnhIUbDErE7j/HtFIMIk9wadwbidVgCZv9fqBpfx1Giw==, tarball: file:projects/confidential-ledger.tgz}
resolution: {integrity: sha512-CfY0ocy8x0pNfd6YHV0qDb2Sx+QpvfossY2kKFlq2QO5MC6iXr7pGiJ9WFo/75YDjSfG3BosKwO4e5eKOGkadw==, tarball: file:projects/confidential-ledger.tgz}
name: '@rush-temp/confidential-ledger'
version: 0.0.0
dependencies:
@ -13556,7 +13556,7 @@ packages:
dev: false
file:projects/cosmos.tgz:
resolution: {integrity: sha512-FT89IjhpMiUOiBzt/uZDeqVKcfDfx+JuVYGy2BUvPpCXb4wY+3XGd5rm503sdUsSo3A4CbpygNhQYiaG/NN+Zg==, tarball: file:projects/cosmos.tgz}
resolution: {integrity: sha512-/O1zcTjD8j6vCMskO0SBDyrSuac9/LADzo0e6IWxFD4wmNv/DdasrmDFTbLFzEpSKeuG6nm/AAFlFmALo8B8EA==, tarball: file:projects/cosmos.tgz}
name: '@rush-temp/cosmos'
version: 0.0.0
dependencies:
@ -13912,7 +13912,7 @@ packages:
dev: false
file:projects/eventgrid.tgz:
resolution: {integrity: sha512-cRipNDlfS0co7HptArkxqp6lbNAffyBqpvSVSDhMe/ZR5cBJs6ywzCsV/QxHhxBpp6Z7p5To9h98IYOOIhMp+A==, tarball: file:projects/eventgrid.tgz}
resolution: {integrity: sha512-5cMNL6d3puoJz7tLWxl1yyAwtd3EI7uAMvn+q3AAyZHJFG7WdS3l7IfCL8i8LD2qvRdpRJxm88jqVsLU3oA+Eg==, tarball: file:projects/eventgrid.tgz}
name: '@rush-temp/eventgrid'
version: 0.0.0
dependencies:
@ -13960,7 +13960,6 @@ packages:
- '@swc/wasm'
- bufferutil
- debug
- encoding
- supports-color
- utf-8-validate
dev: false
@ -14547,7 +14546,7 @@ packages:
dev: false
file:projects/mixed-reality-authentication.tgz:
resolution: {integrity: sha512-ireSIDtkXJsNgz4Dnt7//b7i/ZXBBYSFHlZJuIP5kyPCQwi9L6cYK/BNVaMbqr3aY04nXJB06N1xa4/72Yw1ig==, tarball: file:projects/mixed-reality-authentication.tgz}
resolution: {integrity: sha512-kUKj3HVSS+3ub+3HC4dRdr494TlT33kdcHOLGsMkGcBu56vQ69qj65oJU++VayyRpQn4+B0KMLeVAWL4EpNvAw==, tarball: file:projects/mixed-reality-authentication.tgz}
name: '@rush-temp/mixed-reality-authentication'
version: 0.0.0
dependencies:
@ -15215,7 +15214,7 @@ packages:
dev: false
file:projects/purview-administration.tgz:
resolution: {integrity: sha512-qwAKjd1LG91KHMU3KDLYYcn4kaXGAAt9bOPSmQhdw+SfogUEnorWSRDpC8wiaJIkFGNaqLnLLxxTjGRIsnKv6g==, tarball: file:projects/purview-administration.tgz}
resolution: {integrity: sha512-Z16hjklcfBBkYbwEMmEEC4QtxSnbIFdVyiD1OFdjnPeFt+ZbHxhs4BOtkc6vCQEZb5vgPEqJ5PULYbtKpJHuWg==, tarball: file:projects/purview-administration.tgz}
name: '@rush-temp/purview-administration'
version: 0.0.0
dependencies:
@ -15261,7 +15260,7 @@ packages:
dev: false
file:projects/purview-catalog.tgz:
resolution: {integrity: sha512-aI0F2b35+d39Ofj5Ll6m2HN1lBlXoZW0jHp7H+5/b31YL+Ggtd5/Fes9+3Fy+WzMbVu00/oLxUsEj74ZhcRxRQ==, tarball: file:projects/purview-catalog.tgz}
resolution: {integrity: sha512-cQaHJb4jVWl+mTuCSJZ1anD4t1eVre5FR//AEZeIdneTG2v+K/dBs5hNIa9IvHGoMl0yE0JNcb7cbMod+kAW3g==, tarball: file:projects/purview-catalog.tgz}
name: '@rush-temp/purview-catalog'
version: 0.0.0
dependencies:
@ -15307,7 +15306,7 @@ packages:
dev: false
file:projects/purview-scanning.tgz:
resolution: {integrity: sha512-pVwr6HLjqikx6FznSmPj44guD9UcjaUINtlJdjQ4Md5V5zus/v5OjhgGiJmL2LEvD774hJ/H8OvAf669HMycMw==, tarball: file:projects/purview-scanning.tgz}
resolution: {integrity: sha512-WnLaSRZ6CxnvKrbs6jpe/E/bwaNuNKvHFrC2xf1hNtmbCQffNmeVdCa0GHmsZ/GUruKGIIfeqKTw+cYOBeW0/Q==, tarball: file:projects/purview-scanning.tgz}
name: '@rush-temp/purview-scanning'
version: 0.0.0
dependencies:
@ -16348,7 +16347,7 @@ packages:
dev: false
file:projects/test-utils.tgz:
resolution: {integrity: sha512-AFgkL3dgLAohwVqFbcheVU/1ilNuMd0EKWTXQa3icxO3aqg6o1lvZRCCfPAtUNfApHLJHOZ59atB5j11Z22PXg==, tarball: file:projects/test-utils.tgz}
resolution: {integrity: sha512-6YltGfIt/N0fCMBst9a1WUIdPHEd1P07BVbpdSywL40SvBUrIl5KPmupCINQAYHCf6BvExke3q712AwIb3BGcA==, tarball: file:projects/test-utils.tgz}
name: '@rush-temp/test-utils'
version: 0.0.0
dependencies:
@ -16364,6 +16363,7 @@ packages:
chai: 4.3.6
chai-as-promised: 7.1.1_chai@4.3.6
chai-exclude: 2.1.0_chai@4.3.6
cross-env: 7.0.3
eslint: 7.32.0
karma: 6.3.15
karma-chrome-launcher: 3.1.0

Просмотреть файл

@ -281,6 +281,12 @@
{
"name": "mixed-reality-remote-rendering",
"path": "sdk/remoterendering/mixed-reality-remote-rendering"
},
{
"path": "sdk/test-utils/test-utils"
},
{
"path": "sdk/purview/purview-administration-rest"
}
],
"settings": {

Просмотреть файл

@ -83,7 +83,7 @@
"autoPublish": false,
"dependencies": {
"@azure/core-auth": "^1.3.0",
"@azure-rest/core-client": "1.0.0-beta.8",
"@azure-rest/core-client": "1.0.0-beta.9",
"@azure/core-rest-pipeline": "^1.1.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0"
@ -92,6 +92,7 @@
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/identity": "^2.0.1",
"@azure/test-utils": "^1.0.0",
"@azure-tools/test-recorder": "^1.0.0",
"@microsoft/api-extractor": "^7.18.11",
"@types/chai": "^4.1.6",

Просмотреть файл

@ -5,9 +5,16 @@
import { Context } from "mocha";
import { env, Recorder, record, RecorderEnvironmentSetup } from "@azure-tools/test-recorder";
import {
env,
Recorder,
record,
RecorderEnvironmentSetup,
isLiveMode,
} from "@azure-tools/test-recorder";
import ConfidentialLedger, { ConfidentialLedgerRestClient } from "../../../src";
import { ClientSecretCredential } from "@azure/identity";
import { isNode, createXhrHttpClient } from "@azure/test-utils";
import "./env";
@ -38,12 +45,14 @@ export const environmentSetup: RecorderEnvironmentSetup = {
};
export function createClient(): ConfidentialLedgerRestClient {
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
const credential = new ClientSecretCredential(
env["AZURE_TENANT_ID"],
env["AZURE_CLIENT_ID"],
env["AZURE_CLIENT_SECRET"]
env["AZURE_CLIENT_SECRET"],
{ httpClient }
);
return ConfidentialLedger(env.ENDPOINT, env.LEDGER_IDENTITY, credential);
return ConfidentialLedger(env.ENDPOINT, env.LEDGER_IDENTITY, credential, { httpClient });
}
/**

Просмотреть файл

@ -6,8 +6,11 @@ import {
env,
RecorderEnvironmentSetup,
pluginForClientSecretCredentialTests,
isLiveMode,
} from "@azure-tools/test-recorder";
import { ContainerRegistryClient, KnownContainerRegistryAudience } from "../../src";
import { isNode } from "./isNode";
import { createXhrHttpClient } from "@azure/test-utils";
// When the recorder observes the values of these environment variables in any
// recorded HTTP request or response, it will replace them with the values they
@ -92,9 +95,11 @@ export function createRegistryClient(
const authorityHost = getAuthority(endpoint);
const audience = getAudience(authorityHost);
const tokenCredentialOptions = authorityHost ? { authorityHost } : undefined;
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
const clientOptions = {
audience,
serviceVersion: serviceVersion as ContainerRegistryServiceVersions,
httpClient,
};
if (options.anonymous) {
@ -110,7 +115,7 @@ export function createRegistryClient(
env.CONTAINERREGISTRY_TENANT_ID,
env.CONTAINERREGISTRY_CLIENT_ID,
env.CONTAINERREGISTRY_CLIENT_SECRET,
tokenCredentialOptions
{ ...tokenCredentialOptions, httpClient }
);
return new ContainerRegistryClient(endpoint, credential, clientOptions);

Просмотреть файл

@ -4,6 +4,7 @@
```ts
import { HttpClient } from '@azure/core-rest-pipeline';
import { KeyCredential } from '@azure/core-auth';
import { Pipeline } from '@azure/core-rest-pipeline';
import { PipelineOptions } from '@azure/core-rest-pipeline';
@ -43,6 +44,7 @@ export type ClientOptions = PipelineOptions & {
apiVersion?: string;
allowInsecureConnection?: boolean;
additionalPolicies?: AdditionalPolicyConfig[];
httpClient?: HttpClient;
};
// @public

Просмотреть файл

@ -2,6 +2,7 @@
// Licensed under the MIT license.
import {
HttpClient,
Pipeline,
PipelineOptions,
PipelinePolicy,
@ -181,6 +182,10 @@ export type ClientOptions = PipelineOptions & {
* Additional policies to include in the HTTP pipeline.
*/
additionalPolicies?: AdditionalPolicyConfig[];
/**
* Specify a custom HttpClient when making requests.
*/
httpClient?: HttpClient;
};
/**

Просмотреть файл

@ -3,7 +3,7 @@
import { isTokenCredential, KeyCredential, TokenCredential } from "@azure/core-auth";
import { isCertificateCredential } from "./certificateCredential";
import { HttpMethods, Pipeline, PipelineOptions } from "@azure/core-rest-pipeline";
import { HttpClient, HttpMethods, Pipeline, PipelineOptions } from "@azure/core-rest-pipeline";
import { createDefaultPipeline } from "./clientHelpers";
import { Client, ClientOptions, HttpResponse, RequestParameters } from "./common";
import { sendRequest } from "./sendRequest";
@ -52,7 +52,7 @@ export function getClient(
}
}
const { allowInsecureConnection } = clientOptions;
const { allowInsecureConnection, httpClient } = clientOptions;
const client = (path: string, ...args: Array<any>) => {
return {
get: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -62,7 +62,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
post: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -72,7 +73,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
put: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -82,7 +84,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
patch: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -92,7 +95,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
delete: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -102,7 +106,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
head: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -112,7 +117,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
options: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -122,7 +128,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
trace: (options: RequestParameters = {}): Promise<HttpResponse> => {
@ -132,7 +139,8 @@ export function getClient(
path,
pipeline,
{ allowInsecureConnection, ...options },
args
args,
httpClient
);
},
};
@ -151,11 +159,12 @@ function buildSendRequest(
path: string,
pipeline: Pipeline,
requestOptions: RequestParameters = {},
args: string[] = []
args: string[] = [],
httpClient?: HttpClient
): Promise<HttpResponse> {
// If the client has an api-version and the request doesn't specify one, inject the one in the client options
const url = buildRequestUrl(baseUrl, path, args, requestOptions);
return sendRequest(method, url, pipeline, requestOptions);
return sendRequest(method, url, pipeline, requestOptions, httpClient);
}
function isCredential(

Просмотреть файл

@ -5,6 +5,7 @@ import {
createHttpHeaders,
createPipelineRequest,
FormDataMap,
HttpClient,
HttpMethods,
Pipeline,
PipelineRequest,
@ -23,15 +24,17 @@ import { binaryArrayToString, stringToBinaryArray } from "./helpers/getBinaryBod
* @param url - url to send the request to
* @param pipeline - pipeline with the policies to run when sending the request
* @param options - request options
* @param customHttpClient - a custom HttpClient to use when making the request
* @returns returns and HttpResponse
*/
export async function sendRequest(
method: HttpMethods,
url: string,
pipeline: Pipeline,
options: RequestParameters = {}
options: RequestParameters = {},
customHttpClient?: HttpClient
): Promise<HttpResponse> {
const httpClient = getCachedDefaultHttpsClient();
const httpClient = customHttpClient ?? getCachedDefaultHttpsClient();
const request = buildPipelineRequest(method, url, options);
const response = await pipeline.sendRequest(httpClient, request);
const rawHeaders: RawHttpHeaders = response.headers.toJSON();

Просмотреть файл

@ -2,11 +2,11 @@
// Licensed under the MIT license.
import { HttpClient } from "./interfaces";
import { createXhrHttpClient } from "./xhrHttpClient";
import { createFetchHttpClient } from "./fetchHttpClient";
/**
* Create the correct HttpClient for the current environment.
*/
export function createDefaultHttpClient(): HttpClient {
return createXhrHttpClient();
return createFetchHttpClient();
}

Просмотреть файл

@ -26,6 +26,17 @@ export function prepareMSALResponses(): RawTestResponse[] {
return [];
}
/**
* Keep track of requested resources.
* @internal
*/
export type TrackedRequest = {
url: string;
body: string;
method: string;
headers: Record<string, string>;
};
/**
* Sets up the environment necessary to do unit testing to Identity credentials.
* We leverage Sinon to mock the internals of the http and the https modules (in Node, and the SinonFakeXMLHttpRequest in the browser).
@ -41,8 +52,8 @@ export class IdentityTestContext implements IdentityTestContextInterface {
public oldLogLevel: AzureLogLevel | undefined;
public oldLogger: any;
public logMessages: string[];
public server: sinon.SinonFakeServer;
public requests: sinon.SinonFakeXMLHttpRequest[];
public fetch: sinon.SinonStub;
public requests: TrackedRequest[];
public responses: RawTestResponse[];
constructor({ replaceLogger, logLevel }: { replaceLogger?: boolean; logLevel?: AzureLogLevel }) {
@ -54,9 +65,9 @@ export class IdentityTestContext implements IdentityTestContextInterface {
/**
* Browser specific code.
* Sets up a fake server that will be used to answer any outgoing request.
* Sets up a fake fetch implementation that will be used to answer any outgoing request.
*/
this.server = this.sandbox.useFakeServer();
this.fetch = this.sandbox.stub(self, "fetch");
this.requests = [];
this.responses = [];
@ -71,6 +82,22 @@ export class IdentityTestContext implements IdentityTestContextInterface {
}
}
private _trackRequest(url: RequestInfo, request?: RequestInit) {
const headers = new Headers(request?.headers);
const rawHeaders: Record<string, string> = {};
headers.forEach((key, value) => {
rawHeaders[key] = value;
});
this.requests.push({
url: url.toString(),
body: request?.body?.toString() ?? "",
method: request?.method ?? "GET",
headers: rawHeaders,
});
}
async restore(): Promise<void> {
this.sandbox.restore();
AzureLogger.log = this.oldLogger;
@ -89,12 +116,15 @@ export class IdentityTestContext implements IdentityTestContextInterface {
* Both keeps track of the outgoing requests,
* and ensures each request answers with each received response, in order.
*/
this.server.respondWith((xhr) => {
this.requests.push(xhr);
xhr.respond(response.statusCode, response.headers, response.body);
this.fetch.callsFake(async (url, request) => {
this._trackRequest(url, request);
return new Response(response.body, {
headers: response.headers,
status: response.statusCode,
});
});
const promise = sendPromise();
this.server.respond();
await this.clock.runAllAsync();
return promise;
}
@ -135,16 +165,22 @@ export class IdentityTestContext implements IdentityTestContextInterface {
}[];
}> {
this.responses.push(...[...insecureResponses, ...secureResponses]);
this.server.respondWith((xhr) => {
this.requests.push(xhr);
this.fetch.callsFake(async (url, request) => {
this._trackRequest(url, request);
if (!this.responses.length) {
throw new Error("No responses to send");
}
const { response, error } = this.responses.shift()!;
if (response) {
xhr.respond(response.statusCode, response.headers, response.body);
return new Response(response.body, {
headers: response.headers,
status: response.statusCode,
});
} else if (error) {
xhr.respond(error.statusCode!, {}, error.message);
return new Response(error.message, {
headers: {},
status: error.statusCode,
});
} else {
throw new Error("No response or error to send");
}
@ -158,7 +194,6 @@ export class IdentityTestContext implements IdentityTestContextInterface {
// We need the promises to begin triggering, so the server has something to respond to,
// and only then we can wait for all of the async processes to finish.
const promise = credential.getToken(scopes, getTokenOptions);
this.server.respond();
await this.clock.runAllAsync();
result = await promise;
} catch (e) {
@ -168,14 +203,7 @@ export class IdentityTestContext implements IdentityTestContextInterface {
return {
result,
error,
requests: this.requests.map((request) => {
return {
url: request.url,
body: request.requestBody,
method: request.method,
headers: request.requestHeaders,
};
}),
requests: this.requests,
};
}
}

Просмотреть файл

@ -6,10 +6,10 @@
/// <reference lib="esnext.asynciterable" />
import { CommonClientOptions } from '@azure/core-client';
import { FullOperationResponse } from '@azure/core-client';
import { OperationOptions } from '@azure/core-client';
import { PagedAsyncIterableIterator } from '@azure/core-paging';
import { PipelineOptions } from '@azure/core-rest-pipeline';
import { TokenCredential } from '@azure/core-auth';
// @public
@ -885,7 +885,7 @@ export class MetricsAdvisorAdministrationClient {
}
// @public
export interface MetricsAdvisorAdministrationClientOptions extends PipelineOptions {
export interface MetricsAdvisorAdministrationClientOptions extends CommonClientOptions {
}
// @public
@ -910,7 +910,7 @@ export class MetricsAdvisorClient {
}
// @public
export interface MetricsAdvisorClientOptions extends PipelineOptions {
export interface MetricsAdvisorClientOptions extends CommonClientOptions {
}
// @public

Просмотреть файл

@ -6,9 +6,8 @@
import {
bearerTokenAuthenticationPolicy,
InternalPipelineOptions,
PipelineOptions,
} from "@azure/core-rest-pipeline";
import { FullOperationResponse, OperationOptions } from "@azure/core-client";
import { FullOperationResponse, OperationOptions, CommonClientOptions } from "@azure/core-client";
import { isTokenCredential, TokenCredential } from "@azure/core-auth";
import { PagedAsyncIterableIterator, PageSettings } from "@azure/core-paging";
import "@azure/core-paging";
@ -73,7 +72,7 @@ import {
/**
* Client options used to configure API requests.
*/
export interface MetricsAdvisorAdministrationClientOptions extends PipelineOptions {}
export interface MetricsAdvisorAdministrationClientOptions extends CommonClientOptions {}
/**
* Options for listing data feed ingestion status

Просмотреть файл

@ -3,13 +3,11 @@
/// <reference lib="esnext.asynciterable" />
// operationOptionsTofinalOptionsBase
import {
bearerTokenAuthenticationPolicy,
InternalPipelineOptions,
PipelineOptions,
} from "@azure/core-rest-pipeline";
import { OperationOptions } from "@azure/core-client";
import { OperationOptions, CommonClientOptions } from "@azure/core-client";
import { PagedAsyncIterableIterator, PageSettings } from "@azure/core-paging";
import { isTokenCredential, TokenCredential } from "@azure/core-auth";
import { GeneratedClient } from "./generated/generatedClient";
@ -51,7 +49,7 @@ import { logger } from "./logger";
/**
* Client options used to configure Metrics Advisor API requests.
*/
export interface MetricsAdvisorClientOptions extends PipelineOptions {}
export interface MetricsAdvisorClientOptions extends CommonClientOptions {}
/**
* Options for listing incidents for detection configurations

Просмотреть файл

@ -3,7 +3,13 @@
import { Context } from "mocha";
import { env, Recorder, record, RecorderEnvironmentSetup } from "@azure-tools/test-recorder";
import {
env,
Recorder,
record,
RecorderEnvironmentSetup,
isLiveMode,
} from "@azure-tools/test-recorder";
import { ClientSecretCredential } from "@azure/identity";
import { TokenCredential } from "@azure/core-auth";
import {
@ -12,6 +18,7 @@ import {
MetricsAdvisorAdministrationClient,
} from "../../../src";
import * as dotenv from "dotenv";
import { createXhrHttpClient } from "@azure/test-utils";
/**
* A constant that indicates whether the environment is node.js or browser based.
@ -25,6 +32,7 @@ export const isNode =
if (isNode) {
dotenv.config();
}
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
export interface RecordedAdminClient {
client: MetricsAdvisorAdministrationClient;
@ -94,7 +102,9 @@ export function createRecordedAdminClient(
): RecordedAdminClient {
const recorder = record(context, environmentSetup);
return {
client: new MetricsAdvisorAdministrationClient(testEnv.METRICS_ADVISOR_ENDPOINT, apiKey),
client: new MetricsAdvisorAdministrationClient(testEnv.METRICS_ADVISOR_ENDPOINT, apiKey, {
httpClient,
}),
recorder,
};
}
@ -105,7 +115,7 @@ export function createRecordedAdvisorClient(
): RecordedAdvisorClient {
const recorder = record(context, environmentSetup);
return {
client: new MetricsAdvisorClient(testEnv.METRICS_ADVISOR_ENDPOINT, apiKey),
client: new MetricsAdvisorClient(testEnv.METRICS_ADVISOR_ENDPOINT, apiKey, { httpClient }),
recorder,
};
}
@ -118,7 +128,10 @@ export function makeCredential(useAad: boolean): TokenCredential | MetricsAdviso
? new ClientSecretCredential(
testEnv.AZURE_TENANT_ID,
testEnv.AZURE_CLIENT_ID,
testEnv.AZURE_CLIENT_SECRET
testEnv.AZURE_CLIENT_SECRET,
{
httpClient,
}
)
: new MetricsAdvisorKeyCredential(
testEnv.METRICS_ADVISOR_SUBSCRIPTION_KEY,

Просмотреть файл

@ -71,6 +71,7 @@
"devDependencies": {
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/test-utils": "^1.0.0",
"@azure-tools/test-recorder": "^1.0.0",
"@microsoft/api-extractor": "^7.18.11",
"@types/chai": "^4.1.6",

Просмотреть файл

@ -2,7 +2,14 @@
// Licensed under the MIT license.
import "./env";
import { Recorder, RecorderEnvironmentSetup, env, record } from "@azure-tools/test-recorder";
import {
Recorder,
RecorderEnvironmentSetup,
env,
isLiveMode,
record,
} from "@azure-tools/test-recorder";
import { createXhrHttpClient, isNode } from "@azure/test-utils";
import { AzureKeyCredential } from "@azure/core-auth";
import { Context } from "mocha";
import { MixedRealityStsClient } from "../../src";
@ -41,10 +48,11 @@ export function createClient(): MixedRealityStsClient {
const accountDomain = getEnv("MIXEDREALITY_ACCOUNT_DOMAIN");
const accountId = getEnv("MIXEDREALITY_ACCOUNT_ID");
const accountKey = getEnv("MIXEDREALITY_ACCOUNT_KEY");
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
const keyCredential = new AzureKeyCredential(accountKey);
return new MixedRealityStsClient(accountId, accountDomain, keyCredential);
return new MixedRealityStsClient(accountId, accountDomain, keyCredential, { httpClient });
}
/**

Просмотреть файл

@ -85,7 +85,7 @@
"dependencies": {
"@azure/core-paging": "^1.1.1",
"@azure/core-auth": "^1.3.0",
"@azure-rest/core-client": "1.0.0-beta.7",
"@azure-rest/core-client": "1.0.0-beta.9",
"@azure/core-rest-pipeline": "^1.1.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0"
@ -94,6 +94,7 @@
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/identity": "^2.0.1",
"@azure/test-utils": "^1.0.0",
"@azure-tools/test-recorder": "^1.0.0",
"@microsoft/api-extractor": "^7.18.0",
"@types/chai": "^4.1.6",

Просмотреть файл

@ -5,7 +5,13 @@
import { Context } from "mocha";
import { env, Recorder, record, RecorderEnvironmentSetup } from "@azure-tools/test-recorder";
import {
env,
isLiveMode,
Recorder,
record,
RecorderEnvironmentSetup,
} from "@azure-tools/test-recorder";
import {
PurviewAccount,
PurviewAccountClient,
@ -13,10 +19,13 @@ import {
PurviewMetadataPoliciesClient,
} from "../../../src";
import { ClientSecretCredential } from "@azure/identity";
import { isNode, createXhrHttpClient } from "@azure/test-utils";
import "./env";
import { ClientOptions } from "@azure-rest/core-client";
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
const replaceableVariables: { [k: string]: string } = {
ENDPOINT: "https://endpoint",
AZURE_CLIENT_ID: "azure_client_id",
@ -47,9 +56,10 @@ export function createAccountClient(
const credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET
env.AZURE_CLIENT_SECRET,
{ httpClient }
);
return PurviewAccountClient(env.ENDPOINT, credential, options);
return PurviewAccountClient(env.ENDPOINT, credential, { httpClient, ...options });
}
export function createMetadataClient(
@ -58,9 +68,10 @@ export function createMetadataClient(
const credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET
env.AZURE_CLIENT_SECRET,
{ httpClient }
);
return PurviewMetadataPoliciesClient(env.ENDPOINT, credential, options);
return PurviewMetadataPoliciesClient(env.ENDPOINT, credential, { httpClient, ...options });
}
/**

Просмотреть файл

@ -50,9 +50,7 @@
"disableDocsMs": true,
"apiRefLink": "https://docs.microsoft.com/rest/api/purview/"
},
"browser": {
"./dist-esm/test/public/utils/env.js": "./dist-esm/test/public/utils/env.browser.js"
},
"browser": {},
"scripts": {
"audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
"build:browser": "tsc -p . && dev-tool run bundle",
@ -85,7 +83,7 @@
"dependencies": {
"@azure/core-lro": "^2.2.0",
"@azure/core-auth": "^1.3.0",
"@azure-rest/core-client": "1.0.0-beta.7",
"@azure-rest/core-client": "1.0.0-beta.9",
"@azure/core-rest-pipeline": "^1.1.0",
"@azure/logger": "^1.0.0",
"tslib": "^2.2.0"
@ -94,6 +92,7 @@
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/identity": "^2.0.1",
"@azure/test-utils": "^1.0.0",
"@azure-tools/test-recorder": "^1.0.0",
"@microsoft/api-extractor": "^7.18.11",
"@types/chai": "^4.1.6",

Просмотреть файл

@ -1,2 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

Просмотреть файл

@ -1,6 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import * as dotenv from "dotenv";
dotenv.config();

Просмотреть файл

@ -3,14 +3,19 @@
/// <reference lib="esnext.asynciterable" />
import { Context } from "mocha";
import { env, Recorder, record, RecorderEnvironmentSetup } from "@azure-tools/test-recorder";
import PurviewCatalog, { PurviewCatalogRestClient } from "../../../src";
import { ClientSecretCredential } from "@azure/identity";
import "./env";
import { ClientOptions } from "@azure-rest/core-client";
import { env, isLiveMode } from "@azure-tools/test-recorder";
import { createXhrHttpClient, isNode } from "@azure/test-utils";
import * as dotenv from "dotenv";
import { Context } from "mocha";
import { Recorder, record, RecorderEnvironmentSetup } from "@azure-tools/test-recorder";
if (isNode) {
dotenv.config();
}
const replaceableVariables: { [k: string]: string } = {
ENDPOINT: "https://endpoint",
@ -19,6 +24,20 @@ const replaceableVariables: { [k: string]: string } = {
AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888",
};
export function createClient(options?: ClientOptions): PurviewCatalogRestClient {
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
const credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET,
{ httpClient }
);
return PurviewCatalog(env.ENDPOINT, credential, {
...options,
httpClient,
});
}
export const environmentSetup: RecorderEnvironmentSetup = {
replaceableVariables,
customizationsOnRecordings: [
@ -36,15 +55,6 @@ export const environmentSetup: RecorderEnvironmentSetup = {
queryParametersToSkip: [],
};
export function createClient(options?: ClientOptions): PurviewCatalogRestClient {
const credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET
);
return PurviewCatalog(env.ENDPOINT, credential, options);
}
/**
* creates the recorder and reads the environment variables from the `.env` file.
* Should be called first in the test suite to make sure environment variables are

Просмотреть файл

@ -84,7 +84,7 @@
"autoPublish": false,
"dependencies": {
"@azure/core-auth": "^1.3.0",
"@azure-rest/core-client": "1.0.0-beta.7",
"@azure-rest/core-client": "1.0.0-beta.9",
"@azure/core-paging": "^1.1.1",
"@azure/core-rest-pipeline": "^1.1.0",
"@azure/logger": "^1.0.0",
@ -94,6 +94,7 @@
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/identity": "^2.0.1",
"@azure/test-utils": "^1.0.0",
"@azure-tools/test-recorder": "^1.0.0",
"@microsoft/api-extractor": "^7.18.11",
"@types/chai": "^4.1.6",

Просмотреть файл

@ -5,9 +5,16 @@
import { Context } from "mocha";
import { env, Recorder, record, RecorderEnvironmentSetup } from "@azure-tools/test-recorder";
import {
env,
Recorder,
record,
RecorderEnvironmentSetup,
isLiveMode,
} from "@azure-tools/test-recorder";
import PurviewScanning, { PurviewScanningRestClient } from "../../../src";
import { ClientSecretCredential } from "@azure/identity";
import { isNode, createXhrHttpClient } from "@azure/test-utils";
import "./env";
import { ClientOptions } from "@azure-rest/core-client";
@ -37,12 +44,14 @@ export const environmentSetup: RecorderEnvironmentSetup = {
};
export function createClient(options?: ClientOptions): PurviewScanningRestClient {
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
const credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET
env.AZURE_CLIENT_SECRET,
{ httpClient }
);
return PurviewScanning(env.ENDPOINT, credential, options);
return PurviewScanning(env.ENDPOINT, credential, { httpClient, ...options });
}
/**

Просмотреть файл

@ -3,10 +3,12 @@
import "./env";
import { AzureNamedKeyCredential, AzureSASCredential } from "@azure/core-auth";
import { RecorderEnvironmentSetup, env } from "@azure-tools/test-recorder";
import { RecorderEnvironmentSetup, env, isLiveMode } from "@azure-tools/test-recorder";
import { TableClient, TableServiceClient } from "../../../src";
import { createXhrHttpClient, isNode } from "@azure/test-utils";
import { ClientSecretCredential } from "@azure/identity";
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
const mockAccountName = "fakeaccount";
const mockAccountKey = "fakeKey";
const fakeSas =
@ -73,7 +75,7 @@ export function createTableClient(
);
}
return TableClient.fromConnectionString(env.SAS_CONNECTION_STRING, tableName);
return TableClient.fromConnectionString(env.SAS_CONNECTION_STRING, tableName, { httpClient });
case "SASToken":
if (!env.SAS_TOKEN || !env.TABLES_URL) {
@ -85,7 +87,8 @@ export function createTableClient(
return new TableClient(
env.TABLES_URL,
tableName,
new AzureSASCredential(env.SAS_TOKEN ?? "")
new AzureSASCredential(env.SAS_TOKEN ?? ""),
{ httpClient }
);
case "AccountKey":
@ -98,7 +101,8 @@ export function createTableClient(
return new TableClient(
env.TABLES_URL,
tableName,
new AzureNamedKeyCredential(env.ACCOUNT_NAME, env.ACCOUNT_KEY)
new AzureNamedKeyCredential(env.ACCOUNT_NAME, env.ACCOUNT_KEY),
{ httpClient }
);
case "TokenCredential": {
@ -111,10 +115,11 @@ export function createTableClient(
const credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET
env.AZURE_CLIENT_SECRET,
{ httpClient }
);
return new TableClient(env.TABLES_URL, tableName, credential);
return new TableClient(env.TABLES_URL, tableName, credential, { httpClient });
}
case "AccountConnectionString":
@ -124,7 +129,9 @@ export function createTableClient(
);
}
return TableClient.fromConnectionString(env.ACCOUNT_CONNECTION_STRING, tableName);
return TableClient.fromConnectionString(env.ACCOUNT_CONNECTION_STRING, tableName, {
httpClient,
});
default:
throw new Error(`Unknown authentication mode ${mode}`);
@ -142,7 +149,7 @@ export function createTableServiceClient(
);
}
return TableServiceClient.fromConnectionString(env.SAS_CONNECTION_STRING);
return TableServiceClient.fromConnectionString(env.SAS_CONNECTION_STRING, { httpClient });
case "SASToken":
if (!env.SAS_TOKEN || !env.TABLES_URL) {
@ -151,7 +158,7 @@ export function createTableServiceClient(
);
}
return new TableServiceClient(`${env.TABLES_URL}${env.SAS_TOKEN}`);
return new TableServiceClient(`${env.TABLES_URL}${env.SAS_TOKEN}`, { httpClient });
case "AccountKey":
if (!env.ACCOUNT_NAME || !env.ACCOUNT_KEY || !env.TABLES_URL) {
@ -162,7 +169,8 @@ export function createTableServiceClient(
return new TableServiceClient(
env.TABLES_URL,
new AzureNamedKeyCredential(env.ACCOUNT_NAME, env.ACCOUNT_KEY)
new AzureNamedKeyCredential(env.ACCOUNT_NAME, env.ACCOUNT_KEY),
{ httpClient }
);
case "TokenCredential": {
@ -175,10 +183,11 @@ export function createTableServiceClient(
const credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET
env.AZURE_CLIENT_SECRET,
{ httpClient }
);
return new TableServiceClient(env.TABLES_URL, credential);
return new TableServiceClient(env.TABLES_URL, credential, { httpClient });
}
case "AccountConnectionString":
@ -188,7 +197,7 @@ export function createTableServiceClient(
);
}
return TableServiceClient.fromConnectionString(env.ACCOUNT_CONNECTION_STRING);
return TableServiceClient.fromConnectionString(env.ACCOUNT_CONNECTION_STRING, { httpClient });
default:
throw new Error(`Unknown authentication mode ${mode}`);

Просмотреть файл

@ -46,7 +46,7 @@ import { getTestServerUrl, makeRequestAndVerifyResponse, setTestMode } from "./u
{
path: `/sample_response/abcdef`,
body: "abcdef",
method: "GET",
method: "POST",
},
{ val: "I am the answer!" }
);
@ -69,7 +69,7 @@ import { getTestServerUrl, makeRequestAndVerifyResponse, setTestMode } from "./u
{
path: `/sample_response/abcdef`,
body: "abcdef",
method: "GET",
method: "POST",
},
{ val: "I am the answer!" }
);

Просмотреть файл

@ -75,7 +75,7 @@ import { getTestServerUrl, makeRequestAndVerifyResponse, setTestMode } from "./u
{
path: `/sample_response`,
body,
method: "GET",
method: "POST",
headers: [{ headerName: "Content-Type", value: "text/plain" }],
},
{ val: "abc" }
@ -96,7 +96,7 @@ import { getTestServerUrl, makeRequestAndVerifyResponse, setTestMode } from "./u
{
path: `/sample_response`,
body: "body",
method: "GET",
method: "POST",
headers: [{ headerName: "Content-Type", value: "text/plain" }, testHeader],
},
{ val: "abc" }

Просмотреть файл

@ -19,10 +19,18 @@ app.get("/sample_response", (_, res) => {
res.send({ val: "abc" });
});
app.post("/sample_response", (_, res) => {
res.send({ val: "abc" });
});
app.get(`/sample_response/:secret_info`, (_, res) => {
res.send({ val: "I am the answer!" });
});
app.post(`/sample_response/:secret_info`, (_, res) => {
res.send({ val: "I am the answer!" });
});
app.get(`/subscriptions/:secret_info`, (_, res) => {
res.send({ val: "I am the answer!" });
});

Просмотреть файл

@ -0,0 +1,143 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// https://github.com/karma-runner/karma-chrome-launcher
process.env.CHROME_BIN = require("puppeteer").executablePath();
require("dotenv").config();
const {
jsonRecordingFilterFunction,
isPlaybackMode,
isSoftRecordMode,
isRecordMode,
} = require("@azure-tools/test-recorder");
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "./",
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["source-map-support", "mocha"],
plugins: [
"karma-mocha",
"karma-mocha-reporter",
"karma-chrome-launcher",
"karma-edge-launcher",
"karma-firefox-launcher",
"karma-ie-launcher",
"karma-env-preprocessor",
"karma-coverage",
"karma-sourcemap-loader",
"karma-junit-reporter",
"karma-json-to-file-reporter",
"karma-source-map-support",
"karma-json-preprocessor",
],
// list of files / patterns to load in the browser
files: [
"dist-test/index.browser.js",
{ pattern: "dist-test/index.browser.js.map", type: "html", included: false, served: true },
].concat(isPlaybackMode() || isSoftRecordMode() ? ["recordings/browsers/**/*.json"] : []),
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"**/*.js": ["sourcemap", "env"],
"recordings/browsers/**/*.json": ["json"],
// IMPORTANT: COMMENT following line if you want to debug in your browsers!!
// Preprocess source file to calculate code coverage, however this will make source file unreadable
// "dist-test/index.js": ["coverage"]
},
envPreprocessor: [
"TEST_MODE",
"ENDPOINT",
"AZURE_CLIENT_SECRET",
"AZURE_CLIENT_ID",
"AZURE_TENANT_ID",
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["mocha", "coverage", "junit", "json-to-file"],
coverageReporter: {
// specify a common output directory
dir: "coverage-browser/",
reporters: [
{ type: "json", subdir: ".", file: "coverage.json" },
{ type: "lcovonly", subdir: ".", file: "lcov.info" },
{ type: "html", subdir: "html" },
{ type: "cobertura", subdir: ".", file: "cobertura-coverage.xml" },
],
},
junitReporter: {
outputDir: "", // results will be saved as $outputDir/$browserName.xml
outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile
suite: "", // suite will become the package name attribute in xml testsuite element
useBrowserName: false, // add browser name to report and classes names
nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element
classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element
properties: {}, // key value pair of properties to add to the <properties> section of the report
},
jsonToFileReporter: {
filter: jsonRecordingFilterFunction,
outputPath: ".",
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// --no-sandbox allows our tests to run in Linux without having to change the system.
// --disable-web-security allows us to authenticate from the browser without having to write tests using interactive auth, which would be far more complex.
browsers: ["ChromeHeadlessNoSandbox"],
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",
flags: ["--no-sandbox", "--disable-web-security"],
},
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: 1,
browserNoActivityTimeout: 60000000,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 3,
browserConsoleLogOptions: {
terminal: !isRecordMode(),
},
client: {
mocha: {
// change Karma's debug.html to the mocha web reporter
reporter: "html",
timeout: "600000",
},
},
});
};

Просмотреть файл

@ -14,9 +14,9 @@
},
"scripts": {
"audit": "node ../../../common/scripts/rush-audit.js && rimraf node_modules package-lock.json && npm i --package-lock-only 2>&1 && npm audit",
"build": "npm run clean && tsc -p . && dev-tool run bundle --browser-test=false",
"build": "npm run clean && tsc -p . && dev-tool run bundle",
"build:samples": "echo Skipped.",
"build:test": "echo not needed",
"build:test": "tsc -p . && dev-tool run bundle",
"check-format": "prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
"clean": "rimraf dist dist-* types *.tgz *.log",
"format": "prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"*.{js,json}\"",
@ -26,12 +26,12 @@
"lint:fix": "eslint --no-eslintrc -c ../../.eslintrc.internal.json package.json src test --ext .ts --fix --fix-type [problem,suggestion]",
"lint": "eslint --no-eslintrc -c ../../.eslintrc.internal.json package.json src test --ext .ts",
"pack": "npm pack 2>&1",
"unit-test:browser": "echo skipped",
"unit-test:browser": "cross-env karma start --single-run",
"unit-test:node": "mocha -r esm --require ts-node/register --reporter ../../../common/tools/mocha-multi-reporter.js --timeout 120000 --full-trace \"test/{,!(browser)/**/}*.spec.ts\"",
"unit-test": "npm run unit-test:node && npm run unit-test:browser",
"test:browser": "npm run clean && npm run build npm run unit-test:browser",
"test:node": "npm run clean && npm run build && npm run unit-test:node",
"test": "npm run clean && npm run build && npm run unit-test"
"test:browser": "npm run clean && npm run build:test npm run unit-test:browser",
"test:node": "npm run clean && npm run build:test && npm run unit-test:node",
"test": "npm run clean && npm run build:test && npm run unit-test"
},
"files": [
"dist/",
@ -57,6 +57,8 @@
"private": true,
"dependencies": {
"@azure-tools/test-recorder": "^1.0.0",
"@azure/abort-controller": "^1.0.0",
"@azure/core-rest-pipeline": "^1.1.0",
"@azure/core-tracing": "1.0.0-preview.14",
"@opentelemetry/api": "^1.0.3",
"@types/chai": "^4.1.6",
@ -74,6 +76,7 @@
"@types/mocha": "^7.0.2",
"@types/node": "^12.0.0",
"@types/sinon": "^9.0.4",
"cross-env": "^7.0.2",
"eslint": "^7.15.0",
"karma": "^6.2.0",
"karma-chrome-launcher": "^3.0.0",

Просмотреть файл

@ -20,3 +20,5 @@ export * from "./tracing/mockTracingSpan";
export * from "./tracing/testTracer";
export * from "./tracing/testTracerProvider";
export * from "./tracing/spanGraphModel";
export { createXhrHttpClient } from "./xhrHttpClient";

Просмотреть файл

@ -8,9 +8,9 @@ import {
PipelineResponse,
TransferProgressEvent,
HttpHeaders,
} from "./interfaces";
import { RestError } from "./restError";
import { createHttpHeaders } from "./httpHeaders";
RestError,
createHttpHeaders,
} from "@azure/core-rest-pipeline";
function isReadableStream(body: any): body is NodeJS.ReadableStream {
return body && typeof body.pipe === "function";

Просмотреть файл

@ -5,7 +5,7 @@ import { assert } from "chai";
import * as sinon from "sinon";
import { AbortController } from "@azure/abort-controller";
import { createXhrHttpClient } from "../../src/xhrHttpClient";
import { createPipelineRequest } from "../../src/pipelineRequest";
import { createPipelineRequest } from "@azure/core-rest-pipeline";
describe("XhrHttpClient", function () {
let xhrMock: sinon.SinonFakeXMLHttpRequestStatic;

Просмотреть файл

@ -2,7 +2,6 @@
"extends": "../../../tsconfig.package",
"compilerOptions": {
"declarationDir": "./types",
"target": "es5",
"outDir": "./dist-esm",
"lib": ["dom", "es5", "es6", "es7", "esnext"]
},

Просмотреть файл

@ -3,8 +3,15 @@
import { Context } from "mocha";
import { env, Recorder, record, RecorderEnvironmentSetup } from "@azure-tools/test-recorder";
import {
env,
Recorder,
record,
RecorderEnvironmentSetup,
isLiveMode,
} from "@azure-tools/test-recorder";
import { TokenCredential, ClientSecretCredential } from "@azure/identity";
import { isNode, createXhrHttpClient } from "@azure/test-utils";
import { AzureKeyCredential, TextAnalyticsClient, TextAnalyticsClientOptions } from "../../../src/";
import "./env";
@ -48,6 +55,7 @@ export function createClient(
authMethod: AuthMethod,
options?: TextAnalyticsClientOptions
): TextAnalyticsClient {
const httpClient = isNode || isLiveMode() ? undefined : createXhrHttpClient();
let credential: AzureKeyCredential | TokenCredential;
switch (authMethod) {
case "APIKey": {
@ -58,7 +66,8 @@ export function createClient(
credential = new ClientSecretCredential(
env.AZURE_TENANT_ID,
env.AZURE_CLIENT_ID,
env.AZURE_CLIENT_SECRET
env.AZURE_CLIENT_SECRET,
{ httpClient }
);
break;
}
@ -73,7 +82,7 @@ export function createClient(
return new TextAnalyticsClient(
env.ENDPOINT || "https://dummy.cognitiveservices.azure.com/",
credential,
options
{ httpClient, ...options }
);
}