[communication] Migrate @azure/communication-sms to ESM/vitest (#31723)

### Packages impacted by this PR

- @azure/communication-sms

### Issues associated with this PR

- https://github.com/Azure/azure-sdk-for-js/issues/31338

### Describe the problem that is addressed by this PR

Migrates @azure/communication-sms to ESM/vitest

### What are the possible designs available to address the problem? If
there are more than one possible design, why was the one in this PR
chosen?


### Are there test cases added in this PR? _(If not, why?)_


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


### Command used to generate this PR:**_(Applicable only to SDK release
request PRs)_

### 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)
This commit is contained in:
Matthew Podwysocki 2024-11-14 18:41:49 -05:00 коммит произвёл GitHub
Родитель 10ab5dc4a8
Коммит ae05a39d0f
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: B5690EEEBB952194
27 изменённых файлов: 495 добавлений и 451 удалений

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

@ -19559,7 +19559,7 @@ packages:
dev: false
file:projects/communication-sms.tgz:
resolution: {integrity: sha512-haVPGnQ12Pl0W69/eg2MhmTpiF+DTrxGi+y1TMCm736KXUIeNrW87yhASdKXOOM15k2n3LJC2qi/KBKH0T9j7w==, tarball: file:projects/communication-sms.tgz}
resolution: {integrity: sha512-dmscPn+No1b2ix4Mc9o8yZR34qSg/0GaILdZES+WE1tBsYeSqo8yWKJo3/bTOSNBRR5oIdHe+XafVl1sWObFdw==, tarball: file:projects/communication-sms.tgz}
name: '@rush-temp/communication-sms'
version: 0.0.0
dependencies:
@ -19569,6 +19569,8 @@ packages:
'@types/mocha': 10.0.9
'@types/node': 18.19.64
'@types/sinon': 17.0.3
'@vitest/browser': 2.1.5(@types/node@18.19.64)(playwright@1.48.2)(typescript@5.6.3)(vitest@2.1.5)
'@vitest/coverage-istanbul': 2.1.5(vitest@2.1.5)
chai: 4.3.10
dotenv: 16.4.5
eslint: 9.14.0
@ -19585,19 +19587,33 @@ packages:
karma-sourcemap-loader: 0.3.8
mocha: 10.8.2
nyc: 17.1.0
playwright: 1.48.2
sinon: 17.0.1
ts-node: 10.9.2(@types/node@18.19.64)(typescript@5.6.3)
tslib: 2.8.1
typescript: 5.6.3
util: 0.12.5
vitest: 2.1.5(@types/node@18.19.64)(@vitest/browser@2.1.5)
transitivePeerDependencies:
- '@swc/core'
- '@swc/wasm'
- '@edge-runtime/vm'
- '@vitest/ui'
- bufferutil
- debug
- happy-dom
- jiti
- jsdom
- less
- lightningcss
- msw
- safaridriver
- sass
- sass-embedded
- stylus
- sugarss
- supports-color
- terser
- utf-8-validate
- vite
- webdriverio
dev: false
file:projects/communication-tiering.tgz:

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

@ -1,10 +0,0 @@
{
"include": ["dist-esm/src/**/*.js"],
"exclude": ["**/*.d.ts", "dist-esm/src/generated/*"],
"reporter": ["text-summary", "html", "cobertura"],
"exclude-after-remap": false,
"sourceMap": true,
"produce-source-map": true,
"instrument": true,
"all": true
}

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

@ -1,6 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
"mainEntryPointFilePath": "types/src/index.d.ts",
"mainEntryPointFilePath": "dist/esm/index.d.ts",
"docModel": {
"enabled": true
},
@ -11,7 +11,7 @@
"dtsRollup": {
"enabled": true,
"untrimmedFilePath": "",
"publicTrimmedFilePath": "./types/communication-sms.d.ts"
"publicTrimmedFilePath": "dist/communication-sms.d.ts"
},
"messages": {
"tsdocMessageReporting": {

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

@ -1,128 +0,0 @@
// https://github.com/karma-runner/karma-chrome-launcher
process.env.CHROME_BIN = require("puppeteer").executablePath();
require("dotenv").config();
const { relativeRecordingsPath } = require("@azure-tools/test-recorder");
process.env.RECORDINGS_RELATIVE_PATH = relativeRecordingsPath();
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "./",
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["mocha"],
plugins: [
"karma-mocha",
"karma-mocha-reporter",
"karma-chrome-launcher",
"karma-firefox-launcher",
"karma-env-preprocessor",
"karma-coverage",
"karma-sourcemap-loader",
"karma-junit-reporter",
],
// list of files / patterns to load in the browser
files: ["dist-test/index.browser.js"],
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"**/*.js": ["sourcemap", "env"],
// IMPORTANT: COMMENT following line if you want to debug in your browsers!!
// Preprocess source file to calculate code coverage, however this will make source file unreadable
// "dist-test/index.browser.js": ["coverage"]
},
// inject following environment values into browser testing with window.__env__
// environment values MUST be exported or set with same console running "karma start"
// https://www.npmjs.com/package/karma-env-preprocessor
envPreprocessor: [
"COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING",
"AZURE_PHONE_NUMBER",
"TEST_MODE",
"AZURE_CLIENT_ID",
"AZURE_CLIENT_SECRET",
"AZURE_TENANT_ID",
"COMMUNICATION_SKIP_INT_SMS_TEST",
"RECORDINGS_RELATIVE_PATH",
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["mocha", "coverage", "junit"],
coverageReporter: {
// specify a common output directory
dir: "coverage-browser/",
reporters: [
{ type: "json", subdir: ".", file: "coverage.json" },
{ type: "lcovonly", subdir: ".", file: "lcov.info" },
{ type: "html", subdir: "html" },
{ type: "cobertura", subdir: ".", file: "cobertura-coverage.xml" },
],
},
junitReporter: {
outputDir: "", // results will be saved as $outputDir/$browserName.xml
outputFile: "test-results.browser.xml", // if included, results will be saved as $outputDir/$browserName/$outputFile
suite: "", // suite will become the package name attribute in xml testsuite element
useBrowserName: false, // add browser name to report and classes names
nameFormatter: undefined, // function (browser, result) to customize the name attribute in xml testcase element
classNameFormatter: undefined, // function (browser, result) to customize the classname attribute in xml testcase element
properties: {}, // key value pair of properties to add to the <properties> section of the report
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
// 'ChromeHeadless', 'Chrome', 'Firefox', 'Edge', 'IE'
browsers: ["HeadlessChrome"],
customLaunchers: {
HeadlessChrome: {
base: "ChromeHeadless",
flags: ["--no-sandbox", "--disable-web-security"],
},
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: 1,
browserNoActivityTimeout: 600000,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 3,
client: {
mocha: {
// change Karma's debug.html to the mocha web reporter
reporter: "html",
timeout: "600000",
},
},
});
};

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

@ -3,23 +3,20 @@
"version": "1.2.0-beta.1",
"description": "SDK for Azure Communication SMS service which facilitates the sending of SMS messages.",
"sdk-type": "client",
"main": "dist/index.js",
"module": "dist-esm/src/index.js",
"browser": {
"stream": "./node_modules/stream-browserify/index.js",
"./dist-esm/src/credentials/cryptoUtils.js": "./dist-esm/src/credentials/cryptoUtils.browser.js"
},
"types": "types/communication-sms.d.ts",
"main": "./dist/commonjs/index.js",
"module": "./dist/esm/index.js",
"browser": "./dist/browser/index.js",
"types": "./dist/commonjs/index.d.ts",
"scripts": {
"build": "npm run clean && tsc -p . && dev-tool run bundle && dev-tool run extract-api",
"build:browser": "tsc -p . && dev-tool run bundle",
"build:node": "tsc -p . && dev-tool run bundle",
"build": "npm run clean && dev-tool run build-package && dev-tool run extract-api",
"build:browser": "dev-tool run build-package && dev-tool run bundle",
"build:node": "dev-tool run build-package && dev-tool run bundle",
"build:samples": "dev-tool samples publish --force",
"build:test": "tsc -p . && dev-tool run bundle",
"build:test": "dev-tool run build-package && dev-tool run bundle",
"check-format": "dev-tool run vendored prettier --list-different --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
"clean": "dev-tool run vendored rimraf --glob dist dist-* temp types *.tgz *.log",
"execute:samples": "dev-tool samples run samples-dev",
"extract-api": "tsc -p . && dev-tool run extract-api",
"extract-api": "dev-tool run build-package && dev-tool run extract-api",
"format": "dev-tool run vendored prettier --write --config ../../../.prettierrc.json --ignore-path ../../../.prettierignore \"src/**/*.ts\" \"test/**/*.ts\" \"samples-dev/**/*.ts\" \"*.{js,json}\"",
"generate:client": "autorest --typescript ./swagger/README.md && rushx format",
"integration-test": "npm run integration-test:node && npm run integration-test:browser",
@ -32,14 +29,12 @@
"test:browser": "npm run build:test && npm run unit-test:browser && npm run integration-test:browser",
"test:node": "npm run build:test && npm run unit-test:node && npm run integration-test:node",
"unit-test": "npm run unit-test:node && npm run unit-test:browser",
"unit-test:browser": "dev-tool run test:browser",
"unit-test:node": "dev-tool run test:node-ts-input -- --timeout 1200000 --exclude 'test/**/browser/*.spec.ts' 'test/**/*.spec.ts'",
"unit-test:browser": "npm run clean && dev-tool run build-package && dev-tool run build-test && dev-tool run test:vitest --browser",
"unit-test:node": "dev-tool run test:vitest",
"update-snippets": "echo skipped"
},
"files": [
"dist/",
"dist-esm/src",
"types/communication-sms.d.ts",
"README.md",
"LICENSE"
],
@ -75,35 +70,20 @@
"tslib": "^2.2.0"
},
"devDependencies": {
"@azure-tools/test-credential": "^1.0.0",
"@azure-tools/test-recorder": "^3.0.0",
"@azure-tools/test-utils": "^1.0.1",
"@azure-tools/test-credential": "^2.0.0",
"@azure-tools/test-recorder": "^4.1.0",
"@azure-tools/test-utils-vitest": "^1.0.0",
"@azure/dev-tool": "^1.0.0",
"@azure/eslint-plugin-azure-sdk": "^3.0.0",
"@azure/identity": "^4.0.1",
"@types/chai": "^4.1.6",
"@types/mocha": "^10.0.0",
"@types/node": "^18.0.0",
"@types/sinon": "^17.0.0",
"chai": "^4.2.0",
"@vitest/browser": "^2.1.4",
"@vitest/coverage-istanbul": "^2.1.4",
"dotenv": "^16.0.0",
"eslint": "^9.9.0",
"inherits": "^2.0.3",
"karma": "^6.2.0",
"karma-chrome-launcher": "^3.0.0",
"karma-coverage": "^2.0.0",
"karma-env-preprocessor": "^0.1.1",
"karma-firefox-launcher": "^1.1.0",
"karma-junit-reporter": "^2.0.1",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5",
"karma-sourcemap-loader": "^0.3.8",
"mocha": "^10.0.0",
"nyc": "^17.0.0",
"sinon": "^17.0.0",
"ts-node": "^10.0.0",
"playwright": "^1.48.2",
"typescript": "~5.6.2",
"util": "^0.12.1"
"vitest": "^2.1.4"
},
"//metadata": {
"constantPaths": [
@ -134,5 +114,42 @@
"requiredResources": {
"Azure Communication Services account": "https://docs.microsoft.com/azure/communication-services/quickstarts/create-communication-resource"
}
},
"type": "module",
"tshy": {
"exports": {
"./package.json": "./package.json",
".": "./src/index.ts"
},
"dialects": [
"esm",
"commonjs"
],
"esmDialects": [
"browser",
"react-native"
],
"selfLink": false
},
"exports": {
"./package.json": "./package.json",
".": {
"browser": {
"types": "./dist/browser/index.d.ts",
"default": "./dist/browser/index.js"
},
"react-native": {
"types": "./dist/react-native/index.d.ts",
"default": "./dist/react-native/index.js"
},
"import": {
"types": "./dist/esm/index.d.ts",
"default": "./dist/esm/index.js"
},
"require": {
"types": "./dist/commonjs/index.d.ts",
"default": "./dist/commonjs/index.js"
}
}
}
}

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

@ -9,7 +9,7 @@ import { SmsClient, SmsSendRequest } from "@azure/communication-sms";
// Load the .env file if it exists
import * as dotenv from "dotenv";
import { SmsSendOptions } from "../src/generated/src/models";
import { SmsSendOptions } from "../src/generated/src/models/index.js";
dotenv.config();
export async function main() {

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

@ -6,6 +6,6 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
export * from "./models";
export { SmsApiClient } from "./smsApiClient";
export * from "./operationsInterfaces";
export * from "./models/index.js";
export { SmsApiClient } from "./smsApiClient.js";
export * from "./operationsInterfaces/index.js";

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

@ -11,7 +11,7 @@ import {
OperationURLParameter,
OperationQueryParameter,
} from "@azure/core-client";
import { SendMessageRequest as SendMessageRequestMapper } from "../models/mappers";
import { SendMessageRequest as SendMessageRequestMapper } from "../models/mappers.js";
export const contentType: OperationParameter = {
parameterPath: ["options", "contentType"],

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

@ -6,4 +6,4 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
export * from "./sms";
export * from "./sms.js";

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

@ -6,17 +6,17 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
import { tracingClient } from "../tracing";
import { Sms } from "../operationsInterfaces";
import { tracingClient } from "../tracing.js";
import { Sms } from "../operationsInterfaces/index.js";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { SmsApiClient } from "../smsApiClient";
import * as Mappers from "../models/mappers.js";
import * as Parameters from "../models/parameters.js";
import { SmsApiClient } from "../smsApiClient.js";
import {
SendMessageRequest,
SmsSendOptionalParams,
SmsSendOperationResponse,
} from "../models";
} from "../models/index.js";
/** Class containing Sms operations. */
export class SmsImpl implements Sms {

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

@ -6,4 +6,4 @@
* Changes may cause incorrect behavior and will be lost if the code is regenerated.
*/
export * from "./sms";
export * from "./sms.js";

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

@ -10,7 +10,7 @@ import {
SendMessageRequest,
SmsSendOptionalParams,
SmsSendOperationResponse,
} from "../models";
} from "../models/index.js";
/** Interface representing a Sms. */
export interface Sms {

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

@ -12,9 +12,9 @@ import {
PipelineResponse,
SendRequest,
} from "@azure/core-rest-pipeline";
import { SmsImpl } from "./operations";
import { Sms } from "./operationsInterfaces";
import { SmsApiClientOptionalParams } from "./models";
import { SmsImpl } from "./operations/index.js";
import { Sms } from "./operationsInterfaces/index.js";
import { SmsApiClientOptionalParams } from "./models/index.js";
export class SmsApiClient extends coreClient.ServiceClient {
endpoint: string;

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

@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
export * from "./smsClient";
export * from "./smsClient.js";

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

@ -11,11 +11,11 @@ import type { KeyCredential, TokenCredential } from "@azure/core-auth";
import { isTokenCredential } from "@azure/core-auth";
import type { CommonClientOptions, OperationOptions } from "@azure/core-client";
import type { InternalPipelineOptions } from "@azure/core-rest-pipeline";
import { SmsApiClient } from "./generated/src/smsApiClient";
import { extractOperationOptions } from "./extractOperationOptions";
import { generateSendMessageRequest } from "./utils/smsUtils";
import { logger } from "./logger";
import { tracingClient } from "./generated/src/tracing";
import { SmsApiClient } from "./generated/src/smsApiClient.js";
import { extractOperationOptions } from "./extractOperationOptions.js";
import { generateSendMessageRequest } from "./utils/smsUtils.js";
import { logger } from "./logger.js";
import { tracingClient } from "./generated/src/tracing.js";
/**
* Client options used to configure SMS Client API requests.

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

@ -1,10 +1,10 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import type { SendMessageRequest } from "../generated/src/models";
import type { SmsSendOptions, SmsSendRequest } from "../smsClient";
import { Uuid } from "./uuid";
import type { SmsSendOptions as InternalOptions } from "../generated/src/models";
import type { SendMessageRequest } from "../generated/src/models/index.js";
import type { SmsSendOptions, SmsSendRequest } from "../smsClient.js";
import { Uuid } from "./uuid.js";
import type { SmsSendOptions as InternalOptions } from "../generated/src/models/index.js";
export function generateSendMessageRequest(
smsRequest: SmsSendRequest,

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

@ -1,26 +1,25 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import type { HttpClient } from "@azure/core-rest-pipeline";
import type { HttpClient, SendRequest } from "@azure/core-rest-pipeline";
import { generateSendMessageRequest } from "../../src/utils/smsUtils";
import { Uuid } from "../../src/utils/uuid";
import { assert } from "chai";
import sinon from "sinon";
import { apiVersion } from "../../src/generated/src/models/parameters";
import type { SmsSendRequest } from "../../src/smsClient";
import { SmsClient } from "../../src/smsClient";
import { MockHttpClient } from "../public/utils/mockHttpClient";
import { generateSendMessageRequest } from "../../src/utils/smsUtils.js";
import { Uuid } from "../../src/utils/uuid.js";
import { apiVersion } from "../../src/generated/src/models/parameters.js";
import type { SmsSendRequest } from "../../src/smsClient.js";
import { SmsClient } from "../../src/smsClient.js";
import { MockHttpClient } from "../public/utils/mockHttpClient.js";
import type { MockInstance } from "vitest";
import { describe, it, assert, expect, vi, beforeEach, afterEach } from "vitest";
const API_VERSION = apiVersion.mapper.defaultValue;
const TEST_NUMBER = "+14255550123";
describe("[mocked] SmsClient Internal", async function () {
describe("[mocked] SmsClient Internal", async () => {
const baseUri = "https://contoso.api.fake";
const connectionString = `endpoint=${baseUri};accesskey=banana`;
let sendRequestSpy: sinon.SinonSpy;
let uuidStub: sinon.SinonStub;
let sendRequestSpy: MockInstance<SendRequest>;
let uuidStub: MockInstance<() => string>;
const mockHttpClient: HttpClient = new MockHttpClient(TEST_NUMBER);
const mockedGuid = "42bf408f-1931-4314-8971-2b538625a2b0";
@ -30,35 +29,36 @@ describe("[mocked] SmsClient Internal", async function () {
message: "message",
};
describe("when sending an SMS", function () {
describe("when sending an SMS", () => {
let smsClient: SmsClient;
beforeEach(function () {
uuidStub = sinon.stub(Uuid, "generateUuid");
uuidStub.returns(mockedGuid);
sendRequestSpy = sinon.spy(mockHttpClient, "sendRequest");
sinon.useFakeTimers();
beforeEach(() => {
uuidStub = vi.spyOn(Uuid, "generateUuid");
uuidStub.mockReturnValue(mockedGuid);
sendRequestSpy = vi.spyOn(mockHttpClient, "sendRequest");
vi.useFakeTimers();
smsClient = new SmsClient(connectionString, { httpClient: mockHttpClient });
});
it("sends with the correct request body", async function () {
it("sends with the correct request body", async () => {
await smsClient.send(testSendRequest);
const request = sendRequestSpy.getCall(0).args[0];
const request = sendRequestSpy.mock.calls[0][0];
assert.equal(request.url, `${baseUri}/sms?api-version=${API_VERSION}`);
assert.equal(request.method, "POST");
const expectedRequestBody = generateSendMessageRequest(testSendRequest);
assert.deepEqual(JSON.parse(request.body as string), expectedRequestBody);
});
it("generates a new repeatability id each time", async function () {
it("generates a new repeatability id each time", async () => {
await smsClient.send(testSendRequest);
assert.isTrue(uuidStub.calledOnce);
expect(uuidStub).toHaveBeenCalledOnce();
await smsClient.send(testSendRequest);
assert.isTrue(uuidStub.calledTwice);
expect(uuidStub).toHaveBeenCalledTimes(2);
});
afterEach(function () {
sinon.restore();
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});
});
});

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

@ -9,48 +9,165 @@
*/
import type { Recorder } from "@azure-tools/test-recorder";
import { isLiveMode, isPlaybackMode } from "@azure-tools/test-recorder";
import { matrix } from "@azure-tools/test-utils";
import type { Context } from "mocha";
import * as sinon from "sinon";
import type { SmsClient } from "../../src";
import { Uuid } from "../../src/utils/uuid";
import sendSmsSuites from "../public/suites/smsClient.send";
import { env, isLiveMode, isPlaybackMode } from "@azure-tools/test-recorder";
import { matrix } from "@azure-tools/test-utils-vitest";
import type { SmsClient, SmsSendOptions, SmsSendRequest } from "../../src/index.js";
import { Uuid } from "../../src/utils/uuid.js";
import {
createRecordedSmsClient,
createRecordedSmsClientWithToken,
} from "../public/utils/recordedClient";
} from "../public/utils/recordedClient.js";
import { assertIsFailureResult, assertIsSuccessResult } from "../public/utils/assertHelpers.js";
import { describe, it, assert, vi, beforeEach, afterEach } from "vitest";
matrix([[true, false]], async function (useAad: boolean) {
describe(`SmsClient [Playback/Record]${useAad ? " [AAD]" : ""}`, async function () {
describe(`SmsClient [Playback/Record]${useAad ? " [AAD]" : ""}`, async () => {
let recorder: Recorder;
let client: SmsClient;
beforeEach(async function (this: Context) {
beforeEach(async function (ctx) {
if (isLiveMode()) {
this.skip();
ctx.skip();
} else if (isPlaybackMode()) {
sinon.stub(Uuid, "generateUuid").returns("sanitized");
sinon.stub(Date, "now").returns(0);
vi.spyOn(Uuid, "generateUuid").mockReturnValue("sanitized");
vi.spyOn(Date, "now").mockReturnValue(0);
}
if (useAad) {
({ client, recorder } = await createRecordedSmsClientWithToken(this));
({ client, recorder } = await createRecordedSmsClientWithToken(ctx));
} else {
({ client, recorder } = await createRecordedSmsClient(this));
({ client, recorder } = await createRecordedSmsClient(ctx));
}
this.smsClient = client;
});
afterEach(async function (this: Context) {
if (!this.currentTest?.isPending()) {
afterEach(async function (ctx) {
if (!ctx.task.pending) {
await recorder.stop();
}
if (isPlaybackMode()) {
sinon.restore();
vi.restoreAllMocks();
}
});
describe("when sending SMS", sendSmsSuites);
describe("when sending SMS", async () => {
it("can send an SMS message", { timeout: 5000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const results = await client.send({
from: fromNumber,
to: [validToNumber],
message: "test message",
});
assert.lengthOf(results, 1, "must return as many results as there were recipients");
assertIsSuccessResult(results[0], validToNumber);
});
it("can send an SMS message with options passed in", { timeout: 4000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const results = await client.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
deliveryReportTimeoutInSeconds: 300,
},
);
assert.lengthOf(results, 1, "must return as many results as there were recipients");
assertIsSuccessResult(results[0], validToNumber);
});
it("sends a new message each time send is called", { timeout: 4000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const sendRequest: SmsSendRequest = {
from: fromNumber,
to: [validToNumber],
message: "test message",
};
const options: SmsSendOptions = {
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
};
const firstResults = await client.send(sendRequest, options);
const secondResults = await client.send(sendRequest, options);
assertIsSuccessResult(firstResults[0], validToNumber);
assertIsSuccessResult(secondResults[0], validToNumber);
assert.notEqual(firstResults[0].messageId, secondResults[0].messageId);
});
it("can send an SMS message to multiple recipients", { timeout: 4000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const invalidToNumber = "+1425555012345"; // invalid number that's too long
const recipients = [validToNumber, invalidToNumber];
const results = await client.send({
from: fromNumber,
to: recipients,
message: "test message",
});
assert.lengthOf(
results,
recipients.length,
"must return as many results as there were recipients",
);
assertIsSuccessResult(results[0], validToNumber);
assertIsFailureResult(results[1], invalidToNumber, "Unknown country code.");
});
it("throws an exception when sending from a number you don't own", async () => {
const fromNumber = "+14255550123";
const validToNumber = env.AZURE_PHONE_NUMBER as string;
try {
await client.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
},
);
assert.fail("Should have thrown an error");
} catch (e: any) {
assert.equal(e.statusCode, 401);
}
});
it("throws an exception when sending from an invalid number", async () => {
const fromNumber = "+1425555012345"; // invalid number that's too long
const validToNumber = env.AZURE_PHONE_NUMBER as string;
try {
await client.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
},
);
assert.fail("Should have thrown an error");
} catch (e: any) {
assert.equal(e.statusCode, 401);
}
});
});
});
});

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

@ -2,14 +2,14 @@
// Licensed under the MIT License.
import { AzureKeyCredential } from "@azure/core-auth";
import type { HttpClient } from "@azure/core-rest-pipeline";
import { isNode } from "@azure/core-util";
import type { HttpClient, SendRequest } from "@azure/core-rest-pipeline";
import { isNodeLike } from "@azure/core-util";
import type { TokenCredential } from "@azure/identity";
import { assert } from "chai";
import sinon from "sinon";
import type { SmsClientOptions, SmsSendRequest } from "../../src";
import { SmsClient } from "../../src";
import { MockHttpClient } from "./utils/mockHttpClient";
import type { SmsClientOptions, SmsSendRequest } from "../../src/index.js";
import { SmsClient } from "../../src/index.js";
import { MockHttpClient } from "./utils/mockHttpClient.js";
import type { MockInstance } from "vitest";
import { describe, it, assert, expect, vi, beforeEach, afterEach } from "vitest";
const TEST_NUMBER = "+14255550123";
@ -17,7 +17,7 @@ describe("[mocked] SmsClient", async function () {
const baseUri = "https://contoso.api.fake";
const connectionString = `endpoint=${baseUri};accesskey=banana`;
const dateHeader = "x-ms-date";
let sendRequestSpy: sinon.SinonSpy;
let sendRequestSpy: MockInstance<SendRequest>;
const mockHttpClient: HttpClient = new MockHttpClient(TEST_NUMBER);
const testSendRequest: SmsSendRequest = {
@ -48,8 +48,8 @@ describe("[mocked] SmsClient", async function () {
describe("when sending an SMS", function () {
let smsClient: SmsClient;
beforeEach(function () {
sendRequestSpy = sinon.spy(mockHttpClient, "sendRequest");
sinon.useFakeTimers();
sendRequestSpy = vi.spyOn(mockHttpClient, "sendRequest");
vi.useFakeTimers();
// workaround: casting because min testing has issues with httpClient newer versions having extra optional fields
smsClient = new SmsClient(connectionString, {
httpClient: mockHttpClient,
@ -59,8 +59,8 @@ describe("[mocked] SmsClient", async function () {
it("sends with the correct headers", async function () {
await smsClient.send(testSendRequest);
const request = sendRequestSpy.getCall(0).args[0];
if (isNode) {
const request = sendRequestSpy.mock.calls[0][0];
if (isNodeLike) {
assert.equal(request.headers.get("host"), "contoso.api.fake");
}
assert.typeOf(request.headers.get(dateHeader), "string");
@ -75,13 +75,14 @@ describe("[mocked] SmsClient", async function () {
const smsTestResults = await smsClient.send(testSendRequest);
const smsTestResult = smsTestResults[0];
sinon.assert.calledOnce(sendRequestSpy);
expect(sendRequestSpy).toHaveBeenCalled();
assert.equal(smsTestResult.httpStatusCode, 202);
assert.equal(smsTestResult.messageId, "id");
});
afterEach(function () {
sinon.restore();
vi.restoreAllMocks();
vi.useRealTimers();
});
});
});

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

@ -8,48 +8,167 @@
import type { Recorder } from "@azure-tools/test-recorder";
import { env, isPlaybackMode } from "@azure-tools/test-recorder";
import { matrix } from "@azure-tools/test-utils";
import type { Context } from "mocha";
import sinon from "sinon";
import type { SmsClient } from "../../src";
import { Uuid } from "../../src/utils/uuid";
import sendSmsSuites from "./suites/smsClient.send";
import { createRecordedSmsClient, createRecordedSmsClientWithToken } from "./utils/recordedClient";
import { matrix } from "@azure-tools/test-utils-vitest";
import type { SmsClient, SmsSendOptions, SmsSendRequest } from "../../src/index.js";
import { Uuid } from "../../src/utils/uuid.js";
import {
createRecordedSmsClient,
createRecordedSmsClientWithToken,
} from "./utils/recordedClient.js";
import { assertIsFailureResult, assertIsSuccessResult } from "./utils/assertHelpers.js";
import { describe, it, assert, vi, beforeEach, afterEach } from "vitest";
matrix([[true, false]], async function (useAad: boolean) {
describe(`SmsClient [Live]${useAad ? " [AAD]" : ""}`, async function () {
let recorder: Recorder;
let client: SmsClient;
const skipIntSMSTests = env.COMMUNICATION_SKIP_INT_SMS_TEST === "true";
before(function (this: Context) {
const skipIntSMSTests = env.COMMUNICATION_SKIP_INT_SMS_TEST === "true";
if (skipIntSMSTests) {
this.skip();
}
});
describe(
`SmsClient [Live]${useAad ? " [AAD]" : ""}`,
{ skip: skipIntSMSTests },
async function () {
let recorder: Recorder;
let client: SmsClient;
beforeEach(async function (this: Context) {
if (isPlaybackMode()) {
sinon.stub(Uuid, "generateUuid").returns("sanitized");
sinon.stub(Date, "now").returns(0);
}
if (useAad) {
({ client, recorder } = await createRecordedSmsClientWithToken(this));
} else {
({ client, recorder } = await createRecordedSmsClient(this));
}
this.smsClient = client;
});
beforeEach(async function (ctx) {
if (isPlaybackMode()) {
vi.spyOn(Uuid, "generateUuid").mockReturnValue("sanitized");
vi.spyOn(Date, "now").mockReturnValue(0);
}
if (useAad) {
({ client, recorder } = await createRecordedSmsClientWithToken(ctx));
} else {
({ client, recorder } = await createRecordedSmsClient(ctx));
}
});
afterEach(async function (this: Context) {
if (!this.currentTest?.isPending()) {
await recorder.stop();
}
if (isPlaybackMode()) {
sinon.restore();
}
});
afterEach(async function (ctx) {
if (!ctx.task.pending) {
await recorder.stop();
}
if (isPlaybackMode()) {
vi.restoreAllMocks();
}
});
describe("test send method", sendSmsSuites);
});
describe("test send method", async () => {
it("can send an SMS message", { timeout: 5000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const results = await client.send({
from: fromNumber,
to: [validToNumber],
message: "test message",
});
assert.lengthOf(results, 1, "must return as many results as there were recipients");
assertIsSuccessResult(results[0], validToNumber);
});
it("can send an SMS message with options passed in", { timeout: 4000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const results = await client.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
deliveryReportTimeoutInSeconds: 300,
},
);
assert.lengthOf(results, 1, "must return as many results as there were recipients");
assertIsSuccessResult(results[0], validToNumber);
});
it("sends a new message each time send is called", { timeout: 4000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const sendRequest: SmsSendRequest = {
from: fromNumber,
to: [validToNumber],
message: "test message",
};
const options: SmsSendOptions = {
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
};
const firstResults = await client.send(sendRequest, options);
const secondResults = await client.send(sendRequest, options);
assertIsSuccessResult(firstResults[0], validToNumber);
assertIsSuccessResult(secondResults[0], validToNumber);
assert.notEqual(firstResults[0].messageId, secondResults[0].messageId);
});
it("can send an SMS message to multiple recipients", { timeout: 4000 }, async () => {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const invalidToNumber = "+1425555012345"; // invalid number that's too long
const recipients = [validToNumber, invalidToNumber];
const results = await client.send({
from: fromNumber,
to: recipients,
message: "test message",
});
assert.lengthOf(
results,
recipients.length,
"must return as many results as there were recipients",
);
assertIsSuccessResult(results[0], validToNumber);
assertIsFailureResult(results[1], invalidToNumber, "Unknown country code.");
});
it("throws an exception when sending from a number you don't own", async () => {
const fromNumber = "+14255550123";
const validToNumber = env.AZURE_PHONE_NUMBER as string;
try {
await client.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
},
);
assert.fail("Should have thrown an error");
} catch (e: any) {
assert.equal(e.statusCode, 401);
}
});
it("throws an exception when sending from an invalid number", async () => {
const fromNumber = "+1425555012345"; // invalid number that's too long
const validToNumber = env.AZURE_PHONE_NUMBER as string;
try {
await client.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
},
);
assert.fail("Should have thrown an error");
} catch (e: any) {
assert.equal(e.statusCode, 401);
}
});
});
},
);
});

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

@ -1,129 +0,0 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { assert } from "chai";
import type { SmsSendOptions, SmsSendRequest } from "../../../src";
import { env } from "@azure-tools/test-recorder";
import type { Context } from "mocha";
import { assertIsFailureResult, assertIsSuccessResult } from "../utils/assertHelpers";
export default function testCases(): void {
it("can send an SMS message", async function (this: Context) {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const results = await this.smsClient.send({
from: fromNumber,
to: [validToNumber],
message: "test message",
});
assert.lengthOf(results, 1, "must return as many results as there were recipients");
assertIsSuccessResult(results[0], validToNumber);
}).timeout(5000);
it("can send an SMS message with options passed in", async function (this: Context) {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const results = await this.smsClient.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
deliveryReportTimeoutInSeconds: 300,
},
);
assert.lengthOf(results, 1, "must return as many results as there were recipients");
assertIsSuccessResult(results[0], validToNumber);
}).timeout(4000);
it("sends a new message each time send is called", async function (this: Context) {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const sendRequest: SmsSendRequest = {
from: fromNumber,
to: [validToNumber],
message: "test message",
};
const options: SmsSendOptions = {
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
};
const firstResults = await this.smsClient.send(sendRequest, options);
const secondResults = await this.smsClient.send(sendRequest, options);
assertIsSuccessResult(firstResults[0], validToNumber);
assertIsSuccessResult(secondResults[0], validToNumber);
assert.notEqual(firstResults[0].messageId, secondResults[0].messageId);
}).timeout(4000);
it("can send an SMS message to multiple recipients", async function (this: Context) {
const fromNumber = env.AZURE_PHONE_NUMBER as string;
const validToNumber = env.AZURE_PHONE_NUMBER as string;
const invalidToNumber = "+1425555012345"; // invalid number that's too long
const recipients = [validToNumber, invalidToNumber];
const results = await this.smsClient.send({
from: fromNumber,
to: recipients,
message: "test message",
});
assert.lengthOf(
results,
recipients.length,
"must return as many results as there were recipients",
);
assertIsSuccessResult(results[0], validToNumber);
assertIsFailureResult(results[1], invalidToNumber, "Unknown country code.");
}).timeout(4000);
it("throws an exception when sending from a number you don't own", async function (this: Context) {
const fromNumber = "+14255550123";
const validToNumber = env.AZURE_PHONE_NUMBER as string;
try {
await this.smsClient.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
},
);
assert.fail("Should have thrown an error");
} catch (e: any) {
assert.equal(e.statusCode, 401);
}
});
it("throws an exception when sending from an invalid number", async function (this: Context) {
const fromNumber = "+1425555012345"; // invalid number that's too long
const validToNumber = env.AZURE_PHONE_NUMBER as string;
try {
await this.smsClient.send(
{
from: fromNumber,
to: [validToNumber],
message: "test message",
},
{
enableDeliveryReport: true,
tag: "SMS_LIVE_TEST",
},
);
assert.fail("Should have thrown an error");
} catch (e: any) {
assert.equal(e.statusCode, 401);
}
});
}

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

@ -1,8 +1,8 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { assert } from "chai";
import type { SmsSendResult } from "../../../src";
import type { SmsSendResult } from "../../../src/index.js";
import { assert } from "vitest";
export const assertIsSuccessResult = (
actualSmsResult: SmsSendResult,

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

@ -1,10 +1,8 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import type { Context, Test } from "mocha";
import type { RecorderStartOptions, SanitizerOptions } from "@azure-tools/test-recorder";
import type { RecorderStartOptions, SanitizerOptions, TestInfo } from "@azure-tools/test-recorder";
import { Recorder, env, isPlaybackMode } from "@azure-tools/test-recorder";
import { SmsClient } from "../../../src";
import { SmsClient } from "../../../src/index.js";
import { parseConnectionString } from "@azure/communication-common";
import type { TokenCredential } from "@azure/core-auth";
import { createTestCredential } from "@azure-tools/test-credential";
@ -54,7 +52,7 @@ const recorderOptions: RecorderStartOptions = {
],
};
export async function createRecorder(context: Test | undefined): Promise<Recorder> {
export async function createRecorder(context: TestInfo | undefined): Promise<Recorder> {
const recorder = new Recorder(context);
await recorder.start(recorderOptions);
await recorder.setMatcher("CustomDefaultMatcher", {
@ -69,9 +67,9 @@ export async function createRecorder(context: Test | undefined): Promise<Recorde
}
export async function createRecordedSmsClient(
context: Context,
context: TestInfo,
): Promise<RecordedClient<SmsClient>> {
const recorder = await createRecorder(context.currentTest);
const recorder = await createRecorder(context);
const client = new SmsClient(
env.COMMUNICATION_LIVETEST_STATIC_CONNECTION_STRING ?? "",
@ -84,9 +82,9 @@ export async function createRecordedSmsClient(
}
export async function createRecordedSmsClientWithToken(
context: Context,
context: TestInfo,
): Promise<RecordedClient<SmsClient>> {
const recorder = await createRecorder(context.currentTest);
const recorder = await createRecorder(context);
let credential: TokenCredential;
const endpoint = parseConnectionString(

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

@ -0,0 +1,10 @@
{
"extends": "./.tshy/build.json",
"include": ["./src/**/*.ts", "./src/**/*.mts", "./test/**/*.spec.ts", "./test/**/*.mts"],
"exclude": ["./test/**/node/**/*.ts"],
"compilerOptions": {
"outDir": "./dist-test/browser",
"rootDir": ".",
"skipLibCheck": true
}
}

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

@ -1,11 +1,12 @@
{
"extends": "../../../tsconfig",
"compilerOptions": {
"outDir": "./dist-esm",
"declarationDir": "./types",
"paths": {
"@azure/communication-sms": ["./src/index"]
}
},
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "."
},
"include": ["src/**/*.ts", "test/**/*.ts", "samples-dev/**/*.ts"]
"include": ["src/**/*.ts", "src/**/*.mts", "src/**/*.cts", "samples-dev/**/*.ts", "test/**/*.ts"]
}

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

@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { defineConfig, mergeConfig } from "vitest/config";
import viteConfig from "../../../vitest.browser.shared.config.ts";
export default mergeConfig(
viteConfig,
defineConfig({
test: {
include: [
"dist-test/browser/test/**/*.spec.js",
],
},
}),
);

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

@ -0,0 +1,15 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { defineConfig, mergeConfig } from "vitest/config";
import viteConfig from "../../../vitest.shared.config.ts";
export default mergeConfig(
viteConfig,
defineConfig({
test: {
include: ["test/**/*.spec.ts"],
},
}),
);