Skip to content

Commit

Permalink
Update tests with environmental changes (#30464)
Browse files Browse the repository at this point in the history
### Packages impacted by this PR
@azure-rest/ai-vision-image-analysis

### Issues associated with this PR
N/A

### Describe the problem that is addressed by this PR
Test cases were failing on playback due to environment
mis-configuration.

### Provide a list of related PRs _(if any)_

### Checklists
- [ ] Added impacted package name to the issue description
- [ ] Does this PR needs any fixes in the SDK Generator?** _(If so,
create an Issue in the
[Autorest/typescript](https://github.com/Azure/autorest.typescript)
repository and link it here)_
- [ ] Added a changelog (if necessary)
  • Loading branch information
rhurey authored Jul 19, 2024
1 parent 6f78d49 commit 95c6595
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 69 deletions.
15 changes: 4 additions & 11 deletions sdk/vision/ai-vision-image-analysis-rest/src/clientDefinitions.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,24 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import {
AnalyzeFromImageDataParameters,
AnalyzeFromUrlParameters,
} from "./parameters.js";
import { AnalyzeFromImageDataParameters, AnalyzeFromUrlParameters } from "./parameters";
import {
AnalyzeFromImageData200Response,
AnalyzeFromImageDataDefaultResponse,
AnalyzeFromUrl200Response,
AnalyzeFromUrlDefaultResponse,
} from "./responses.js";
} from "./responses";
import { Client, StreamableMethod } from "@azure-rest/core-client";

export interface AnalyzeFromImageData {
/** Performs a single Image Analysis operation */
post(
options: AnalyzeFromImageDataParameters,
): StreamableMethod<
AnalyzeFromImageData200Response | AnalyzeFromImageDataDefaultResponse
>;
): StreamableMethod<AnalyzeFromImageData200Response | AnalyzeFromImageDataDefaultResponse>;
/** Performs a single Image Analysis operation */
post(
options: AnalyzeFromUrlParameters,
): StreamableMethod<
AnalyzeFromUrl200Response | AnalyzeFromUrlDefaultResponse
>;
): StreamableMethod<AnalyzeFromUrl200Response | AnalyzeFromUrlDefaultResponse>;
}

export interface Routes {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ export default function createClient(
credentials: TokenCredential | KeyCredential,
{ apiVersion = "2023-10-01", ...options }: ImageAnalysisClientOptions = {},
): ImageAnalysisClient {
const endpointUrl =
options.endpoint ?? options.baseUrl ?? `${endpointParam}/computervision`;
const endpointUrl = options.endpoint ?? options.baseUrl ?? `${endpointParam}/computervision`;
const userAgentInfo = `azsdk-js-ai-vision-image-analysis-rest/1.0.0-beta.3`;
const userAgentPrefix =
options.userAgentOptions && options.userAgentOptions.userAgentPrefix
Expand All @@ -40,18 +39,11 @@ export default function createClient(
logger: options.loggingOptions?.logger ?? logger.info,
},
credentials: {
scopes: options.credentials?.scopes ?? [
"https://cognitiveservices.azure.com/.default",
],
apiKeyHeaderName:
options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key",
scopes: options.credentials?.scopes ?? ["https://cognitiveservices.azure.com/.default"],
apiKeyHeaderName: options.credentials?.apiKeyHeaderName ?? "Ocp-Apim-Subscription-Key",
},
};
const client = getClient(
endpointUrl,
credentials,
options,
) as ImageAnalysisClient;
const client = getClient(endpointUrl, credentials, options) as ImageAnalysisClient;

client.pipeline.removePolicy({ name: "ApiVersionPolicy" });
client.pipeline.addPolicy({
Expand Down
25 changes: 7 additions & 18 deletions sdk/vision/ai-vision-image-analysis-rest/src/isUnexpected.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ const responseMap: Record<string, string[]> = {
};

export function isUnexpected(
response:
| AnalyzeFromImageData200Response
| AnalyzeFromImageDataDefaultResponse,
response: AnalyzeFromImageData200Response | AnalyzeFromImageDataDefaultResponse,
): response is AnalyzeFromImageDataDefaultResponse;
export function isUnexpected(
response: AnalyzeFromUrl200Response | AnalyzeFromUrlDefaultResponse,
Expand All @@ -26,9 +24,7 @@ export function isUnexpected(
| AnalyzeFromImageDataDefaultResponse
| AnalyzeFromUrl200Response
| AnalyzeFromUrlDefaultResponse,
): response is
| AnalyzeFromImageDataDefaultResponse
| AnalyzeFromUrlDefaultResponse {
): response is AnalyzeFromImageDataDefaultResponse | AnalyzeFromUrlDefaultResponse {
const lroOriginal = response.headers["x-ms-original-url"];
const url = new URL(lroOriginal ?? response.request.url);
const method = response.request.method;
Expand Down Expand Up @@ -61,24 +57,17 @@ function getParametrizedPathSuccess(method: string, path: string): string[] {

// track if we have found a match to return the values found.
let found = true;
for (
let i = candidateParts.length - 1, j = pathParts.length - 1;
i >= 1 && j >= 1;
i--, j--
) {
if (
candidateParts[i]?.startsWith("{") &&
candidateParts[i]?.indexOf("}") !== -1
) {
for (let i = candidateParts.length - 1, j = pathParts.length - 1; i >= 1 && j >= 1; i--, j--) {
if (candidateParts[i]?.startsWith("{") && candidateParts[i]?.indexOf("}") !== -1) {
const start = candidateParts[i]!.indexOf("}") + 1,
end = candidateParts[i]?.length;
// If the current part of the candidate is a "template" part
// Try to use the suffix of pattern to match the path
// {guid} ==> $
// {guid}:export ==> :export$
const isMatched = new RegExp(
`${candidateParts[i]?.slice(start, end)}`,
).test(pathParts[j] || "");
const isMatched = new RegExp(`${candidateParts[i]?.slice(start, end)}`).test(
pathParts[j] || "",
);

if (!isMatched) {
found = false;
Expand Down
6 changes: 1 addition & 5 deletions sdk/vision/ai-vision-image-analysis-rest/src/parameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ export interface AnalyzeFromImageDataBodyParam {
*
* Value may contain any sequence of octets
*/
body:
| string
| Uint8Array
| ReadableStream<Uint8Array>
| NodeJS.ReadableStream;
body: string | Uint8Array | ReadableStream<Uint8Array> | NodeJS.ReadableStream;
}

export interface AnalyzeFromImageDataQueryParamProperties {
Expand Down
2 changes: 1 addition & 1 deletion sdk/vision/ai-vision-image-analysis-rest/src/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { RawHttpHeaders } from "@azure/core-rest-pipeline";
import { HttpResponse, ErrorResponse } from "@azure-rest/core-client";
import { ImageAnalysisResultOutput } from "./outputModels.js";
import { ImageAnalysisResultOutput } from "./outputModels";

/** The request has succeeded. */
export interface AnalyzeFromImageData200Response extends HttpResponse {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ import { createClient } from "./utils/clientMethods";
import { AzureKeyCredential } from "@azure/core-auth";
import { createTestCredential } from "@azure-tools/test-credential";

const key = assertEnvironmentVariable("VISION_KEY");
const KeyCredential = new AzureKeyCredential(key);

const credentials = [
{ credential: KeyCredential, title: "AzureKeyCredential" },
{ credential: createTestCredential(), title: "TokenCredential" }
{
credential: () => new AzureKeyCredential(assertEnvironmentVariable("VISION_KEY")),
title: "AzureKeyCredential",
},
{ credential: () => createTestCredential(), title: "TokenCredential" },
];

describe("Analyze Tests", () => {
Expand All @@ -33,12 +33,13 @@ describe("Analyze Tests", () => {

beforeEach(async function (this: Context) {
recorder = await createRecorder(this);

recorder.addSanitizers({
headerSanitizers: [{ key: "Ocp-Apim-Subscription-Key", value: "***********" }],
uriSanitizers: [{ target: "https://[a-zA-Z0-9-]*/", value: "https://endpoint/" }],
});
client = await createClient(recorder, credential.credential);

client = await createClient(recorder, credential.credential());
});

afterEach(async function () {
Expand Down Expand Up @@ -271,7 +272,9 @@ describe("Analyze Tests", () => {
assert.isNotNull(captionResult);
assert.isAbove(captionResult.confidence, 0);
assert.isBelow(captionResult.confidence, 1);
assert.isTrue(captionResult.text.toLowerCase().includes(genderNeutral ? "person" : "woman"));
assert.isTrue(
captionResult.text.toLowerCase().includes(genderNeutral ? "person" : "woman"),
);
assert.isTrue(captionResult.text.toLowerCase().includes("table"));
assert.isTrue(captionResult.text.toLowerCase().includes("laptop"));
}
Expand Down Expand Up @@ -314,9 +317,9 @@ describe("Analyze Tests", () => {
assert.isNotNull(oneObject.boundingBox);
assert.isTrue(
oneObject.boundingBox.x > 0 ||
oneObject.boundingBox.y > 0 ||
oneObject.boundingBox.h > 0 ||
oneObject.boundingBox.w > 0,
oneObject.boundingBox.y > 0 ||
oneObject.boundingBox.h > 0 ||
oneObject.boundingBox.w > 0,
);
assert.isNotNull(oneObject.tags);
for (const oneTag of oneObject.tags) {
Expand All @@ -327,8 +330,9 @@ describe("Analyze Tests", () => {
}

assert.isAtLeast(
objectsResult.values.filter((v) => v.tags.filter((t) => t.name.toLowerCase() === "person"))
.length,
objectsResult.values.filter((v) =>
v.tags.filter((t) => t.name.toLowerCase() === "person"),
).length,
0,
);
}
Expand Down Expand Up @@ -390,4 +394,4 @@ describe("Analyze Tests", () => {
}
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import "./env";
import { AzureKeyCredential, TokenCredential } from "@azure/core-auth";
import importedCreateClient, { ImageAnalysisClient } from "../../../src/index";

export async function createClient(recorder: Recorder, credential : AzureKeyCredential | TokenCredential): Promise<ImageAnalysisClient> {
const endpoint = assertEnvironmentVariable("VISION_ENDPOINT");
return importedCreateClient(endpoint, credential, recorder.configureClientOptions({}));
}

export async function createClient(
recorder: Recorder,
credential: AzureKeyCredential | TokenCredential,
): Promise<ImageAnalysisClient> {
const endpoint = assertEnvironmentVariable("VISION_ENDPOINT");
return importedCreateClient(endpoint, credential, recorder.configureClientOptions({}));
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ const envSetupForPlayback: Record<string, string> = {
AZURE_CLIENT_SECRET: "azure_client_secret",
AZURE_TENANT_ID: "88888888-8888-8888-8888-888888888888",
SUBSCRIPTION_ID: "azure_subscription_id",
VISION_ENDPOINT: "https://endpoint.cognitiveservices.azure.com/",
VISION_KEY: "***********",
};

const recorderEnvSetup: RecorderStartOptions = {
envSetupForPlayback,
removeCentralSanitizers: [
"AZSDK3493",
]
removeCentralSanitizers: ["AZSDK3493"],
};

/**
Expand Down

0 comments on commit 95c6595

Please sign in to comment.