From e82bb3f384f5e198e7924141f710e624dfab2a32 Mon Sep 17 00:00:00 2001 From: Ramya Achutha Rao Date: Mon, 7 Oct 2019 18:38:51 -0700 Subject: [PATCH] Run prettier on all files in core-http --- .../lib/credentials/apiKeyCredentials.ts | 8 +- .../basicAuthenticationCredentials.ts | 6 +- sdk/core/core-http/lib/fetchHttpClient.ts | 52 +- sdk/core/core-http/lib/httpClient.ts | 3 +- sdk/core/core-http/lib/httpHeaders.ts | 5 +- .../core-http/lib/httpOperationResponse.ts | 2 +- sdk/core/core-http/lib/httpPipelineLogger.ts | 21 +- sdk/core/core-http/lib/nodeFetchHttpClient.ts | 16 +- sdk/core/core-http/lib/operationParameter.ts | 5 +- sdk/core/core-http/lib/operationSpec.ts | 11 +- .../bearerTokenAuthenticationPolicy.ts | 33 +- .../lib/policies/deserializationPolicy.ts | 138 +++- .../lib/policies/exponentialRetryPolicy.ts | 103 ++- .../policies/generateClientRequestIdPolicy.ts | 17 +- sdk/core/core-http/lib/policies/logPolicy.ts | 14 +- .../lib/policies/proxyPolicy.browser.ts | 7 +- .../core-http/lib/policies/proxyPolicy.ts | 14 +- .../core-http/lib/policies/redirectPolicy.ts | 29 +- .../core-http/lib/policies/requestPolicy.ts | 17 +- .../lib/policies/rpRegistrationPolicy.ts | 100 ++- .../core-http/lib/policies/signingPolicy.ts | 22 +- .../lib/policies/systemErrorRetryPolicy.ts | 95 ++- .../lib/policies/throttlingRetryPolicy.ts | 33 +- .../core-http/lib/policies/userAgentPolicy.ts | 38 +- sdk/core/core-http/lib/proxyAgent.ts | 14 +- .../core-http/lib/queryCollectionFormat.ts | 2 +- sdk/core/core-http/lib/restError.ts | 9 +- sdk/core/core-http/lib/serializer.ts | 402 ++++++--- sdk/core/core-http/lib/serviceClient.ts | 293 +++++-- sdk/core/core-http/lib/url.ts | 175 ++-- sdk/core/core-http/lib/util/base64.ts | 2 +- sdk/core/core-http/lib/webResource.ts | 18 +- sdk/core/core-http/lib/xhrHttpClient.ts | 68 +- sdk/core/core-http/test/credentialTests.ts | 43 +- .../data/TestClient/lib/models/mappers.ts | 8 +- .../core-http/test/defaultHttpClientTests.ts | 139 +++- .../test/expiringAccessTokenCacheTests.ts | 2 +- sdk/core/core-http/test/logFilterTests.ts | 27 +- sdk/core/core-http/test/mockHttp.ts | 28 +- sdk/core/core-http/test/msAssert.ts | 26 +- .../test/msRestUserAgentPolicyTests.ts | 12 +- .../core-http/test/operationParameterTests.ts | 4 +- .../bearerTokenAuthenticationPolicyTests.ts | 20 +- .../policies/deserializationPolicyTests.ts | 265 +++--- .../test/policies/proxyPolicyTests.ts | 43 +- .../policies/throttlingRetryPolicyTests.ts | 28 +- .../test/policies/tracingPolicyTests.ts | 17 +- sdk/core/core-http/test/proxyAgent.node.ts | 30 +- sdk/core/core-http/test/serializationTests.ts | 764 +++++++++++------- sdk/core/core-http/test/serviceClientTests.ts | 352 +++++--- sdk/core/core-http/test/urlTests.ts | 181 +++-- sdk/core/core-http/test/xhrTests.browser.ts | 11 +- sdk/core/core-http/test/xmlTests.ts | 78 +- sdk/core/core-http/tsconfig.json | 10 +- 54 files changed, 2585 insertions(+), 1275 deletions(-) diff --git a/sdk/core/core-http/lib/credentials/apiKeyCredentials.ts b/sdk/core/core-http/lib/credentials/apiKeyCredentials.ts index 333616a7c4d0..e2b841d81a5e 100644 --- a/sdk/core/core-http/lib/credentials/apiKeyCredentials.ts +++ b/sdk/core/core-http/lib/credentials/apiKeyCredentials.ts @@ -39,7 +39,9 @@ export class ApiKeyCredentials implements ServiceClientCredentials { */ constructor(options: ApiKeyCredentialOptions) { if (!options || (options && !options.inHeader && !options.inQuery)) { - throw new Error(`options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.`); + throw new Error( + `options cannot be null or undefined. Either "inHeader" or "inQuery" property of the options object needs to be provided.` + ); } this.inHeader = options.inHeader; this.inQuery = options.inQuery; @@ -53,7 +55,9 @@ export class ApiKeyCredentials implements ServiceClientCredentials { */ signRequest(webResource: WebResource): Promise { if (!webResource) { - return Promise.reject(new Error(`webResource cannot be null or undefined and must be of type "object".`)); + return Promise.reject( + new Error(`webResource cannot be null or undefined and must be of type "object".`) + ); } if (this.inHeader) { diff --git a/sdk/core/core-http/lib/credentials/basicAuthenticationCredentials.ts b/sdk/core/core-http/lib/credentials/basicAuthenticationCredentials.ts index 0e7a90bc8206..e68db83f7d7c 100644 --- a/sdk/core/core-http/lib/credentials/basicAuthenticationCredentials.ts +++ b/sdk/core/core-http/lib/credentials/basicAuthenticationCredentials.ts @@ -22,7 +22,11 @@ export class BasicAuthenticationCredentials implements ServiceClientCredentials * @param {string} password Password. * @param {string} [authorizationScheme] The authorization scheme. */ - constructor(userName: string, password: string, authorizationScheme: string = DEFAULT_AUTHORIZATION_SCHEME) { + constructor( + userName: string, + password: string, + authorizationScheme: string = DEFAULT_AUTHORIZATION_SCHEME + ) { if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") { throw new Error("userName cannot be null or undefined and must be of type string."); } diff --git a/sdk/core/core-http/lib/fetchHttpClient.ts b/sdk/core/core-http/lib/fetchHttpClient.ts index c2561ecccdee..51f9b8325f67 100644 --- a/sdk/core/core-http/lib/fetchHttpClient.ts +++ b/sdk/core/core-http/lib/fetchHttpClient.ts @@ -26,7 +26,7 @@ class ReportTransform extends Transform { callback(undefined, chunk); } - constructor(private progressCallback: ((progress: TransferProgressEvent) => void)) { + constructor(private progressCallback: (progress: TransferProgressEvent) => void) { super(); } } @@ -34,13 +34,20 @@ class ReportTransform extends Transform { export abstract class FetchHttpClient implements HttpClient { async sendRequest(httpRequest: WebResource): Promise { if (!httpRequest && typeof httpRequest !== "object") { - throw new Error("'httpRequest' (WebResource) cannot be null or undefined and must be of type object."); + throw new Error( + "'httpRequest' (WebResource) cannot be null or undefined and must be of type object." + ); } const abortController = new AbortController(); if (httpRequest.abortSignal) { if (httpRequest.abortSignal.aborted) { - throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); + throw new RestError( + "The request was aborted", + RestError.REQUEST_ABORTED_ERROR, + undefined, + httpRequest + ); } httpRequest.abortSignal.addEventListener("abort", (event: Event) => { @@ -60,7 +67,7 @@ export abstract class FetchHttpClient implements HttpClient { const formData: any = httpRequest.formData; const requestForm = new FormData(); const appendFormValue = (key: string, value: any) => { - // value function probably returns a stream so we can provide a fresh stream on each retry + // value function probably returns a stream so we can provide a fresh stream on each retry if (typeof value === "function") { value = value(); } @@ -86,7 +93,10 @@ export abstract class FetchHttpClient implements HttpClient { const contentType = httpRequest.headers.get("Content-Type"); if (contentType && contentType.indexOf("multipart/form-data") !== -1) { if (typeof requestForm.getBoundary === "function") { - httpRequest.headers.set("Content-Type", `multipart/form-data; boundary=${requestForm.getBoundary()}`); + httpRequest.headers.set( + "Content-Type", + `multipart/form-data; boundary=${requestForm.getBoundary()}` + ); } else { // browser will automatically apply a suitable content-type header httpRequest.headers.remove("Content-Type"); @@ -95,8 +105,10 @@ export abstract class FetchHttpClient implements HttpClient { } let body = httpRequest.body - ? (typeof httpRequest.body === "function" ? httpRequest.body() : httpRequest.body) - : undefined; + ? typeof httpRequest.body === "function" + ? httpRequest.body() + : httpRequest.body + : undefined; if (httpRequest.onUploadProgress && httpRequest.body) { const onUploadProgress = httpRequest.onUploadProgress; const uploadReportStream = new ReportTransform(onUploadProgress); @@ -109,7 +121,9 @@ export abstract class FetchHttpClient implements HttpClient { body = uploadReportStream; } - const platformSpecificRequestInit: Partial = await this.prepareRequest(httpRequest); + const platformSpecificRequestInit: Partial = await this.prepareRequest( + httpRequest + ); const requestInit: RequestInit = { body: body, @@ -127,12 +141,14 @@ export abstract class FetchHttpClient implements HttpClient { headers: headers, request: httpRequest, status: response.status, - readableStreamBody: httpRequest.streamResponseBody ? (response.body as unknown) as NodeJS.ReadableStream : undefined, - bodyAsText: !httpRequest.streamResponseBody ? await response.text() : undefined, + readableStreamBody: httpRequest.streamResponseBody + ? ((response.body as unknown) as NodeJS.ReadableStream) + : undefined, + bodyAsText: !httpRequest.streamResponseBody ? await response.text() : undefined }; const onDownloadProgress = httpRequest.onDownloadProgress; - if (onDownloadProgress) { + if (onDownloadProgress) { const responseBody: ReadableStream | undefined = response.body || undefined; if (isReadableStream(responseBody)) { @@ -154,9 +170,19 @@ export abstract class FetchHttpClient implements HttpClient { } catch (error) { const fetchError: FetchError = error; if (fetchError.code === "ENOTFOUND") { - throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest); + throw new RestError( + fetchError.message, + RestError.REQUEST_SEND_ERROR, + undefined, + httpRequest + ); } else if (fetchError.type === "aborted") { - throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest); + throw new RestError( + "The request was aborted", + RestError.REQUEST_ABORTED_ERROR, + undefined, + httpRequest + ); } throw fetchError; diff --git a/sdk/core/core-http/lib/httpClient.ts b/sdk/core/core-http/lib/httpClient.ts index fa0be99cfffe..10bd14cb83f1 100644 --- a/sdk/core/core-http/lib/httpClient.ts +++ b/sdk/core/core-http/lib/httpClient.ts @@ -6,5 +6,4 @@ import { RequestPolicy } from "./policies/requestPolicy"; /** * An interface that can send HttpRequests and receive promised HttpResponses. */ -export interface HttpClient extends RequestPolicy { -} +export interface HttpClient extends RequestPolicy {} diff --git a/sdk/core/core-http/lib/httpHeaders.ts b/sdk/core/core-http/lib/httpHeaders.ts index 78c510343c66..0654e7cb8455 100644 --- a/sdk/core/core-http/lib/httpHeaders.ts +++ b/sdk/core/core-http/lib/httpHeaders.ts @@ -50,7 +50,10 @@ export class HttpHeaders { * @param headerValue The value of the header to set. */ public set(headerName: string, headerValue: string | number): void { - this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() }; + this._headersMap[getHeaderKey(headerName)] = { + name: headerName, + value: headerValue.toString() + }; } /** diff --git a/sdk/core/core-http/lib/httpOperationResponse.ts b/sdk/core/core-http/lib/httpOperationResponse.ts index 9b30056b32df..3def9cbdcfae 100644 --- a/sdk/core/core-http/lib/httpOperationResponse.ts +++ b/sdk/core/core-http/lib/httpOperationResponse.ts @@ -29,7 +29,7 @@ declare global { * Stub declaration of the browser-only Blob type. * Full type information can be obtained by including "lib": ["dom"] in tsconfig.json. */ - interface Blob { } + interface Blob {} } /** diff --git a/sdk/core/core-http/lib/httpPipelineLogger.ts b/sdk/core/core-http/lib/httpPipelineLogger.ts index aa32472120d0..6723b951fec5 100644 --- a/sdk/core/core-http/lib/httpPipelineLogger.ts +++ b/sdk/core/core-http/lib/httpPipelineLogger.ts @@ -29,8 +29,7 @@ export class ConsoleHttpPipelineLogger implements HttpPipelineLogger { * Create a new ConsoleHttpPipelineLogger. * @param minimumLogLevel The log level threshold for what logs will be logged. */ - constructor(public minimumLogLevel: HttpPipelineLogLevel) { - } + constructor(public minimumLogLevel: HttpPipelineLogLevel) {} /** * Log the provided message. @@ -40,17 +39,17 @@ export class ConsoleHttpPipelineLogger implements HttpPipelineLogger { log(logLevel: HttpPipelineLogLevel, message: string): void { const logMessage = `${HttpPipelineLogLevel[logLevel]}: ${message}`; switch (logLevel) { - case HttpPipelineLogLevel.ERROR: - console.error(logMessage); - break; + case HttpPipelineLogLevel.ERROR: + console.error(logMessage); + break; - case HttpPipelineLogLevel.WARNING: - console.warn(logMessage); - break; + case HttpPipelineLogLevel.WARNING: + console.warn(logMessage); + break; - case HttpPipelineLogLevel.INFO: - console.log(logMessage); - break; + case HttpPipelineLogLevel.INFO: + console.log(logMessage); + break; } } } diff --git a/sdk/core/core-http/lib/nodeFetchHttpClient.ts b/sdk/core/core-http/lib/nodeFetchHttpClient.ts index 5de0a44e895a..b7c24fda35bc 100644 --- a/sdk/core/core-http/lib/nodeFetchHttpClient.ts +++ b/sdk/core/core-http/lib/nodeFetchHttpClient.ts @@ -21,7 +21,6 @@ if (typeof globalWithFetch.fetch !== "function") { globalWithFetch.fetch = fetch; } - export class NodeFetchHttpClient extends FetchHttpClient { private readonly cookieJar = new tough.CookieJar(undefined, { looseMode: true }); @@ -47,7 +46,11 @@ export class NodeFetchHttpClient extends FetchHttpClient { } if (httpRequest.proxySettings) { - const tunnel: ProxyAgent = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers); + const tunnel: ProxyAgent = createProxyAgent( + httpRequest.url, + httpRequest.proxySettings, + httpRequest.headers + ); requestInit.agent = tunnel.agent; } @@ -56,7 +59,9 @@ export class NodeFetchHttpClient extends FetchHttpClient { requestInit.agent.keepAlive = true; } else { const options: http.AgentOptions | https.AgentOptions = { keepAlive: true }; - const agent = httpRequest.url.startsWith("https") ? new https.Agent(options) : new http.Agent(options); + const agent = httpRequest.url.startsWith("https") + ? new https.Agent(options) + : new http.Agent(options); requestInit.agent = agent; } } @@ -73,13 +78,14 @@ export class NodeFetchHttpClient extends FetchHttpClient { setCookieHeader, operationResponse.request.url, { ignoreError: true }, - err => { + (err) => { if (err) { reject(err); } else { resolve(); } - }); + } + ); }); } } diff --git a/sdk/core/core-http/lib/operationParameter.ts b/sdk/core/core-http/lib/operationParameter.ts index 64b2670d95f5..dc5a23a5c0e9 100644 --- a/sdk/core/core-http/lib/operationParameter.ts +++ b/sdk/core/core-http/lib/operationParameter.ts @@ -58,7 +58,10 @@ export function getPathStringFromParameter(parameter: OperationParameter): strin return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper); } -export function getPathStringFromParameterPath(parameterPath: ParameterPath, mapper: Mapper): string { +export function getPathStringFromParameterPath( + parameterPath: ParameterPath, + mapper: Mapper +): string { let result: string; if (typeof parameterPath === "string") { result = parameterPath; diff --git a/sdk/core/core-http/lib/operationSpec.ts b/sdk/core/core-http/lib/operationSpec.ts index 31243d839d68..666edc6b6af8 100644 --- a/sdk/core/core-http/lib/operationSpec.ts +++ b/sdk/core/core-http/lib/operationSpec.ts @@ -1,7 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { OperationParameter, OperationQueryParameter, OperationURLParameter } from "./operationParameter"; +import { + OperationParameter, + OperationQueryParameter, + OperationURLParameter +} from "./operationParameter"; import { OperationResponse } from "./operationResponse"; import { MapperType, Serializer } from "./serializer"; import { HttpMethods } from "./webResource"; @@ -82,7 +86,10 @@ export function isStreamOperation(operationSpec: OperationSpec): boolean { let result = false; for (const statusCode in operationSpec.responses) { const operationResponse: OperationResponse = operationSpec.responses[statusCode]; - if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) { + if ( + operationResponse.bodyMapper && + operationResponse.bodyMapper.type.name === MapperType.Stream + ) { result = true; break; } diff --git a/sdk/core/core-http/lib/policies/bearerTokenAuthenticationPolicy.ts b/sdk/core/core-http/lib/policies/bearerTokenAuthenticationPolicy.ts index 58784def0674..4dccf60eb266 100644 --- a/sdk/core/core-http/lib/policies/bearerTokenAuthenticationPolicy.ts +++ b/sdk/core/core-http/lib/policies/bearerTokenAuthenticationPolicy.ts @@ -2,10 +2,15 @@ // Licensed under the MIT License. import { TokenCredential, GetTokenOptions } from "@azure/core-auth"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyOptions, RequestPolicyFactory } from "../policies/requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyOptions, + RequestPolicyFactory +} from "../policies/requestPolicy"; import { Constants } from "../util/constants"; import { HttpOperationResponse } from "../httpOperationResponse"; -import { HttpHeaders, } from "../httpHeaders"; +import { HttpHeaders } from "../httpHeaders"; import { WebResource } from "../webResource"; import { AccessTokenCache, ExpiringAccessTokenCache } from "../credentials/accessTokenCache"; @@ -15,11 +20,20 @@ import { AccessTokenCache, ExpiringAccessTokenCache } from "../credentials/acces * @param credential The TokenCredential implementation that can supply the bearer token. * @param scopes The scopes for which the bearer token applies. */ -export function bearerTokenAuthenticationPolicy(credential: TokenCredential, scopes: string | string[]): RequestPolicyFactory { +export function bearerTokenAuthenticationPolicy( + credential: TokenCredential, + scopes: string | string[] +): RequestPolicyFactory { const tokenCache: AccessTokenCache = new ExpiringAccessTokenCache(); return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { - return new BearerTokenAuthenticationPolicy(nextPolicy, options, credential, scopes, tokenCache); + return new BearerTokenAuthenticationPolicy( + nextPolicy, + options, + credential, + scopes, + tokenCache + ); } }; } @@ -55,24 +69,19 @@ export class BearerTokenAuthenticationPolicy extends BaseRequestPolicy { * Applies the Bearer token to the request through the Authorization header. * @param webResource */ - public async sendRequest( - webResource: WebResource - ): Promise { + public async sendRequest(webResource: WebResource): Promise { if (!webResource.headers) webResource.headers = new HttpHeaders(); const token = await this.getToken({ abortSignal: webResource.abortSignal }); - webResource.headers.set( - Constants.HeaderConstants.AUTHORIZATION, - `Bearer ${token}` - ); + webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${token}`); return this._nextPolicy.sendRequest(webResource); } private async getToken(options: GetTokenOptions): Promise { let accessToken = this.tokenCache.getCachedToken(); if (accessToken === undefined) { - accessToken = await this.credential.getToken(this.scopes, options) || undefined; + accessToken = (await this.credential.getToken(this.scopes, options)) || undefined; this.tokenCache.setCachedToken(accessToken); } diff --git a/sdk/core/core-http/lib/policies/deserializationPolicy.ts b/sdk/core/core-http/lib/policies/deserializationPolicy.ts index 29161cf1742f..f6ab68826d3e 100644 --- a/sdk/core/core-http/lib/policies/deserializationPolicy.ts +++ b/sdk/core/core-http/lib/policies/deserializationPolicy.ts @@ -9,7 +9,12 @@ import { Mapper, MapperType } from "../serializer"; import * as utils from "../util/utils"; import { parseXML } from "../util/xml"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; /** * The content-types that will indicate that an operation response should be deserialized in a @@ -33,7 +38,9 @@ export interface DeserializationContentTypes { * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they * pass through the HTTP pipeline. */ -export function deserializationPolicy(deserializationContentTypes?: DeserializationContentTypes): RequestPolicyFactory { +export function deserializationPolicy( + deserializationContentTypes?: DeserializationContentTypes +): RequestPolicyFactory { return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options); @@ -52,24 +59,41 @@ export class DeserializationPolicy extends BaseRequestPolicy { public readonly jsonContentTypes: string[]; public readonly xmlContentTypes: string[]; - constructor(nextPolicy: RequestPolicy, deserializationContentTypes: DeserializationContentTypes | undefined, options: RequestPolicyOptions) { + constructor( + nextPolicy: RequestPolicy, + deserializationContentTypes: DeserializationContentTypes | undefined, + options: RequestPolicyOptions + ) { super(nextPolicy, options); - this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes; - this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes; + this.jsonContentTypes = + (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes; + this.xmlContentTypes = + (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes; } public async sendRequest(request: WebResource): Promise { - return this._nextPolicy.sendRequest(request).then((response: HttpOperationResponse) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response)); + return this._nextPolicy + .sendRequest(request) + .then((response: HttpOperationResponse) => + deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response) + ); } } -function getOperationResponse(parsedResponse: HttpOperationResponse): undefined | OperationResponse { +function getOperationResponse( + parsedResponse: HttpOperationResponse +): undefined | OperationResponse { let result: OperationResponse | undefined; const request: WebResource = parsedResponse.request; const operationSpec: OperationSpec | undefined = request.operationSpec; if (operationSpec) { - const operationResponseGetter: undefined | ((operationSpec: OperationSpec, response: HttpOperationResponse) => (undefined | OperationResponse)) = request.operationResponseGetter; + const operationResponseGetter: + | undefined + | (( + operationSpec: OperationSpec, + response: HttpOperationResponse + ) => undefined | OperationResponse) = request.operationResponseGetter; if (!operationResponseGetter) { result = operationSpec.responses[parsedResponse.status]; } else { @@ -80,7 +104,8 @@ function getOperationResponse(parsedResponse: HttpOperationResponse): undefined } function shouldDeserializeResponse(parsedResponse: HttpOperationResponse): boolean { - const shouldDeserialize: undefined | boolean | ((response: HttpOperationResponse) => boolean) = parsedResponse.request.shouldDeserialize; + const shouldDeserialize: undefined | boolean | ((response: HttpOperationResponse) => boolean) = + parsedResponse.request.shouldDeserialize; let result: boolean; if (shouldDeserialize === undefined) { result = true; @@ -92,8 +117,12 @@ function shouldDeserializeResponse(parsedResponse: HttpOperationResponse): boole return result; } -export function deserializeResponseBody(jsonContentTypes: string[], xmlContentTypes: string[], response: HttpOperationResponse): Promise { - return parse(jsonContentTypes, xmlContentTypes, response).then(parsedResponse => { +export function deserializeResponseBody( + jsonContentTypes: string[], + xmlContentTypes: string[], + response: HttpOperationResponse +): Promise { + return parse(jsonContentTypes, xmlContentTypes, response).then((parsedResponse) => { const shouldDeserialize: boolean = shouldDeserializeResponse(parsedResponse); if (shouldDeserialize) { const operationSpec: OperationSpec | undefined = parsedResponse.request.operationSpec; @@ -102,17 +131,21 @@ export function deserializeResponseBody(jsonContentTypes: string[], xmlContentTy const expectedStatusCodes: string[] = Object.keys(operationSpec.responses); - const hasNoExpectedStatusCodes: boolean = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); + const hasNoExpectedStatusCodes: boolean = + expectedStatusCodes.length === 0 || + (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"); const responseSpec: OperationResponse | undefined = getOperationResponse(parsedResponse); - const isExpectedStatusCode: boolean = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec; + const isExpectedStatusCode: boolean = hasNoExpectedStatusCodes + ? 200 <= statusCode && statusCode < 300 + : !!responseSpec; if (!isExpectedStatusCode) { const defaultResponseSpec: OperationResponse = operationSpec.responses.default; if (defaultResponseSpec) { const initialErrorMessage: string = isStreamOperation(operationSpec) ? `Unexpected status code: ${statusCode}` - : parsedResponse.bodyAsText as string; + : (parsedResponse.bodyAsText as string); const error = new RestError(initialErrorMessage); error.statusCode = statusCode; @@ -122,8 +155,12 @@ export function deserializeResponseBody(jsonContentTypes: string[], xmlContentTy let parsedErrorResponse: { [key: string]: any } = parsedResponse.parsedBody; try { if (parsedErrorResponse) { - const defaultResponseBodyMapper: Mapper | undefined = defaultResponseSpec.bodyMapper; - if (defaultResponseBodyMapper && defaultResponseBodyMapper.serializedName === "CloudError") { + const defaultResponseBodyMapper: Mapper | undefined = + defaultResponseSpec.bodyMapper; + if ( + defaultResponseBodyMapper && + defaultResponseBodyMapper.serializedName === "CloudError" + ) { if (parsedErrorResponse.error) { parsedErrorResponse = parsedErrorResponse.error; } @@ -147,12 +184,20 @@ export function deserializeResponseBody(jsonContentTypes: string[], xmlContentTy if (defaultResponseBodyMapper) { let valueToDeserialize: any = parsedErrorResponse; - if (operationSpec.isXML && defaultResponseBodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = typeof parsedErrorResponse === "object" - ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName!] - : []; + if ( + operationSpec.isXML && + defaultResponseBodyMapper.type.name === MapperType.Sequence + ) { + valueToDeserialize = + typeof parsedErrorResponse === "object" + ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName!] + : []; } - error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body"); + error.body = operationSpec.serializer.deserialize( + defaultResponseBodyMapper, + valueToDeserialize, + "error.body" + ); } } } catch (defaultError) { @@ -164,12 +209,21 @@ export function deserializeResponseBody(jsonContentTypes: string[], xmlContentTy if (responseSpec.bodyMapper) { let valueToDeserialize: any = parsedResponse.parsedBody; if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) { - valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName!] : []; + valueToDeserialize = + typeof valueToDeserialize === "object" + ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName!] + : []; } try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody"); + parsedResponse.parsedBody = operationSpec.serializer.deserialize( + responseSpec.bodyMapper, + valueToDeserialize, + "operationRes.parsedBody" + ); } catch (error) { - const restError = new RestError(`Error ${error} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`); + const restError = new RestError( + `Error ${error} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}` + ); restError.request = utils.stripRequest(parsedResponse.request); restError.response = utils.stripResponse(parsedResponse); return Promise.reject(restError); @@ -180,7 +234,11 @@ export function deserializeResponseBody(jsonContentTypes: string[], xmlContentTy } if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders"); + parsedResponse.parsedHeaders = operationSpec.serializer.deserialize( + responseSpec.headersMapper, + parsedResponse.headers.rawHeaders(), + "operationRes.parsedHeaders" + ); } } } @@ -189,26 +247,42 @@ export function deserializeResponseBody(jsonContentTypes: string[], xmlContentTy }); } -function parse(jsonContentTypes: string[], xmlContentTypes: string[], operationResponse: HttpOperationResponse): Promise { +function parse( + jsonContentTypes: string[], + xmlContentTypes: string[], + operationResponse: HttpOperationResponse +): Promise { const errorHandler = (err: Error & { code: string }) => { const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; const errCode = err.code || RestError.PARSE_ERROR; - const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText); + const e = new RestError( + msg, + errCode, + operationResponse.status, + operationResponse.request, + operationResponse, + operationResponse.bodyAsText + ); return Promise.reject(e); }; if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) { const text = operationResponse.bodyAsText; const contentType: string = operationResponse.headers.get("Content-Type") || ""; - const contentComponents: string[] = !contentType ? [] : contentType.split(";").map(component => component.toLowerCase()); - if (contentComponents.length === 0 || contentComponents.some(component => jsonContentTypes.indexOf(component) !== -1)) { - return new Promise(resolve => { + const contentComponents: string[] = !contentType + ? [] + : contentType.split(";").map((component) => component.toLowerCase()); + if ( + contentComponents.length === 0 || + contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1) + ) { + return new Promise((resolve) => { operationResponse.parsedBody = JSON.parse(text); resolve(operationResponse); }).catch(errorHandler); - } else if (contentComponents.some(component => xmlContentTypes.indexOf(component) !== -1)) { + } else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { return parseXML(text) - .then(body => { + .then((body) => { operationResponse.parsedBody = body; return operationResponse; }) diff --git a/sdk/core/core-http/lib/policies/exponentialRetryPolicy.ts b/sdk/core/core-http/lib/policies/exponentialRetryPolicy.ts index 305b5ed088c5..5e8bef6c5e01 100644 --- a/sdk/core/core-http/lib/policies/exponentialRetryPolicy.ts +++ b/sdk/core/core-http/lib/policies/exponentialRetryPolicy.ts @@ -4,7 +4,12 @@ import { HttpOperationResponse } from "../httpOperationResponse"; import * as utils from "../util/utils"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; import { RestError } from "../restError"; export interface RetryData { @@ -19,10 +24,22 @@ export interface RetryError extends Error { innerError?: RetryError; } -export function exponentialRetryPolicy(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number): RequestPolicyFactory { +export function exponentialRetryPolicy( + retryCount?: number, + retryInterval?: number, + minRetryInterval?: number, + maxRetryInterval?: number +): RequestPolicyFactory { return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { - return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); + return new ExponentialRetryPolicy( + nextPolicy, + options, + retryCount, + retryInterval, + minRetryInterval, + maxRetryInterval + ); } }; } @@ -63,19 +80,33 @@ export class ExponentialRetryPolicy extends BaseRequestPolicy { * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds. * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds. */ - constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number) { + constructor( + nextPolicy: RequestPolicy, + options: RequestPolicyOptions, + retryCount?: number, + retryInterval?: number, + minRetryInterval?: number, + maxRetryInterval?: number + ) { super(nextPolicy, options); - function isNumber(n: any): n is number { return typeof n === "number"; } + function isNumber(n: any): n is number { + return typeof n === "number"; + } this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT; this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL; - this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + this.minRetryInterval = isNumber(minRetryInterval) + ? minRetryInterval + : DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + this.maxRetryInterval = isNumber(maxRetryInterval) + ? maxRetryInterval + : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; } public sendRequest(request: WebResource): Promise { - return this._nextPolicy.sendRequest(request.clone()) - .then(response => retry(this, request, response)) - .catch(error => retry(this, request, error.response, undefined, error)); + return this._nextPolicy + .sendRequest(request.clone()) + .then((response) => retry(this, request, response)) + .catch((error) => retry(this, request, error.response, undefined, error)); } } @@ -87,8 +118,17 @@ export class ExponentialRetryPolicy extends BaseRequestPolicy { * @param {RetryData} retryData The retry data. * @return {boolean} True if the operation qualifies for a retry; false otherwise. */ -function shouldRetry(policy: ExponentialRetryPolicy, statusCode: number | undefined, retryData: RetryData): boolean { - if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) { +function shouldRetry( + policy: ExponentialRetryPolicy, + statusCode: number | undefined, + retryData: RetryData +): boolean { + if ( + statusCode == undefined || + (statusCode < 500 && statusCode !== 408) || + statusCode === 501 || + statusCode === 505 + ) { return false; } @@ -96,10 +136,10 @@ function shouldRetry(policy: ExponentialRetryPolicy, statusCode: number | undefi if (!retryData) { throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null."); } else { - currentCount = (retryData && retryData.retryCount); + currentCount = retryData && retryData.retryCount; } - return (currentCount < policy.retryCount); + return currentCount < policy.retryCount; } /** @@ -109,7 +149,11 @@ function shouldRetry(policy: ExponentialRetryPolicy, statusCode: number | undefi * @param {RetryData} retryData The retry data. * @param {RetryError} [err] The operation"s error, if any. */ -function updateRetryData(policy: ExponentialRetryPolicy, retryData?: RetryData, err?: RetryError): RetryData { +function updateRetryData( + policy: ExponentialRetryPolicy, + retryData?: RetryData, + err?: RetryError +): RetryData { if (!retryData) { retryData = { retryCount: 0, @@ -130,32 +174,45 @@ function updateRetryData(policy: ExponentialRetryPolicy, retryData?: RetryData, // Adjust retry interval let incrementDelta = Math.pow(2, retryData.retryCount) - 1; - const boundedRandDelta = policy.retryInterval * 0.8 + + const boundedRandDelta = + policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8)); incrementDelta *= boundedRandDelta; - retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval); + retryData.retryInterval = Math.min( + policy.minRetryInterval + incrementDelta, + policy.maxRetryInterval + ); return retryData; } -function retry(policy: ExponentialRetryPolicy, request: WebResource, response?: HttpOperationResponse, retryData?: RetryData, requestError?: RetryError): Promise { +function retry( + policy: ExponentialRetryPolicy, + request: WebResource, + response?: HttpOperationResponse, + retryData?: RetryData, + requestError?: RetryError +): Promise { retryData = updateRetryData(policy, retryData, requestError); const isAborted: boolean | undefined = request.abortSignal && request.abortSignal.aborted; if (!isAborted && shouldRetry(policy, response && response.status, retryData)) { - return utils.delay(retryData.retryInterval) + return utils + .delay(retryData.retryInterval) .then(() => policy._nextPolicy.sendRequest(request.clone())) - .then(res => retry(policy, request, res, retryData, undefined)) - .catch(err => retry(policy, request, response, retryData, err)); + .then((res) => retry(policy, request, res, retryData, undefined)) + .catch((err) => retry(policy, request, response, retryData, err)); } else if (isAborted || requestError || !response) { // If the operation failed in the end, return all errors instead of just the last one - const err = retryData.error || + const err = + retryData.error || new RestError( "Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, - response); + response + ); return Promise.reject(err); } else { return Promise.resolve(response); diff --git a/sdk/core/core-http/lib/policies/generateClientRequestIdPolicy.ts b/sdk/core/core-http/lib/policies/generateClientRequestIdPolicy.ts index f4988b887c35..419bffa05091 100644 --- a/sdk/core/core-http/lib/policies/generateClientRequestIdPolicy.ts +++ b/sdk/core/core-http/lib/policies/generateClientRequestIdPolicy.ts @@ -4,9 +4,16 @@ import { HttpOperationResponse } from "../httpOperationResponse"; import * as utils from "../util/utils"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; -export function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id"): RequestPolicyFactory { +export function generateClientRequestIdPolicy( + requestIdHeaderName = "x-ms-client-request-id" +): RequestPolicyFactory { return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName); @@ -15,7 +22,11 @@ export function generateClientRequestIdPolicy(requestIdHeaderName = "x-ms-client } export class GenerateClientRequestIdPolicy extends BaseRequestPolicy { - constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, private _requestIdHeaderName: string) { + constructor( + nextPolicy: RequestPolicy, + options: RequestPolicyOptions, + private _requestIdHeaderName: string + ) { super(nextPolicy, options); } diff --git a/sdk/core/core-http/lib/policies/logPolicy.ts b/sdk/core/core-http/lib/policies/logPolicy.ts index df1f15724658..c44703619399 100644 --- a/sdk/core/core-http/lib/policies/logPolicy.ts +++ b/sdk/core/core-http/lib/policies/logPolicy.ts @@ -3,7 +3,12 @@ import { HttpOperationResponse } from "../httpOperationResponse"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; export function logPolicy(logger: any = console.log): RequestPolicyFactory { return { @@ -22,11 +27,14 @@ export class LogPolicy extends BaseRequestPolicy { } public sendRequest(request: WebResource): Promise { - return this._nextPolicy.sendRequest(request).then(response => logResponse(this, response)); + return this._nextPolicy.sendRequest(request).then((response) => logResponse(this, response)); } } -function logResponse(policy: LogPolicy, response: HttpOperationResponse): Promise { +function logResponse( + policy: LogPolicy, + response: HttpOperationResponse +): Promise { policy.logger(`>> Request: ${JSON.stringify(response.request, undefined, 2)}`); policy.logger(`>> Response status code: ${response.status}`); const responseBody = response.bodyAsText; diff --git a/sdk/core/core-http/lib/policies/proxyPolicy.browser.ts b/sdk/core/core-http/lib/policies/proxyPolicy.browser.ts index 0543b045062b..7b2b5742d32e 100644 --- a/sdk/core/core-http/lib/policies/proxyPolicy.browser.ts +++ b/sdk/core/core-http/lib/policies/proxyPolicy.browser.ts @@ -2,7 +2,12 @@ // Licensed under the MIT License. import { ProxySettings } from "../serviceClient"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; import { HttpOperationResponse } from "../httpOperationResponse"; import { WebResource } from "../webResource"; diff --git a/sdk/core/core-http/lib/policies/proxyPolicy.ts b/sdk/core/core-http/lib/policies/proxyPolicy.ts index 88a40fb9d727..3fe443946194 100644 --- a/sdk/core/core-http/lib/policies/proxyPolicy.ts +++ b/sdk/core/core-http/lib/policies/proxyPolicy.ts @@ -1,7 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; import { HttpOperationResponse } from "../httpOperationResponse"; import { ProxySettings } from "../serviceClient"; import { WebResource } from "../webResource"; @@ -41,7 +46,6 @@ export function getDefaultProxySettings(proxyUrl?: string): ProxySettings | unde }; } - export function proxyPolicy(proxySettings?: ProxySettings): RequestPolicyFactory { return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { @@ -53,7 +57,11 @@ export function proxyPolicy(proxySettings?: ProxySettings): RequestPolicyFactory export class ProxyPolicy extends BaseRequestPolicy { proxySettings: ProxySettings; - constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, proxySettings: ProxySettings) { + constructor( + nextPolicy: RequestPolicy, + options: RequestPolicyOptions, + proxySettings: ProxySettings + ) { super(nextPolicy, options); this.proxySettings = proxySettings; } diff --git a/sdk/core/core-http/lib/policies/redirectPolicy.ts b/sdk/core/core-http/lib/policies/redirectPolicy.ts index 4b10325c96ad..8128c9eb43d7 100644 --- a/sdk/core/core-http/lib/policies/redirectPolicy.ts +++ b/sdk/core/core-http/lib/policies/redirectPolicy.ts @@ -4,7 +4,12 @@ import { HttpOperationResponse } from "../httpOperationResponse"; import { URLBuilder } from "../url"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; export function redirectPolicy(maximumRetries = 20): RequestPolicyFactory { return { @@ -20,17 +25,24 @@ export class RedirectPolicy extends BaseRequestPolicy { } public sendRequest(request: WebResource): Promise { - return this._nextPolicy.sendRequest(request).then(response => handleRedirect(this, response, 0)); + return this._nextPolicy + .sendRequest(request) + .then((response) => handleRedirect(this, response, 0)); } } -function handleRedirect(policy: RedirectPolicy, response: HttpOperationResponse, currentRetries: number): Promise { +function handleRedirect( + policy: RedirectPolicy, + response: HttpOperationResponse, + currentRetries: number +): Promise { const { request, status } = response; const locationHeader = response.headers.get("location"); - if (locationHeader && + if ( + locationHeader && (status === 300 || status === 307 || (status === 303 && request.method === "POST")) && - (!policy.maxRetries || currentRetries < policy.maxRetries)) { - + (!policy.maxRetries || currentRetries < policy.maxRetries) + ) { const builder = URLBuilder.parse(request.url); builder.setPath(locationHeader); request.url = builder.toString(); @@ -41,8 +53,9 @@ function handleRedirect(policy: RedirectPolicy, response: HttpOperationResponse, request.method = "GET"; } - return policy._nextPolicy.sendRequest(request) - .then(res => handleRedirect(policy, res, currentRetries + 1)); + return policy._nextPolicy + .sendRequest(request) + .then((res) => handleRedirect(policy, res, currentRetries + 1)); } return Promise.resolve(response); diff --git a/sdk/core/core-http/lib/policies/requestPolicy.ts b/sdk/core/core-http/lib/policies/requestPolicy.ts index 8ee6f154f4d0..2690b049aa42 100644 --- a/sdk/core/core-http/lib/policies/requestPolicy.ts +++ b/sdk/core/core-http/lib/policies/requestPolicy.ts @@ -10,7 +10,7 @@ import { WebResource } from "../webResource"; * Creates a new RequestPolicy per-request that uses the provided nextPolicy. */ export type RequestPolicyFactory = { - create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RequestPolicy + create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RequestPolicy; }; export interface RequestPolicy { @@ -18,8 +18,10 @@ export interface RequestPolicy { } export abstract class BaseRequestPolicy implements RequestPolicy { - protected constructor(readonly _nextPolicy: RequestPolicy, readonly _options: RequestPolicyOptions) { - } + protected constructor( + readonly _nextPolicy: RequestPolicy, + readonly _options: RequestPolicyOptions + ) {} public abstract sendRequest(webResource: WebResource): Promise; @@ -47,8 +49,7 @@ export abstract class BaseRequestPolicy implements RequestPolicy { * Optional properties that can be used when creating a RequestPolicy. */ export class RequestPolicyOptions { - constructor(private _logger?: HttpPipelineLogger) { - } + constructor(private _logger?: HttpPipelineLogger) {} /** * Get whether or not a log with the provided log level should be logged. @@ -56,9 +57,11 @@ export class RequestPolicyOptions { * @returns Whether or not a log with the provided log level should be logged. */ public shouldLog(logLevel: HttpPipelineLogLevel): boolean { - return !!this._logger && + return ( + !!this._logger && logLevel !== HttpPipelineLogLevel.OFF && - logLevel <= this._logger.minimumLogLevel; + logLevel <= this._logger.minimumLogLevel + ); } /** diff --git a/sdk/core/core-http/lib/policies/rpRegistrationPolicy.ts b/sdk/core/core-http/lib/policies/rpRegistrationPolicy.ts index bfeacc739673..de5b9b198879 100644 --- a/sdk/core/core-http/lib/policies/rpRegistrationPolicy.ts +++ b/sdk/core/core-http/lib/policies/rpRegistrationPolicy.ts @@ -3,7 +3,12 @@ import { HttpOperationResponse } from "../httpOperationResponse"; import * as utils from "../util/utils"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; export function rpRegistrationPolicy(retryTimeout = 30): RequestPolicyFactory { return { @@ -14,36 +19,46 @@ export function rpRegistrationPolicy(retryTimeout = 30): RequestPolicyFactory { } export class RPRegistrationPolicy extends BaseRequestPolicy { - constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, readonly _retryTimeout = 30) { + constructor( + nextPolicy: RequestPolicy, + options: RequestPolicyOptions, + readonly _retryTimeout = 30 + ) { super(nextPolicy, options); } public sendRequest(request: WebResource): Promise { - return this._nextPolicy.sendRequest(request.clone()) - .then(response => registerIfNeeded(this, request, response)); + return this._nextPolicy + .sendRequest(request.clone()) + .then((response) => registerIfNeeded(this, request, response)); } } - -function registerIfNeeded(policy: RPRegistrationPolicy, request: WebResource, response: HttpOperationResponse): Promise { +function registerIfNeeded( + policy: RPRegistrationPolicy, + request: WebResource, + response: HttpOperationResponse +): Promise { if (response.status === 409) { const rpName = checkRPNotRegisteredError(response.bodyAsText as string); if (rpName) { const urlPrefix = extractSubscriptionUrl(request.url); - return registerRP(policy, urlPrefix, rpName, request) - // Autoregistration of ${provider} failed for some reason. We will not return this error - // instead will return the initial response with 409 status code back to the user. - // do nothing here as we are returning the original response at the end of this method. - .catch(() => false) - .then(registrationStatus => { - if (registrationStatus) { - // Retry the original request. We have to change the x-ms-client-request-id - // otherwise Azure endpoint will return the initial 409 (cached) response. - request.headers.set("x-ms-client-request-id", utils.generateUuid()); - return policy._nextPolicy.sendRequest(request.clone()); - } - return response; - }); + return ( + registerRP(policy, urlPrefix, rpName, request) + // Autoregistration of ${provider} failed for some reason. We will not return this error + // instead will return the initial response with 409 status code back to the user. + // do nothing here as we are returning the original response at the end of this method. + .catch(() => false) + .then((registrationStatus) => { + if (registrationStatus) { + // Retry the original request. We have to change the x-ms-client-request-id + // otherwise Azure endpoint will return the initial 409 (cached) response. + request.headers.set("x-ms-client-request-id", utils.generateUuid()); + return policy._nextPolicy.sendRequest(request.clone()); + } + return response; + }) + ); } } @@ -86,8 +101,13 @@ function checkRPNotRegisteredError(body: string): string { } catch (err) { // do nothing; } - if (responseBody && responseBody.error && responseBody.error.message && - responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") { + if ( + responseBody && + responseBody.error && + responseBody.error.message && + responseBody.error.code && + responseBody.error.code === "MissingSubscriptionRegistration" + ) { const matchRes = responseBody.error.message.match(/.*'(.*)'/i); if (matchRes) { result = matchRes.pop(); @@ -105,7 +125,7 @@ function checkRPNotRegisteredError(body: string): string { */ function extractSubscriptionUrl(url: string): string { let result; - const matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//ig); + const matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi); if (matchRes && matchRes[0]) { result = matchRes[0]; } else { @@ -123,20 +143,24 @@ function extractSubscriptionUrl(url: string): string { * with a message that the provider is not registered. * @param {registrationCallback} callback The callback that handles the RP registration */ -function registerRP(policy: RPRegistrationPolicy, urlPrefix: string, provider: string, originalRequest: WebResource): Promise { +function registerRP( + policy: RPRegistrationPolicy, + urlPrefix: string, + provider: string, + originalRequest: WebResource +): Promise { const postUrl = `${urlPrefix}providers/${provider}/register?api-version=2016-02-01`; const getUrl = `${urlPrefix}providers/${provider}?api-version=2016-02-01`; const reqOptions = getRequestEssentials(originalRequest); reqOptions.method = "POST"; reqOptions.url = postUrl; - return policy._nextPolicy.sendRequest(reqOptions) - .then(response => { - if (response.status !== 200) { - throw new Error(`Autoregistration of ${provider} failed. Please try registering manually.`); - } - return getRegistrationStatus(policy, getUrl, originalRequest); - }); + return policy._nextPolicy.sendRequest(reqOptions).then((response) => { + if (response.status !== 200) { + throw new Error(`Autoregistration of ${provider} failed. Please try registering manually.`); + } + return getRegistrationStatus(policy, getUrl, originalRequest); + }); } /** @@ -148,17 +172,23 @@ function registerRP(policy: RPRegistrationPolicy, urlPrefix: string, provider: s * with a message that the provider is not registered. * @returns {Promise} True if RP Registration is successful. */ -function getRegistrationStatus(policy: RPRegistrationPolicy, url: string, originalRequest: WebResource): Promise { +function getRegistrationStatus( + policy: RPRegistrationPolicy, + url: string, + originalRequest: WebResource +): Promise { const reqOptions: any = getRequestEssentials(originalRequest); reqOptions.url = url; reqOptions.method = "GET"; - return policy._nextPolicy.sendRequest(reqOptions).then(res => { - const obj = (res.parsedBody as any); + return policy._nextPolicy.sendRequest(reqOptions).then((res) => { + const obj = res.parsedBody as any; if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") { return true; } else { - return utils.delay(policy._retryTimeout * 1000).then(() => getRegistrationStatus(policy, url, originalRequest)); + return utils + .delay(policy._retryTimeout * 1000) + .then(() => getRegistrationStatus(policy, url, originalRequest)); } }); } diff --git a/sdk/core/core-http/lib/policies/signingPolicy.ts b/sdk/core/core-http/lib/policies/signingPolicy.ts index 73fdbe86b1a2..b7dfab54c498 100644 --- a/sdk/core/core-http/lib/policies/signingPolicy.ts +++ b/sdk/core/core-http/lib/policies/signingPolicy.ts @@ -4,9 +4,16 @@ import { ServiceClientCredentials } from "../credentials/serviceClientCredentials"; import { HttpOperationResponse } from "../httpOperationResponse"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicyFactory, RequestPolicy, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicyFactory, + RequestPolicy, + RequestPolicyOptions +} from "./requestPolicy"; -export function signingPolicy(authenticationProvider: ServiceClientCredentials): RequestPolicyFactory { +export function signingPolicy( + authenticationProvider: ServiceClientCredentials +): RequestPolicyFactory { return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { return new SigningPolicy(nextPolicy, options, authenticationProvider); @@ -15,8 +22,11 @@ export function signingPolicy(authenticationProvider: ServiceClientCredentials): } export class SigningPolicy extends BaseRequestPolicy { - - constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, public authenticationProvider: ServiceClientCredentials) { + constructor( + nextPolicy: RequestPolicy, + options: RequestPolicyOptions, + public authenticationProvider: ServiceClientCredentials + ) { super(nextPolicy, options); } @@ -25,6 +35,8 @@ export class SigningPolicy extends BaseRequestPolicy { } public sendRequest(request: WebResource): Promise { - return this.signRequest(request).then(nextRequest => this._nextPolicy.sendRequest(nextRequest)); + return this.signRequest(request).then((nextRequest) => + this._nextPolicy.sendRequest(nextRequest) + ); } } diff --git a/sdk/core/core-http/lib/policies/systemErrorRetryPolicy.ts b/sdk/core/core-http/lib/policies/systemErrorRetryPolicy.ts index 18ea88b5cf10..27e5dbece22c 100644 --- a/sdk/core/core-http/lib/policies/systemErrorRetryPolicy.ts +++ b/sdk/core/core-http/lib/policies/systemErrorRetryPolicy.ts @@ -4,7 +4,12 @@ import { HttpOperationResponse } from "../httpOperationResponse"; import * as utils from "../util/utils"; import { WebResource } from "../webResource"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; export interface RetryData { retryCount: number; @@ -18,10 +23,22 @@ export interface RetryError extends Error { innerError?: RetryError; } -export function systemErrorRetryPolicy(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number): RequestPolicyFactory { +export function systemErrorRetryPolicy( + retryCount?: number, + retryInterval?: number, + minRetryInterval?: number, + maxRetryInterval?: number +): RequestPolicyFactory { return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { - return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval); + return new SystemErrorRetryPolicy( + nextPolicy, + options, + retryCount, + retryInterval, + minRetryInterval, + maxRetryInterval + ); } }; } @@ -46,16 +63,32 @@ export class SystemErrorRetryPolicy extends BaseRequestPolicy { DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90; DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3; - constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number) { + constructor( + nextPolicy: RequestPolicy, + options: RequestPolicyOptions, + retryCount?: number, + retryInterval?: number, + minRetryInterval?: number, + maxRetryInterval?: number + ) { super(nextPolicy, options); this.retryCount = typeof retryCount === "number" ? retryCount : this.DEFAULT_CLIENT_RETRY_COUNT; - this.retryInterval = typeof retryInterval === "number" ? retryInterval : this.DEFAULT_CLIENT_RETRY_INTERVAL; - this.minRetryInterval = typeof minRetryInterval === "number" ? minRetryInterval : this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL; - this.maxRetryInterval = typeof maxRetryInterval === "number" ? maxRetryInterval : this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL; + this.retryInterval = + typeof retryInterval === "number" ? retryInterval : this.DEFAULT_CLIENT_RETRY_INTERVAL; + this.minRetryInterval = + typeof minRetryInterval === "number" + ? minRetryInterval + : this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL; + this.maxRetryInterval = + typeof maxRetryInterval === "number" + ? maxRetryInterval + : this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL; } public sendRequest(request: WebResource): Promise { - return this._nextPolicy.sendRequest(request.clone()).then(response => retry(this, request, response)); + return this._nextPolicy + .sendRequest(request.clone()) + .then((response) => retry(this, request, response)); } } @@ -71,9 +104,9 @@ function shouldRetry(policy: SystemErrorRetryPolicy, retryData: RetryData): bool if (!retryData) { throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null."); } else { - currentCount = (retryData && retryData.retryCount); + currentCount = retryData && retryData.retryCount; } - return (currentCount < policy.retryCount); + return currentCount < policy.retryCount; } /** @@ -82,7 +115,11 @@ function shouldRetry(policy: SystemErrorRetryPolicy, retryData: RetryData): bool * @param {RetryData} retryData The retry data. * @param {object} err The operation"s error, if any. */ -function updateRetryData(policy: SystemErrorRetryPolicy, retryData?: RetryData, err?: RetryError): RetryData { +function updateRetryData( + policy: SystemErrorRetryPolicy, + retryData?: RetryData, + err?: RetryError +): RetryData { if (!retryData) { retryData = { retryCount: 0, @@ -103,25 +140,43 @@ function updateRetryData(policy: SystemErrorRetryPolicy, retryData?: RetryData, // Adjust retry interval let incrementDelta = Math.pow(2, retryData.retryCount) - 1; - const boundedRandDelta = policy.retryInterval * 0.8 + + const boundedRandDelta = + policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8)); incrementDelta *= boundedRandDelta; - retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval); + retryData.retryInterval = Math.min( + policy.minRetryInterval + incrementDelta, + policy.maxRetryInterval + ); return retryData; } -function retry(policy: SystemErrorRetryPolicy, request: WebResource, operationResponse: HttpOperationResponse, retryData?: RetryData, err?: RetryError): Promise { +function retry( + policy: SystemErrorRetryPolicy, + request: WebResource, + operationResponse: HttpOperationResponse, + retryData?: RetryData, + err?: RetryError +): Promise { retryData = updateRetryData(policy, retryData, err); - if (err && err.code && shouldRetry(policy, retryData) && - (err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" || - err.code === "ECONNRESET" || err.code === "ENOENT")) { + if ( + err && + err.code && + shouldRetry(policy, retryData) && + (err.code === "ETIMEDOUT" || + err.code === "ESOCKETTIMEDOUT" || + err.code === "ECONNREFUSED" || + err.code === "ECONNRESET" || + err.code === "ENOENT") + ) { // If previous operation ended with an error and the policy allows a retry, do that - return utils.delay(retryData.retryInterval) + return utils + .delay(retryData.retryInterval) .then(() => policy._nextPolicy.sendRequest(request.clone())) - .then(res => retry(policy, request, res, retryData, err)) - .catch(err => retry(policy, request, operationResponse, retryData, err)); + .then((res) => retry(policy, request, res, retryData, err)) + .catch((err) => retry(policy, request, operationResponse, retryData, err)); } else { if (err != undefined) { // If the operation failed in the end, return all errors instead of just the last one diff --git a/sdk/core/core-http/lib/policies/throttlingRetryPolicy.ts b/sdk/core/core-http/lib/policies/throttlingRetryPolicy.ts index a866b18e9e69..939ef108c744 100644 --- a/sdk/core/core-http/lib/policies/throttlingRetryPolicy.ts +++ b/sdk/core/core-http/lib/policies/throttlingRetryPolicy.ts @@ -1,13 +1,21 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -import { BaseRequestPolicy, RequestPolicy, RequestPolicyOptions, RequestPolicyFactory } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyOptions, + RequestPolicyFactory +} from "./requestPolicy"; import { WebResource } from "../webResource"; import { HttpOperationResponse } from "../httpOperationResponse"; import { Constants } from "../util/constants"; import { delay } from "../util/utils"; -type ResponseHandler = (httpRequest: WebResource, response: HttpOperationResponse) => Promise; +type ResponseHandler = ( + httpRequest: WebResource, + response: HttpOperationResponse +) => Promise; const StatusCodes = Constants.HttpConstants.StatusCodes; export function throttlingRetryPolicy(): RequestPolicyFactory { @@ -27,13 +35,17 @@ export function throttlingRetryPolicy(): RequestPolicyFactory { export class ThrottlingRetryPolicy extends BaseRequestPolicy { private _handleResponse: ResponseHandler; - constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, _handleResponse?: ResponseHandler) { + constructor( + nextPolicy: RequestPolicy, + options: RequestPolicyOptions, + _handleResponse?: ResponseHandler + ) { super(nextPolicy, options); this._handleResponse = _handleResponse || this._defaultResponseHandler; } public async sendRequest(httpRequest: WebResource): Promise { - return this._nextPolicy.sendRequest(httpRequest.clone()).then(response => { + return this._nextPolicy.sendRequest(httpRequest.clone()).then((response) => { if (response.status !== StatusCodes.TooManyRequests) { return response; } else { @@ -42,11 +54,18 @@ export class ThrottlingRetryPolicy extends BaseRequestPolicy { }); } - private async _defaultResponseHandler(httpRequest: WebResource, httpResponse: HttpOperationResponse): Promise { - const retryAfterHeader: string | undefined = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER); + private async _defaultResponseHandler( + httpRequest: WebResource, + httpResponse: HttpOperationResponse + ): Promise { + const retryAfterHeader: string | undefined = httpResponse.headers.get( + Constants.HeaderConstants.RETRY_AFTER + ); if (retryAfterHeader) { - const delayInMs: number | undefined = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader); + const delayInMs: number | undefined = ThrottlingRetryPolicy.parseRetryAfterHeader( + retryAfterHeader + ); if (delayInMs) { return delay(delayInMs).then((_: any) => this._nextPolicy.sendRequest(httpRequest)); } diff --git a/sdk/core/core-http/lib/policies/userAgentPolicy.ts b/sdk/core/core-http/lib/policies/userAgentPolicy.ts index c1be3524a980..9409189d4bce 100644 --- a/sdk/core/core-http/lib/policies/userAgentPolicy.ts +++ b/sdk/core/core-http/lib/policies/userAgentPolicy.ts @@ -6,7 +6,12 @@ import { HttpOperationResponse } from "../httpOperationResponse"; import { Constants } from "../util/constants"; import { WebResource } from "../webResource"; import { getDefaultUserAgentKey, getPlatformSpecificData } from "./msRestUserAgentPolicy"; -import { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./requestPolicy"; +import { + BaseRequestPolicy, + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./requestPolicy"; export type TelemetryInfo = { key?: string; value?: string }; @@ -19,11 +24,17 @@ function getRuntimeInfo(): TelemetryInfo[] { return [msRestRuntime]; } -function getUserAgentString(telemetryInfo: TelemetryInfo[], keySeparator = " ", valueSeparator = "/"): string { - return telemetryInfo.map(info => { - const value = info.value ? `${valueSeparator}${info.value}` : ""; - return `${info.key}${value}`; - }).join(keySeparator); +function getUserAgentString( + telemetryInfo: TelemetryInfo[], + keySeparator = " ", + valueSeparator = "/" +): string { + return telemetryInfo + .map((info) => { + const value = info.value ? `${valueSeparator}${info.value}` : ""; + return `${info.key}${value}`; + }) + .join(keySeparator); } export const getDefaultUserAgentHeaderName = getDefaultUserAgentKey; @@ -36,8 +47,12 @@ export function getDefaultUserAgentValue(): string { } export function userAgentPolicy(userAgentData?: TelemetryInfo): RequestPolicyFactory { - const key: string = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key; - const value: string = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value; + const key: string = + !userAgentData || userAgentData.key == undefined ? getDefaultUserAgentKey() : userAgentData.key; + const value: string = + !userAgentData || userAgentData.value == undefined + ? getDefaultUserAgentValue() + : userAgentData.value; return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { @@ -47,7 +62,12 @@ export function userAgentPolicy(userAgentData?: TelemetryInfo): RequestPolicyFac } export class UserAgentPolicy extends BaseRequestPolicy { - constructor(readonly _nextPolicy: RequestPolicy, readonly _options: RequestPolicyOptions, protected headerKey: string, protected headerValue: string) { + constructor( + readonly _nextPolicy: RequestPolicy, + readonly _options: RequestPolicyOptions, + protected headerKey: string, + protected headerValue: string + ) { super(_nextPolicy, _options); } diff --git a/sdk/core/core-http/lib/proxyAgent.ts b/sdk/core/core-http/lib/proxyAgent.ts index 81a8dc1cdafd..b6564c66eaf7 100644 --- a/sdk/core/core-http/lib/proxyAgent.ts +++ b/sdk/core/core-http/lib/proxyAgent.ts @@ -10,7 +10,11 @@ import { URLBuilder } from "./url"; import { HttpHeaders } from "./httpHeaders"; export type ProxyAgent = { isHttps: boolean; agent: http.Agent | https.Agent }; -export function createProxyAgent(requestUrl: string, proxySettings: ProxySettings, headers?: HttpHeaders): ProxyAgent { +export function createProxyAgent( + requestUrl: string, + proxySettings: ProxySettings, + headers?: HttpHeaders +): ProxyAgent { const tunnelOptions: tunnel.HttpsOverHttpsOptions = { proxy: { host: URLBuilder.parse(proxySettings.host).getHost() as string, @@ -19,7 +23,7 @@ export function createProxyAgent(requestUrl: string, proxySettings: ProxySetting } }; - if ((proxySettings.username && proxySettings.password)) { + if (proxySettings.username && proxySettings.password) { tunnelOptions.proxy!.proxyAuth = `${proxySettings.username}:${proxySettings.password}`; } @@ -36,7 +40,11 @@ export function createProxyAgent(requestUrl: string, proxySettings: ProxySetting return proxyAgent; } -export function createTunnel(isRequestHttps: boolean, isProxyHttps: boolean, tunnelOptions: tunnel.HttpsOverHttpsOptions): http.Agent | https.Agent { +export function createTunnel( + isRequestHttps: boolean, + isProxyHttps: boolean, + tunnelOptions: tunnel.HttpsOverHttpsOptions +): http.Agent | https.Agent { if (isRequestHttps && isProxyHttps) { return tunnel.httpsOverHttps(tunnelOptions); } else if (isRequestHttps && !isProxyHttps) { diff --git a/sdk/core/core-http/lib/queryCollectionFormat.ts b/sdk/core/core-http/lib/queryCollectionFormat.ts index 965be933d8d5..8009e261291a 100644 --- a/sdk/core/core-http/lib/queryCollectionFormat.ts +++ b/sdk/core/core-http/lib/queryCollectionFormat.ts @@ -9,5 +9,5 @@ export enum QueryCollectionFormat { Ssv = " ", Tsv = "\t", Pipes = "|", - Multi = "Multi", + Multi = "Multi" } diff --git a/sdk/core/core-http/lib/restError.ts b/sdk/core/core-http/lib/restError.ts index 7609ea3e6590..4a71a1f2251e 100644 --- a/sdk/core/core-http/lib/restError.ts +++ b/sdk/core/core-http/lib/restError.ts @@ -14,7 +14,14 @@ export class RestError extends Error { request?: WebResource; response?: HttpOperationResponse; body?: any; - constructor(message: string, code?: string, statusCode?: number, request?: WebResource, response?: HttpOperationResponse, body?: any) { + constructor( + message: string, + code?: string, + statusCode?: number, + request?: WebResource, + response?: HttpOperationResponse, + body?: any + ) { super(message); this.code = code; this.statusCode = statusCode; diff --git a/sdk/core/core-http/lib/serializer.ts b/sdk/core/core-http/lib/serializer.ts index 33aabf67c0fb..b0d1813c6994 100644 --- a/sdk/core/core-http/lib/serializer.ts +++ b/sdk/core/core-http/lib/serializer.ts @@ -5,13 +5,18 @@ import * as base64 from "./util/base64"; import * as utils from "./util/utils"; export class Serializer { - constructor(public readonly modelMappers: { [key: string]: any } = {}, public readonly isXML?: boolean) { } + constructor( + public readonly modelMappers: { [key: string]: any } = {}, + public readonly isXML?: boolean + ) {} validateConstraints(mapper: Mapper, value: any, objectName: string): void { const failValidation = (constraintName: keyof MapperConstraints, constraintValue: any) => { - throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); + throw new Error( + `"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.` + ); }; - if (mapper.constraints && (value != undefined)) { + if (mapper.constraints && value != undefined) { const { ExclusiveMaximum, ExclusiveMinimum, @@ -54,11 +59,14 @@ export class Serializer { } if (Pattern) { const pattern: RegExp = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; - if ((typeof value !== "string") || (value.match(pattern) === null)) { + if (typeof value !== "string" || value.match(pattern) === null) { failValidation("Pattern", Pattern); } } - if (UniqueItems && value.some((item: any, i: number, ar: Array) => ar.indexOf(item) !== i)) { + if ( + UniqueItems && + value.some((item: any, i: number, ar: Array) => ar.indexOf(item) !== i) + ) { failValidation("UniqueItems", UniqueItems); } } @@ -81,7 +89,7 @@ export class Serializer { if (!objectName) { objectName = mapper.serializedName!; } - if (mapperType.match(/^Sequence$/ig) !== null) { + if (mapperType.match(/^Sequence$/gi) !== null) { payload = []; } @@ -116,24 +124,26 @@ export class Serializer { } else { // Validate Constraints if any this.validateConstraints(mapper, object, objectName); - if (mapperType.match(/^any$/ig) !== null) { + if (mapperType.match(/^any$/gi) !== null) { payload = object; - } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) { + } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/gi) !== null) { payload = serializeBasicTypes(mapperType, objectName, object); - } else if (mapperType.match(/^Enum$/ig) !== null) { + } else if (mapperType.match(/^Enum$/gi) !== null) { const enumMapper: EnumMapper = mapper as EnumMapper; payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); - } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) { + } else if ( + mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/gi) !== null + ) { payload = serializeDateTypes(mapperType, object, objectName); - } else if (mapperType.match(/^ByteArray$/ig) !== null) { + } else if (mapperType.match(/^ByteArray$/gi) !== null) { payload = serializeByteArrayType(objectName, object); - } else if (mapperType.match(/^Base64Url$/ig) !== null) { + } else if (mapperType.match(/^Base64Url$/gi) !== null) { payload = serializeBase64UrlType(objectName, object); - } else if (mapperType.match(/^Sequence$/ig) !== null) { + } else if (mapperType.match(/^Sequence$/gi) !== null) { payload = serializeSequenceType(this, mapper as SequenceMapper, object, objectName); - } else if (mapperType.match(/^Dictionary$/ig) !== null) { + } else if (mapperType.match(/^Dictionary$/gi) !== null) { payload = serializeDictionaryType(this, mapper as DictionaryMapper, object, objectName); - } else if (mapperType.match(/^Composite$/ig) !== null) { + } else if (mapperType.match(/^Composite$/gi) !== null) { payload = serializeCompositeType(this, mapper as CompositeMapper, object, objectName); } } @@ -172,7 +182,7 @@ export class Serializer { objectName = mapper.serializedName!; } - if (mapperType.match(/^Composite$/ig) !== null) { + if (mapperType.match(/^Composite$/gi) !== null) { payload = deserializeCompositeType(this, mapper as CompositeMapper, responseBody, objectName); } else { if (this.isXML) { @@ -186,12 +196,12 @@ export class Serializer { } } - if (mapperType.match(/^Number$/ig) !== null) { + if (mapperType.match(/^Number$/gi) !== null) { payload = parseFloat(responseBody); if (isNaN(payload)) { payload = responseBody; } - } else if (mapperType.match(/^Boolean$/ig) !== null) { + } else if (mapperType.match(/^Boolean$/gi) !== null) { if (responseBody === "true") { payload = true; } else if (responseBody === "false") { @@ -199,20 +209,25 @@ export class Serializer { } else { payload = responseBody; } - } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) { + } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/gi) !== null) { payload = responseBody; - } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) { + } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/gi) !== null) { payload = new Date(responseBody); - } else if (mapperType.match(/^UnixTime$/ig) !== null) { + } else if (mapperType.match(/^UnixTime$/gi) !== null) { payload = unixTimeToDate(responseBody); - } else if (mapperType.match(/^ByteArray$/ig) !== null) { + } else if (mapperType.match(/^ByteArray$/gi) !== null) { payload = base64.decodeString(responseBody); - } else if (mapperType.match(/^Base64Url$/ig) !== null) { + } else if (mapperType.match(/^Base64Url$/gi) !== null) { payload = base64UrlToByteArray(responseBody); - } else if (mapperType.match(/^Sequence$/ig) !== null) { + } else if (mapperType.match(/^Sequence$/gi) !== null) { payload = deserializeSequenceType(this, mapper as SequenceMapper, responseBody, objectName); - } else if (mapperType.match(/^Dictionary$/ig) !== null) { - payload = deserializeDictionaryType(this, mapper as DictionaryMapper, responseBody, objectName); + } else if (mapperType.match(/^Dictionary$/gi) !== null) { + payload = deserializeDictionaryType( + this, + mapper as DictionaryMapper, + responseBody, + objectName + ); } } @@ -226,7 +241,7 @@ export class Serializer { function trimEnd(str: string, ch: string) { let len = str.length; - while ((len - 1) >= 0 && str[len - 1] === ch) { + while (len - 1 >= 0 && str[len - 1] === ch) { --len; } return str.substr(0, len); @@ -242,7 +257,9 @@ function bufferToBase64Url(buffer: any): string | undefined { // Uint8Array to Base64. const str = base64.encodeByteArray(buffer); // Base64 to Base64Url. - return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); + return trimEnd(str, "=") + .replace(/\+/g, "-") + .replace(/\//g, "_"); } function base64UrlToByteArray(str: string): Uint8Array | undefined { @@ -298,30 +315,36 @@ function unixTimeToDate(n: number): Date | undefined { function serializeBasicTypes(typeName: string, objectName: string, value: any): any { if (value !== null && value !== undefined) { - if (typeName.match(/^Number$/ig) !== null) { + if (typeName.match(/^Number$/gi) !== null) { if (typeof value !== "number") { throw new Error(`${objectName} with value ${value} must be of type number.`); } - } else if (typeName.match(/^String$/ig) !== null) { + } else if (typeName.match(/^String$/gi) !== null) { if (typeof value.valueOf() !== "string") { throw new Error(`${objectName} with value "${value}" must be of type string.`); } - } else if (typeName.match(/^Uuid$/ig) !== null) { + } else if (typeName.match(/^Uuid$/gi) !== null) { if (!(typeof value.valueOf() === "string" && utils.isValidUuid(value))) { - throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); + throw new Error( + `${objectName} with value "${value}" must be of type string and a valid uuid.` + ); } - } else if (typeName.match(/^Boolean$/ig) !== null) { + } else if (typeName.match(/^Boolean$/gi) !== null) { if (typeof value !== "boolean") { throw new Error(`${objectName} with value ${value} must be of type boolean.`); } - } else if (typeName.match(/^Stream$/ig) !== null) { + } else if (typeName.match(/^Stream$/gi) !== null) { const objectType = typeof value; - if (objectType !== "string" && + if ( + objectType !== "string" && objectType !== "function" && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value) && - !(typeof Blob === "function" && value instanceof Blob)) { - throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.`); + !(typeof Blob === "function" && value instanceof Blob) + ) { + throw new Error( + `${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.` + ); } } } @@ -330,7 +353,9 @@ function serializeBasicTypes(typeName: string, objectName: string, value: any): function serializeEnumType(objectName: string, allowedValues: Array, value: any): any { if (!allowedValues) { - throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); + throw new Error( + `Please provide a set of allowedValues to validate ${objectName} as an Enum Type.` + ); } const isPresent = allowedValues.some((item) => { if (typeof item.valueOf() === "string") { @@ -339,7 +364,11 @@ function serializeEnumType(objectName: string, allowedValues: Array, value: return item === value; }); if (!isPresent) { - throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); + throw new Error( + `${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify( + allowedValues + )}.` + ); } return value; } @@ -366,34 +395,57 @@ function serializeBase64UrlType(objectName: string, value: any): any { function serializeDateTypes(typeName: string, value: any, objectName: string) { if (value != undefined) { - if (typeName.match(/^Date$/ig) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + if (typeName.match(/^Date$/gi) !== null) { + if ( + !( + value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))) + ) + ) { throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } - value = (value instanceof Date) ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10); - } else if (typeName.match(/^DateTime$/ig) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + value = + value instanceof Date + ? value.toISOString().substring(0, 10) + : new Date(value).toISOString().substring(0, 10); + } else if (typeName.match(/^DateTime$/gi) !== null) { + if ( + !( + value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))) + ) + ) { throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); } - value = (value instanceof Date) ? value.toISOString() : new Date(value).toISOString(); - } else if (typeName.match(/^DateTimeRfc1123$/ig) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { + value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + } else if (typeName.match(/^DateTimeRfc1123$/gi) !== null) { + if ( + !( + value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))) + ) + ) { throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); } - value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString(); - } else if (typeName.match(/^UnixTime$/ig) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + - `for it to be serialized in UnixTime/Epoch format.`); + value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); + } else if (typeName.match(/^UnixTime$/gi) !== null) { + if ( + !( + value instanceof Date || + (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))) + ) + ) { + throw new Error( + `${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + + `for it to be serialized in UnixTime/Epoch format.` + ); } value = dateToUnixTime(value); - } else if (typeName.match(/^TimeSpan$/ig) !== null) { + } else if (typeName.match(/^TimeSpan$/gi) !== null) { if (!utils.isDuration(value)) { - throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); + throw new Error( + `${objectName} must be a string in ISO 8601 format. Instead was "${value}".` + ); } value = value; } @@ -401,14 +453,21 @@ function serializeDateTypes(typeName: string, value: any, objectName: string) { return value; } -function serializeSequenceType(serializer: Serializer, mapper: SequenceMapper, object: any, objectName: string) { +function serializeSequenceType( + serializer: Serializer, + mapper: SequenceMapper, + object: any, + objectName: string +) { if (!Array.isArray(object)) { throw new Error(`${objectName} must be of type Array.`); } const elementType = mapper.type.element; if (!elementType || typeof elementType !== "object") { - throw new Error(`element" metadata for an Array must be defined in the ` + - `mapper and it must of type "object" in ${objectName}.`); + throw new Error( + `element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.` + ); } const tempArray = []; for (let i = 0; i < object.length; i++) { @@ -417,14 +476,21 @@ function serializeSequenceType(serializer: Serializer, mapper: SequenceMapper, o return tempArray; } -function serializeDictionaryType(serializer: Serializer, mapper: DictionaryMapper, object: any, objectName: string) { +function serializeDictionaryType( + serializer: Serializer, + mapper: DictionaryMapper, + object: any, + objectName: string +) { if (typeof object !== "object") { throw new Error(`${objectName} must be of type object.`); } const valueType = mapper.type.value; if (!valueType || typeof valueType !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the ` + - `mapper and it must of type "object" in ${objectName}.`); + throw new Error( + `"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}.` + ); } const tempDictionary: { [key: string]: any } = {}; for (const key of Object.keys(object)) { @@ -438,12 +504,22 @@ function serializeDictionaryType(serializer: Serializer, mapper: DictionaryMappe * @param serializer the serializer containing the entire set of mappers * @param mapper the composite mapper to resolve */ -function resolveModelProperties(serializer: Serializer, mapper: CompositeMapper, objectName: string): { [propertyName: string]: Mapper } { +function resolveModelProperties( + serializer: Serializer, + mapper: CompositeMapper, + objectName: string +): { [propertyName: string]: Mapper } { let modelProps = mapper.type.modelProperties; if (!modelProps) { const className = mapper.type.className; if (!className) { - throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); + throw new Error( + `Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify( + mapper, + undefined, + 2 + )}".` + ); } const modelMapper = serializer.modelMappers[className]; @@ -452,15 +528,24 @@ function resolveModelProperties(serializer: Serializer, mapper: CompositeMapper, } modelProps = modelMapper.type.modelProperties; if (!modelProps) { - throw new Error(`modelProperties cannot be null or undefined in the ` + - `mapper "${JSON.stringify(modelMapper)}" of type "${className}" for object "${objectName}".`); + throw new Error( + `modelProperties cannot be null or undefined in the ` + + `mapper "${JSON.stringify( + modelMapper + )}" of type "${className}" for object "${objectName}".` + ); } } return modelProps; } -function serializeCompositeType(serializer: Serializer, mapper: CompositeMapper, object: any, objectName: string) { +function serializeCompositeType( + serializer: Serializer, + mapper: CompositeMapper, + object: any, + objectName: string +) { if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); } @@ -488,7 +573,7 @@ function serializeCompositeType(serializer: Serializer, mapper: CompositeMapper, for (const pathName of paths) { const childObject = parentObject[pathName]; - if ((childObject == undefined) && (object[key] != undefined)) { + if (childObject == undefined && object[key] != undefined) { parentObject[pathName] = {}; } parentObject = parentObject[pathName]; @@ -496,17 +581,26 @@ function serializeCompositeType(serializer: Serializer, mapper: CompositeMapper, } if (parentObject != undefined) { - const propertyObjectName = propertyMapper.serializedName !== "" - ? objectName + "." + propertyMapper.serializedName - : objectName; + const propertyObjectName = + propertyMapper.serializedName !== "" + ? objectName + "." + propertyMapper.serializedName + : objectName; let toSerialize = object[key]; const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) { + if ( + polymorphicDiscriminator && + polymorphicDiscriminator.clientName === key && + toSerialize == undefined + ) { toSerialize = mapper.serializedName; } - const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName); + const serializedValue = serializer.serialize( + propertyMapper, + toSerialize, + propertyObjectName + ); if (serializedValue !== undefined && propName != undefined) { if (propertyMapper.xmlIsAttribute) { // $ is the key attributes are kept under in xml2js. @@ -527,9 +621,13 @@ function serializeCompositeType(serializer: Serializer, mapper: CompositeMapper, if (additionalPropertiesMapper) { const propNames = Object.keys(modelProps); for (const clientPropName in object) { - const isAdditionalProperty = propNames.every(pn => pn !== clientPropName); + const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]'); + payload[clientPropName] = serializer.serialize( + additionalPropertiesMapper, + object[clientPropName], + objectName + '["' + clientPropName + '"]' + ); } } } @@ -543,7 +641,12 @@ function isSpecialXmlProperty(propertyName: string): boolean { return ["$", "_"].includes(propertyName); } -function deserializeCompositeType(serializer: Serializer, mapper: CompositeMapper, responseBody: any, objectName: string): any { +function deserializeCompositeType( + serializer: Serializer, + mapper: CompositeMapper, + responseBody: any, + objectName: string +): any { if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); } @@ -567,7 +670,11 @@ function deserializeCompositeType(serializer: Serializer, mapper: CompositeMappe const dictionary: any = {}; for (const headerKey of Object.keys(responseBody)) { if (headerKey.startsWith(headerCollectionPrefix)) { - dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize((propertyMapper as DictionaryMapper).type.value, responseBody[headerKey], propertyObjectName); + dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize( + (propertyMapper as DictionaryMapper).type.value, + responseBody[headerKey], + propertyObjectName + ); } handledPropertyNames.push(headerKey); @@ -575,7 +682,11 @@ function deserializeCompositeType(serializer: Serializer, mapper: CompositeMappe instance[key] = dictionary; } else if (serializer.isXML) { if (propertyMapper.xmlIsAttribute && responseBody.$) { - instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName!], propertyObjectName); + instance[key] = serializer.deserialize( + propertyMapper, + responseBody.$[xmlName!], + propertyObjectName + ); } else { const propertyName = xmlElementName || xmlName || serializedName; let unwrappedProperty = responseBody[propertyName!]; @@ -588,7 +699,11 @@ function deserializeCompositeType(serializer: Serializer, mapper: CompositeMappe unwrappedProperty = []; } } - instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName); + instance[key] = serializer.deserialize( + propertyMapper, + unwrappedProperty, + propertyObjectName + ); } } else { // deserialize the property if it is present in the provided responseBody instance @@ -610,7 +725,11 @@ function deserializeCompositeType(serializer: Serializer, mapper: CompositeMappe // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and // the transformation of model property name (ex: "fishtype") is done consistently. // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. - if (polymorphicDiscriminator && key === polymorphicDiscriminator.clientName && propertyInstance == undefined) { + if ( + polymorphicDiscriminator && + key === polymorphicDiscriminator.clientName && + propertyInstance == undefined + ) { propertyInstance = mapper.serializedName; } @@ -620,7 +739,11 @@ function deserializeCompositeType(serializer: Serializer, mapper: CompositeMappe propertyInstance = responseBody[key]; instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); } else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { - serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName); + serializedValue = serializer.deserialize( + propertyMapper, + propertyInstance, + propertyObjectName + ); instance[key] = serializedValue; } } @@ -640,12 +763,20 @@ function deserializeCompositeType(serializer: Serializer, mapper: CompositeMappe for (const responsePropName in responseBody) { if (isAdditionalProperty(responsePropName)) { - instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]'); + instance[responsePropName] = serializer.deserialize( + additionalPropertiesMapper, + responseBody[responsePropName], + objectName + '["' + responsePropName + '"]' + ); } } } else if (responseBody) { for (const key of Object.keys(responseBody)) { - if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) { + if ( + instance[key] === undefined && + !handledPropertyNames.includes(key) && + !isSpecialXmlProperty(key) + ) { instance[key] = responseBody[key]; } } @@ -654,12 +785,19 @@ function deserializeCompositeType(serializer: Serializer, mapper: CompositeMappe return instance; } -function deserializeDictionaryType(serializer: Serializer, mapper: DictionaryMapper, responseBody: any, objectName: string): any { +function deserializeDictionaryType( + serializer: Serializer, + mapper: DictionaryMapper, + responseBody: any, + objectName: string +): any { /*jshint validthis: true */ const value = mapper.type.value; if (!value || typeof value !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the ` + - `mapper and it must of type "object" in ${objectName}`); + throw new Error( + `"value" metadata for a Dictionary must be defined in the ` + + `mapper and it must of type "object" in ${objectName}` + ); } if (responseBody) { const tempDictionary: { [key: string]: any } = {}; @@ -671,12 +809,19 @@ function deserializeDictionaryType(serializer: Serializer, mapper: DictionaryMap return responseBody; } -function deserializeSequenceType(serializer: Serializer, mapper: SequenceMapper, responseBody: any, objectName: string): any { +function deserializeSequenceType( + serializer: Serializer, + mapper: SequenceMapper, + responseBody: any, + objectName: string +): any { /*jshint validthis: true */ const element = mapper.type.element; if (!element || typeof element !== "object") { - throw new Error(`element" metadata for an Array must be defined in the ` + - `mapper and it must of type "object" in ${objectName}`); + throw new Error( + `element" metadata for an Array must be defined in the ` + + `mapper and it must of type "object" in ${objectName}` + ); } if (responseBody) { if (!Array.isArray(responseBody)) { @@ -693,7 +838,12 @@ function deserializeSequenceType(serializer: Serializer, mapper: SequenceMapper, return responseBody; } -function getPolymorphicMapper(serializer: Serializer, mapper: CompositeMapper, object: any, polymorphicPropertyName: "clientName" | "serializedName"): CompositeMapper { +function getPolymorphicMapper( + serializer: Serializer, + mapper: CompositeMapper, + object: any, + polymorphicPropertyName: "clientName" | "serializedName" +): CompositeMapper { const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); if (polymorphicDiscriminator) { const discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; @@ -701,9 +851,10 @@ function getPolymorphicMapper(serializer: Serializer, mapper: CompositeMapper, o const discriminatorValue = object[discriminatorName]; if (discriminatorValue != undefined) { const typeName = mapper.type.uberParent || mapper.type.className; - const indexDiscriminator = discriminatorValue === typeName - ? discriminatorValue - : typeName + "." + discriminatorValue; + const indexDiscriminator = + discriminatorValue === typeName + ? discriminatorValue + : typeName + "." + discriminatorValue; const polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator]; if (polymorphicMapper) { mapper = polymorphicMapper; @@ -714,14 +865,23 @@ function getPolymorphicMapper(serializer: Serializer, mapper: CompositeMapper, o return mapper; } -function getPolymorphicDiscriminatorRecursively(serializer: Serializer, mapper: CompositeMapper): PolymorphicDiscriminator | undefined { - return mapper.type.polymorphicDiscriminator - || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) - || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className); +function getPolymorphicDiscriminatorRecursively( + serializer: Serializer, + mapper: CompositeMapper +): PolymorphicDiscriminator | undefined { + return ( + mapper.type.polymorphicDiscriminator || + getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || + getPolymorphicDiscriminatorSafely(serializer, mapper.type.className) + ); } function getPolymorphicDiscriminatorSafely(serializer: Serializer, typeName?: string) { - return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator); + return ( + typeName && + serializer.modelMappers[typeName] && + serializer.modelMappers[typeName].type.polymorphicDiscriminator + ); } export interface MapperConstraints { @@ -738,23 +898,29 @@ export interface MapperConstraints { MultipleOf?: number; } -export type MapperType = SimpleMapperType | CompositeMapperType | SequenceMapperType | DictionaryMapperType | EnumMapperType; +export type MapperType = + | SimpleMapperType + | CompositeMapperType + | SequenceMapperType + | DictionaryMapperType + | EnumMapperType; export interface SimpleMapperType { - name: "Base64Url" - | "Boolean" - | "ByteArray" - | "Date" - | "DateTime" - | "DateTimeRfc1123" - | "Object" - | "Stream" - | "String" - | "TimeSpan" - | "UnixTime" - | "Uuid" - | "Number" - | "any"; + name: + | "Base64Url" + | "Boolean" + | "ByteArray" + | "Date" + | "DateTime" + | "DateTimeRfc1123" + | "Object" + | "Stream" + | "String" + | "TimeSpan" + | "UnixTime" + | "Uuid" + | "Number" + | "any"; } export interface CompositeMapperType { @@ -838,11 +1004,9 @@ export function serializeObject(toSerialize: any): any { if (toSerialize instanceof Uint8Array) { toSerialize = base64.encodeByteArray(toSerialize); return toSerialize; - } - else if (toSerialize instanceof Date) { + } else if (toSerialize instanceof Date) { return toSerialize.toISOString(); - } - else if (Array.isArray(toSerialize)) { + } else if (Array.isArray(toSerialize)) { const array = []; for (let i = 0; i < toSerialize.length; i++) { array.push(serializeObject(toSerialize[i])); diff --git a/sdk/core/core-http/lib/serviceClient.ts b/sdk/core/core-http/lib/serviceClient.ts index ac32512647f3..2902ed535b28 100644 --- a/sdk/core/core-http/lib/serviceClient.ts +++ b/sdk/core/core-http/lib/serviceClient.ts @@ -7,14 +7,30 @@ import { HttpClient } from "./httpClient"; import { HttpOperationResponse, RestResponse } from "./httpOperationResponse"; import { HttpPipelineLogger } from "./httpPipelineLogger"; import { OperationArguments } from "./operationArguments"; -import { getPathStringFromParameter, getPathStringFromParameterPath, OperationParameter, ParameterPath } from "./operationParameter"; +import { + getPathStringFromParameter, + getPathStringFromParameterPath, + OperationParameter, + ParameterPath +} from "./operationParameter"; import { isStreamOperation, OperationSpec } from "./operationSpec"; -import { deserializationPolicy, DeserializationContentTypes } from "./policies/deserializationPolicy"; +import { + deserializationPolicy, + DeserializationContentTypes +} from "./policies/deserializationPolicy"; import { exponentialRetryPolicy } from "./policies/exponentialRetryPolicy"; import { generateClientRequestIdPolicy } from "./policies/generateClientRequestIdPolicy"; -import { userAgentPolicy, getDefaultUserAgentHeaderName, getDefaultUserAgentValue } from "./policies/userAgentPolicy"; +import { + userAgentPolicy, + getDefaultUserAgentHeaderName, + getDefaultUserAgentValue +} from "./policies/userAgentPolicy"; import { redirectPolicy } from "./policies/redirectPolicy"; -import { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from "./policies/requestPolicy"; +import { + RequestPolicy, + RequestPolicyFactory, + RequestPolicyOptions +} from "./policies/requestPolicy"; import { rpRegistrationPolicy } from "./policies/rpRegistrationPolicy"; import { bearerTokenAuthenticationPolicy } from "./policies/bearerTokenAuthenticationPolicy"; import { systemErrorRetryPolicy } from "./policies/systemErrorRetryPolicy"; @@ -29,8 +45,7 @@ import { ServiceCallback } from "./util/utils"; import { proxyPolicy, getDefaultProxySettings } from "./policies/proxyPolicy"; import { throttlingRetryPolicy } from "./policies/throttlingRetryPolicy"; import { ServiceClientCredentials } from "./credentials/serviceClientCredentials"; -import { signingPolicy } from './policies/signingPolicy'; - +import { signingPolicy } from "./policies/signingPolicy"; /** * HTTP proxy settings (Node.js only) @@ -51,7 +66,9 @@ export interface ServiceClientOptions { * request on the wire, or a function that takes in the defaultRequestPolicyFactories and returns * the requestPolicyFactories that will be used. */ - requestPolicyFactories?: RequestPolicyFactory[] | ((defaultRequestPolicyFactories: RequestPolicyFactory[]) => (void | RequestPolicyFactory[])); + requestPolicyFactories?: + | RequestPolicyFactory[] + | ((defaultRequestPolicyFactories: RequestPolicyFactory[]) => void | RequestPolicyFactory[]); /** * The HttpClient that will be used to send HTTP requests. */ @@ -120,7 +137,6 @@ export class ServiceClient { */ protected requestContentType?: string; - /** * The HTTP client that will be used to send requests. */ @@ -136,7 +152,10 @@ export class ServiceClient { * @param credentials The credentials used for authentication with the service. * @param options The service client options that govern the behavior of the client. */ - constructor(credentials?: TokenCredential | ServiceClientCredentials, options?: ServiceClientOptions) { + constructor( + credentials?: TokenCredential | ServiceClientCredentials, + options?: ServiceClientOptions + ) { if (!options) { options = {}; } @@ -163,12 +182,15 @@ export class ServiceClient { return { create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RequestPolicy { if (bearerTokenPolicyFactory === undefined) { - bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, `${serviceClient.baseUri || ""}/.default`) + bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy( + credentials, + `${serviceClient.baseUri || ""}/.default` + ); } return bearerTokenPolicyFactory.create(nextPolicy, options); } - } + }; }; authPolicyFactory = wrappedPolicyFactory(); @@ -182,7 +204,9 @@ export class ServiceClient { if (options.requestPolicyFactories) { // options.requestPolicyFactories can also be a function that manipulates // the default requestPolicyFactories array - const newRequestPolicyFactories: void | RequestPolicyFactory[] = options.requestPolicyFactories(requestPolicyFactories); + const newRequestPolicyFactories: + | void + | RequestPolicyFactory[] = options.requestPolicyFactories(requestPolicyFactories); if (newRequestPolicyFactories) { requestPolicyFactories = newRequestPolicyFactories; } @@ -215,7 +239,10 @@ export class ServiceClient { let httpPipeline: RequestPolicy = this._httpClient; if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) { for (let i = this._requestPolicyFactories.length - 1; i >= 0; --i) { - httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions); + httpPipeline = this._requestPolicyFactories[i].create( + httpPipeline, + this._requestPolicyOptions + ); } } return httpPipeline.sendRequest(httpRequest); @@ -227,7 +254,11 @@ export class ServiceClient { * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest. * @param {ServiceCallback} callback The callback to call when the response is received. */ - sendOperationRequest(operationArguments: OperationArguments, operationSpec: OperationSpec, callback?: ServiceCallback): Promise { + sendOperationRequest( + operationArguments: OperationArguments, + operationSpec: OperationSpec, + callback?: ServiceCallback + ): Promise { if (typeof operationArguments.options === "function") { callback = operationArguments.options; operationArguments.options = undefined; @@ -239,7 +270,9 @@ export class ServiceClient { try { const baseUri: string | undefined = operationSpec.baseUrl || this.baseUri; if (!baseUri) { - throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use."); + throw new Error( + "If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use." + ); } httpRequest.method = operationSpec.httpMethod; @@ -251,19 +284,40 @@ export class ServiceClient { } if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) { for (const urlParameter of operationSpec.urlParameters) { - let urlParameterValue: string = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter)); + let urlParameterValue: string = getOperationArgumentValueFromParameter( + this, + operationArguments, + urlParameter, + operationSpec.serializer + ); + urlParameterValue = operationSpec.serializer.serialize( + urlParameter.mapper, + urlParameterValue, + getPathStringFromParameter(urlParameter) + ); if (!urlParameter.skipEncoding) { urlParameterValue = encodeURIComponent(urlParameterValue); } - requestUrl.replaceAll(`{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`, urlParameterValue); + requestUrl.replaceAll( + `{${urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)}}`, + urlParameterValue + ); } } if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) { for (const queryParameter of operationSpec.queryParameters) { - let queryParameterValue: any = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer); + let queryParameterValue: any = getOperationArgumentValueFromParameter( + this, + operationArguments, + queryParameter, + operationSpec.serializer + ); if (queryParameterValue != undefined) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter)); + queryParameterValue = operationSpec.serializer.serialize( + queryParameter.mapper, + queryParameterValue, + getPathStringFromParameter(queryParameter) + ); if (queryParameter.collectionFormat != undefined) { if (queryParameter.collectionFormat === QueryCollectionFormat.Multi) { if (queryParameterValue.length === 0) { @@ -283,12 +337,14 @@ export class ServiceClient { for (const index in queryParameterValue) { queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]); } - } - else { + } else { queryParameterValue = encodeURIComponent(queryParameterValue); } } - requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); + requestUrl.setQueryParameter( + queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), + queryParameterValue + ); } } } @@ -301,16 +357,30 @@ export class ServiceClient { if (operationSpec.headerParameters) { for (const headerParameter of operationSpec.headerParameters) { - let headerValue: any = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer); + let headerValue: any = getOperationArgumentValueFromParameter( + this, + operationArguments, + headerParameter, + operationSpec.serializer + ); if (headerValue != undefined) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); - const headerCollectionPrefix = (headerParameter.mapper as DictionaryMapper).headerCollectionPrefix; + headerValue = operationSpec.serializer.serialize( + headerParameter.mapper, + headerValue, + getPathStringFromParameter(headerParameter) + ); + const headerCollectionPrefix = (headerParameter.mapper as DictionaryMapper) + .headerCollectionPrefix; if (headerCollectionPrefix) { for (const key of Object.keys(headerValue)) { httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]); } } else { - httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue); + httpRequest.headers.set( + headerParameter.mapper.serializedName || + getPathStringFromParameter(headerParameter), + headerValue + ); } } } @@ -353,8 +423,9 @@ export class ServiceClient { httpRequest.streamResponseBody = isStreamOperation(operationSpec); } - result = this.sendRequest(httpRequest) - .then(res => flattenResponse(res, operationSpec.responses[res.status])); + result = this.sendRequest(httpRequest).then((res) => + flattenResponse(res, operationSpec.responses[res.status]) + ); } catch (error) { result = Promise.reject(error); } @@ -363,53 +434,95 @@ export class ServiceClient { if (cb) { result // tslint:disable-next-line:no-null-keyword - .then(res => cb(null, res._response.parsedBody, res._response.request, res._response)) - .catch(err => cb(err)); + .then((res) => cb(null, res._response.parsedBody, res._response.request, res._response)) + .catch((err) => cb(err)); } return result; } } -export function serializeRequestBody(serviceClient: ServiceClient, httpRequest: WebResource, operationArguments: OperationArguments, operationSpec: OperationSpec): void { +export function serializeRequestBody( + serviceClient: ServiceClient, + httpRequest: WebResource, + operationArguments: OperationArguments, + operationSpec: OperationSpec +): void { if (operationSpec.requestBody && operationSpec.requestBody.mapper) { - httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer); + httpRequest.body = getOperationArgumentValueFromParameter( + serviceClient, + operationArguments, + operationSpec.requestBody, + operationSpec.serializer + ); const bodyMapper = operationSpec.requestBody.mapper; const { required, xmlName, xmlElementName, serializedName } = bodyMapper; const typeName = bodyMapper.type.name; try { if (httpRequest.body != undefined || required) { - const requestBodyParameterPathString: string = getPathStringFromParameter(operationSpec.requestBody); - httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString); + const requestBodyParameterPathString: string = getPathStringFromParameter( + operationSpec.requestBody + ); + httpRequest.body = operationSpec.serializer.serialize( + bodyMapper, + httpRequest.body, + requestBodyParameterPathString + ); const isStream = typeName === MapperType.Stream; if (operationSpec.isXML) { if (typeName === MapperType.Sequence) { - httpRequest.body = stringifyXML(utils.prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName!), { rootName: xmlName || serializedName }); - } - else if (!isStream) { - httpRequest.body = stringifyXML(httpRequest.body, { rootName: xmlName || serializedName }); + httpRequest.body = stringifyXML( + utils.prepareXMLRootList( + httpRequest.body, + xmlElementName || xmlName || serializedName! + ), + { rootName: xmlName || serializedName } + ); + } else if (!isStream) { + httpRequest.body = stringifyXML(httpRequest.body, { + rootName: xmlName || serializedName + }); } } else if (!isStream) { httpRequest.body = JSON.stringify(httpRequest.body); } } } catch (error) { - throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); + throw new Error( + `Error "${error.message}" occurred in serializing the payload - ${JSON.stringify( + serializedName, + undefined, + " " + )}.` + ); } } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { httpRequest.formData = {}; for (const formDataParameter of operationSpec.formDataParameters) { - const formDataParameterValue: any = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer); + const formDataParameterValue: any = getOperationArgumentValueFromParameter( + serviceClient, + operationArguments, + formDataParameter, + operationSpec.serializer + ); if (formDataParameterValue != undefined) { - const formDataParameterPropertyName: string = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); - httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter)); + const formDataParameterPropertyName: string = + formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); + httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize( + formDataParameter.mapper, + formDataParameterValue, + getPathStringFromParameter(formDataParameter) + ); } } } } -function getValueOrFunctionResult(value: undefined | string | ((defaultValue: string) => string), defaultValueCreator: (() => string)): string { +function getValueOrFunctionResult( + value: undefined | string | ((defaultValue: string) => string), + defaultValueCreator: () => string +): string { let result: string; if (typeof value === "string") { result = value; @@ -422,7 +535,10 @@ function getValueOrFunctionResult(value: undefined | string | ((defaultValue: st return result; } -function createDefaultRequestPolicyFactories(authPolicyFactory: RequestPolicyFactory | undefined, options: ServiceClientOptions): RequestPolicyFactory[] { +function createDefaultRequestPolicyFactories( + authPolicyFactory: RequestPolicyFactory | undefined, + options: ServiceClientOptions +): RequestPolicyFactory[] { const factories: RequestPolicyFactory[] = []; if (options.generateClientRequestIdHeader) { @@ -433,8 +549,14 @@ function createDefaultRequestPolicyFactories(authPolicyFactory: RequestPolicyFac factories.push(authPolicyFactory); } - const userAgentHeaderName: string = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName); - const userAgentHeaderValue: string = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue); + const userAgentHeaderName: string = getValueOrFunctionResult( + options.userAgentHeaderName, + getDefaultUserAgentHeaderName + ); + const userAgentHeaderValue: string = getValueOrFunctionResult( + options.userAgent, + getDefaultUserAgentValue + ); if (userAgentHeaderName && userAgentHeaderValue) { factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue })); } @@ -477,11 +599,28 @@ export function getPropertyParent(parent: PropertyParent, propertyPath: string[] return parent; } -function getOperationArgumentValueFromParameter(serviceClient: ServiceClient, operationArguments: OperationArguments, parameter: OperationParameter, serializer: Serializer): any { - return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer); +function getOperationArgumentValueFromParameter( + serviceClient: ServiceClient, + operationArguments: OperationArguments, + parameter: OperationParameter, + serializer: Serializer +): any { + return getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameter.parameterPath, + parameter.mapper, + serializer + ); } -export function getOperationArgumentValueFromParameterPath(serviceClient: ServiceClient, operationArguments: OperationArguments, parameterPath: ParameterPath, parameterMapper: Mapper, serializer: Serializer): any { +export function getOperationArgumentValueFromParameterPath( + serviceClient: ServiceClient, + operationArguments: OperationArguments, + parameterPath: ParameterPath, + parameterMapper: Mapper, + serializer: Serializer +): any { let value: any; if (typeof parameterPath === "string") { parameterPath = [parameterPath]; @@ -491,20 +630,28 @@ export function getOperationArgumentValueFromParameterPath(serviceClient: Servic if (parameterMapper.isConstant) { value = parameterMapper.defaultValue; } else { - let propertySearchResult: PropertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); + let propertySearchResult: PropertySearchResult = getPropertyFromParameterPath( + operationArguments, + parameterPath + ); if (!propertySearchResult.propertyFound) { propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath); } let useDefaultValue = false; if (!propertySearchResult.propertyFound) { - useDefaultValue = parameterMapper.required || (parameterPath[0] === "options" && parameterPath.length === 2); + useDefaultValue = + parameterMapper.required || + (parameterPath[0] === "options" && parameterPath.length === 2); } value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; } // Serialize just for validation purposes. - const parameterPathString: string = getPathStringFromParameterPath(parameterPath, parameterMapper); + const parameterPathString: string = getPathStringFromParameterPath( + parameterPath, + parameterMapper + ); serializer.serialize(parameterMapper, value, parameterPathString); } } else { @@ -513,11 +660,22 @@ export function getOperationArgumentValueFromParameterPath(serviceClient: Servic } for (const propertyName in parameterPath) { - const propertyMapper: Mapper = (parameterMapper as CompositeMapper).type.modelProperties![propertyName]; + const propertyMapper: Mapper = (parameterMapper as CompositeMapper).type.modelProperties![ + propertyName + ]; const propertyPath: ParameterPath = parameterPath[propertyName]; - const propertyValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer); + const propertyValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + propertyPath, + propertyMapper, + serializer + ); // Serialize just for validation purposes. - const propertyPathString: string = getPathStringFromParameterPath(propertyPath, propertyMapper); + const propertyPathString: string = getPathStringFromParameterPath( + propertyPath, + propertyMapper + ); serializer.serialize(propertyMapper, propertyValue, propertyPathString); if (propertyValue !== undefined) { if (!value) { @@ -535,7 +693,10 @@ interface PropertySearchResult { propertyFound: boolean; } -function getPropertyFromParameterPath(parent: { [parameterName: string]: any }, parameterPath: string[]): PropertySearchResult { +function getPropertyFromParameterPath( + parent: { [parameterName: string]: any }, + parameterPath: string[] +): PropertySearchResult { const result: PropertySearchResult = { propertyFound: false }; let i = 0; for (; i < parameterPath.length; ++i) { @@ -554,7 +715,10 @@ function getPropertyFromParameterPath(parent: { [parameterName: string]: any }, return result; } -export function flattenResponse(_response: HttpOperationResponse, responseSpec: OperationResponse | undefined): RestResponse { +export function flattenResponse( + _response: HttpOperationResponse, + responseSpec: OperationResponse | undefined +): RestResponse { const parsedHeaders = _response.parsedHeaders; const bodyMapper = responseSpec && responseSpec.bodyMapper; @@ -573,8 +737,11 @@ export function flattenResponse(_response: HttpOperationResponse, responseSpec: }); } - const modelProperties = typeName === "Composite" && (bodyMapper as CompositeMapper).type.modelProperties || {}; - const isPageableResponse = Object.keys(modelProperties).some(k => modelProperties[k].serializedName === ""); + const modelProperties = + (typeName === "Composite" && (bodyMapper as CompositeMapper).type.modelProperties) || {}; + const isPageableResponse = Object.keys(modelProperties).some( + (k) => modelProperties[k].serializedName === "" + ); if (typeName === "Sequence" || isPageableResponse) { const arrayResponse = [...(_response.parsedBody || [])] as RestResponse & any[]; @@ -601,7 +768,11 @@ export function flattenResponse(_response: HttpOperationResponse, responseSpec: } } - if (bodyMapper || _response.request.method === "HEAD" || utils.isPrimitiveType(_response.parsedBody)) { + if ( + bodyMapper || + _response.request.method === "HEAD" || + utils.isPrimitiveType(_response.parsedBody) + ) { // primitive body types and HEAD booleans return addOperationResponse({ ...parsedHeaders, diff --git a/sdk/core/core-http/lib/url.ts b/sdk/core/core-http/lib/url.ts index 1721f0d6cd8f..65a13f26a350 100644 --- a/sdk/core/core-http/lib/url.ts +++ b/sdk/core/core-http/lib/url.ts @@ -83,52 +83,52 @@ export class URLQuery { for (let i = 0; i < text.length; ++i) { const currentCharacter: string = text[i]; switch (currentState) { - case "ParameterName": - switch (currentCharacter) { - case "=": - currentState = "ParameterValue"; + case "ParameterName": + switch (currentCharacter) { + case "=": + currentState = "ParameterValue"; + break; + + case "&": + parameterName = ""; + parameterValue = ""; + break; + + default: + parameterName += currentCharacter; + break; + } break; - case "&": - parameterName = ""; - parameterValue = ""; + case "ParameterValue": + switch (currentCharacter) { + case "=": + parameterName = ""; + parameterValue = ""; + currentState = "Invalid"; + break; + + case "&": + result.set(parameterName, parameterValue); + parameterName = ""; + parameterValue = ""; + currentState = "ParameterName"; + break; + + default: + parameterValue += currentCharacter; + break; + } break; - default: - parameterName += currentCharacter; - break; - } - break; - - case "ParameterValue": - switch (currentCharacter) { - case "=": - parameterName = ""; - parameterValue = ""; - currentState = "Invalid"; - break; - - case "&": - result.set(parameterName, parameterValue); - parameterName = ""; - parameterValue = ""; - currentState = "ParameterName"; + case "Invalid": + if (currentCharacter === "&") { + currentState = "ParameterName"; + } break; default: - parameterValue += currentCharacter; - break; - } - break; - - case "Invalid": - if (currentCharacter === "&") { - currentState = "ParameterName"; - } - break; - - default: - throw new Error("Unrecognized URLQuery parse state: " + currentState); + throw new Error("Unrecognized URLQuery parse state: " + currentState); } } if (currentState === "ParameterValue") { @@ -302,31 +302,31 @@ export class URLBuilder { const token: URLToken | undefined = tokenizer.current(); if (token) { switch (token.type) { - case "SCHEME": - this._scheme = token.text || undefined; - break; + case "SCHEME": + this._scheme = token.text || undefined; + break; - case "HOST": - this._host = token.text || undefined; - break; + case "HOST": + this._host = token.text || undefined; + break; - case "PORT": - this._port = token.text || undefined; - break; + case "PORT": + this._port = token.text || undefined; + break; - case "PATH": - const tokenPath: string | undefined = token.text || undefined; - if (!this._path || this._path === "/" || tokenPath !== "/") { - this._path = tokenPath; - } - break; + case "PATH": + const tokenPath: string | undefined = token.text || undefined; + if (!this._path || this._path === "/" || tokenPath !== "/") { + this._path = tokenPath; + } + break; - case "QUERY": - this._query = URLQuery.parse(token.text); - break; + case "QUERY": + this._query = URLQuery.parse(token.text); + break; - default: - throw new Error(`Unrecognized URLTokenType: ${token.type}`); + default: + throw new Error(`Unrecognized URLTokenType: ${token.type}`); } } } @@ -387,8 +387,7 @@ type URLTokenizerState = "SCHEME" | "SCHEME_OR_HOST" | "HOST" | "PORT" | "PATH" type URLTokenType = "SCHEME" | "HOST" | "PORT" | "PATH" | "QUERY"; export class URLToken { - public constructor(public readonly text: string, public readonly type: URLTokenType) { - } + public constructor(public readonly text: string, public readonly type: URLTokenType) {} public static scheme(text: string): URLToken { return new URLToken(text, "SCHEME"); @@ -417,9 +416,11 @@ export class URLToken { */ export function isAlphaNumericCharacter(character: string): boolean { const characterCode: number = character.charCodeAt(0); - return (48 /* '0' */ <= characterCode && characterCode <= 57 /* '9' */) || - (65 /* 'A' */ <= characterCode && characterCode <= 90 /* 'Z' */) || - (97 /* 'a' */ <= characterCode && characterCode <= 122 /* 'z' */); + return ( + (48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ || + (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ || + (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */ + ); } /** @@ -453,39 +454,38 @@ export class URLTokenizer { this._currentToken = undefined; } else { switch (this._currentState) { - case "SCHEME": - nextScheme(this); - break; + case "SCHEME": + nextScheme(this); + break; - case "SCHEME_OR_HOST": - nextSchemeOrHost(this); - break; + case "SCHEME_OR_HOST": + nextSchemeOrHost(this); + break; - case "HOST": - nextHost(this); - break; + case "HOST": + nextHost(this); + break; - case "PORT": - nextPort(this); - break; + case "PORT": + nextPort(this); + break; - case "PATH": - nextPath(this); - break; + case "PATH": + nextPath(this); + break; - case "QUERY": - nextQuery(this); - break; + case "QUERY": + nextQuery(this); + break; - default: - throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); + default: + throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`); } } return !!this._currentToken; } } - /** * Read the remaining characters from this Tokenizer's character stream. */ @@ -570,7 +570,10 @@ function readWhileLetterOrDigit(tokenizer: URLTokenizer): string { * the end of the character stream is reached. */ function readUntilCharacter(tokenizer: URLTokenizer, ...terminatingCharacters: string[]): string { - return readWhile(tokenizer, (character: string) => terminatingCharacters.indexOf(character) === -1); + return readWhile( + tokenizer, + (character: string) => terminatingCharacters.indexOf(character) === -1 + ); } function nextScheme(tokenizer: URLTokenizer): void { diff --git a/sdk/core/core-http/lib/util/base64.ts b/sdk/core/core-http/lib/util/base64.ts index 435c33ef8d77..94f2e10f56f9 100644 --- a/sdk/core/core-http/lib/util/base64.ts +++ b/sdk/core/core-http/lib/util/base64.ts @@ -16,7 +16,7 @@ export function encodeString(value: string): string { export function encodeByteArray(value: Uint8Array): string { // Buffer.from accepts | -- the TypeScript definition is off here // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length - const bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer as ArrayBuffer); + const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer as ArrayBuffer); return bufferValue.toString("base64"); } diff --git a/sdk/core/core-http/lib/webResource.ts b/sdk/core/core-http/lib/webResource.ts index 3fa3309f424a..2daf254d5f8a 100644 --- a/sdk/core/core-http/lib/webResource.ts +++ b/sdk/core/core-http/lib/webResource.ts @@ -175,9 +175,9 @@ export class WebResource { if (validMethods.indexOf(options.method.toUpperCase()) === -1) { throw new Error( 'The provided method "' + - options.method + - '" is invalid. Supported HTTP methods are: ' + - JSON.stringify(validMethods) + options.method + + '" is invalid. Supported HTTP methods are: ' + + JSON.stringify(validMethods) ); } } @@ -204,7 +204,7 @@ export class WebResource { `pathTemplate: ${pathTemplate} has been provided. Hence, options.pathParameters must also be provided.` ); } - segments.forEach(function (item) { + segments.forEach(function(item) { const pathParamName = item.slice(1, -1); const pathParam = (pathParameters as { [key: string]: any })[pathParamName]; if ( @@ -215,9 +215,9 @@ export class WebResource { const stringifiedPathParameters = JSON.stringify(pathParameters, undefined, 2); throw new Error( `pathTemplate: ${pathTemplate} contains the path parameter ${pathParamName}` + - ` however, it is not present in parameters: ${stringifiedPathParameters}.` + - `The value of the path parameter can either be a "string" of the form { ${pathParamName}: "some sample value" } or ` + - `it can be an "object" of the form { "${pathParamName}": { value: "some sample value", skipUrlEncoding: true } }.` + ` however, it is not present in parameters: ${stringifiedPathParameters}.` + + `The value of the path parameter can either be a "string" of the form { ${pathParamName}: "some sample value" } or ` + + `it can be an "object" of the form { "${pathParamName}": { value: "some sample value", skipUrlEncoding: true } }.` ); } @@ -248,8 +248,8 @@ export class WebResource { if (typeof queryParameters !== "object") { throw new Error( `options.queryParameters must be of type object. It should be a JSON object ` + - `of "query-parameter-name" as the key and the "query-parameter-value" as the value. ` + - `The "query-parameter-value" may be fo type "string" or an "object" of the form { value: "query-parameter-value", skipUrlEncoding: true }.` + `of "query-parameter-name" as the key and the "query-parameter-value" as the value. ` + + `The "query-parameter-value" may be fo type "string" or an "object" of the form { value: "query-parameter-value", skipUrlEncoding: true }.` ); } // append question mark if it is not present in the url diff --git a/sdk/core/core-http/lib/xhrHttpClient.ts b/sdk/core/core-http/lib/xhrHttpClient.ts index a5db595b9ae9..ea7d46a23247 100644 --- a/sdk/core/core-http/lib/xhrHttpClient.ts +++ b/sdk/core/core-http/lib/xhrHttpClient.ts @@ -97,31 +97,41 @@ export class XhrHttpClient implements HttpClient { rejectOnTerminalEvent(request, xhr, reject); }); } else { - return new Promise(function (resolve, reject) { - xhr.addEventListener("load", () => resolve({ - request, - status: xhr.status, - headers: parseHeaders(xhr), - bodyAsText: xhr.responseText - })); + return new Promise(function(resolve, reject) { + xhr.addEventListener("load", () => + resolve({ + request, + status: xhr.status, + headers: parseHeaders(xhr), + bodyAsText: xhr.responseText + }) + ); rejectOnTerminalEvent(request, xhr, reject); }); } } } -function addProgressListener(xhr: XMLHttpRequestEventTarget, listener?: (progress: TransferProgressEvent) => void) { +function addProgressListener( + xhr: XMLHttpRequestEventTarget, + listener?: (progress: TransferProgressEvent) => void +) { if (listener) { - xhr.addEventListener("progress", rawEvent => listener({ - loadedBytes: rawEvent.loaded - })); + xhr.addEventListener("progress", (rawEvent) => + listener({ + loadedBytes: rawEvent.loaded + }) + ); } } // exported locally for testing export function parseHeaders(xhr: XMLHttpRequest) { const responseHeaders = new HttpHeaders(); - const headerLines = xhr.getAllResponseHeaders().trim().split(/[\r\n]+/); + const headerLines = xhr + .getAllResponseHeaders() + .trim() + .split(/[\r\n]+/); for (const line of headerLines) { const index = line.indexOf(":"); const headerName = line.slice(0, index); @@ -131,8 +141,34 @@ export function parseHeaders(xhr: XMLHttpRequest) { return responseHeaders; } -function rejectOnTerminalEvent(request: WebResource, xhr: XMLHttpRequest, reject: (err: any) => void) { - xhr.addEventListener("error", () => reject(new RestError(`Failed to send request to ${request.url}`, RestError.REQUEST_SEND_ERROR, undefined, request))); - xhr.addEventListener("abort", () => reject(new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, request))); - xhr.addEventListener("timeout", () => reject(new RestError(`timeout of ${xhr.timeout}ms exceeded`, RestError.REQUEST_SEND_ERROR, undefined, request))); +function rejectOnTerminalEvent( + request: WebResource, + xhr: XMLHttpRequest, + reject: (err: any) => void +) { + xhr.addEventListener("error", () => + reject( + new RestError( + `Failed to send request to ${request.url}`, + RestError.REQUEST_SEND_ERROR, + undefined, + request + ) + ) + ); + xhr.addEventListener("abort", () => + reject( + new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, request) + ) + ); + xhr.addEventListener("timeout", () => + reject( + new RestError( + `timeout of ${xhr.timeout}ms exceeded`, + RestError.REQUEST_SEND_ERROR, + undefined, + request + ) + ) + ); } diff --git a/sdk/core/core-http/test/credentialTests.ts b/sdk/core/core-http/test/credentialTests.ts index beac96db970d..0b411192b247 100644 --- a/sdk/core/core-http/test/credentialTests.ts +++ b/sdk/core/core-http/test/credentialTests.ts @@ -18,7 +18,9 @@ describe("Basic Authentication credentials", () => { const request = new msRest.WebResource(); creds.signRequest(request).then((signedRequest: msRest.WebResource) => { signedRequest.headers.get("authorization")!.should.exist; - signedRequest.headers.get("authorization")!.should.match(new RegExp("^Basic\\s+" + encodedCredentials + "$")); + signedRequest.headers + .get("authorization")! + .should.match(new RegExp("^Basic\\s+" + encodedCredentials + "$")); done(); }); }); @@ -29,7 +31,9 @@ describe("Basic Authentication credentials", () => { creds.signRequest(request).then((signedRequest: msRest.WebResource) => { signedRequest.headers.get("authorization")!.should.exist; - signedRequest.headers.get("authorization")!.should.match(new RegExp("^" + fakeScheme + "\\s+" + encodedCredentials + "$")); + signedRequest.headers + .get("authorization")! + .should.match(new RegExp("^" + fakeScheme + "\\s+" + encodedCredentials + "$")); done(); }); }); @@ -44,9 +48,9 @@ describe("Basic Authentication credentials", () => { }); describe("ApiKey credentials", () => { - describe("usage", function () { - it("should set header parameters properly in request", async function () { - const creds = new ApiKeyCredentials({inHeader: {"key1": "value1", "key2": "value2"}}); + describe("usage", function() { + it("should set header parameters properly in request", async function() { + const creds = new ApiKeyCredentials({ inHeader: { key1: "value1", key2: "value2" } }); const request = new msRest.WebResource(); request.headers = new msRest.HttpHeaders(); @@ -58,8 +62,8 @@ describe("Basic Authentication credentials", () => { request.headers.get("key2")!.should.match(new RegExp("^value2$")); }); - it("should set query parameters properly in the request url without any query parameters", async function () { - const creds = new ApiKeyCredentials({inQuery: {"key1": "value1", "key2": "value2"}}); + it("should set query parameters properly in the request url without any query parameters", async function() { + const creds = new ApiKeyCredentials({ inQuery: { key1: "value1", key2: "value2" } }); const request = { headers: {}, url: "https://example.com" @@ -69,8 +73,8 @@ describe("Basic Authentication credentials", () => { request.url.should.equal("https://example.com?key1=value1&key2=value2"); }); - it("should set query parameters properly in the request url with existing query parameters", async function () { - const creds = new ApiKeyCredentials({inQuery: {"key1": "value1", "key2": "value2"}}); + it("should set query parameters properly in the request url with existing query parameters", async function() { + const creds = new ApiKeyCredentials({ inQuery: { key1: "value1", key2: "value2" } }); const request = { headers: {}, url: "https://example.com?q1=v2" @@ -81,26 +85,25 @@ describe("Basic Authentication credentials", () => { }); }); - describe("construction", function () { - - it("should fail with options.inHeader and options.inQuery set to null or undefined", function (done) { - (function () { + describe("construction", function() { + it("should fail with options.inHeader and options.inQuery set to null or undefined", function(done) { + (function() { new ApiKeyCredentials({ inHeader: undefined, inQuery: undefined } as any); - }).should.throw(); + }.should.throw()); done(); }); - it("should fail without options", function (done) { - (function () { + it("should fail without options", function(done) { + (function() { new (ApiKeyCredentials as any)(); - }).should.throw(); + }.should.throw()); done(); }); - it("should fail with empty options", function (done) { - (function () { + it("should fail with empty options", function(done) { + (function() { new ApiKeyCredentials({}); - }).should.throw(); + }.should.throw()); done(); }); }); diff --git a/sdk/core/core-http/test/data/TestClient/lib/models/mappers.ts b/sdk/core/core-http/test/data/TestClient/lib/models/mappers.ts index 52fcc8cf7779..71cf2b69acb8 100644 --- a/sdk/core/core-http/test/data/TestClient/lib/models/mappers.ts +++ b/sdk/core/core-http/test/data/TestClient/lib/models/mappers.ts @@ -351,9 +351,7 @@ internalMappers.Product = { modelProperties: { id: { serializedName: "id", - constraints: { - - }, + constraints: {}, required: true, type: { name: "Number" @@ -671,10 +669,10 @@ internalMappers.SubProduct = { }; internalMappers.discriminators = { - "Fish": internalMappers.Fish, + Fish: internalMappers.Fish, "Fish.shark": internalMappers.Shark, "Fish.sawshark": internalMappers.SawShark, - "Pet": internalMappers.Pet, + Pet: internalMappers.Pet, "Pet.Cat": internalMappers.Cat, "Pet.Dog": internalMappers.Dog }; diff --git a/sdk/core/core-http/test/defaultHttpClientTests.ts b/sdk/core/core-http/test/defaultHttpClientTests.ts index 2695ef297892..8e2043d3a0fc 100644 --- a/sdk/core/core-http/test/defaultHttpClientTests.ts +++ b/sdk/core/core-http/test/defaultHttpClientTests.ts @@ -16,9 +16,9 @@ import { TestFunction } from "mocha"; const nodeIt = (isNode ? it : it.skip) as TestFunction; -describe("defaultHttpClient", function () { +describe("defaultHttpClient", function() { function sleep(ms: number): Promise { - return new Promise(resolve => setTimeout(resolve, ms)); + return new Promise((resolve) => setTimeout(resolve, ms)); } let httpMock: HttpMockFacade; @@ -29,7 +29,7 @@ describe("defaultHttpClient", function () { afterEach(() => httpMock.teardown()); after(() => httpMock.teardown()); - it("should return a response instead of throwing for awaited 404", async function () { + it("should return a response instead of throwing for awaited 404", async function() { const resourceUrl = "/nonexistent"; httpMock.get(resourceUrl, async () => { @@ -43,7 +43,7 @@ describe("defaultHttpClient", function () { response.status.should.equal(404); }); - it("should allow canceling requests", async function () { + it("should allow canceling requests", async function() { const resourceUrl = `/fileupload`; httpMock.post(resourceUrl, async () => { await sleep(10000); @@ -52,7 +52,16 @@ describe("defaultHttpClient", function () { }); const controller = new AbortController(); const veryBigPayload = "very long string"; - const request = new WebResource(resourceUrl, "POST", veryBigPayload, undefined, undefined, true, undefined, controller.signal); + const request = new WebResource( + resourceUrl, + "POST", + veryBigPayload, + undefined, + undefined, + true, + undefined, + controller.signal + ); const client = new DefaultHttpClient(); const promise = client.sendRequest(request); controller.abort(); @@ -64,7 +73,7 @@ describe("defaultHttpClient", function () { } }); - nodeIt("should not overwrite a user-provided cookie (nodejs only)", async function () { + nodeIt("should not overwrite a user-provided cookie (nodejs only)", async function() { // Cookie is only allowed to be set by the browser based on an actual response Set-Cookie header httpMock.get("http://my.fake.domain/set-cookie", { status: 200, @@ -90,12 +99,14 @@ describe("defaultHttpClient", function () { const response2 = await client.sendRequest(request2); response2.headers.get("Cookie")!.should.equal("data=123456"); - const request3 = new WebResource("http://my.fake.domain/cookie", "GET", undefined, undefined, { Cookie: "data=abcdefg" }); + const request3 = new WebResource("http://my.fake.domain/cookie", "GET", undefined, undefined, { + Cookie: "data=abcdefg" + }); const response3 = await client.sendRequest(request3); response3.headers.get("Cookie")!.should.equal("data=abcdefg"); }); - it("should allow canceling multiple requests with one token", async function () { + it("should allow canceling multiple requests with one token", async function() { httpMock.post("/fileupload", async () => { await sleep(1000); assert.fail(); @@ -105,11 +116,29 @@ describe("defaultHttpClient", function () { const controller = new AbortController(); const buf = "Very large string"; const requests = [ - new WebResource("/fileupload", "POST", buf, undefined, undefined, true, undefined, controller.signal), - new WebResource("/fileupload", "POST", buf, undefined, undefined, true, undefined, controller.signal) + new WebResource( + "/fileupload", + "POST", + buf, + undefined, + undefined, + true, + undefined, + controller.signal + ), + new WebResource( + "/fileupload", + "POST", + buf, + undefined, + undefined, + true, + undefined, + controller.signal + ) ]; const client = new DefaultHttpClient(); - const promises = requests.map(r => client.sendRequest(r)); + const promises = requests.map((r) => client.sendRequest(r)); controller.abort(); // Ensure each promise is individually rejected for (const promise of promises) { @@ -132,18 +161,32 @@ describe("defaultHttpClient", function () { ev.loadedBytes.should.be.a("Number"); }; - it("for simple bodies", async function () { + it("for simple bodies", async function() { httpMock.post("/fileupload", async (_url, _method, _body) => { - return { status: 251, body: body.repeat(9).substring(0, 200), headers: { "Content-Length": "200" } }; + return { + status: 251, + body: body.repeat(9).substring(0, 200), + headers: { "Content-Length": "200" } + }; }); const upload: Notified = { notified: false }; const download: Notified = { notified: false }; const body = "Very large string to upload"; - const request = new WebResource("/fileupload", "POST", body, undefined, undefined, false, undefined, undefined, 0, - ev => listener(upload, ev), - ev => listener(download, ev)); + const request = new WebResource( + "/fileupload", + "POST", + body, + undefined, + undefined, + false, + undefined, + undefined, + 0, + (ev) => listener(upload, ev), + (ev) => listener(download, ev) + ); const client = new DefaultHttpClient(); const response = await client.sendRequest(request); @@ -153,7 +196,7 @@ describe("defaultHttpClient", function () { download.notified.should.be.true; }); - it("for blob or stream bodies", async function () { + it("for blob or stream bodies", async function() { let payload: HttpRequestBody; if (isNode) { payload = () => createReadStream(__filename); @@ -164,24 +207,38 @@ describe("defaultHttpClient", function () { const size = isNode ? payload.toString().length : undefined; httpMock.post("/bigfileupload", async (_url, _method, _body) => { - return { status: 250, body: payload, headers: { "Content-Type": "text/javascript", "Content-length": size } }; + return { + status: 250, + body: payload, + headers: { "Content-Type": "text/javascript", "Content-length": size } + }; }); const upload: Notified = { notified: false }; const download: Notified = { notified: false }; - const request = new WebResource("/bigfileupload", "POST", payload, undefined, undefined, true, undefined, undefined, 0, - ev => listener(upload, ev), - ev => listener(download, ev)); + const request = new WebResource( + "/bigfileupload", + "POST", + payload, + undefined, + undefined, + true, + undefined, + undefined, + 0, + (ev) => listener(upload, ev), + (ev) => listener(download, ev) + ); const client = new DefaultHttpClient(); const response = await client.sendRequest(request); response.status.should.equal(250); if (response.blobBody) { await response.blobBody; - } else if ((typeof response.readableStreamBody === "function")) { + } else if (typeof response.readableStreamBody === "function") { const streamBody = (response.readableStreamBody as Function)(); - streamBody.on("data", () => { }); + streamBody.on("data", () => {}); await new Promise((resolve, reject) => { streamBody.on("end", resolve); streamBody.on("error", reject); @@ -193,10 +250,20 @@ describe("defaultHttpClient", function () { }); }); - it("should honor request timeouts", async function () { + it("should honor request timeouts", async function() { httpMock.timeout("GET", "/slow"); - const request = new WebResource("/slow", "GET", undefined, undefined, undefined, false, false, undefined, 100); + const request = new WebResource( + "/slow", + "GET", + undefined, + undefined, + undefined, + false, + false, + undefined, + 100 + ); const client = new DefaultHttpClient(); try { await client.sendRequest(request); @@ -206,7 +273,7 @@ describe("defaultHttpClient", function () { } }); - it("should give a graceful error for nonexistent hosts", async function () { + it("should give a graceful error for nonexistent hosts", async function() { // Increase timeout to give the request time to fail this.timeout(10000); const requestUrl = "http://fake.domain"; @@ -222,7 +289,7 @@ describe("defaultHttpClient", function () { } }); - it("should interpret undefined as an empty body", async function () { + it("should interpret undefined as an empty body", async function() { const requestUrl = "/expect-empty"; httpMock.put(requestUrl, async (_url, _method, body, _headers) => { if (!body) { @@ -243,14 +310,16 @@ describe("defaultHttpClient", function () { response.status.should.equal(200, response.bodyAsText!); }); - nodeIt("should send HTTP requests", async function () { + nodeIt("should send HTTP requests", async function() { const localPort = 32293; const responseContent = "Under Construction"; - const localServer = http.createServer(function (_req, res) { - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.write(responseContent); - res.end(); - }).listen(localPort); + const localServer = http + .createServer(function(_req, res) { + res.writeHead(200, { "Content-Type": "text/html" }); + res.write(responseContent); + res.end(); + }) + .listen(localPort); httpMock.passThrough(); const request = new WebResource(`http://127.0.0.1:${localPort}`, "GET"); @@ -266,9 +335,7 @@ describe("defaultHttpClient", function () { assert(response.headers); assert.strictEqual(response.headers.get("content-type")!.split(";")[0], "text/html"); const responseBody: string | null | undefined = response.bodyAsText; - assert.strictEqual( - responseBody, - responseContent); + assert.strictEqual(responseBody, responseContent); httpMock.teardown(); }); diff --git a/sdk/core/core-http/test/expiringAccessTokenCacheTests.ts b/sdk/core/core-http/test/expiringAccessTokenCacheTests.ts index 3eafe6e91e03..07dd04ffd0d0 100644 --- a/sdk/core/core-http/test/expiringAccessTokenCacheTests.ts +++ b/sdk/core/core-http/test/expiringAccessTokenCacheTests.ts @@ -8,7 +8,7 @@ function mockToken(expirationDeltaMs: number) { }; } -describe("ExpiringAccessTokenCache", function () { +describe("ExpiringAccessTokenCache", function() { it("returns a cached token within the expiration window", function() { const tokenCache = new ExpiringAccessTokenCache(2000); const accessToken = mockToken(5000); diff --git a/sdk/core/core-http/test/logFilterTests.ts b/sdk/core/core-http/test/logFilterTests.ts index 0221fd85c82a..e1dc25fe583a 100644 --- a/sdk/core/core-http/test/logFilterTests.ts +++ b/sdk/core/core-http/test/logFilterTests.ts @@ -16,7 +16,6 @@ const emptyRequestPolicy: RequestPolicy = { }; describe("Log filter", () => { - it("should log messages when a logger object is provided", (done) => { const expected = `>> Request: { "url": "https://foo.com", @@ -34,17 +33,21 @@ describe("Log filter", () => { >> Body: null `; let output = ""; - const logger = (message: string): void => { output += message + "\n"; }; + const logger = (message: string): void => { + output += message + "\n"; + }; const lf = new LogPolicy(emptyRequestPolicy, new RequestPolicyOptions(), logger); - const req = new WebResource("https://foo.com", "PUT", { "a": 1 }); - lf.sendRequest(req).then(() => { - // console.dir(output, { depth: null }); - // console.log(">>>>>>>"); - // console.dir(expected); - assert.deepEqual(output, expected); - done(); - }).catch((err: Error) => { - done(err); - }); + const req = new WebResource("https://foo.com", "PUT", { a: 1 }); + lf.sendRequest(req) + .then(() => { + // console.dir(output, { depth: null }); + // console.log(">>>>>>>"); + // console.dir(expected); + assert.deepEqual(output, expected); + done(); + }) + .catch((err: Error) => { + done(err); + }); }); }); diff --git a/sdk/core/core-http/test/mockHttp.ts b/sdk/core/core-http/test/mockHttp.ts index e7e8af89d794..294b679259af 100644 --- a/sdk/core/core-http/test/mockHttp.ts +++ b/sdk/core/core-http/test/mockHttp.ts @@ -14,7 +14,12 @@ export type MockResponseData = { headers?: any; }; -export type MockResponseFunction = (url?: string, method?: string, body?: any, headers?: any) => Promise; +export type MockResponseFunction = ( + url?: string, + method?: string, + body?: any, + headers?: any +) => Promise; export type MockResponse = MockResponseData | MockResponseFunction; @@ -30,7 +35,7 @@ export interface HttpMockFacade { } export function getHttpMock(): HttpMockFacade { - return (isNode ? new FetchHttpMock() : new BrowserHttpMock()); + return isNode ? new FetchHttpMock() : new BrowserHttpMock(); } class FetchHttpMock implements HttpMockFacade { @@ -48,7 +53,7 @@ class FetchHttpMock implements HttpMockFacade { timeout(_method: HttpMethods, url: UrlFilter): void { const delay = new Promise((resolve) => { - setTimeout(() => resolve({$uri: url, delay: 500}), 2500); + setTimeout(() => resolve({ $uri: url, delay: 500 }), 2500); }); fetchMock.mock(url, delay); @@ -82,7 +87,8 @@ class FetchHttpMock implements HttpMockFacade { }) as fetch.MockResponseFunction; } - const matcher = (_url: string, opts: fetch.MockRequest) => (url === _url) && (opts.method === method); + const matcher = (_url: string, opts: fetch.MockRequest) => + url === _url && opts.method === method; fetchMock.mock(matcher, mockResponse); } @@ -111,8 +117,16 @@ export class BrowserHttpMock implements HttpMockFacade { mockHttpMethod(method: HttpMethods, url: UrlFilter, response: MockResponse): void { if (typeof response === "function") { xhrMock.use(method, url, async (req, res) => { - const result = await response(req.url().toString(), req.method().toString(), req.body(), req.headers()); - return res.status(result.status || 200).body(result.body || {}).headers(result.headers || {}); + const result = await response( + req.url().toString(), + req.method().toString(), + req.body(), + req.headers() + ); + return res + .status(result.status || 200) + .body(result.body || {}) + .headers(result.headers || {}); }); } else { xhrMock.use(method, url, { @@ -143,6 +157,6 @@ export class BrowserHttpMock implements HttpMockFacade { } timeout(method: HttpMethods, url: UrlFilter): void { - return this.mockHttpMethod(method, url, () => new Promise(() => { })); + return this.mockHttpMethod(method, url, () => new Promise(() => {})); } } diff --git a/sdk/core/core-http/test/msAssert.ts b/sdk/core/core-http/test/msAssert.ts index 0b24dd2c2386..495e33347444 100644 --- a/sdk/core/core-http/test/msAssert.ts +++ b/sdk/core/core-http/test/msAssert.ts @@ -5,10 +5,14 @@ import { assert } from "chai"; import { SuiteFunction, PendingSuiteFunction, TestFunction, PendingTestFunction } from "mocha"; import { isNode } from "../lib/util/utils"; -export const nodeIt: TestFunction | PendingTestFunction = (!isNode ? it.skip : it); -export const browserIt: TestFunction | PendingTestFunction = (isNode ? it.skip : it); -export const nodeDescribe: SuiteFunction | PendingSuiteFunction = (!isNode ? describe.skip : describe); -export const browserDescribe: SuiteFunction | PendingSuiteFunction = (isNode ? describe.skip : describe); +export const nodeIt: TestFunction | PendingTestFunction = !isNode ? it.skip : it; +export const browserIt: TestFunction | PendingTestFunction = isNode ? it.skip : it; +export const nodeDescribe: SuiteFunction | PendingSuiteFunction = !isNode + ? describe.skip + : describe; +export const browserDescribe: SuiteFunction | PendingSuiteFunction = isNode + ? describe.skip + : describe; /** * Assert that the provided syncFunction throws an Error. If the expectedError is undefined, then @@ -17,7 +21,10 @@ export const browserDescribe: SuiteFunction | PendingSuiteFunction = (isNode ? d * @param syncFunction The synchronous function that is expected to thrown an Error. * @param expectedError The Error that is expected to be thrown. */ -export function throws(syncFunction: () => void, expectedError?: ((error: Error) => void) | Error): Error { +export function throws( + syncFunction: () => void, + expectedError?: ((error: Error) => void) | Error +): Error { let thrownError: Error | undefined; try { @@ -27,7 +34,7 @@ export function throws(syncFunction: () => void, expectedError?: ((error: Error) } if (!thrownError) { - assert.throws(() => { }); + assert.throws(() => {}); } else if (expectedError instanceof Error) { assert.deepEqual(thrownError, expectedError); } else if (expectedError) { @@ -44,7 +51,10 @@ export function throws(syncFunction: () => void, expectedError?: ((error: Error) * @param asyncFunction The asynchronous function that is expected to thrown an Error. * @param expectedError The Error that is expected to be thrown. */ -export async function throwsAsync(asyncFunction: (() => Promise) | Promise, expectedError?: ((error: Error) => void) | Error): Promise { +export async function throwsAsync( + asyncFunction: (() => Promise) | Promise, + expectedError?: ((error: Error) => void) | Error +): Promise { let thrownError: Error | undefined; try { @@ -54,7 +64,7 @@ export async function throwsAsync(asyncFunction: (() => Promise) | Promise } if (!thrownError) { - assert.throws(() => { }); + assert.throws(() => {}); } else if (expectedError instanceof Error) { assert.deepEqual(thrownError, expectedError); } else if (expectedError) { diff --git a/sdk/core/core-http/test/msRestUserAgentPolicyTests.ts b/sdk/core/core-http/test/msRestUserAgentPolicyTests.ts index b2be92135809..da0bfa06fd10 100644 --- a/sdk/core/core-http/test/msRestUserAgentPolicyTests.ts +++ b/sdk/core/core-http/test/msRestUserAgentPolicyTests.ts @@ -96,7 +96,7 @@ describe("MsRestUserAgentPolicy", () => { }); }); - browserDescribe("for browser", function () { + browserDescribe("for browser", function() { const userAgentHeaderKey = "x-ms-command-name"; const emptyRequestPolicy: RequestPolicy = { @@ -118,7 +118,10 @@ describe("MsRestUserAgentPolicy", () => { describe("MsRestUserAgentPolicy (Browser)", () => { it("should not modify user agent header if already present", async () => { const factory = userAgentPolicy(); - const browserUserAgentPolicy = factory.create(emptyRequestPolicy, new RequestPolicyOptions()); + const browserUserAgentPolicy = factory.create( + emptyRequestPolicy, + new RequestPolicyOptions() + ); const customUserAgent = "my custom user agent"; const resource = new WebResource(); resource.headers.set(userAgentHeaderKey, customUserAgent); @@ -132,7 +135,10 @@ describe("MsRestUserAgentPolicy", () => { it("should use injected user agent string if provided", async () => { const customUserAgent = "my custom user agent"; const factory = userAgentPolicy({ value: customUserAgent }); - const browserUserAgentPolicy = factory.create(emptyRequestPolicy, new RequestPolicyOptions()); + const browserUserAgentPolicy = factory.create( + emptyRequestPolicy, + new RequestPolicyOptions() + ); const resource = new WebResource(); await browserUserAgentPolicy.sendRequest(resource); diff --git a/sdk/core/core-http/test/operationParameterTests.ts b/sdk/core/core-http/test/operationParameterTests.ts index 46dedb282807..49e275f786b8 100644 --- a/sdk/core/core-http/test/operationParameterTests.ts +++ b/sdk/core/core-http/test/operationParameterTests.ts @@ -56,8 +56,8 @@ describe("getParameterPathString()", () => { it("should return the mapper's serialized name when the parameterPath is an object", () => { const parameter: OperationParameter = { parameterPath: { - "a": "A", - "b": "B" + a: "A", + b: "B" }, mapper: { serializedName: "value", diff --git a/sdk/core/core-http/test/policies/bearerTokenAuthenticationPolicyTests.ts b/sdk/core/core-http/test/policies/bearerTokenAuthenticationPolicyTests.ts index cd3a432a11bb..e6689fcdbf0d 100644 --- a/sdk/core/core-http/test/policies/bearerTokenAuthenticationPolicyTests.ts +++ b/sdk/core/core-http/test/policies/bearerTokenAuthenticationPolicyTests.ts @@ -5,15 +5,18 @@ import { assert } from "chai"; import { fake } from "sinon"; import { OperationSpec } from "../../lib/operationSpec"; import { TokenCredential, GetTokenOptions, AccessToken } from "@azure/core-auth"; -import { RequestPolicy, RequestPolicyOptions, } from "../../lib/policies/requestPolicy"; +import { RequestPolicy, RequestPolicyOptions } from "../../lib/policies/requestPolicy"; import { Constants } from "../../lib/util/constants"; import { HttpOperationResponse } from "../../lib/httpOperationResponse"; -import { HttpHeaders, } from "../../lib/httpHeaders"; +import { HttpHeaders } from "../../lib/httpHeaders"; import { WebResource } from "../../lib/webResource"; import { BearerTokenAuthenticationPolicy } from "../../lib/policies/bearerTokenAuthenticationPolicy"; -import { ExpiringAccessTokenCache, TokenRefreshBufferMs } from "../../lib/credentials/accessTokenCache"; +import { + ExpiringAccessTokenCache, + TokenRefreshBufferMs +} from "../../lib/credentials/accessTokenCache"; -describe("BearerTokenAuthenticationPolicy", function () { +describe("BearerTokenAuthenticationPolicy", function() { const mockPolicy: RequestPolicy = { sendRequest(request: WebResource): Promise { return Promise.resolve({ @@ -24,7 +27,7 @@ describe("BearerTokenAuthenticationPolicy", function () { } }; - it("correctly adds an Authentication header with the Bearer token", async function () { + it("correctly adds an Authentication header with the Bearer token", async function() { const mockToken = "token"; const tokenScopes = ["scope1", "scope2"]; const fakeGetToken = fake.returns(Promise.resolve({ token: mockToken, expiresOn: new Date() })); @@ -47,9 +50,7 @@ describe("BearerTokenAuthenticationPolicy", function () { const now = Date.now(); const refreshCred1 = new MockRefreshAzureCredential(now); const refreshCred2 = new MockRefreshAzureCredential(now + TokenRefreshBufferMs); - const notRefreshCred1 = new MockRefreshAzureCredential( - now + TokenRefreshBufferMs + 5000 - ); + const notRefreshCred1 = new MockRefreshAzureCredential(now + TokenRefreshBufferMs + 5000); const credentialsToTest: [MockRefreshAzureCredential, number][] = [ [refreshCred1, 2], @@ -78,7 +79,8 @@ describe("BearerTokenAuthenticationPolicy", function () { new RequestPolicyOptions(), credential, scopes, - new ExpiringAccessTokenCache()); + new ExpiringAccessTokenCache() + ); } }); diff --git a/sdk/core/core-http/test/policies/deserializationPolicyTests.ts b/sdk/core/core-http/test/policies/deserializationPolicyTests.ts index 1e43b4a329a1..e8689b715089 100644 --- a/sdk/core/core-http/test/policies/deserializationPolicyTests.ts +++ b/sdk/core/core-http/test/policies/deserializationPolicyTests.ts @@ -5,11 +5,17 @@ import { assert } from "chai"; import { HttpHeaders } from "../../lib/httpHeaders"; import { HttpOperationResponse } from "../../lib/httpOperationResponse"; import { HttpClient, OperationSpec, Serializer } from "../../lib/coreHttp"; -import { DeserializationPolicy, deserializationPolicy, deserializeResponseBody, defaultJsonContentTypes, defaultXmlContentTypes } from "../../lib/policies/deserializationPolicy"; +import { + DeserializationPolicy, + deserializationPolicy, + deserializeResponseBody, + defaultJsonContentTypes, + defaultXmlContentTypes +} from "../../lib/policies/deserializationPolicy"; import { RequestPolicy, RequestPolicyOptions } from "../../lib/policies/requestPolicy"; import { WebResource } from "../../lib/webResource"; -describe("deserializationPolicy", function () { +describe("deserializationPolicy", function() { const mockPolicy: RequestPolicy = { sendRequest(request: WebResource): Promise { return Promise.resolve({ @@ -20,8 +26,12 @@ describe("deserializationPolicy", function () { } }; - it(`should not modify a request that has no request body mapper`, async function () { - const deserializationPolicy = new DeserializationPolicy(mockPolicy, {}, new RequestPolicyOptions()); + it(`should not modify a request that has no request body mapper`, async function() { + const deserializationPolicy = new DeserializationPolicy( + mockPolicy, + {}, + new RequestPolicyOptions() + ); const request = createRequest(); request.body = "hello there!"; @@ -30,15 +40,16 @@ describe("deserializationPolicy", function () { assert.strictEqual(request.body, "hello there!"); }); - it("should parse a JSON response body", async function () { + it("should parse a JSON response body", async function() { const request: WebResource = createRequest(); const mockClient: HttpClient = { - sendRequest: req => Promise.resolve({ - request: req, - status: 200, - headers: new HttpHeaders({ "Content-Type": "application/json" }), - bodyAsText: "[123, 456, 789]" - }) + sendRequest: (req) => + Promise.resolve({ + request: req, + status: 200, + headers: new HttpHeaders({ "Content-Type": "application/json" }), + bodyAsText: "[123, 456, 789]" + }) }; const policy = deserializationPolicy().create(mockClient, new RequestPolicyOptions()); @@ -46,15 +57,16 @@ describe("deserializationPolicy", function () { assert.deepEqual(response.parsedBody, [123, 456, 789]); }); - it("should parse a JSON response body with a charset specified in Content-Type", async function () { + it("should parse a JSON response body with a charset specified in Content-Type", async function() { const request: WebResource = createRequest(); const mockClient: HttpClient = { - sendRequest: req => Promise.resolve({ - request: req, - status: 200, - headers: new HttpHeaders({ "Content-Type": "application/json;charset=UTF-8" }), - bodyAsText: "[123, 456, 789]" - }) + sendRequest: (req) => + Promise.resolve({ + request: req, + status: 200, + headers: new HttpHeaders({ "Content-Type": "application/json;charset=UTF-8" }), + bodyAsText: "[123, 456, 789]" + }) }; const policy = deserializationPolicy().create(mockClient, new RequestPolicyOptions()); @@ -62,15 +74,16 @@ describe("deserializationPolicy", function () { assert.deepEqual(response.parsedBody, [123, 456, 789]); }); - it("should parse a JSON response body with an uppercase Content-Type", async function () { + it("should parse a JSON response body with an uppercase Content-Type", async function() { const request: WebResource = createRequest(); const mockClient: HttpClient = { - sendRequest: req => Promise.resolve({ - request: req, - status: 200, - headers: new HttpHeaders({ "Content-Type": "APPLICATION/JSON" }), - bodyAsText: "[123, 456, 789]" - }) + sendRequest: (req) => + Promise.resolve({ + request: req, + status: 200, + headers: new HttpHeaders({ "Content-Type": "APPLICATION/JSON" }), + bodyAsText: "[123, 456, 789]" + }) }; const policy = deserializationPolicy().create(mockClient, new RequestPolicyOptions()); @@ -78,15 +91,16 @@ describe("deserializationPolicy", function () { assert.deepEqual(response.parsedBody, [123, 456, 789]); }); - it("should parse a JSON response body with a missing Content-Type", async function () { + it("should parse a JSON response body with a missing Content-Type", async function() { const request: WebResource = createRequest(); const mockClient: HttpClient = { - sendRequest: req => Promise.resolve({ - request: req, - status: 200, - headers: new HttpHeaders(), - bodyAsText: "[123, 456, 789]" - }) + sendRequest: (req) => + Promise.resolve({ + request: req, + status: 200, + headers: new HttpHeaders(), + bodyAsText: "[123, 456, 789]" + }) }; const policy = deserializationPolicy().create(mockClient, new RequestPolicyOptions()); @@ -95,7 +109,7 @@ describe("deserializationPolicy", function () { }); describe(`parse(HttpOperationResponse)`, () => { - it(`with no response headers or body`, async function () { + it(`with no response headers or body`, async function() { const response: HttpOperationResponse = { request: createRequest(), status: 200, @@ -112,7 +126,7 @@ describe("deserializationPolicy", function () { assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml response body, application/xml content-type, but no operation spec`, async function () { + it(`with xml response body, application/xml content-type, but no operation spec`, async function() { const response: HttpOperationResponse = { request: createRequest(), status: 200, @@ -128,11 +142,11 @@ describe("deserializationPolicy", function () { assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); assert.strictEqual(deserializedResponse.bodyAsText, `3`); - assert.deepEqual(deserializedResponse.parsedBody, { "apples": "3" }); + assert.deepEqual(deserializedResponse.parsedBody, { apples: "3" }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml response body with child element with attributes and value, application/xml content-type, but no operation spec`, async function () { + it(`with xml response body with child element with attributes and value, application/xml content-type, but no operation spec`, async function() { const response: HttpOperationResponse = { request: createRequest(), status: 200, @@ -147,19 +161,22 @@ describe("deserializationPolicy", function () { assert(deserializedResponse); assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); - assert.strictEqual(deserializedResponse.bodyAsText, `3`); + assert.strictEqual( + deserializedResponse.bodyAsText, + `3` + ); assert.deepEqual(deserializedResponse.parsedBody, { - "apples": { - "$": { - "tasty": "yes" + apples: { + $: { + tasty: "yes" }, - "_": "3" + _: "3" } }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml response body, application/xml content-type, and operation spec for only String value`, async function () { + it(`with xml response body, application/xml content-type, and operation spec for only String value`, async function() { const response: HttpOperationResponse = { request: createRequest({ httpMethod: "GET", @@ -198,12 +215,15 @@ describe("deserializationPolicy", function () { assert(deserializedResponse); assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); - assert.strictEqual(deserializedResponse.bodyAsText, `3`); - assert.deepEqual(deserializedResponse.parsedBody, { "apples": "3" }); + assert.strictEqual( + deserializedResponse.bodyAsText, + `3` + ); + assert.deepEqual(deserializedResponse.parsedBody, { apples: "3" }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml response body, application/xml content-type, and operation spec for only number value`, async function () { + it(`with xml response body, application/xml content-type, and operation spec for only number value`, async function() { const response: HttpOperationResponse = { request: createRequest({ httpMethod: "GET", @@ -242,12 +262,15 @@ describe("deserializationPolicy", function () { assert(deserializedResponse); assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); - assert.strictEqual(deserializedResponse.bodyAsText, `3`); - assert.deepEqual(deserializedResponse.parsedBody, { "apples": 3 }); + assert.strictEqual( + deserializedResponse.bodyAsText, + `3` + ); + assert.deepEqual(deserializedResponse.parsedBody, { apples: 3 }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml response body, application/xml content-type, and operation spec for only headers`, async function () { + it(`with xml response body, application/xml content-type, and operation spec for only headers`, async function() { const response: HttpOperationResponse = { request: createRequest({ httpMethod: "GET", @@ -297,12 +320,15 @@ describe("deserializationPolicy", function () { assert(deserializedResponse); assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); - assert.strictEqual(deserializedResponse.bodyAsText, `3`); - assert.deepEqual(deserializedResponse.parsedBody, { "apples": { "tasty": "yes" } }); + assert.strictEqual( + deserializedResponse.bodyAsText, + `3` + ); + assert.deepEqual(deserializedResponse.parsedBody, { apples: { tasty: "yes" } }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml response body, application/atom+xml content-type, but no operation spec`, async function () { + it(`with xml response body, application/atom+xml content-type, but no operation spec`, async function() { const response: HttpOperationResponse = { request: createRequest(), status: 200, @@ -318,11 +344,11 @@ describe("deserializationPolicy", function () { assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); assert.strictEqual(deserializedResponse.bodyAsText, `3`); - assert.deepEqual(deserializedResponse.parsedBody, { "apples": "3" }); + assert.deepEqual(deserializedResponse.parsedBody, { apples: "3" }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml property with attribute and value, application/atom+xml content-type, but no operation spec`, async function () { + it(`with xml property with attribute and value, application/atom+xml content-type, but no operation spec`, async function() { const response: HttpOperationResponse = { request: createRequest(), status: 200, @@ -337,19 +363,22 @@ describe("deserializationPolicy", function () { assert(deserializedResponse); assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); - assert.strictEqual(deserializedResponse.bodyAsText, `3`); + assert.strictEqual( + deserializedResponse.bodyAsText, + `3` + ); assert.deepEqual(deserializedResponse.parsedBody, { - "apples": { - "$": { - "taste": "good" + apples: { + $: { + taste: "good" }, - "_": "3" + _: "3" } }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with xml property with attribute and value, my/weird-xml content-type, but no operation spec`, async function () { + it(`with xml property with attribute and value, my/weird-xml content-type, but no operation spec`, async function() { const response: HttpOperationResponse = { request: createRequest(), status: 200, @@ -359,24 +388,31 @@ describe("deserializationPolicy", function () { bodyAsText: `3` }; - const deserializedResponse: HttpOperationResponse = await deserializeResponseBody([], ["my/weird-xml"], response); + const deserializedResponse: HttpOperationResponse = await deserializeResponseBody( + [], + ["my/weird-xml"], + response + ); assert(deserializedResponse); assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); - assert.strictEqual(deserializedResponse.bodyAsText, `3`); + assert.strictEqual( + deserializedResponse.bodyAsText, + `3` + ); assert.deepEqual(deserializedResponse.parsedBody, { - "apples": { - "$": { - "taste": "good" + apples: { + $: { + taste: "good" }, - "_": "3" + _: "3" } }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); - it(`with service bus response body, application/atom+xml content-type, and no operationSpec`, async function () { + it(`with service bus response body, application/atom+xml content-type, and no operationSpec`, async function() { const response: HttpOperationResponse = { request: createRequest(), status: 200, @@ -391,28 +427,31 @@ describe("deserializationPolicy", function () { assert(deserializedResponse); assert.strictEqual(deserializedResponse.readableStreamBody, undefined); assert.strictEqual(deserializedResponse.blobBody, undefined); - assert.strictEqual(deserializedResponse.bodyAsText, `https://daschulttest1.servicebus.windows.net/testQueuePath/?api-version=2017-04&enrich=FalsetestQueuePath2018-10-09T19:56:34Z2018-10-09T19:56:35Zdaschulttest1PT1M1024falsefalseP14DfalsePT10M10true00falseActive2018-10-09T19:56:34.903Z2018-10-09T19:56:35.013Z0001-01-01T00:00:00Ztrue00000P10675199DT2H48M5.4775807SfalseAvailablefalse`); + assert.strictEqual( + deserializedResponse.bodyAsText, + `https://daschulttest1.servicebus.windows.net/testQueuePath/?api-version=2017-04&enrich=FalsetestQueuePath2018-10-09T19:56:34Z2018-10-09T19:56:35Zdaschulttest1PT1M1024falsefalseP14DfalsePT10M10true00falseActive2018-10-09T19:56:34.903Z2018-10-09T19:56:35.013Z0001-01-01T00:00:00Ztrue00000P10675199DT2H48M5.4775807SfalseAvailablefalse` + ); assert.deepEqual(deserializedResponse.parsedBody, { - "$": { - "xmlns": "http://www.w3.org/2005/Atom" + $: { + xmlns: "http://www.w3.org/2005/Atom" }, - "author": { - "name": "daschulttest1" + author: { + name: "daschulttest1" }, - "content": { - "$": { - "type": "application/xml" + content: { + $: { + type: "application/xml" }, - "QueueDescription": { - "$": { - "xmlns": "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", + QueueDescription: { + $: { + xmlns: "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "xmlns:i": "http://www.w3.org/2001/XMLSchema-instance" }, - "AccessedAt": "0001-01-01T00:00:00Z", - "AuthorizationRules": "", - "AutoDeleteOnIdle": "P10675199DT2H48M5.4775807S", - "CountDetails": { - "$": { + AccessedAt: "0001-01-01T00:00:00Z", + AuthorizationRules: "", + AutoDeleteOnIdle: "P10675199DT2H48M5.4775807S", + CountDetails: { + $: { "xmlns:d2p1": "http://schemas.microsoft.com/netservices/2011/06/servicebus" }, "d2p1:ActiveMessageCount": "0", @@ -421,42 +460,44 @@ describe("deserializationPolicy", function () { "d2p1:TransferDeadLetterMessageCount": "0", "d2p1:TransferMessageCount": "0" }, - "CreatedAt": "2018-10-09T19:56:34.903Z", - "DeadLetteringOnMessageExpiration": "false", - "DefaultMessageTimeToLive": "P14D", - "DuplicateDetectionHistoryTimeWindow": "PT10M", - "EnableBatchedOperations": "true", - "EnableExpress": "false", - "EnablePartitioning": "false", - "EntityAvailabilityStatus": "Available", - "IsAnonymousAccessible": "false", - "LockDuration": "PT1M", - "MaxDeliveryCount": "10", - "MaxSizeInMegabytes": "1024", - "MessageCount": "0", - "RequiresDuplicateDetection": "false", - "RequiresSession": "false", - "SizeInBytes": "0", - "Status": "Active", - "SupportOrdering": "true", - "UpdatedAt": "2018-10-09T19:56:35.013Z" + CreatedAt: "2018-10-09T19:56:34.903Z", + DeadLetteringOnMessageExpiration: "false", + DefaultMessageTimeToLive: "P14D", + DuplicateDetectionHistoryTimeWindow: "PT10M", + EnableBatchedOperations: "true", + EnableExpress: "false", + EnablePartitioning: "false", + EntityAvailabilityStatus: "Available", + IsAnonymousAccessible: "false", + LockDuration: "PT1M", + MaxDeliveryCount: "10", + MaxSizeInMegabytes: "1024", + MessageCount: "0", + RequiresDuplicateDetection: "false", + RequiresSession: "false", + SizeInBytes: "0", + Status: "Active", + SupportOrdering: "true", + UpdatedAt: "2018-10-09T19:56:35.013Z" } }, - "id": "https://daschulttest1.servicebus.windows.net/testQueuePath/?api-version=2017-04&enrich=False", - "link": { - "$": { - "href": "https://daschulttest1.servicebus.windows.net/testQueuePath/?api-version=2017-04&enrich=False", - "rel": "self" + id: + "https://daschulttest1.servicebus.windows.net/testQueuePath/?api-version=2017-04&enrich=False", + link: { + $: { + href: + "https://daschulttest1.servicebus.windows.net/testQueuePath/?api-version=2017-04&enrich=False", + rel: "self" } }, - "published": "2018-10-09T19:56:34Z", - "title": { - "$": { - "type": "text" + published: "2018-10-09T19:56:34Z", + title: { + $: { + type: "text" }, - "_": "testQueuePath" + _: "testQueuePath" }, - "updated": "2018-10-09T19:56:35Z" + updated: "2018-10-09T19:56:35Z" }); assert.strictEqual(deserializedResponse.parsedHeaders, undefined); }); diff --git a/sdk/core/core-http/test/policies/proxyPolicyTests.ts b/sdk/core/core-http/test/policies/proxyPolicyTests.ts index 5404836a2374..2017acefb8a1 100644 --- a/sdk/core/core-http/test/policies/proxyPolicyTests.ts +++ b/sdk/core/core-http/test/policies/proxyPolicyTests.ts @@ -11,7 +11,7 @@ import { proxyPolicy, ProxyPolicy, getDefaultProxySettings } from "../../lib/pol import { Constants } from "../../lib/coreHttp"; import { nodeDescribe, browserDescribe } from "../msAssert"; -describe("ProxyPolicy", function () { +describe("ProxyPolicy", function() { const proxySettings: ProxySettings = { host: "https://example.com", port: 3030, @@ -20,17 +20,18 @@ describe("ProxyPolicy", function () { }; const emptyRequestPolicy = { - sendRequest: (_: WebResource) => Promise.resolve({ - request: new WebResource(), - status: 404, - headers: new HttpHeaders(undefined) - }) + sendRequest: (_: WebResource) => + Promise.resolve({ + request: new WebResource(), + status: 404, + headers: new HttpHeaders(undefined) + }) }; const emptyPolicyOptions = new RequestPolicyOptions(); - nodeDescribe("for Node.js", function () { - it("factory passes correct proxy settings", function (done) { + nodeDescribe("for Node.js", function() { + it("factory passes correct proxy settings", function(done) { const factory = proxyPolicy(proxySettings); const policy = factory.create(emptyRequestPolicy, emptyPolicyOptions) as ProxyPolicy; @@ -38,8 +39,7 @@ describe("ProxyPolicy", function () { done(); }); - - it("sets correct proxy settings through constructor", function (done) { + it("sets correct proxy settings through constructor", function(done) { const policy = new ProxyPolicy(emptyRequestPolicy, emptyPolicyOptions, proxySettings); policy.proxySettings.should.be.deep.equal(proxySettings); done(); @@ -68,7 +68,8 @@ describe("ProxyPolicy", function () { browserDescribe("for browser", () => { it("should throw an Error while constructing object", () => { - const construct = () => new ProxyPolicy(emptyRequestPolicy, emptyPolicyOptions, proxySettings); + const construct = () => + new ProxyPolicy(emptyRequestPolicy, emptyPolicyOptions, proxySettings); construct.should.throw(); }); }); @@ -78,7 +79,7 @@ describe("getDefaultProxySettings", () => { const proxyUrl = "https://proxy.microsoft.com"; const defaultPort = 80; - nodeDescribe("for Node.js", function () { + nodeDescribe("for Node.js", function() { it("should return settings with passed address", () => { const proxySettings: ProxySettings = getDefaultProxySettings(proxyUrl)!; proxySettings.host.should.equal(proxyUrl); @@ -124,7 +125,7 @@ describe("getDefaultProxySettings", () => { [ { name: "lower case", func: (envVar: string) => envVar.toLowerCase() }, { name: "upper case", func: (envVar: string) => envVar.toUpperCase() } - ].forEach(testCase => { + ].forEach((testCase) => { it(`with ${testCase.name}`, () => { const httpProxy = "http://proxy.microsoft.com"; const httpsProxy = "https://proxy.azure.com"; @@ -149,7 +150,7 @@ describe("getDefaultProxySettings", () => { }); }); - ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"].forEach(envVariableName => { + ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"].forEach((envVariableName) => { it(`should should load setting from "${envVariableName}" environmental variable`, () => { process.env[envVariableName] = proxyUrl; const proxySettings: ProxySettings = getDefaultProxySettings()!; @@ -162,11 +163,13 @@ describe("getDefaultProxySettings", () => { }); browserDescribe("for browser", () => { - [undefined, "http://proxy.microsoft.com", "https://proxy.azure.com:8080"].forEach(proxyUrl => { - it(`should return undefined for ${proxyUrl}`, () => { - const proxySettings = getDefaultProxySettings(proxyUrl); - should().not.exist(proxySettings); - }); - }); + [undefined, "http://proxy.microsoft.com", "https://proxy.azure.com:8080"].forEach( + (proxyUrl) => { + it(`should return undefined for ${proxyUrl}`, () => { + const proxySettings = getDefaultProxySettings(proxyUrl); + should().not.exist(proxySettings); + }); + } + ); }); }); diff --git a/sdk/core/core-http/test/policies/throttlingRetryPolicyTests.ts b/sdk/core/core-http/test/policies/throttlingRetryPolicyTests.ts index ab7d9c6303e9..7f6860e7683a 100644 --- a/sdk/core/core-http/test/policies/throttlingRetryPolicyTests.ts +++ b/sdk/core/core-http/test/policies/throttlingRetryPolicyTests.ts @@ -10,7 +10,7 @@ import { HttpHeaders, RequestPolicyOptions } from "../../lib/coreHttp"; describe("ThrottlingRetryPolicy", () => { class PassThroughPolicy { - constructor(private _response: HttpOperationResponse) { } + constructor(private _response: HttpOperationResponse) {} public sendRequest(request: WebResource): Promise { const response = { ...this._response, @@ -27,7 +27,13 @@ describe("ThrottlingRetryPolicy", () => { headers: new HttpHeaders() }; - function createDefaultThrottlingRetryPolicy(response?: HttpOperationResponse, actionHandler?: (httpRequest: WebResource, response: HttpOperationResponse) => Promise) { + function createDefaultThrottlingRetryPolicy( + response?: HttpOperationResponse, + actionHandler?: ( + httpRequest: WebResource, + response: HttpOperationResponse + ) => Promise + ) { if (!response) { response = defaultResponse; } @@ -54,7 +60,7 @@ describe("ThrottlingRetryPolicy", () => { request.url = "http://url"; request.method = "PATCH"; request.body = { someProperty: "someValue" }; - request.headers = new HttpHeaders({ "header": "abc" }); + request.headers = new HttpHeaders({ header: "abc" }); request.query = { q: "param" }; const policy = createDefaultThrottlingRetryPolicy(); @@ -72,7 +78,9 @@ describe("ThrottlingRetryPolicy", () => { }), request: request }; - const policy = createDefaultThrottlingRetryPolicy(mockResponse, _ => { throw new AssertionError("fail"); }); + const policy = createDefaultThrottlingRetryPolicy(mockResponse, (_) => { + throw new AssertionError("fail"); + }); const response = await policy.sendRequest(request); @@ -99,20 +107,22 @@ describe("ThrottlingRetryPolicy", () => { }); describe("parseRetryAfterHeader", () => { - it("should return undefined for ill-formed header", function () { + it("should return undefined for ill-formed header", function() { const retryAfter = ThrottlingRetryPolicy.parseRetryAfterHeader("foobar"); assert.equal(retryAfter, undefined); }); - it("should return sleep interval value in milliseconds if parameter is a number", function (done) { + it("should return sleep interval value in milliseconds if parameter is a number", function(done) { const retryAfter = ThrottlingRetryPolicy.parseRetryAfterHeader("1"); assert.equal(retryAfter, 1000); done(); }); - it("should return sleep interval value in milliseconds for full date format", function (done) { + it("should return sleep interval value in milliseconds for full date format", function(done) { const clock = sinon.useFakeTimers(new Date("Fri, 31 Dec 1999 23:00:00 GMT").getTime()); - const retryAfter = ThrottlingRetryPolicy.parseRetryAfterHeader("Fri, 31 Dec 1999 23:02:00 GMT"); + const retryAfter = ThrottlingRetryPolicy.parseRetryAfterHeader( + "Fri, 31 Dec 1999 23:02:00 GMT" + ); assert.equal(retryAfter, 2 * 60 * 1000); @@ -120,7 +130,7 @@ describe("ThrottlingRetryPolicy", () => { done(); }); - it("should return sleep interval value in milliseconds for shorter date format", function (done) { + it("should return sleep interval value in milliseconds for shorter date format", function(done) { const clock = sinon.useFakeTimers(new Date("Fri, 31 Dec 1999 23:00:00 GMT").getTime()); const retryAfter = ThrottlingRetryPolicy.parseRetryAfterHeader("31 Dec 1999 23:03:00 GMT"); diff --git a/sdk/core/core-http/test/policies/tracingPolicyTests.ts b/sdk/core/core-http/test/policies/tracingPolicyTests.ts index fd1a11bd769f..f22a0ba02ee2 100644 --- a/sdk/core/core-http/test/policies/tracingPolicyTests.ts +++ b/sdk/core/core-http/test/policies/tracingPolicyTests.ts @@ -2,8 +2,21 @@ // Licensed under the MIT License. import { assert } from "chai"; -import { RequestPolicy, WebResource, HttpOperationResponse, HttpHeaders, RequestPolicyOptions } from "../../lib/coreHttp"; -import { setTracer, TraceFlags, NoOpTracer, SpanOptions, SpanContext, NoOpSpan } from "@azure/core-tracing"; +import { + RequestPolicy, + WebResource, + HttpOperationResponse, + HttpHeaders, + RequestPolicyOptions +} from "../../lib/coreHttp"; +import { + setTracer, + TraceFlags, + NoOpTracer, + SpanOptions, + SpanContext, + NoOpSpan +} from "@azure/core-tracing"; import { tracingPolicy } from "../../lib/policies/tracingPolicy"; class MockSpan extends NoOpSpan { diff --git a/sdk/core/core-http/test/proxyAgent.node.ts b/sdk/core/core-http/test/proxyAgent.node.ts index 2d36d7b4e484..3c7e9bd87a4e 100644 --- a/sdk/core/core-http/test/proxyAgent.node.ts +++ b/sdk/core/core-http/test/proxyAgent.node.ts @@ -12,11 +12,11 @@ import { createProxyAgent, createTunnel } from "../lib/proxyAgent"; describe("proxyAgent", () => { describe("createProxyAgent", () => { type HttpsAgent = https.Agent & { - defaultPort: number | undefined, + defaultPort: number | undefined; options: { - proxy: tunnel.ProxyOptions - }, - proxyOptions: tunnel.ProxyOptions + proxy: tunnel.ProxyOptions; + }; + proxyOptions: tunnel.ProxyOptions; }; [ @@ -25,8 +25,10 @@ describe("proxyAgent", () => { { proxy: "hTtp", request: "https", port: 443, isProxyHttps: true }, { proxy: "HTTPS", request: "http", port: undefined, isProxyHttps: false }, { proxy: "https", request: "hTTps", port: 443, isProxyHttps: true } - ].forEach(testCase => { - it(`should return ${testCase.isProxyHttps ? "HTTPS" : "HTTP"} proxy for ${testCase.proxy.toUpperCase()} proxy server and ${testCase.request.toUpperCase()} request`, function (done) { + ].forEach((testCase) => { + it(`should return ${ + testCase.isProxyHttps ? "HTTPS" : "HTTP" + } proxy for ${testCase.proxy.toUpperCase()} proxy server and ${testCase.request.toUpperCase()} request`, function(done) { const urlHost = "proxy.microsoft.com"; const proxySettings = { host: `${testCase.proxy}://${urlHost}`, @@ -45,7 +47,7 @@ describe("proxyAgent", () => { }); }); - it("should copy headers correctly", function (done) { + it("should copy headers correctly", function(done) { const proxySettings = { host: "http://proxy.microsoft.com", port: 8080 @@ -70,14 +72,14 @@ describe("proxyAgent", () => { }; type HttpsAgent = https.Agent & { - defaultPort: number | undefined, + defaultPort: number | undefined; options: { - proxy: tunnel.ProxyOptions - } + proxy: tunnel.ProxyOptions; + }; }; - [true, false].forEach(value => { - it(`returns HTTP agent for HTTP request and HTTP${value ? "S" : ""} proxy`, function () { + [true, false].forEach((value) => { + it(`returns HTTP agent for HTTP request and HTTP${value ? "S" : ""} proxy`, function() { const tunnelConfig: tunnel.HttpsOverHttpsOptions = { proxy: { host: defaultProxySettings.host, @@ -93,8 +95,8 @@ describe("proxyAgent", () => { }); }); - [true, false].forEach(value => { - it(`returns HTTPS agent for HTTPS request and HTTP${value ? "S" : ""} proxy`, function () { + [true, false].forEach((value) => { + it(`returns HTTPS agent for HTTPS request and HTTP${value ? "S" : ""} proxy`, function() { const tunnelConfig: tunnel.HttpsOverHttpsOptions = { proxy: { host: defaultProxySettings.host, diff --git a/sdk/core/core-http/test/serializationTests.ts b/sdk/core/core-http/test/serializationTests.ts index 9e2b84f84ee3..8d2c84f54855 100644 --- a/sdk/core/core-http/test/serializationTests.ts +++ b/sdk/core/core-http/test/serializationTests.ts @@ -19,29 +19,29 @@ function stringToByteArray(str: string): Uint8Array { } } -describe("msrest", function () { - describe("serializeObject", function () { - it("should correctly serialize a Date Object", function (done) { +describe("msrest", function() { + describe("serializeObject", function() { + it("should correctly serialize a Date Object", function(done) { const dateObj = new Date("2015-01-01"); const dateISO = "2015-01-01T00:00:00.000Z"; msRest.serializeObject(dateObj).should.equal(dateISO); done(); }); - it("should correctly serialize a Date object with max value", function (done) { + it("should correctly serialize a Date object with max value", function(done) { const serializedDateString = msRest.serializeObject(new Date("9999-12-31T23:59:59-12:00")); serializedDateString.should.equal("+010000-01-01T11:59:59.000Z"); done(); }); - it("should correctly serialize a Uint8Array Object", function (done) { + it("should correctly serialize a Uint8Array Object", function(done) { const byteArray = stringToByteArray("Javascript"); const base64str = "SmF2YXNjcmlwdA=="; msRest.serializeObject(byteArray).should.equal(base64str); done(); }); - it("should correctly serialize Primitive types", function (done) { + it("should correctly serialize Primitive types", function(done) { msRest.serializeObject(true).should.equal(true); msRest.serializeObject(false).should.equal(false); msRest.serializeObject("true").should.equal("true"); @@ -51,36 +51,36 @@ describe("msrest", function () { done(); }); - it("should correctly serialize an empty array and an empty dictionary", function (done) { + it("should correctly serialize an empty array and an empty dictionary", function(done) { assert.deepEqual(msRest.serializeObject([]), []); assert.deepEqual(msRest.serializeObject({}), {}); done(); }); - it("should correctly serialize a complex JSON object", function (done) { + it("should correctly serialize a complex JSON object", function(done) { const o1: unknown = { - "p1": "value1", - "p2": "value2", + p1: "value1", + p2: "value2", "top-buf": stringToByteArray("top string"), "top-date": new Date("2014"), "top-dates": [new Date("1900"), new Date("1901")], - "insider": { + insider: { "insider-buf": stringToByteArray("insider string"), "insider-date": new Date("2015"), "insider-dates": [new Date("2100"), new Date("2101")], "insider-dictionary": { - "k1": new Date("2015"), - "k2": new Date("2016"), - "k3": new Date("2017") + k1: new Date("2015"), + k2: new Date("2016"), + k3: new Date("2017") }, "top-complex": { - "id": 1, - "name": "Joey", - "age": 23.36, - "male": true, - "birthday": "1992-01-01T00:00:00.000Z", - "anniversary": new Date("2013-12-08"), - "memory": stringToByteArray("Yadadadada") + id: 1, + name: "Joey", + age: 23.36, + male: true, + birthday: "1992-01-01T00:00:00.000Z", + anniversary: new Date("2013-12-08"), + memory: stringToByteArray("Yadadadada") } } }; @@ -90,17 +90,11 @@ describe("msrest", function () { p2: "value2", "top-buf": "dG9wIHN0cmluZw==", "top-date": "2014-01-01T00:00:00.000Z", - "top-dates": [ - "1900-01-01T00:00:00.000Z", - "1901-01-01T00:00:00.000Z" - ], + "top-dates": ["1900-01-01T00:00:00.000Z", "1901-01-01T00:00:00.000Z"], insider: { "insider-buf": "aW5zaWRlciBzdHJpbmc=", "insider-date": "2015-01-01T00:00:00.000Z", - "insider-dates": [ - "2100-01-01T00:00:00.000Z", - "2101-01-01T00:00:00.000Z" - ], + "insider-dates": ["2100-01-01T00:00:00.000Z", "2101-01-01T00:00:00.000Z"], "insider-dictionary": { k1: "2015-01-01T00:00:00.000Z", k2: "2016-01-01T00:00:00.000Z", @@ -122,79 +116,121 @@ describe("msrest", function () { }); }); - describe("serialize", function () { + describe("serialize", function() { const invalid_uuid = "abcd-efgd90-90890jkh"; - it("should correctly serialize a string if the type is 'any'", function (done) { - const mapper: msRest.Mapper = { type: { name: "any" }, required: false, serializedName: "any" }; + it("should correctly serialize a string if the type is 'any'", function(done) { + const mapper: msRest.Mapper = { + type: { name: "any" }, + required: false, + serializedName: "any" + }; const serializedObject = Serializer.serialize(mapper, "foo", "anyBody"); serializedObject.should.equal("foo"); done(); }); - it("should correctly serialize an array if the type is 'any'", function (done) { - const mapper: msRest.Mapper = { type: { name: "any" }, required: false, serializedName: "any" }; + it("should correctly serialize an array if the type is 'any'", function(done) { + const mapper: msRest.Mapper = { + type: { name: "any" }, + required: false, + serializedName: "any" + }; const serializedObject = Serializer.serialize(mapper, [1, 2], "anyBody"); assert.deepEqual(serializedObject, [1, 2]); done(); }); - it("should correctly serialize a string", function (done) { - const mapper: msRest.Mapper = { type: { name: "String" }, required: false, serializedName: "string" }; + it("should correctly serialize a string", function(done) { + const mapper: msRest.Mapper = { + type: { name: "String" }, + required: false, + serializedName: "string" + }; const serializedObject = Serializer.serialize(mapper, "foo", "stringBody"); serializedObject.should.equal("foo"); done(); }); - it("should correctly serialize a uuid", function (done) { - const mapper: msRest.Mapper = { type: { name: "Uuid" }, required: false, serializedName: "Uuid" }; + it("should correctly serialize a uuid", function(done) { + const mapper: msRest.Mapper = { + type: { name: "Uuid" }, + required: false, + serializedName: "Uuid" + }; const serializedObject = Serializer.serialize(mapper, valid_uuid, "uuidBody"); serializedObject.should.equal(valid_uuid); done(); }); - it("should throw an error if the value is not a valid Uuid", function (done) { - const mapper: msRest.Mapper = { type: { name: "Uuid" }, required: false, serializedName: "Uuid" }; + it("should throw an error if the value is not a valid Uuid", function(done) { + const mapper: msRest.Mapper = { + type: { name: "Uuid" }, + required: false, + serializedName: "Uuid" + }; try { Serializer.serialize(mapper, invalid_uuid, "uuidBody"); } catch (error) { - error.message.should.match(/.*with value.*must be of type string and a valid uuid/ig); + error.message.should.match(/.*with value.*must be of type string and a valid uuid/gi); done(); } }); - it("should correctly serialize a number", function (done) { - const mapper: msRest.Mapper = { type: { name: "Number" }, required: false, serializedName: "Number" }; + it("should correctly serialize a number", function(done) { + const mapper: msRest.Mapper = { + type: { name: "Number" }, + required: false, + serializedName: "Number" + }; const serializedObject = Serializer.serialize(mapper, 1.506, "stringBody"); serializedObject.should.equal(1.506); done(); }); - it("should correctly serialize a boolean", function (done) { - const mapper: msRest.Mapper = { type: { name: "Boolean" }, required: false, serializedName: "Boolean" }; + it("should correctly serialize a boolean", function(done) { + const mapper: msRest.Mapper = { + type: { name: "Boolean" }, + required: false, + serializedName: "Boolean" + }; const serializedObject = Serializer.serialize(mapper, false, "stringBody"); serializedObject.should.equal(false); done(); }); - it("should correctly serialize an Enum", function (done) { - const mapper: msRest.EnumMapper = { type: { name: "Enum", allowedValues: [1, 2, 3, 4] }, required: false, serializedName: "Enum" }; + it("should correctly serialize an Enum", function(done) { + const mapper: msRest.EnumMapper = { + type: { name: "Enum", allowedValues: [1, 2, 3, 4] }, + required: false, + serializedName: "Enum" + }; const serializedObject = Serializer.serialize(mapper, 1, "enumBody"); serializedObject.should.equal(1); done(); }); - it("should throw an error if the value is not valid for an Enum", function (done) { - const mapper: msRest.EnumMapper = { type: { name: "Enum", allowedValues: [1, 2, 3, 4] }, required: false, serializedName: "Enum" }; + it("should throw an error if the value is not valid for an Enum", function(done) { + const mapper: msRest.EnumMapper = { + type: { name: "Enum", allowedValues: [1, 2, 3, 4] }, + required: false, + serializedName: "Enum" + }; try { Serializer.serialize(mapper, 6, "enumBody"); } catch (error) { - error.message.should.match(/6 is not a valid value for enumBody\. The valid values are: \[1,2,3,4\]/ig); + error.message.should.match( + /6 is not a valid value for enumBody\. The valid values are: \[1,2,3,4\]/gi + ); done(); } }); - it("should correctly serialize a ByteArray Object", function (done) { - const mapper: msRest.Mapper = { type: { name: "ByteArray" }, required: false, serializedName: "ByteArray" }; + it("should correctly serialize a ByteArray Object", function(done) { + const mapper: msRest.Mapper = { + type: { name: "ByteArray" }, + required: false, + serializedName: "ByteArray" + }; const byteArray = stringToByteArray("Javascript"); const base64str = "SmF2YXNjcmlwdA=="; const serializedObject = Serializer.serialize(mapper, byteArray, "stringBody"); @@ -202,50 +238,84 @@ describe("msrest", function () { done(); }); - it("should correctly serialize a Date Object", function (done) { + it("should correctly serialize a Date Object", function(done) { const dateObj = new Date("2015-01-01"); const dateISO = "2015-01-01"; - const mapper: msRest.Mapper = { type: { name: "Date" }, required: false, serializedName: "Date" }; + const mapper: msRest.Mapper = { + type: { name: "Date" }, + required: false, + serializedName: "Date" + }; Serializer.serialize(mapper, dateObj, "dateObj").should.equal(dateISO); done(); }); - it("should correctly serialize a Date object with max value", function (done) { - const mapper: msRest.Mapper = { type: { name: "DateTime" }, required: false, serializedName: "DateTime" }; - const serializedDateString = Serializer.serialize(mapper, new Date("9999-12-31T23:59:59-12:00"), "dateTimeObj"); + it("should correctly serialize a Date object with max value", function(done) { + const mapper: msRest.Mapper = { + type: { name: "DateTime" }, + required: false, + serializedName: "DateTime" + }; + const serializedDateString = Serializer.serialize( + mapper, + new Date("9999-12-31T23:59:59-12:00"), + "dateTimeObj" + ); serializedDateString.should.equal("+010000-01-01T11:59:59.000Z"); done(); }); - it("should correctly serialize a Date object with max value and format UnixTime", function (done) { - const mapper: msRest.Mapper = { type: { name: "UnixTime" }, required: false, serializedName: "UnixTime" }; - const serializedDate = Serializer.serialize(mapper, new Date("9999-12-31T23:59:59-12:00"), "dateTimeObj"); + it("should correctly serialize a Date object with max value and format UnixTime", function(done) { + const mapper: msRest.Mapper = { + type: { name: "UnixTime" }, + required: false, + serializedName: "UnixTime" + }; + const serializedDate = Serializer.serialize( + mapper, + new Date("9999-12-31T23:59:59-12:00"), + "dateTimeObj" + ); serializedDate.should.equal(253402343999); done(); }); - it("should correctly serialize a string in DateTimeRfc1123", function (done) { - const mapper: msRest.Mapper = { type: { name: "DateTimeRfc1123" }, required: false, serializedName: "DateTimeRfc1123" }; + it("should correctly serialize a string in DateTimeRfc1123", function(done) { + const mapper: msRest.Mapper = { + type: { name: "DateTimeRfc1123" }, + required: false, + serializedName: "DateTimeRfc1123" + }; const rfc = new Date("Mon, 01 Jan 0001 00:00:00 GMT"); const serializedDateString = Serializer.serialize(mapper, rfc, "dateTimeObj"); serializedDateString.should.equal("Mon, 01 Jan 2001 00:00:00 GMT"); done(); }); - it("should correctly serialize an ISO 8601 duration", function () { - const mapper: msRest.Mapper = { type: { name: "TimeSpan" }, required: false, serializedName: "TimeSpan" }; + it("should correctly serialize an ISO 8601 duration", function() { + const mapper: msRest.Mapper = { + type: { name: "TimeSpan" }, + required: false, + serializedName: "TimeSpan" + }; const duration = "P123DT22H14M12.011S"; const serializedDateString = Serializer.serialize(mapper, duration, "dateTimeObj"); serializedDateString.should.equal(duration); }); - it("should throw an error when given an invalid ISO 8601 duration", function () { - const mapper: msRest.Mapper = { type: { name: "TimeSpan" }, required: false, serializedName: "TimeSpan" }; + it("should throw an error when given an invalid ISO 8601 duration", function() { + const mapper: msRest.Mapper = { + type: { name: "TimeSpan" }, + required: false, + serializedName: "TimeSpan" + }; const duration = "P123Z42DT22H14M12.011S"; - (() => Serializer.serialize(mapper, duration, "dateTimeObj")).should.throw(/must be a string in ISO 8601 format/); + (() => Serializer.serialize(mapper, duration, "dateTimeObj")).should.throw( + /must be a string in ISO 8601 format/ + ); }); - it("should correctly serialize an array of primitives", function (done) { + it("should correctly serialize an array of primitives", function(done) { const mapper: msRest.SequenceMapper = { required: false, serializedName: "Sequence", @@ -264,7 +334,7 @@ describe("msrest", function () { done(); }); - it("should correctly serialize an array of array of primitives", function (done) { + it("should correctly serialize an array of array of primitives", function(done) { const mapper: msRest.SequenceMapper = { required: false, serializedName: "Sequence", @@ -292,7 +362,7 @@ describe("msrest", function () { done(); }); - it("should correctly serialize an array of array of object types", function (done) { + it("should correctly serialize an array of array of object types", function(done) { const mapper: msRest.SequenceMapper = { serializedName: "arrayObj", required: true, @@ -316,7 +386,7 @@ describe("msrest", function () { done(); }); - it('should fail while serializing an array of array of "object" types when a null value is provided', function (done) { + it('should fail while serializing an array of array of "object" types when a null value is provided', function(done) { const mapper: msRest.Mapper = { serializedName: "arrayObj", required: true, @@ -344,8 +414,7 @@ describe("msrest", function () { done(); }); - - it("should correctly serialize an array of dictionary of primitives", function (done) { + it("should correctly serialize an array of dictionary of primitives", function(done) { const mapper: msRest.SequenceMapper = { required: false, serializedName: "Sequence", @@ -373,7 +442,7 @@ describe("msrest", function () { done(); }); - it("should correctly serialize a dictionary of primitives", function (done) { + it("should correctly serialize a dictionary of primitives", function(done) { const mapper: msRest.DictionaryMapper = { required: false, serializedName: "Dictionary", @@ -394,7 +463,7 @@ describe("msrest", function () { done(); }); - it("should correctly serialize a dictionary of array of primitives", function (done) { + it("should correctly serialize a dictionary of array of primitives", function(done) { const mapper: msRest.DictionaryMapper = { required: false, serializedName: "Dictionary", @@ -416,13 +485,13 @@ describe("msrest", function () { } } }; - const dict = { "One": [1], "Two": [1, 2], "three": [1, 2, 3] }; + const dict = { One: [1], Two: [1, 2], three: [1, 2, 3] }; const serializedDictionary = Serializer.serialize(mapper, dict, "dictObj"); assert.deepEqual(dict, serializedDictionary); done(); }); - it("should correctly serialize a dictionary of dictionary of primitives", function (done) { + it("should correctly serialize a dictionary of dictionary of primitives", function(done) { const mapper: msRest.DictionaryMapper = { required: false, serializedName: "Dictionary", @@ -444,13 +513,13 @@ describe("msrest", function () { } } }; - const dict = { 1: { "One": true }, 2: { "Two": false }, 3: { "three": true } }; + const dict = { 1: { One: true }, 2: { Two: false }, 3: { three: true } }; const serializedDictionary = Serializer.serialize(mapper, dict, "dictObj"); assert.deepEqual(dict, serializedDictionary); done(); }); - it("should correctly serialize a composite type", function (done) { + it("should correctly serialize a composite type", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.Product; const productObj = { @@ -467,13 +536,13 @@ describe("msrest", function () { invDate: "2015-12-25", invProducts: [ { - "Product1": { + Product1: { id: 101, name: "TestProduct" } }, { - "Product2": { + Product2: { id: 104, name: "TestProduct1" } @@ -512,41 +581,49 @@ describe("msrest", function () { } else if (prop === "tags") { JSON.stringify(serializedProduct[prop]).should.equal(JSON.stringify(productObj.tags)); } else if (prop === "dispatchTime") { - JSON.stringify(serializedProduct[prop]).should.equal(JSON.stringify(productObj.dispatchTime)); + JSON.stringify(serializedProduct[prop]).should.equal( + JSON.stringify(productObj.dispatchTime) + ); } else if (prop === "invoiceInfo") { - (JSON.stringify(serializedProduct[prop]).length - JSON.stringify(productObj.invoiceInfo).length).should.equal(4); + ( + JSON.stringify(serializedProduct[prop]).length - + JSON.stringify(productObj.invoiceInfo).length + ).should.equal(4); } else if (prop === "subProducts") { - (JSON.stringify(serializedProduct[prop]).length - JSON.stringify(productObj.subProducts).length).should.equal(8); + ( + JSON.stringify(serializedProduct[prop]).length - + JSON.stringify(productObj.subProducts).length + ).should.equal(8); } } done(); }); - it("should correctly serialize object version of polymorphic discriminator", function (done) { + it("should correctly serialize object version of polymorphic discriminator", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.SawShark; const sawshark = { - "fishtype": "sawshark", - "age": 22, - "birthday": new Date("2012-01-05T01:00:00Z"), - "species": "king", - "length": 1.0, - "picture": new Uint8Array([255, 255, 255, 255, 254]), - "siblings": [ + fishtype: "sawshark", + age: 22, + birthday: new Date("2012-01-05T01:00:00Z"), + species: "king", + length: 1.0, + picture: new Uint8Array([255, 255, 255, 255, 254]), + siblings: [ { - "fishtype": "shark", - "age": 6, - "birthday": new Date("2012-01-05T01:00:00Z"), - "length": 20.0, - "species": "predator" + fishtype: "shark", + age: 6, + birthday: new Date("2012-01-05T01:00:00Z"), + length: 20.0, + species: "predator" }, { - "fishtype": "sawshark", - "age": 105, - "birthday": new Date("1900-01-05T01:00:00Z"), - "length": 10.0, - "picture": new Uint8Array([255, 255, 255, 255, 254]), - "species": "dangerous" + fishtype: "sawshark", + age: 105, + birthday: new Date("1900-01-05T01:00:00Z"), + length: 10.0, + picture: new Uint8Array([255, 255, 255, 255, 254]), + species: "dangerous" } ] }; @@ -556,16 +633,20 @@ describe("msrest", function () { serializedSawshark.siblings.length.should.equal(2); serializedSawshark.siblings[0]["fish.type"].should.equal("shark"); serializedSawshark.siblings[0].age.should.equal(6); - serializedSawshark.siblings[0].birthday.should.equal(new Date("2012-01-05T01:00:00Z").toISOString()); + serializedSawshark.siblings[0].birthday.should.equal( + new Date("2012-01-05T01:00:00Z").toISOString() + ); serializedSawshark.siblings[1]["fish.type"].should.equal("sawshark"); serializedSawshark.siblings[1].age.should.equal(105); - serializedSawshark.siblings[1].birthday.should.equal(new Date("1900-01-05T01:00:00Z").toISOString()); + serializedSawshark.siblings[1].birthday.should.equal( + new Date("1900-01-05T01:00:00Z").toISOString() + ); serializedSawshark.siblings[1].picture.should.equal("//////4="); serializedSawshark.picture.should.equal("//////4="); done(); }); - it("should correctly serialize additionalProperties when the mapper knows that additional properties are allowed", function () { + it("should correctly serialize additionalProperties when the mapper knows that additional properties are allowed", function() { const bodyParameter = { id: 5, name: "Funny", @@ -597,7 +678,7 @@ describe("msrest", function () { result.birthdate.should.equal("2017-12-13T02:29:51.000Z"); }); - it("should allow null when required: true and nullable: true", function () { + it("should allow null when required: true and nullable: true", function() { const mapper: msRest.Mapper = { required: false, serializedName: "testmodel", @@ -622,7 +703,7 @@ describe("msrest", function () { result.should.exist; }); - it("should not allow undefined when required: true and nullable: true", function () { + it("should not allow undefined when required: true and nullable: true", function() { const mapper: msRest.Mapper = { required: false, serializedName: "testmodel", @@ -642,10 +723,12 @@ describe("msrest", function () { } }; - (function () { Serializer.serialize(mapper, { length: undefined }, "testobj"); }).should.throw("testobj.length cannot be undefined."); + (function() { + Serializer.serialize(mapper, { length: undefined }, "testobj"); + }.should.throw("testobj.length cannot be undefined.")); }); - it("should not allow null when required: true and nullable: false", function () { + it("should not allow null when required: true and nullable: false", function() { const mapper: msRest.Mapper = { required: false, serializedName: "testmodel", @@ -665,10 +748,12 @@ describe("msrest", function () { } }; - (function () { Serializer.serialize(mapper, { length: undefined }, "testobj"); }).should.throw("testobj.length cannot be null or undefined."); + (function() { + Serializer.serialize(mapper, { length: undefined }, "testobj"); + }.should.throw("testobj.length cannot be null or undefined.")); }); - it("should not allow undefined when required: true and nullable: false", function () { + it("should not allow undefined when required: true and nullable: false", function() { const mapper: msRest.Mapper = { required: false, serializedName: "testmodel", @@ -688,10 +773,12 @@ describe("msrest", function () { } }; - (function () { Serializer.serialize(mapper, { length: undefined }, "testobj"); }).should.throw("testobj.length cannot be null or undefined."); + (function() { + Serializer.serialize(mapper, { length: undefined }, "testobj"); + }.should.throw("testobj.length cannot be null or undefined.")); }); - it("should not allow null when required: true and nullable is undefined", function () { + it("should not allow null when required: true and nullable is undefined", function() { const mapper: msRest.Mapper = { serializedName: "foo", required: true, @@ -699,10 +786,12 @@ describe("msrest", function () { name: "String" } }; - (function () { Serializer.serialize(mapper, undefined, "testobj"); }).should.throw("testobj cannot be null or undefined."); + (function() { + Serializer.serialize(mapper, undefined, "testobj"); + }.should.throw("testobj cannot be null or undefined.")); }); - it("should not allow undefined when required: true and nullable is undefined", function () { + it("should not allow undefined when required: true and nullable is undefined", function() { const mapper: msRest.Mapper = { serializedName: "foo", required: true, @@ -710,10 +799,12 @@ describe("msrest", function () { name: "String" } }; - (function () { Serializer.serialize(mapper, undefined, "testobj"); }).should.throw("testobj cannot be null or undefined."); + (function() { + Serializer.serialize(mapper, undefined, "testobj"); + }.should.throw("testobj cannot be null or undefined.")); }); - it("should allow null when required: false and nullable: true", function () { + it("should allow null when required: false and nullable: true", function() { const mapper: msRest.Mapper = { serializedName: "foo", required: false, @@ -726,7 +817,7 @@ describe("msrest", function () { Serializer.serialize(mapper, undefined, "testobj"); }); - it("should not allow null when required: false and nullable: false", function () { + it("should not allow null when required: false and nullable: false", function() { const mapper: msRest.Mapper = { serializedName: "foo", required: false, @@ -737,10 +828,12 @@ describe("msrest", function () { }; // tslint:disable-next-line - (function () { Serializer.serialize(mapper, null, "testobj"); }).should.throw("testobj cannot be null."); + (function() { + Serializer.serialize(mapper, null, "testobj"); + }.should.throw("testobj cannot be null.")); }); - it("should allow null when required: false and nullable is undefined", function () { + it("should allow null when required: false and nullable is undefined", function() { const mapper: msRest.Mapper = { serializedName: "foo", required: false, @@ -752,7 +845,7 @@ describe("msrest", function () { Serializer.serialize(mapper, undefined, "testobj"); }); - it("should allow undefined when required: false and nullable: true", function () { + it("should allow undefined when required: false and nullable: true", function() { const mapper: msRest.Mapper = { serializedName: "foo", required: false, @@ -765,7 +858,7 @@ describe("msrest", function () { Serializer.serialize(mapper, undefined, "testobj"); }); - it("should allow undefined when required: false and nullable: false", function () { + it("should allow undefined when required: false and nullable: false", function() { const mapper: msRest.Mapper = { serializedName: "fooType", type: { @@ -787,7 +880,7 @@ describe("msrest", function () { Serializer.serialize(mapper, { length: undefined }, "testobj"); }); - it("should allow undefined when required: false and nullable is undefined", function () { + it("should allow undefined when required: false and nullable is undefined", function() { const mapper: msRest.Mapper = { serializedName: "foo", required: false, @@ -800,28 +893,40 @@ describe("msrest", function () { }); }); - describe("deserialize", function () { - it("should correctly deserialize a Date if the type is 'any'", function (done) { - const mapper: msRest.Mapper = { type: { name: "any" }, required: false, serializedName: "any" }; + describe("deserialize", function() { + it("should correctly deserialize a Date if the type is 'any'", function(done) { + const mapper: msRest.Mapper = { + type: { name: "any" }, + required: false, + serializedName: "any" + }; const d = new Date(); const deserializedObject = Serializer.deserialize(mapper, d, "anyResponseBody"); deserializedObject.should.equal(d); done(); }); - it("should correctly deserialize an array if the type is 'any'", function (done) { - const mapper: msRest.Mapper = { type: { name: "any" }, required: false, serializedName: "any" }; + it("should correctly deserialize an array if the type is 'any'", function(done) { + const mapper: msRest.Mapper = { + type: { name: "any" }, + required: false, + serializedName: "any" + }; const buf = [1, 2, 3]; const deserializedObject = Serializer.deserialize(mapper, buf, "anyBody"); deserializedObject.should.equal(buf); done(); }); - it("should correctly deserialize a uuid", function (done) { - const mapper: msRest.Mapper = { type: { name: "Uuid" }, required: false, serializedName: "Uuid" }; + it("should correctly deserialize a uuid", function(done) { + const mapper: msRest.Mapper = { + type: { name: "Uuid" }, + required: false, + serializedName: "Uuid" + }; const serializedObject = Serializer.deserialize(mapper, valid_uuid, "uuidBody"); serializedObject.should.equal(valid_uuid); done(); }); - it("should correctly deserialize a composite type", function (done) { + it("should correctly deserialize a composite type", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.Product; const responseBody = { @@ -840,13 +945,13 @@ describe("msrest", function () { invDate: "2015-12-25", invProducts: [ { - "Product1": { + Product1: { id: 101, name: "TestProduct" } }, { - "Product2": { + Product2: { id: 104, name: "TestProduct1" } @@ -874,10 +979,16 @@ describe("msrest", function () { } ] }; - const deserializedProduct = client.serializer.deserialize(mapper, responseBody, "responseBody"); + const deserializedProduct = client.serializer.deserialize( + mapper, + responseBody, + "responseBody" + ); for (const prop in deserializedProduct) { if (prop === "provisioningState") { - deserializedProduct.provisioningState.should.equal(responseBody.properties.provisioningState); + deserializedProduct.provisioningState.should.equal( + responseBody.properties.provisioningState + ); } else if (prop === "id") { deserializedProduct[prop].should.equal(responseBody.id); } else if (prop === "name") { @@ -885,17 +996,25 @@ describe("msrest", function () { } else if (prop === "tags") { JSON.stringify(deserializedProduct[prop]).should.equal(JSON.stringify(responseBody.tags)); } else if (prop === "dispatchTime") { - JSON.stringify(deserializedProduct[prop]).should.equal(JSON.stringify(responseBody.dispatchTime)); + JSON.stringify(deserializedProduct[prop]).should.equal( + JSON.stringify(responseBody.dispatchTime) + ); } else if (prop === "invoiceInfo") { - (JSON.stringify(deserializedProduct[prop]).length - JSON.stringify(responseBody.invoiceInfo).length).should.equal(10); + ( + JSON.stringify(deserializedProduct[prop]).length - + JSON.stringify(responseBody.invoiceInfo).length + ).should.equal(10); } else if (prop === "subProducts") { - (JSON.stringify(deserializedProduct[prop]).length - JSON.stringify(responseBody.subProducts).length).should.equal(20); + ( + JSON.stringify(deserializedProduct[prop]).length - + JSON.stringify(responseBody.subProducts).length + ).should.equal(20); } } done(); }); - it("should correctly deserialize a pageable type without nextLink", function (done) { + it("should correctly deserialize a pageable type without nextLink", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.ProductListResult; const responseBody = { @@ -916,8 +1035,12 @@ describe("msrest", function () { } ] }; - const deserializedProduct = client.serializer.deserialize(mapper, responseBody, "responseBody"); - (Array.isArray(deserializedProduct)).should.be.true; + const deserializedProduct = client.serializer.deserialize( + mapper, + responseBody, + "responseBody" + ); + Array.isArray(deserializedProduct).should.be.true; deserializedProduct.length.should.equal(2); for (let i = 0; i < deserializedProduct.length; i++) { if (i === 0) { @@ -933,7 +1056,7 @@ describe("msrest", function () { done(); }); - it("should correctly deserialize a pageable type with nextLink", function (done) { + it("should correctly deserialize a pageable type with nextLink", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.ProductListResultNextLink; const responseBody = { @@ -955,8 +1078,12 @@ describe("msrest", function () { ], nextLink: "https://helloworld.com" }; - const deserializedProduct = client.serializer.deserialize(mapper, responseBody, "responseBody"); - (Array.isArray(deserializedProduct)).should.be.true; + const deserializedProduct = client.serializer.deserialize( + mapper, + responseBody, + "responseBody" + ); + Array.isArray(deserializedProduct).should.be.true; deserializedProduct.length.should.equal(2); deserializedProduct.nextLink.should.equal("https://helloworld.com"); for (let i = 0; i < deserializedProduct.length; i++) { @@ -973,35 +1100,39 @@ describe("msrest", function () { done(); }); - it("should correctly deserialize object version of polymorphic discriminator", function (done) { + it("should correctly deserialize object version of polymorphic discriminator", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.Fish; const responseBody = { "fish.type": "sawshark", - "age": 22, - "birthday": new Date("2012-01-05T01:00:00Z").toISOString(), - "species": "king", - "length": 1.0, - "picture": "/////g==", - "siblings": [ + age: 22, + birthday: new Date("2012-01-05T01:00:00Z").toISOString(), + species: "king", + length: 1.0, + picture: "/////g==", + siblings: [ { "fish.type": "shark", - "age": 6, - "birthday": new Date("2012-01-05T01:00:00Z"), - "length": 20.0, - "species": "predator" + age: 6, + birthday: new Date("2012-01-05T01:00:00Z"), + length: 20.0, + species: "predator" }, { "fish.type": "sawshark", - "age": 105, - "birthday": new Date("1900-01-05T01:00:00Z").toISOString(), - "length": 10.0, - "picture": "/////g==", - "species": "dangerous" + age: 105, + birthday: new Date("1900-01-05T01:00:00Z").toISOString(), + length: 10.0, + picture: "/////g==", + species: "dangerous" } ] }; - const deserializedSawshark = client.serializer.deserialize(mapper, responseBody, "responseBody"); + const deserializedSawshark = client.serializer.deserialize( + mapper, + responseBody, + "responseBody" + ); deserializedSawshark.age.should.equal(22); deserializedSawshark.fishtype.should.equal("sawshark"); @@ -1015,14 +1146,18 @@ describe("msrest", function () { deserializedSawshark.siblings.length.should.equal(2); deserializedSawshark.siblings[0].fishtype.should.equal("shark"); deserializedSawshark.siblings[0].age.should.equal(6); - deserializedSawshark.siblings[0].birthday.toISOString().should.equal("2012-01-05T01:00:00.000Z"); + deserializedSawshark.siblings[0].birthday + .toISOString() + .should.equal("2012-01-05T01:00:00.000Z"); deserializedSawshark.siblings[1].fishtype.should.equal("sawshark"); deserializedSawshark.siblings[1].age.should.equal(105); - deserializedSawshark.siblings[1].birthday.toISOString().should.equal("1900-01-05T01:00:00.000Z"); + deserializedSawshark.siblings[1].birthday + .toISOString() + .should.equal("1900-01-05T01:00:00.000Z"); done(); }); - it("should correctly deserialize an array of array of object types", function (done) { + it("should correctly deserialize an array of array of object types", function(done) { const mapper: msRest.Mapper = { serializedName: "arrayObj", required: true, @@ -1048,36 +1183,40 @@ describe("msrest", function () { done(); }); - it("should correctly deserialize without failing when encountering unrecognized discriminator", function (done) { + it("should correctly deserialize without failing when encountering unrecognized discriminator", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.Fish; const responseBody = { "fish.type": "sawshark", - "age": 22, - "birthday": new Date("2012-01-05T01:00:00Z").toISOString(), - "species": "king", - "length": 1.0, - "picture": "/////g==", - "siblings": [ + age: 22, + birthday: new Date("2012-01-05T01:00:00Z").toISOString(), + species: "king", + length: 1.0, + picture: "/////g==", + siblings: [ { "fish.type": "mutatedshark", - "age": 105, - "birthday": new Date("1900-01-05T01:00:00Z").toISOString(), - "length": 10.0, - "picture": "/////g==", - "species": "dangerous", - "siblings": [ + age: 105, + birthday: new Date("1900-01-05T01:00:00Z").toISOString(), + length: 10.0, + picture: "/////g==", + species: "dangerous", + siblings: [ { "fish.type": "mutatedshark", - "age": 6, - "length": 20.0, - "species": "predator" + age: 6, + length: 20.0, + species: "predator" } ] } ] }; - const deserializedSawshark = client.serializer.deserialize(mapper, responseBody, "responseBody"); + const deserializedSawshark = client.serializer.deserialize( + mapper, + responseBody, + "responseBody" + ); deserializedSawshark.siblings.length.should.equal(1); deserializedSawshark.siblings[0].fishtype.should.equal("mutatedshark"); deserializedSawshark.siblings[0].species.should.equal("dangerous"); @@ -1090,7 +1229,7 @@ describe("msrest", function () { done(); }); - it("should correctly deserialize additionalProperties when the mapper knows that additional properties are allowed", function (done) { + it("should correctly deserialize additionalProperties when the mapper knows that additional properties are allowed", function(done) { const responseBody = { id: 5, name: "Funny", @@ -1125,35 +1264,39 @@ describe("msrest", function () { done(); }); - it("should correctly deserialize without failing when encountering no discriminator", function (done) { + it("should correctly deserialize without failing when encountering no discriminator", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.Fish; const responseBody = { - "age": 22, - "birthday": new Date("2012-01-05T01:00:00Z").toISOString(), - "species": "king", - "length": 1.0, - "picture": Buffer.from([255, 255, 255, 255, 254]).toString(), - "siblings": [ + age: 22, + birthday: new Date("2012-01-05T01:00:00Z").toISOString(), + species: "king", + length: 1.0, + picture: Buffer.from([255, 255, 255, 255, 254]).toString(), + siblings: [ { "fish.type": "mutatedshark", - "age": 105, - "birthday": new Date("1900-01-05T01:00:00Z").toISOString(), - "length": 10.0, - "picture": Buffer.from([255, 255, 255, 255, 254]).toString(), - "species": "dangerous", - "siblings": [ + age: 105, + birthday: new Date("1900-01-05T01:00:00Z").toISOString(), + length: 10.0, + picture: Buffer.from([255, 255, 255, 255, 254]).toString(), + species: "dangerous", + siblings: [ { "fish.type": "mutatedshark", - "age": 6, - "length": 20.0, - "species": "predator" + age: 6, + length: 20.0, + species: "predator" } ] } ] }; - const deserializedSawshark = client.serializer.deserialize(mapper, responseBody, "responseBody"); + const deserializedSawshark = client.serializer.deserialize( + mapper, + responseBody, + "responseBody" + ); deserializedSawshark.fishtype.should.equal("Fish"); deserializedSawshark.siblings.length.should.equal(1); deserializedSawshark.siblings[0].fishtype.should.equal("mutatedshark"); @@ -1166,30 +1309,30 @@ describe("msrest", function () { done(); }); - it("should correctly serialize without failing when encountering no discriminator", function (done) { + it("should correctly serialize without failing when encountering no discriminator", function(done) { const client = new TestClient("http://localhost:9090"); const mapper = Mappers.SawShark; const sawshark = { - "age": 22, - "birthday": new Date("2012-01-05T01:00:00Z"), - "species": "king", - "length": 1.0, - "picture": Buffer.from([255, 255, 255, 255, 254]), - "siblings": [ + age: 22, + birthday: new Date("2012-01-05T01:00:00Z"), + species: "king", + length: 1.0, + picture: Buffer.from([255, 255, 255, 255, 254]), + siblings: [ { - "fishtype": "shark", - "age": 6, - "birthday": new Date("2012-01-05T01:00:00Z"), - "length": 20.0, - "species": "predator" + fishtype: "shark", + age: 6, + birthday: new Date("2012-01-05T01:00:00Z"), + length: 20.0, + species: "predator" }, { - "fishtype": "sawshark", - "age": 105, - "birthday": new Date("1900-01-05T01:00:00Z"), - "length": 10.0, - "picture": Buffer.from([255, 255, 255, 255, 254]), - "species": "dangerous" + fishtype: "sawshark", + age: 105, + birthday: new Date("1900-01-05T01:00:00Z"), + length: 10.0, + picture: Buffer.from([255, 255, 255, 255, 254]), + species: "dangerous" } ] }; @@ -1199,16 +1342,20 @@ describe("msrest", function () { serializedSawshark.siblings.length.should.equal(2); serializedSawshark.siblings[0]["fish.type"].should.equal("shark"); serializedSawshark.siblings[0].age.should.equal(6); - serializedSawshark.siblings[0].birthday.should.equal(new Date("2012-01-05T01:00:00Z").toISOString()); + serializedSawshark.siblings[0].birthday.should.equal( + new Date("2012-01-05T01:00:00Z").toISOString() + ); serializedSawshark.siblings[1]["fish.type"].should.equal("sawshark"); serializedSawshark.siblings[1].age.should.equal(105); - serializedSawshark.siblings[1].birthday.should.equal(new Date("1900-01-05T01:00:00Z").toISOString()); + serializedSawshark.siblings[1].birthday.should.equal( + new Date("1900-01-05T01:00:00Z").toISOString() + ); serializedSawshark.siblings[1].picture.should.equal("//////4="); serializedSawshark.picture.should.equal("//////4="); done(); }); - it("should deserialize headerCollectionPrefix", function () { + it("should deserialize headerCollectionPrefix", function() { const mapper: msRest.CompositeMapper = { serializedName: "something", type: { @@ -1241,13 +1388,13 @@ describe("msrest", function () { const rawHeaders = { "foo-bar-alpha": "hello", "foo-bar-beta": "world", - "unrelated": "42" + unrelated: "42" }; const expected = { metadata: { - "alpha": "hello", - "beta": "world" + alpha: "hello", + beta: "world" }, unrelated: 42 }; @@ -1256,7 +1403,7 @@ describe("msrest", function () { }); describe("composite type", () => { - it("should be deserialized properly when polymorphicDiscriminator specified", function () { + it("should be deserialized properly when polymorphicDiscriminator specified", function() { const fish: msRest.CompositeMapper = { serializedName: "Fish", type: { @@ -1302,21 +1449,25 @@ describe("msrest", function () { Fish: fish, Shark: shark, discriminators: { - "Fish": fish, + Fish: fish, "Fish.shark": shark } }; const serializer = new msRest.Serializer(mappers); - const result = serializer.deserialize(fish, { - fishtype: "shark", - age: 10 - }, ""); + const result = serializer.deserialize( + fish, + { + fishtype: "shark", + age: 10 + }, + "" + ); assert.strictEqual("shark", result.fishtype); assert.strictEqual(10, result.age); }); - it("should be deserialized properly when polymorphicDiscriminator specified in nested property", function () { + it("should be deserialized properly when polymorphicDiscriminator specified in nested property", function() { const fish: msRest.CompositeMapper = { serializedName: "Fish", type: { @@ -1375,16 +1526,20 @@ describe("msrest", function () { Fish: fish, Shark: shark, discriminators: { - "Fish": fish, + Fish: fish, "Fish.shark": shark } }; const serializer = new msRest.Serializer(mappers); - const result = serializer.deserialize(fish, { - fishtype: "shark", - age: 10, - sibling: { fishtype: "shark", age: 15 } - }, ""); + const result = serializer.deserialize( + fish, + { + fishtype: "shark", + age: 10, + sibling: { fishtype: "shark", age: 15 } + }, + "" + ); assert.strictEqual("shark", result.fishtype); assert.strictEqual(10, result.age); @@ -1392,7 +1547,7 @@ describe("msrest", function () { assert.strictEqual(15, result.sibling.age); }); - it("should be deserialized properly when polymorphicDiscriminator specified in the parent", function () { + it("should be deserialized properly when polymorphicDiscriminator specified in the parent", function() { const fish: msRest.CompositeMapper = { serializedName: "Fish", type: { @@ -1447,16 +1602,20 @@ describe("msrest", function () { Fish: fish, Shark: shark, discriminators: { - "Fish": fish, + Fish: fish, "Fish.shark": shark } }; const serializer = new msRest.Serializer(mappers); - const result = serializer.deserialize(fish, { - fishtype: "shark", - age: 10, - sibling: { fishtype: "shark", age: 15 } - }, ""); + const result = serializer.deserialize( + fish, + { + fishtype: "shark", + age: 10, + sibling: { fishtype: "shark", age: 15 } + }, + "" + ); assert.strictEqual("shark", result.fishtype); assert.strictEqual(10, result.age); @@ -1464,7 +1623,7 @@ describe("msrest", function () { assert.strictEqual(15, result.sibling.age); }); - it("should be deserialized properly when responseBody is an empty string", function () { + it("should be deserialized properly when responseBody is an empty string", function() { const fish: msRest.CompositeMapper = { serializedName: "Fish", type: { @@ -1630,47 +1789,52 @@ describe("msrest", function () { const mappers = { discriminators: { - "Fish": Fish, + Fish: Fish, "Fish.salmon": Salmon, "Fish.shark": Shark, "Fish.sawshark": Sawshark, - "Fish.goblin": Goblinshark, + "Fish.goblin": Goblinshark }, Fish, Salmon, Shark, Sawshark, - Goblinshark, + Goblinshark }; - it("should be deserialized with child properties", function () { + it("should be deserialized with child properties", function() { const body = { - "fishtype": "salmon", - "location": "alaska", - "iswild": true, - "species": "king", - "length": 1, - "siblings": [{ - "fishtype": "shark", - "age": 6, - "birthday": "2012-01-05T01:00:00Z", - "length": 20, - "species": "predator" - }, { - "fishtype": "sawshark", - "age": 105, - "birthday": "1900-01-05T01:00:00Z", - "length": 10, - "picture": "//////4=", - "species": "dangerous" - }, { - "fishtype": "goblin", - "age": 1, "birthday": "2015-08-08T00:00:00Z", - "length": 30, - "species": "scary", - "jawsize": 5, - "color": "pinkish-gray" - }] + fishtype: "salmon", + location: "alaska", + iswild: true, + species: "king", + length: 1, + siblings: [ + { + fishtype: "shark", + age: 6, + birthday: "2012-01-05T01:00:00Z", + length: 20, + species: "predator" + }, + { + fishtype: "sawshark", + age: 105, + birthday: "1900-01-05T01:00:00Z", + length: 10, + picture: "//////4=", + species: "dangerous" + }, + { + fishtype: "goblin", + age: 1, + birthday: "2015-08-08T00:00:00Z", + length: 30, + species: "scary", + jawsize: 5, + color: "pinkish-gray" + } + ] }; const serializer = new msRest.Serializer(mappers); @@ -1681,37 +1845,37 @@ describe("msrest", function () { assert.equal(result.siblings[2].jawsize, 5); }); - it("should be serialized with child properties", function () { + it("should be serialized with child properties", function() { const body = { - "fishtype": "salmon", - "location": "alaska", - "iswild": true, - "species": "king", - "length": 1.0, - "siblings": [ + fishtype: "salmon", + location: "alaska", + iswild: true, + species: "king", + length: 1.0, + siblings: [ { - "fishtype": "shark", - "age": 6, - "birthday": new Date("2012-01-05T01:00:00Z"), - "length": 20.0, - "species": "predator" + fishtype: "shark", + age: 6, + birthday: new Date("2012-01-05T01:00:00Z"), + length: 20.0, + species: "predator" }, { - "fishtype": "sawshark", - "age": 105, - "birthday": new Date("1900-01-05T01:00:00Z"), - "length": 10.0, - "picture": new Uint8Array([255, 255, 255, 255, 254]), - "species": "dangerous" + fishtype: "sawshark", + age: 105, + birthday: new Date("1900-01-05T01:00:00Z"), + length: 10.0, + picture: new Uint8Array([255, 255, 255, 255, 254]), + species: "dangerous" }, { - "fishtype": "goblin", - "color": "pinkish-gray", - "age": 1, - "length": 30, - "species": "scary", - "birthday": new Date("2015-08-08T00:00:00Z"), - "jawsize": 5 + fishtype: "goblin", + color: "pinkish-gray", + age: 1, + length: 30, + species: "scary", + birthday: new Date("2015-08-08T00:00:00Z"), + jawsize: 5 } ] }; diff --git a/sdk/core/core-http/test/serviceClientTests.ts b/sdk/core/core-http/test/serviceClientTests.ts index 81df46fe2ad4..997ef3ee60d9 100644 --- a/sdk/core/core-http/test/serviceClientTests.ts +++ b/sdk/core/core-http/test/serviceClientTests.ts @@ -5,23 +5,33 @@ import { assert } from "chai"; import { HttpClient } from "../lib/httpClient"; import { QueryCollectionFormat } from "../lib/queryCollectionFormat"; import { DictionaryMapper, MapperType, Serializer, Mapper } from "../lib/serializer"; -import { serializeRequestBody, ServiceClient, getOperationArgumentValueFromParameterPath } from "../lib/serviceClient"; +import { + serializeRequestBody, + ServiceClient, + getOperationArgumentValueFromParameterPath +} from "../lib/serviceClient"; import { WebResource } from "../lib/webResource"; -import { OperationArguments, HttpHeaders, deserializationPolicy, RestResponse, isNode } from "../lib/coreHttp"; +import { + OperationArguments, + HttpHeaders, + deserializationPolicy, + RestResponse, + isNode +} from "../lib/coreHttp"; import { ParameterPath } from "../lib/operationParameter"; -describe("ServiceClient", function () { - it("should serialize headerCollectionPrefix", async function () { +describe("ServiceClient", function() { + it("should serialize headerCollectionPrefix", async function() { const expected = { "foo-bar-alpha": "hello", "foo-bar-beta": "world", - "unrelated": "42" + unrelated: "42" }; let request: WebResource; const client = new ServiceClient(undefined, { httpClient: { - sendRequest: req => { + sendRequest: (req) => { request = req; return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); } @@ -32,8 +42,8 @@ describe("ServiceClient", function () { await client.sendOperationRequest( { metadata: { - "alpha": "hello", - "beta": "world" + alpha: "hello", + beta: "world" }, unrelated: 42 }, @@ -41,43 +51,47 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", serializer: new Serializer(), - headerParameters: [{ - parameterPath: "metadata", - mapper: { - serializedName: "metadata", - type: { - name: "Dictionary", - value: { - type: { - name: "String" + headerParameters: [ + { + parameterPath: "metadata", + mapper: { + serializedName: "metadata", + type: { + name: "Dictionary", + value: { + type: { + name: "String" + } } + }, + headerCollectionPrefix: "foo-bar-" + } as DictionaryMapper + }, + { + parameterPath: "unrelated", + mapper: { + serializedName: "unrelated", + type: { + name: "Number" } - }, - headerCollectionPrefix: "foo-bar-" - } as DictionaryMapper - }, { - parameterPath: "unrelated", - mapper: { - serializedName: "unrelated", - type: { - name: "Number" } } - }], + ], responses: { 200: {} } - }); + } + ); assert(request!); assert.deepEqual(request!.headers.toJson(), expected); }); - it("responses should not show the _response property when serializing", async function () { + it("responses should not show the _response property when serializing", async function() { let request: WebResource; const client = new ServiceClient(undefined, { httpClient: { - sendRequest: req => { + sendRequest: (req) => { request = req; return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); } @@ -95,24 +109,25 @@ describe("ServiceClient", function () { responses: { 200: {} } - }); + } + ); assert(request!); assert.strictEqual(JSON.stringify(response), "{}"); }); - it("should serialize collection:multi query parameters", async function () { + it("should serialize collection:multi query parameters", async function() { const expected = "?q=1&q=2&q=3"; let request: WebResource; const client = new ServiceClient(undefined, { httpClient: { - sendRequest: req => { + sendRequest: (req) => { request = req; return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); - }, + } }, - requestPolicyFactories: () => [], + requestPolicyFactories: () => [] }); await client.sendOperationRequest( @@ -133,17 +148,17 @@ describe("ServiceClient", function () { name: "Sequence", element: { type: { - name: "Number", + name: "Number" }, - serializedName: "q", - }, - }, - }, - }, + serializedName: "q" + } + } + } + } ], responses: { - 200: {}, - }, + 200: {} + } } ); @@ -151,10 +166,10 @@ describe("ServiceClient", function () { assert(request!.url.endsWith(expected), `"${request!.url}" does not end with "${expected}"`); }); - it("should apply withCredentials to requests", async function () { + it("should apply withCredentials to requests", async function() { let request: WebResource; const httpClient: HttpClient = { - sendRequest: req => { + sendRequest: (req) => { request = req; return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); } @@ -171,7 +186,8 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", responses: { 200: {} } - }); + } + ); assert.strictEqual(request!.withCredentials, false); @@ -187,16 +203,22 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", responses: { 200: {} } - }); + } + ); assert.strictEqual(request!.withCredentials, true); }); - it("should deserialize response bodies", async function () { + it("should deserialize response bodies", async function() { let request: WebResource; const httpClient: HttpClient = { - sendRequest: req => { + sendRequest: (req) => { request = req; - return Promise.resolve({ request, status: 200, headers: new HttpHeaders(), bodyAsText: "[1,2,3]" }); + return Promise.resolve({ + request, + status: 200, + headers: new HttpHeaders(), + bodyAsText: "[1,2,3]" + }); } }; @@ -225,13 +247,14 @@ describe("ServiceClient", function () { } } } - }); + } + ); assert.strictEqual(res._response.status, 200); assert.deepStrictEqual(res.slice(), [1, 2, 3]); }); - it("should use userAgent header name value from options", async function () { + it("should use userAgent header name value from options", async function() { const httpClient: HttpClient = { sendRequest: (request: WebResource) => { return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); @@ -251,13 +274,14 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", responses: {} - }); + } + ); assert.strictEqual(response._response.status, 200); assert.strictEqual(response._response.request.headers.get("my-user-agent-key"), "blah blah"); }); - it("should use userAgent header name function from options", async function () { + it("should use userAgent header name function from options", async function() { const httpClient: HttpClient = { sendRequest: (request: WebResource) => { return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); @@ -277,13 +301,14 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", responses: {} - }); + } + ); assert.strictEqual(response._response.status, 200); assert.strictEqual(response._response.request.headers.get("my-user-agent-key-2"), "blah blah"); }); - it("should use userAgent string from options", async function () { + it("should use userAgent string from options", async function() { const httpClient: HttpClient = { sendRequest: (request: WebResource) => { return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); @@ -302,13 +327,17 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", responses: {} - }); + } + ); assert.strictEqual(response._response.status, 200); - assert.strictEqual(response._response.request.headers.get(isNode ? "user-agent" : "x-ms-command-name"), "blah blah"); + assert.strictEqual( + response._response.request.headers.get(isNode ? "user-agent" : "x-ms-command-name"), + "blah blah" + ); }); - it("should use userAgent function from options that appends to defaultUserAgent", async function () { + it("should use userAgent function from options that appends to defaultUserAgent", async function() { const httpClient: HttpClient = { sendRequest: (request: WebResource) => { return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); @@ -327,16 +356,19 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", responses: {} - }); + } + ); assert.strictEqual(response._response.status, 200); - const userAgentHeaderValue: string | undefined = response._response.request.headers.get(isNode ? "user-agent" : "x-ms-command-name"); + const userAgentHeaderValue: string | undefined = response._response.request.headers.get( + isNode ? "user-agent" : "x-ms-command-name" + ); assert(userAgentHeaderValue); assert(userAgentHeaderValue!.startsWith("core-http/")); assert(userAgentHeaderValue!.endsWith("/blah blah")); }); - it("should use userAgent function from options that ignores defaultUserAgent", async function () { + it("should use userAgent function from options that ignores defaultUserAgent", async function() { const httpClient: HttpClient = { sendRequest: (request: WebResource) => { return Promise.resolve({ request, status: 200, headers: new HttpHeaders() }); @@ -355,10 +387,14 @@ describe("ServiceClient", function () { httpMethod: "GET", baseUrl: "httpbin.org", responses: {} - }); + } + ); assert.strictEqual(response._response.status, 200); - assert.strictEqual(response._response.request.headers.get(isNode ? "user-agent" : "x-ms-command-name"), "blah blah 2"); + assert.strictEqual( + response._response.request.headers.get(isNode ? "user-agent" : "x-ms-command-name"), + "blah blah 2" + ); }); describe("serializeRequestBody()", () => { @@ -384,7 +420,8 @@ describe("ServiceClient", function () { }, responses: { 200: {} }, serializer: new Serializer() - }); + } + ); assert.strictEqual(httpRequest.body, `"body value"`); }); @@ -410,7 +447,8 @@ describe("ServiceClient", function () { }, responses: { 200: {} }, serializer: new Serializer() - }); + } + ); assert.strictEqual(httpRequest.body, `"SmF2YXNjcmlwdA=="`); }); @@ -436,7 +474,8 @@ describe("ServiceClient", function () { }, responses: { 200: {} }, serializer: new Serializer() - }); + } + ); assert.strictEqual(httpRequest.body, "body value"); }); @@ -463,10 +502,12 @@ describe("ServiceClient", function () { responses: { 200: {} }, serializer: new Serializer(), isXML: true - }); + } + ); assert.strictEqual( httpRequest.body, - `body value`); + `body value` + ); }); it("should serialize an XML ByteArray request body", () => { @@ -492,10 +533,12 @@ describe("ServiceClient", function () { responses: { 200: {} }, serializer: new Serializer(), isXML: true - }); + } + ); assert.strictEqual( httpRequest.body, - `SmF2YXNjcmlwdA==`); + `SmF2YXNjcmlwdA==` + ); }); it("should serialize an XML Stream request body", () => { @@ -521,7 +564,8 @@ describe("ServiceClient", function () { responses: { 200: {} }, serializer: new Serializer(), isXML: true - }); + } + ); assert.strictEqual(httpRequest.body, "body value"); }); }); @@ -537,14 +581,20 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, undefined); }); it("should return undefined when the parameter path is found in the operation arguments but is undefined and doesn't have a default value", () => { const serviceClient = new ServiceClient(); const operationArguments: OperationArguments = { - "myParameter": undefined + myParameter: undefined }; const parameterPath: ParameterPath = "myParameter"; const parameterMapper: Mapper = { @@ -553,7 +603,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, undefined); }); @@ -561,7 +617,7 @@ describe("ServiceClient", function () { const serviceClient = new ServiceClient(); const operationArguments: OperationArguments = { // tslint:disable-next-line:no-null-keyword - "myParameter": null + myParameter: null }; const parameterPath: ParameterPath = "myParameter"; const parameterMapper: Mapper = { @@ -570,7 +626,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); // tslint:disable-next-line:no-null-keyword assert.strictEqual(parameterValue, null); }); @@ -578,7 +640,7 @@ describe("ServiceClient", function () { it("should return the operation argument value when the parameter path is found in the operation arguments", () => { const serviceClient = new ServiceClient(); const operationArguments: OperationArguments = { - "myParameter": 20 + myParameter: 20 }; const parameterPath: ParameterPath = "myParameter"; const parameterMapper: Mapper = { @@ -587,15 +649,21 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 20); }); it("should return the options operation argument value when the parameter path is found in the optional operation arguments", () => { const serviceClient = new ServiceClient(); const operationArguments: OperationArguments = { - "options": { - "myParameter": 1 + options: { + myParameter: 1 } }; const parameterPath: ParameterPath = ["options", "myParameter"]; @@ -605,7 +673,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 1); }); @@ -620,7 +694,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 21); }); @@ -628,7 +708,7 @@ describe("ServiceClient", function () { const serviceClient = new ServiceClient(); (serviceClient as any)["myParameter"] = 21; const operationArguments: OperationArguments = { - "myParameter": 22 + myParameter: 22 }; const parameterPath: ParameterPath = "myParameter"; const parameterMapper: Mapper = { @@ -637,7 +717,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 22); }); @@ -653,7 +739,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 1); }); @@ -661,9 +753,9 @@ describe("ServiceClient", function () { const serviceClient = new ServiceClient(); (serviceClient as any)["myParameter"] = 1; const operationArguments: OperationArguments = { - "myParameter": 2, - "options": { - "myParameter": 3 + myParameter: 2, + options: { + myParameter: 3 } }; const parameterPath: ParameterPath = "myParameter"; @@ -675,7 +767,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 4); }); @@ -690,7 +788,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, undefined); }); @@ -706,15 +810,21 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 21); }); it("should return the default value when the parameter path is partially found in the operation arguments, the parameter is required, and it has a default value", () => { const serviceClient = new ServiceClient(); const operationArguments: OperationArguments = { - "myParameter": { - "differentProperty": "hello" + myParameter: { + differentProperty: "hello" } }; const parameterPath: ParameterPath = ["myParameter", "myProperty"]; @@ -726,15 +836,21 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 21); }); it("should return undefined when the parameter path is partially found in the operation arguments, the parameter is optional, and it has a default value", () => { const serviceClient = new ServiceClient(); const operationArguments: OperationArguments = { - "myParameter": { - "differentProperty": "hello" + myParameter: { + differentProperty: "hello" } }; const parameterPath: ParameterPath = ["myParameter", "myProperty"]; @@ -745,7 +861,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, undefined); }); @@ -760,7 +882,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, 21); }); @@ -775,7 +903,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); assert.strictEqual(parameterValue, undefined); }); @@ -783,7 +917,7 @@ describe("ServiceClient", function () { const serviceClient = new ServiceClient(); const operationArguments: OperationArguments = { // tslint:disable-next-line:no-null-keyword - "myParameter": null + myParameter: null }; const parameterPath: ParameterPath = "myParameter"; const parameterMapper: Mapper = { @@ -793,7 +927,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); // tslint:disable-next-line:no-null-keyword assert.strictEqual(parameterValue, null); }); @@ -810,7 +950,13 @@ describe("ServiceClient", function () { name: MapperType.Number } }; - const parameterValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, new Serializer()); + const parameterValue: any = getOperationArgumentValueFromParameterPath( + serviceClient, + operationArguments, + parameterPath, + parameterMapper, + new Serializer() + ); // tslint:disable-next-line:no-null-keyword assert.strictEqual(parameterValue, 5); }); diff --git a/sdk/core/core-http/test/urlTests.ts b/sdk/core/core-http/test/urlTests.ts index e9e6a72b52e4..4432cf0e93f4 100644 --- a/sdk/core/core-http/test/urlTests.ts +++ b/sdk/core/core-http/test/urlTests.ts @@ -257,7 +257,10 @@ describe("URLBuilder", () => { assert.strictEqual(urlBuilder.getScheme(), "https"); assert.strictEqual(urlBuilder.getHost(), "www.example.com"); assert.strictEqual(urlBuilder.getPath(), "mypath"); - assert.strictEqual(urlBuilder.toString(), "https://www.example.com/mypath?thing=stuff&otherthing=otherstuff"); + assert.strictEqual( + urlBuilder.toString(), + "https://www.example.com/mypath?thing=stuff&otherthing=otherstuff" + ); }); it(`to "https" and setHost() to "www.example.com" and setPath() to "http://www.othersite.com/mypath?thing=stuff" and setQueryParameter() to "otherthing=otherstuff"`, () => { @@ -268,7 +271,10 @@ describe("URLBuilder", () => { urlBuilder.setQueryParameter("otherthing", "otherstuff"); assert.strictEqual(urlBuilder.getScheme(), "http"); assert.strictEqual(urlBuilder.getPath(), "/mypath"); - assert.strictEqual(urlBuilder.toString(), "http://www.othersite.com/mypath?thing=stuff&otherthing=otherstuff"); + assert.strictEqual( + urlBuilder.toString(), + "http://www.othersite.com/mypath?thing=stuff&otherthing=otherstuff" + ); }); }); @@ -805,23 +811,38 @@ describe("URLBuilder", () => { }); it(`with "ftp://www.bing.com:8080"`, () => { - assert.strictEqual(URLBuilder.parse("ftp://www.bing.com:8080").toString(), "ftp://www.bing.com:8080"); + assert.strictEqual( + URLBuilder.parse("ftp://www.bing.com:8080").toString(), + "ftp://www.bing.com:8080" + ); }); it(`with "www.bing.com/my/path"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com/my/path").toString(), "www.bing.com/my/path"); + assert.strictEqual( + URLBuilder.parse("www.bing.com/my/path").toString(), + "www.bing.com/my/path" + ); }); it(`with "ftp://www.bing.com/my/path"`, () => { - assert.strictEqual(URLBuilder.parse("ftp://www.bing.com/my/path").toString(), "ftp://www.bing.com/my/path"); + assert.strictEqual( + URLBuilder.parse("ftp://www.bing.com/my/path").toString(), + "ftp://www.bing.com/my/path" + ); }); it(`with "www.bing.com:1234/my/path"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com:1234/my/path").toString(), "www.bing.com:1234/my/path"); + assert.strictEqual( + URLBuilder.parse("www.bing.com:1234/my/path").toString(), + "www.bing.com:1234/my/path" + ); }); it(`with "ftp://www.bing.com:1234/my/path"`, () => { - assert.strictEqual(URLBuilder.parse("ftp://www.bing.com:1234/my/path").toString(), "ftp://www.bing.com:1234/my/path"); + assert.strictEqual( + URLBuilder.parse("ftp://www.bing.com:1234/my/path").toString(), + "ftp://www.bing.com:1234/my/path" + ); }); it(`with "www.bing.com?a=1"`, () => { @@ -829,67 +850,115 @@ describe("URLBuilder", () => { }); it(`with "https://www.bing.com?a=1"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com?a=1").toString(), "https://www.bing.com?a=1"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com?a=1").toString(), + "https://www.bing.com?a=1" + ); }); it(`with "www.bing.com:123?a=1"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com:123?a=1").toString(), "www.bing.com:123?a=1"); + assert.strictEqual( + URLBuilder.parse("www.bing.com:123?a=1").toString(), + "www.bing.com:123?a=1" + ); }); it(`with "https://www.bing.com:987?a=1"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com:987?a=1").toString(), "https://www.bing.com:987?a=1"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com:987?a=1").toString(), + "https://www.bing.com:987?a=1" + ); }); it(`with "www.bing.com/folder/index.html?a=1"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com/folder/index.html?a=1").toString(), "www.bing.com/folder/index.html?a=1"); + assert.strictEqual( + URLBuilder.parse("www.bing.com/folder/index.html?a=1").toString(), + "www.bing.com/folder/index.html?a=1" + ); }); it(`with "https://www.bing.com/image.gif?a=1"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com/image.gif?a=1").toString(), "https://www.bing.com/image.gif?a=1"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com/image.gif?a=1").toString(), + "https://www.bing.com/image.gif?a=1" + ); }); it(`with "www.bing.com:123/index.html?a=1"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com:123/index.html?a=1").toString(), "www.bing.com:123/index.html?a=1"); + assert.strictEqual( + URLBuilder.parse("www.bing.com:123/index.html?a=1").toString(), + "www.bing.com:123/index.html?a=1" + ); }); it(`with "https://www.bing.com:987/my/path/again?a=1"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com:987/my/path/again?a=1").toString(), "https://www.bing.com:987/my/path/again?a=1"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com:987/my/path/again?a=1").toString(), + "https://www.bing.com:987/my/path/again?a=1" + ); }); it(`with "www.bing.com?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com?a=1&b=2").toString(), "www.bing.com?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("www.bing.com?a=1&b=2").toString(), + "www.bing.com?a=1&b=2" + ); }); it(`with "https://www.bing.com?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com?a=1&b=2").toString(), "https://www.bing.com?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com?a=1&b=2").toString(), + "https://www.bing.com?a=1&b=2" + ); }); it(`with "www.bing.com:123?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com:123?a=1&b=2").toString(), "www.bing.com:123?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("www.bing.com:123?a=1&b=2").toString(), + "www.bing.com:123?a=1&b=2" + ); }); it(`with "https://www.bing.com:987?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com:987?a=1&b=2").toString(), "https://www.bing.com:987?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com:987?a=1&b=2").toString(), + "https://www.bing.com:987?a=1&b=2" + ); }); it(`with "www.bing.com/folder/index.html?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com/folder/index.html?a=1&b=2").toString(), "www.bing.com/folder/index.html?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("www.bing.com/folder/index.html?a=1&b=2").toString(), + "www.bing.com/folder/index.html?a=1&b=2" + ); }); it(`with "https://www.bing.com/image.gif?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com/image.gif?a=1&b=2").toString(), "https://www.bing.com/image.gif?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com/image.gif?a=1&b=2").toString(), + "https://www.bing.com/image.gif?a=1&b=2" + ); }); it(`with "www.bing.com:123/index.html?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("www.bing.com:123/index.html?a=1&b=2").toString(), "www.bing.com:123/index.html?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("www.bing.com:123/index.html?a=1&b=2").toString(), + "www.bing.com:123/index.html?a=1&b=2" + ); }); it(`with "https://www.bing.com:987/my/path/again?a=1&b=2"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com:987/my/path/again?a=1&b=2").toString(), "https://www.bing.com:987/my/path/again?a=1&b=2"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com:987/my/path/again?a=1&b=2").toString(), + "https://www.bing.com:987/my/path/again?a=1&b=2" + ); }); it(`with "https://www.bing.com/my:/path"`, () => { - assert.strictEqual(URLBuilder.parse("https://www.bing.com/my:/path").toString(), "https://www.bing.com/my:/path"); + assert.strictEqual( + URLBuilder.parse("https://www.bing.com/my:/path").toString(), + "https://www.bing.com/my:/path" + ); }); }); @@ -979,12 +1048,30 @@ describe("URLTokenizer", () => { const tokenizer = new URLTokenizer(text); if (expectedURLTokens) { for (let i = 0; i < expectedURLTokens.length; ++i) { - assert.strictEqual(tokenizer.next(), true, `Expected to find ${expectedURLTokens.length} URLTokens, but found ${i} instead.`); - assert.deepEqual(tokenizer.current(), expectedURLTokens[i], `Expected the ${i + 1} URLToken to be ${JSON.stringify(expectedURLTokens[i])}, but found ${JSON.stringify(tokenizer.current())} instead.`); + assert.strictEqual( + tokenizer.next(), + true, + `Expected to find ${expectedURLTokens.length} URLTokens, but found ${i} instead.` + ); + assert.deepEqual( + tokenizer.current(), + expectedURLTokens[i], + `Expected the ${i + 1} URLToken to be ${JSON.stringify( + expectedURLTokens[i] + )}, but found ${JSON.stringify(tokenizer.current())} instead.` + ); } } - assert.strictEqual(tokenizer.next(), false, `Only expected to find ${(expectedURLTokens ? expectedURLTokens.length : 0)} URL token(s).`); - assert.strictEqual(tokenizer.current(), undefined, `After reading all of the URLTokens, expected the current value to be undefined.`); + assert.strictEqual( + tokenizer.next(), + false, + `Only expected to find ${expectedURLTokens ? expectedURLTokens.length : 0} URL token(s).` + ); + assert.strictEqual( + tokenizer.current(), + undefined, + `After reading all of the URLTokens, expected the current value to be undefined.` + ); } it(`with ""`, () => { @@ -992,31 +1079,19 @@ describe("URLTokenizer", () => { }); it(`with "http"`, () => { - nextTest("http", [ - URLToken.host("http") - ]); + nextTest("http", [URLToken.host("http")]); }); it(`with "http:"`, () => { - nextTest("http:", [ - URLToken.host("http"), - URLToken.port("") - ]); + nextTest("http:", [URLToken.host("http"), URLToken.port("")]); }); it(`with "http:/"`, () => { - nextTest("http:/", [ - URLToken.host("http"), - URLToken.port(""), - URLToken.path("/") - ]); + nextTest("http:/", [URLToken.host("http"), URLToken.port(""), URLToken.path("/")]); }); it(`with "http://"`, () => { - nextTest("http://", [ - URLToken.scheme("http"), - URLToken.host("") - ]); + nextTest("http://", [URLToken.scheme("http"), URLToken.host("")]); }); it(`with "https://www.example.com"`, () => { @@ -1138,31 +1213,19 @@ describe("URLTokenizer", () => { }); it(`with "www.test.com/"`, () => { - nextTest("www.test.com/", [ - URLToken.host("www.test.com"), - URLToken.path("/") - ]); + nextTest("www.test.com/", [URLToken.host("www.test.com"), URLToken.path("/")]); }); it(`with "www.test.com?"`, () => { - nextTest("www.test.com?", [ - URLToken.host("www.test.com"), - URLToken.query("") - ]); + nextTest("www.test.com?", [URLToken.host("www.test.com"), URLToken.query("")]); }); it(`with "folder/index.html"`, () => { - nextTest("folder/index.html", [ - URLToken.host("folder"), - URLToken.path("/index.html") - ]); + nextTest("folder/index.html", [URLToken.host("folder"), URLToken.path("/index.html")]); }); it(`with "/folder/index.html"`, () => { - nextTest("/folder/index.html", [ - URLToken.host(""), - URLToken.path("/folder/index.html") - ]); + nextTest("/folder/index.html", [URLToken.host(""), URLToken.path("/folder/index.html")]); }); }); }); diff --git a/sdk/core/core-http/test/xhrTests.browser.ts b/sdk/core/core-http/test/xhrTests.browser.ts index 8162db2217ac..ab6a310cd147 100644 --- a/sdk/core/core-http/test/xhrTests.browser.ts +++ b/sdk/core/core-http/test/xhrTests.browser.ts @@ -8,9 +8,7 @@ import { WebResource } from "../lib/webResource"; describe("XhrHttpClient", function() { it("parses headers", function() { const xhr = { - getAllResponseHeaders: () => - "Content-Length: 42\r\n" + - "value: hello\r\n" + getAllResponseHeaders: () => "Content-Length: 42\r\n" + "value: hello\r\n" } as XMLHttpRequest; const headers = parseHeaders(xhr); assert.strictEqual(headers.get("content-length"), "42"); @@ -20,8 +18,7 @@ describe("XhrHttpClient", function() { it("parses empty string headers", function() { const xhr = { getAllResponseHeaders: () => - "Content-Type: \r\n" + // preserve trailing whitespace in test case - "value:\r\n" + "Content-Type: \r\n" + "value:\r\n" // preserve trailing whitespace in test case } as XMLHttpRequest; const headers = parseHeaders(xhr); assert.strictEqual(headers.get("content-type"), ""); @@ -36,6 +33,8 @@ describe("XhrHttpClient", function() { }; const client = new XhrHttpClient(); - assert.throws(() => { client.sendRequest(request); }, Error); + assert.throws(() => { + client.sendRequest(request); + }, Error); }); }); diff --git a/sdk/core/core-http/test/xmlTests.ts b/sdk/core/core-http/test/xmlTests.ts index cbc0c4a3e730..200720fc74cc 100644 --- a/sdk/core/core-http/test/xmlTests.ts +++ b/sdk/core/core-http/test/xmlTests.ts @@ -5,109 +5,117 @@ import { parseXML } from "../lib/util/xml"; import { assert } from "chai"; import * as msAssert from "./msAssert"; -describe("XML serializer", function () { - describe("parseXML(string)", function () { - it("with undefined", async function () { +describe("XML serializer", function() { + describe("parseXML(string)", function() { + it("with undefined", async function() { const error: Error = await msAssert.throwsAsync(parseXML(undefined as any)); - assert.notStrictEqual(error.message.indexOf("Document is empty"), -1, `error.message ("${error.message}") should have contained "Document is empty"`); + assert.notStrictEqual( + error.message.indexOf("Document is empty"), + -1, + `error.message ("${error.message}") should have contained "Document is empty"` + ); }); - it("with null", async function () { + it("with null", async function() { // tslint:disable-next-line:no-null-keyword const error: Error = await msAssert.throwsAsync(parseXML(null as any)); - assert.notStrictEqual(error.message.indexOf("Document is empty"), -1, `error.message ("${error.message}") should have contained "Document is empty"`); + assert.notStrictEqual( + error.message.indexOf("Document is empty"), + -1, + `error.message ("${error.message}") should have contained "Document is empty"` + ); }); - it("with empty", async function () { + it("with empty", async function() { await msAssert.throwsAsync(parseXML("")); }); - it("with text", async function () { + it("with text", async function() { await msAssert.throwsAsync(parseXML("Hello World!")); }); - it("with empty element", async function () { + it("with empty element", async function() { const xml: any = await parseXML(""); assert.deepStrictEqual(xml, ``); }); - it("with empty element with attribute", async function () { + it("with empty element with attribute", async function() { const xml: any = await parseXML(``); assert.deepStrictEqual(xml, { - "$": { - "healthy": "true" + $: { + healthy: "true" } }); }); - it("with element", async function () { + it("with element", async function() { const xml: any = await parseXML(""); assert.deepStrictEqual(xml, ``); }); - it("with element with value", async function () { + it("with element with value", async function() { const xml: any = await parseXML("hurray"); assert.deepStrictEqual(xml, `hurray`); }); - it("with element with attribute", async function () { + it("with element with attribute", async function() { const xml: any = await parseXML(``); assert.deepStrictEqual(xml, { - "$": { - "healthy": "true" + $: { + healthy: "true" } }); }); - it("with element with attribute and value", async function () { + it("with element with attribute and value", async function() { const xml: any = await parseXML(`yum`); assert.deepStrictEqual(xml, { - "$": { - "healthy": "true" + $: { + healthy: "true" }, - "_": "yum" + _: "yum" }); }); - it("with element with child empty element", async function () { + it("with element with child empty element", async function() { const xml: any = await parseXML(``); assert.deepStrictEqual(xml, { - "apples": `` + apples: `` }); }); - it("with element with child empty element with attribute", async function () { + it("with element with child empty element with attribute", async function() { const xml: any = await parseXML(``); assert.deepStrictEqual(xml, { - "apples": { - "$": { - "tasty": "true" + apples: { + $: { + tasty: "true" } } }); }); - it("with element with child element with value", async function () { + it("with element with child element with value", async function() { const xml: any = await parseXML(`yum`); assert.deepStrictEqual(xml, { - "apples": "yum" + apples: "yum" }); }); - it("with element with child element with attribute and value", async function () { + it("with element with child element with attribute and value", async function() { const xml: any = await parseXML(`yum`); assert.deepStrictEqual(xml, { - "apples": { - "$": { - "tasty": "true" + apples: { + $: { + tasty: "true" }, - "_": "yum" + _: "yum" } }); }); }); - it("should handle errors gracefully", async function () { + it("should handle errors gracefully", async function() { try { await parseXML("INVALID"); throw new Error("did not throw"); diff --git a/sdk/core/core-http/tsconfig.json b/sdk/core/core-http/tsconfig.json index 418bf57b79b6..c4ea5684971d 100644 --- a/sdk/core/core-http/tsconfig.json +++ b/sdk/core/core-http/tsconfig.json @@ -27,12 +27,6 @@ ] }, "compileOnSave": true, - "exclude": [ - "node_modules" - ], - "include": [ - "./lib/**/*.ts", - "./samples/**/*.ts", - "./test/**/*.ts" - ] + "exclude": ["node_modules"], + "include": ["./lib/**/*.ts", "./samples/**/*.ts", "./test/**/*.ts"] }