зеркало из
1
0
Форкнуть 0

Apply build configuration from sdk template to client

- Add build configuration from sdk template

- Fix tsc and tslint errors

- Add a README.md for client examples

- Bump version to 2.0.0-preview.1
This commit is contained in:
Jeremy Meng 2019-02-13 00:15:43 +00:00
Родитель 3c34bf0f31
Коммит 4f18a4adb8
35 изменённых файлов: 2014 добавлений и 2223 удалений

4
.gitignore поставляемый
Просмотреть файл

@ -53,6 +53,10 @@ obj/*
.env
typings/
dist/
dist-esm/
browser/
test-browser/
test-dist/
out/
output/
client/examples/js/lib/

30
.vscode/launch.json поставляемый
Просмотреть файл

@ -22,34 +22,6 @@
"internalConsoleOptions": "openOnSessionStart",
"envFile": "${workspaceFolder}/processor/.env" // You can take a look at the sample.env file for supported environment variables.
},
{
"type": "node",
"request": "launch",
"name": "Client Tests",
"program": "${workspaceFolder}/client/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"tdd",
"-r",
"ts-node/register",
"-t",
"999999",
"--colors",
"${workspaceFolder}/client/tests/client.spec.ts"
],
"internalConsoleOptions": "openOnSessionStart",
"envFile": "${workspaceFolder}/client/.env" // You can take a look at the sample.env file for supported environment variables.
},
{
"type": "node",
"request": "launch",
"name": "Client Example",
"program": "${workspaceFolder}/client/examples/simpleSender.ts",
"outFiles": [
"${workspaceFolder}/client/dist/**/*.js"
],
"envFile": "${workspaceFolder}/client/.env" // You can take a look at the sample.env file for supported environment variables.
},
{
"type": "node",
"request": "launch",
@ -80,4 +52,4 @@
]
}
]
}
}

5
.vscode/settings.json поставляемый
Просмотреть файл

@ -23,5 +23,8 @@
"editor.detectIndentation": false
},
"editor.rulers": [100],
"typescript.tsdk": "./client/node_modules/typescript/lib"
"typescript.preferences.quoteStyle": "double",
"javascript.preferences.quoteStyle": "double",
"typescript.tsdk": "./client/node_modules/typescript/lib",
"prettier.arrowParens": "always"
}

35
client/.vscode/launch.json поставляемый Normal file
Просмотреть файл

@ -0,0 +1,35 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Client Unit Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"tdd",
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test-dist/index.js"
],
"internalConsoleOptions": "openOnSessionStart",
"preLaunchTask": "npm: build-test"
},
{
"type": "node",
"request": "launch",
"name": "Client Example",
"program": "${workspaceFolder}/examples/simpleSender.ts",
"preLaunchTask": "npm: build-samples",
"outFiles": [
"${workspaceFolder}/dist-esm/**/*.js"
],
"envFile": "${workspaceFolder}/.env" // You can take a look at the sample.env file for supported environment variables.
}
]
}

47
client/examples/README.md Normal file
Просмотреть файл

@ -0,0 +1,47 @@
## Getting started with samples ##
## Building the library
- Clone the repo and cd to the repo directory
```bash
git clone https://github.com/Azure/azure-event-hubs-node.git
cd client
```
- Install typescript, ts-node globally (required for running the samples)
```bash
npm i -g typescript
npm i -g ts-node
```
- NPM install from the root of the package
```bash
npm i
```
- Build the project
```bash
npm run build
```
## Before executing a sample
- Go to the [Azure Portal](https://portal.azure.com).
- Here are the docs which would help you create a event hubs and eventhub/iothub resources in the portal:
- [Azure Event Hubs - NodeJS DOCS](https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-node-get-started-send).
- [Azure IoT Hubs - NodeJS DOCS](https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-node-node-module-twin-getstarted).
- In the portal, go to **Dashboard > Event Hubs > _your-eventhubs-namespace_**.
- Note down the "Primary Connection String" of **RootManageSharedAccessKey** at **Shared access policies** under **Settings** tab.
- Note down the name of the event hub that you created
> _Note : **RootManageSharedAccessKey** is automatically created for the namespace and has permissions for the entire namespace. If you want to use restricted access, refer [Shared Access Signatures](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-sas), create the Access Keys exclusive to the specific created Queue/Topic._
Before running a sample, update it with the connection string and the hub name you have noted down above.
- to load environment variables from an `.env` file, please refer to [NPM dotenv package](https://www.npmjs.com/package/dotenv) for more details. See the [sample.env](../../sample.env) for an example.
## Executing a sample
- The samples are to be run using ts-node, after changing your current working directory to the `examples` folder.
```bash
cd examples
ts-node <sample>.ts
```
- For debugging:
[VS Code - Debugging](https://code.visualstudio.com/docs/editor/debugging#_launch-configurations) - Update the `Client Example` configuration in `launch.json` by changing the `program` attrbute to point to the sample you want to debug.
```bash
"program": "${workspaceFolder}/client/examples/<sample>.ts"
```

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

@ -2,7 +2,7 @@
// Licensed under the MIT License.
import { EventHubClient, EventData, EventPosition } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "EVENTHUB_CONNECTION_STRING";

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

@ -2,7 +2,7 @@
// Licensed under the MIT License.
import { EventHubClient, EventData, EventPosition, OnMessage, OnError, MessagingError } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "EVENTHUB_CONNECTION_STRING";
@ -21,7 +21,9 @@ async function main(): Promise<void> {
console.log("### Actual message:", eventData.body);
count++;
if (count >= 5) {
client.close();
client.close().catch((err) => {
console.log(">>>>> Error closing the client: ", err);
});
}
};
const onError: OnError = (err: MessagingError | Error) => {

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

@ -2,7 +2,7 @@
// Licensed under the MIT License.
import { EventHubClient, OnError, MessagingError, OnMessage, delay } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "EVENTHUB_CONNECTION_STRING";

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

@ -2,7 +2,7 @@
// Licensed under the MIT License.
import { EventHubClient } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "EVENTHUB_CONNECTION_STRING";

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

@ -2,7 +2,7 @@
// Licensed under the MIT License.
import { EventHubClient } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "IOTHUB_CONNECTION_STRING";

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

@ -2,7 +2,7 @@
// Licensed under the MIT License.
import { EventHubClient, EventPosition, OnMessage, OnError, MessagingError, delay } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "EVENTHUB_CONNECTION_STRING";

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

@ -2,7 +2,7 @@
// Licensed under the MIT License.
import { EventHubClient, EventData } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "EVENTHUB_CONNECTION_STRING";

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

@ -4,7 +4,7 @@
import {
EventHubClient, EventPosition, OnMessage, OnError, MessagingError, ReceiveOptions, delay
} from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
const connectionString = "EVENTHUB_CONNECTION_STRING";

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

@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"module": "commonjs"
},
"include": [
"**/*.ts"
],
"exclude": [
"../node_modules",
"../typings/**",
]
}

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

@ -169,7 +169,7 @@ export class EventHubClient {
*/
async send(data: EventData, partitionId?: string | number): Promise<Delivery> {
const sender = EventHubSender.create(this._context, partitionId);
return await sender.send(data);
return sender.send(data);
}
/**
@ -185,7 +185,7 @@ export class EventHubClient {
*/
async sendBatch(datas: EventData[], partitionId?: string | number): Promise<Delivery> {
const sender = EventHubSender.create(this._context, partitionId);
return await sender.sendBatch(datas);
return sender.sendBatch(datas);
}
/**

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

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as uuid from "uuid/v4";
import uuid from "uuid/v4";
import * as log from "./log";
import {
Receiver, OnAmqpEvent, EventContext, ReceiverOptions, types, AmqpError

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

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as uuid from "uuid/v4";
import uuid from "uuid/v4";
import * as log from "./log";
import {
messageProperties, Sender, EventContext, OnAmqpEvent, SenderOptions, Delivery, SenderEvents,

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

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as uuid from "uuid/v4";
import uuid from "uuid/v4";
import { defaultLock } from "@azure/amqp-common";
import { ConnectionContext } from "./connectionContext";
import { Sender, Receiver } from "rhea-promise";

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

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as debugModule from "debug";
import debugModule from "debug";
/**
* @ignore
* log statements for error

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

@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as uuid from "uuid/v4";
import uuid from "uuid/v4";
import {
RequestResponseLink, defaultLock, translate, Constants
} from "@azure/amqp-common";

3169
client/package-lock.json сгенерированный

Разница между файлами не показана из-за своего большого размера Загрузить разницу

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

@ -1,49 +1,86 @@
{
"name": "@azure/event-hubs",
"version": "1.0.8",
"version": "2.0.0-preview.1",
"description": "Azure Event Hubs SDK for JS.",
"author": "Microsoft Corporation",
"license": "MIT",
"keywords": [
"azure",
"cloud",
"event hubs"
],
"main": "./dist/lib/index.js",
"module": "dist-esm/lib/index.js",
"types": "./typings/lib/index.d.ts",
"browser": {
"./dist/index.js": "./browser/index.js"
},
"engine": {
"node": ">=6.0.0"
},
"dependencies": {
"@azure/amqp-common": "^0.1.3",
"@azure/amqp-common": "^1.0.0-preview.1",
"async-lock": "^1.1.3",
"debug": "^3.1.0",
"is-buffer": "2.0.2",
"jssha": "^2.3.1",
"ms-rest-azure": "^2.5.9",
"rhea-promise": "^0.1.6",
"rhea-promise": "^0.1.13",
"tslib": "^1.9.3",
"uuid": "^3.3.2"
},
"devDependencies": {
"@microsoft/api-extractor": "^6.3.0",
"@types/async-lock": "^1.1.0",
"@types/chai": "^4.1.4",
"@types/chai": "^4.1.6",
"@types/chai-as-promised": "^7.1.0",
"@types/debug": "^0.0.30",
"@types/debug": "^0.0.31",
"@types/dotenv": "^4.0.3",
"@types/long": "^4.0.0",
"@types/mocha": "^5.2.5",
"@types/node": "^8.0.37",
"@types/uuid": "^3.4.3",
"chai": "^4.1.2",
"@types/uuid": "^3.3.2",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"dotenv": "^6.0.0",
"cross-env": "^5.2.0",
"dotenv": "^6.1.0",
"mocha": "^5.2.0",
"nyc": "^12.0.2",
"nyc": "13.3.0",
"prettier": "^1.15.3",
"rimraf": "^2.6.2",
"ts-node": "^5.0.1",
"rollup": "^0.66.6",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-json": "^3.1.0",
"rollup-plugin-multi-entry": "^2.0.2",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-replace": "^2.1.0",
"rollup-plugin-sourcemaps": "^0.4.2",
"rollup-plugin-uglify": "^6.0.0",
"ts-node": "^7.0.1",
"tslint": "^5.11.0",
"typescript": "^3.0.1"
"typescript": "^3.2.1"
},
"files": [
"LICENSE",
"changelog.md",
"README.md",
"dist/",
"dist-esm/lib/",
"lib/",
"typings/"
],
"scripts": {
"tslint": "tslint -p . -c tslint.json --exclude examples/**/*.ts --exclude tests/**/*.ts",
"tslint": "tslint -p . -c tslint.json",
"tsc": "tsc",
"prebuild": "rimraf dist && rimraf typings",
"build": "npm run tslint && npm run tsc",
"build": "npm run tslint && tsc -p . && rollup -c",
"build-browser": "tsc -p . && cross-env ONLY_BROWSER=true rollup -c",
"build-node": "tsc -p . && cross-env ONLY_NODE=true rollup -c",
"build-test": "tsc -p . && cross-env ONLY_NODE=true rollup -c rollup.test.config.js",
"build-samples": "cd examples && tsc -p .",
"test": "npm run build",
"unit": "nyc --reporter=lcov --reporter=text-lcov mocha -r ts-node/register -t 50000 ./tests/**/*.spec.ts --exit",
"unit": "npm run build-test && mocha -t 50000 test-dist/index.js",
"coverage": "npm run build-test && nyc --reporter=lcov mocha -t 65000 test-dist/index.js",
"prepack": "npm i && npm run build",
"extract-api": "tsc -p . && api-extractor run --local"
},

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

@ -0,0 +1,117 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import nodeResolve from "rollup-plugin-node-resolve";
import multiEntry from "rollup-plugin-multi-entry";
import cjs from "rollup-plugin-commonjs";
import json from "rollup-plugin-json";
import replace from "rollup-plugin-replace";
import { uglify } from "rollup-plugin-uglify";
import sourcemaps from "rollup-plugin-sourcemaps";
import path from "path";
const pkg = require("./package.json");
const depNames = Object.keys(pkg.dependencies);
const input = "dist-esm/lib/index.js";
const production = process.env.NODE_ENV === "production";
export function nodeConfig(test = false) {
const externalNodeBuiltins = ["events", "util"];
const baseConfig = {
input: input,
external: depNames.concat(externalNodeBuiltins),
output: { file: "dist/index.js", format: "cjs", sourcemap: true },
plugins: [
sourcemaps(),
replace({
delimiters: ["", ""],
values: {
// replace dynamic checks with if (true) since this is for node only.
// Allows rollup's dead code elimination to be more aggressive.
"if (isNode)": "if (true)"
}
}),
nodeResolve({ preferBuiltins: true }),
cjs(),
json()
]
};
baseConfig.external.push("crypto");
if (test) {
// entry point is every test file
baseConfig.input = "dist-esm/tests/**/*.spec.js";
baseConfig.plugins.unshift(multiEntry({ exports: false }));
// different output file
baseConfig.output.file = "test-dist/index.js";
// mark assert as external
baseConfig.external.push("assert", "fs", "path", "os", "tty", "child_process");
baseConfig.onwarn = (warning) => {
if (
warning.code === "CIRCULAR_DEPENDENCY" &&
warning.importer.indexOf(path.normalize("node_modules/chai/lib") === 0)
) {
// Chai contains circular references, but they are not fatal and can be ignored.
return;
}
console.error(`(!) ${warning.message}`);
};
} else if (production) {
baseConfig.plugins.push(uglify());
}
return baseConfig;
}
export function browserConfig(test = false) {
const baseConfig = {
input: input,
external: ["ms-rest-js"],
output: {
file: "browser/index.js",
format: "umd",
name: "ExampleClient",
sourcemap: true,
globals: { "ms-rest-js": "msRest" }
},
plugins: [
sourcemaps(),
replace(
// ms-rest-js is externalized so users must include it prior to using this bundle.
{
delimiters: ["", ""],
values: {
// replace dynamic checks with if (false) since this is for
// browser only. Rollup's dead code elimination will remove
// any code guarded by if (isNode) { ... }
"if (isNode)": "if (false)"
}
}
),
nodeResolve({
preferBuiltins: false,
browser: true
}),
cjs({
namedExports: { events: ["EventEmitter"] }
}),
json()
]
};
if (test) {
baseConfig.input = "dist-esm/tests/**/*.spec.js";
baseConfig.plugins.unshift(multiEntry({ exports: false }));
baseConfig.output.file = "test-browser/index.js";
} else if (production) {
baseConfig.plugins.push(uglify());
}
return baseConfig;
}

17
client/rollup.config.js Normal file
Просмотреть файл

@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as base from "./rollup.base.config";
const inputs = [];
if (!process.env.ONLY_BROWSER) {
inputs.push(base.nodeConfig());
}
// Disable this until we are ready to run rollup for the browser.
// if (!process.env.ONLY_NODE) {
// inputs.push(base.browserConfig());
// }
export default inputs;

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

@ -0,0 +1,6 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import * as base from "./rollup.base.config";
export default [base.nodeConfig(true) /*, base.browserConfig(true)*/];

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

@ -1,32 +1,32 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as chai from "chai";
import * as os from "os";
import chai from "chai";
import os from "os";
const should = chai.should();
import * as chaiAsPromised from "chai-as-promised";
import * as debugModule from "debug";
import * as dotenv from "dotenv";
import chaiAsPromised from "chai-as-promised";
import debugModule from "debug";
import dotenv from "dotenv";
dotenv.config();
chai.use(chaiAsPromised);
const debug = debugModule("azure:event-hubs:client-spec");
import { EventHubClient } from "../lib";
import { packageJsonInfo } from "../lib/util/constants";
function testFalsyValues(testFn: Function) {
[null, undefined, "", 0].forEach(function (value) {
function testFalsyValues(testFn: Function): void {
// tslint:disable-next-line: no-null-keyword
[null, undefined, "", 0].forEach(function (value: string | number | null | undefined): void {
testFn(value);
});
}
describe("EventHubClient", function () {
describe("#constructor", function () {
["endpoint", "entityPath", "sharedAccessKeyName", "sharedAccessKey"].forEach(function (prop) {
it("throws if config." + prop + " is falsy", function () {
testFalsyValues(function (falsyVal: any) {
const test = function () {
let config: any = { endpoint: "a", entityPath: "b", sharedAccessKey: "c", sharedAccessKeyName: "d" };
describe("EventHubClient", function (): void {
describe("#constructor", function (): void {
["endpoint", "entityPath", "sharedAccessKeyName", "sharedAccessKey"].forEach(function (prop: string): void {
it("throws if config." + prop + " is falsy", function (): void {
testFalsyValues(function (falsyVal: any): void {
const test = function (): EventHubClient {
const config: any = { endpoint: "a", entityPath: "b", sharedAccessKey: "c", sharedAccessKeyName: "d" };
config[prop] = falsyVal;
return new EventHubClient(config as any);
};
@ -36,94 +36,94 @@ describe("EventHubClient", function () {
});
});
describe(".fromConnectionString", function () {
it("throws when there is no connection string", function () {
testFalsyValues(function (value: any) {
const test = function () {
describe(".fromConnectionString", function (): void {
it("throws when there is no connection string", function (): void {
testFalsyValues(function (value: any): void {
const test = function (): EventHubClient {
return EventHubClient.createFromConnectionString(value);
};
test.should.throw(Error, "'connectionString' is a required parameter and must be of type: 'string'.");
});
});
it("throws when it cannot find the Event Hub path", function () {
it("throws when it cannot find the Event Hub path", function (): void {
const endpoint = "Endpoint=sb://abc";
const test = function () {
const test = function (): EventHubClient {
return EventHubClient.createFromConnectionString(endpoint);
};
test.should.throw(Error, `Either provide "path" or the "connectionString": "${endpoint}", must contain EntityPath="<path-to-the-entity>".`);
});
it("creates an EventHubClient from a connection string", function () {
it("creates an EventHubClient from a connection string", function (): void {
const client = EventHubClient.createFromConnectionString("Endpoint=sb://a;SharedAccessKeyName=b;SharedAccessKey=c;EntityPath=d");
client.should.be.an.instanceof(EventHubClient);
});
it("creates an EventHubClient from a connection string and an Event Hub path", function () {
it("creates an EventHubClient from a connection string and an Event Hub path", function (): void {
const client = EventHubClient.createFromConnectionString("Endpoint=sb://a;SharedAccessKeyName=b;SharedAccessKey=c", "path");
client.should.be.an.instanceof(EventHubClient);
});
});
});
function arrayOfIncreasingNumbersFromZero(length: any) {
function arrayOfIncreasingNumbersFromZero(length: any): Array<string> {
// tslint:disable-next-line: no-null-keyword
return Array.apply(null, new Array(length)).map((x: any, i: any) => { return `${i}`; });
}
before("validate environment", function () {
before("validate environment", function (): void {
should.exist(process.env.EVENTHUB_CONNECTION_STRING,
"define EVENTHUB_CONNECTION_STRING in your environment before running integration tests.");
should.exist(process.env.EVENTHUB_NAME,
"define EVENTHUB_NAME in your environment before running integration tests.");
});
const service = { connectionString: process.env.EVENTHUB_CONNECTION_STRING, path: process.env.EVENTHUB_NAME }
const service = { connectionString: process.env.EVENTHUB_CONNECTION_STRING, path: process.env.EVENTHUB_NAME };
describe("EventHubClient on ", function () {
this.timeout(60000);
describe("EventHubClient on ", function (): void {
let client: EventHubClient;
afterEach('close the connection', async function () {
afterEach('close the connection', async function (): Promise<void> {
if (client) {
debug(">>>>>>>> afterEach: closing the client.");
await client.close();
}
});
describe("user-agent", function () {
it("should correctly populate the default user agent", function (done) {
describe("user-agent", function (): void {
it("should correctly populate the default user agent", function (done: Mocha.Done): void {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
const packageVersion = packageJsonInfo.version;
const properties = client["_context"].connection.options.properties;
should.equal(properties["user-agent"], "/js-event-hubs");
should.equal(properties.product, "MSJSClient");
should.equal(properties.version, packageVersion);
should.equal(properties.framework, `Node/${process.version}`);
should.equal(properties.platform, `(${os.arch()}-${os.type()}-${os.release()})`);
should.equal(properties!["user-agent"], "/js-event-hubs");
should.equal(properties!.product, "MSJSClient");
should.equal(properties!.version, packageVersion);
should.equal(properties!.framework, `Node/${process.version}`);
should.equal(properties!.platform, `(${os.arch()}-${os.type()}-${os.release()})`);
done();
});
it("should correctly populate the custom user agent", function (done) {
it("should correctly populate the custom user agent", function (done: Mocha.Done): void {
const customua = "/js-event-processor-host=0.2.0";
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path,
{ userAgent: customua });
const packageVersion = packageJsonInfo.version;
const properties = client["_context"].connection.options.properties;
should.equal(properties["user-agent"], `/js-event-hubs,${customua}`);
should.equal(properties.product, "MSJSClient");
should.equal(properties.version, packageVersion);
should.equal(properties.framework, `Node/${process.version}`);
should.equal(properties.platform, `(${os.arch()}-${os.type()}-${os.release()})`);
should.equal(properties!["user-agent"], `/js-event-hubs,${customua}`);
should.equal(properties!.product, "MSJSClient");
should.equal(properties!.version, packageVersion);
should.equal(properties!.framework, `Node/${process.version}`);
should.equal(properties!.platform, `(${os.arch()}-${os.type()}-${os.release()})`);
done();
});
it("should throw an error if the user-agent string is greater than 128 characters in length", function (done) {
it("should throw an error if the user-agent string is greater than 128 characters in length", function (done: Mocha.Done): void {
const customua = "/js-event-processor-host=0.2.0zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path,
{ userAgent: customua });
} catch (err) {
err.message.should.match(/The user-agent string cannot be more than 128 characters in length.*/ig)
err.message.should.match(/The user-agent string cannot be more than 128 characters in length.*/ig);
done();
}
@ -131,23 +131,23 @@ describe("EventHubClient on ", function () {
});
describe("#close", function () {
it("is a no-op when the connection is already closed", function () {
describe("#close", function (): void {
it("is a no-op when the connection is already closed", function (): Chai.PromisedAssertion {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
return client.close().should.be.fulfilled;
});
});
describe("getPartitionIds", function () {
it("returns an array of partition IDs", async function () {
describe("getPartitionIds", function (): void {
it("returns an array of partition IDs", async function (): Promise<void> {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
const ids = await client.getPartitionIds();
ids.should.have.members(arrayOfIncreasingNumbersFromZero(ids.length));
});
});
describe("non existent eventhub", function () {
it("should throw MessagingEntityNotFoundError while getting hub runtime info", async function () {
describe("non existent eventhub", function (): void {
it("should throw MessagingEntityNotFoundError while getting hub runtime info", async function (): Promise<void> {
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, "bad" + Math.random());
await client.getHubRuntimeInformation();
@ -157,7 +157,7 @@ describe("EventHubClient on ", function () {
}
});
it("should throw MessagingEntityNotFoundError while getting partition runtime info", async function () {
it("should throw MessagingEntityNotFoundError while getting partition runtime info", async function (): Promise<void> {
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, "bad" + Math.random());
await client.getPartitionInformation("0");
@ -167,7 +167,7 @@ describe("EventHubClient on ", function () {
}
});
it("should throw MessagingEntityNotFoundError while creating a sender", async function () {
it("should throw MessagingEntityNotFoundError while creating a sender", async function (): Promise<void> {
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, "bad" + Math.random());
await client.send({ body: "Hello World" }, "0");
@ -177,7 +177,7 @@ describe("EventHubClient on ", function () {
}
});
it("should throw MessagingEntityNotFoundError while creating a receiver", async function () {
it("should throw MessagingEntityNotFoundError while creating a receiver", async function (): Promise<void> {
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, "bad" + Math.random());
await client.receiveBatch("0", 10, 5);
@ -188,8 +188,8 @@ describe("EventHubClient on ", function () {
});
});
describe("non existent consumer group", function () {
it("should throw MessagingEntityNotFoundError while creating a receiver", function (done) {
describe("non existent consumer group", function (): void {
it("should throw MessagingEntityNotFoundError while creating a receiver", function (done: Mocha.Done): void {
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
debug(">>>>>>>> client created.");
@ -202,8 +202,8 @@ describe("EventHubClient on ", function () {
// in aftereach the connection can be closed. closing the connection while the receiver
// link and it's session are being closed (and the session being removed from rhea's
// internal map) can create havoc.
setTimeout(() => { done(should.equal(error.name, "MessagingEntityNotFoundError")) }, 3000);
}
setTimeout(() => { done(should.equal(error.name, "MessagingEntityNotFoundError")); }, 3000);
};
client.receive("0", onMessage, onError, { consumerGroup: "some-randome-name" });
debug(">>>>>>>> attached the error handler on the receiver...");
} catch (err) {
@ -213,10 +213,10 @@ describe("EventHubClient on ", function () {
});
});
describe("on invalid partition ids like", function () {
describe("on invalid partition ids like", function (): void {
const invalidIds = ["XYZ", "-1", "1000", "-", " "];
invalidIds.forEach(function (id) {
it(`"${id}" should throw an error`, async function () {
invalidIds.forEach(function (id: string): void {
it(`"${id}" should throw an error`, async function (): Promise<void> {
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
await client.getPartitionInformation(id);
@ -228,9 +228,10 @@ describe("EventHubClient on ", function () {
});
});
// tslint:disable-next-line: no-null-keyword
const invalidIds2 = ["", null];
invalidIds2.forEach(function (id) {
it(`"${id}" should throw an error`, async function () {
invalidIds2.forEach(function (id: string | null): void {
it(`"${id}" should throw an error`, async function (): Promise<void> {
try {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
await client.getPartitionInformation(id as any);
@ -241,4 +242,4 @@ describe("EventHubClient on ", function () {
});
});
});
});
}).timeout(60000);

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

@ -1,43 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as chai from "chai";
import chai from "chai";
chai.should();
import { EventPosition } from "../lib";
describe("EventPosition", function () {
describe("happy", function () {
it("should create from an offset with inclusive false", function (done) {
describe("EventPosition", function (): void {
describe("happy", function (): void {
it("should create from an offset with inclusive false", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-offset > '1234'";
const pos = EventPosition.fromOffset("1234");
result.should.equal(pos.getExpression());
done();
});
it("should create from an offset with inclusive true", function (done) {
it("should create from an offset with inclusive true", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-offset >= '1234'";
const pos = EventPosition.fromOffset("1234", true);
result.should.equal(pos.getExpression());
done();
});
it("should create from a sequence with inclusive false", function (done) {
it("should create from a sequence with inclusive false", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-sequence-number > '0'";
const pos = EventPosition.fromSequenceNumber(0);
result.should.equal(pos.getExpression());
done();
});
it("should create from a sequence with inclusive true", function (done) {
it("should create from a sequence with inclusive true", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-sequence-number >= '0'";
const pos = EventPosition.fromSequenceNumber(0, true);
result.should.equal(pos.getExpression());
done();
});
it("should create from enqueuedTime with Date as Date", function (done) {
it("should create from enqueuedTime with Date as Date", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-enqueued-time > '1537406052971'";
const d = new Date("2018-09-20T01:14:12.971Z");
const pos = EventPosition.fromEnqueuedTime(d);
@ -45,7 +44,7 @@ describe("EventPosition", function () {
done();
});
it("should create from enqueuedTime with Date as number", function (done) {
it("should create from enqueuedTime with Date as number", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-enqueued-time > '1537406052971'";
const d = new Date("2018-09-20T01:14:12.971Z").getTime();
const pos = EventPosition.fromEnqueuedTime(d);
@ -53,29 +52,29 @@ describe("EventPosition", function () {
done();
});
it("should create custom filter", function (done) {
it("should create custom filter", function (done: Mocha.Done): void {
const custom = "amqp.annotation.x-opt-custom > 'foo-bar'";
const pos = EventPosition.withCustomFilter(custom);
custom.should.equal(pos.getExpression());
done();
});
it("should create from an offset from start", function (done) {
it("should create from an offset from start", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-offset > '-1'";
const pos = EventPosition.fromStart();
result.should.equal(pos.getExpression());
done();
});
it("should create from an offset from end", function (done) {
it("should create from an offset from end", function (done: Mocha.Done): void {
const result = "amqp.annotation.x-opt-offset > '@latest'";
const pos = EventPosition.fromEnd()
const pos = EventPosition.fromEnd();
result.should.equal(pos.getExpression());
done();
});
});
describe("sad", function () {
it("should fail if empty string is provided for offset", function (done) {
describe("sad", function (): void {
it("should fail if empty string is provided for offset", function (done: Mocha.Done): void {
try {
EventPosition.fromOffset("");
} catch (err) {
@ -84,4 +83,4 @@ describe("EventPosition", function () {
done();
});
});
});
});

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

@ -1,8 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as chai from "chai";
import chai from "chai";
chai.should();
import { EventData, Message } from "../lib";
@ -33,66 +32,66 @@ const testMessage: Message = {
const testEventData = EventData.fromAmqpMessage(testMessage);
const messageFromED = EventData.toAmqpMessage(testEventData);
describe("EventData", function () {
describe("fromAmqpMessage", function () {
it("populates annotations with the message annotations", function () {
describe("EventData", function (): void {
describe("fromAmqpMessage", function (): void {
it("populates annotations with the message annotations", function (): void {
testEventData.annotations!.should.equal(testAnnotations);
});
it("populates body with the message body", function () {
it("populates body with the message body", function (): void {
testEventData.body.should.equal(testBody);
});
it("populates the properties with the message properties", function () {
it("populates the properties with the message properties", function (): void {
testEventData.properties!.message_id!.should.equal(messageProperties.message_id!);
});
it("populates the application properties with the message application properties", function () {
it("populates the application properties with the message application properties", function (): void {
testEventData.applicationProperties!.should.equal(applicationProperties);
});
it("preserves the raw amqp message as-is.", function () {
it("preserves the raw amqp message as-is.", function (): void {
testEventData._raw_amqp_mesage!.should.equal(testMessage);
});
});
describe("toAmqpMessage", function () {
it("populates annotations with the message annotations", function () {
describe("toAmqpMessage", function (): void {
it("populates annotations with the message annotations", function (): void {
messageFromED.message_annotations!.should.equal(testAnnotations);
});
it("populates body with the message body", function () {
it("populates body with the message body", function (): void {
messageFromED.body.should.equal(testBody);
});
it("populates properties with the message properties", function () {
it("populates properties with the message properties", function (): void {
messageFromED.message_id!.should.equal(messageProperties.message_id);
});
it("populates application_properties of the message", function () {
it("populates application_properties of the message", function (): void {
messageFromED.application_properties!.should.equal(applicationProperties);
});
});
describe("properties", function () {
it("enqueuedTimeUtc gets the enqueued time from system properties", function () {
describe("properties", function (): void {
it("enqueuedTimeUtc gets the enqueued time from system properties", function (): void {
const testEventData = EventData.fromAmqpMessage(testMessage);
testEventData.enqueuedTimeUtc!.getTime().should.equal(testAnnotations["x-opt-enqueued-time"]);
});
it("offset gets the offset from system properties", function () {
it("offset gets the offset from system properties", function (): void {
const testEventData = EventData.fromAmqpMessage(testMessage);
testEventData.offset!.should.equal(testAnnotations["x-opt-offset"]);
});
it("sequenceNumber gets the sequence number from system properties", function () {
it("sequenceNumber gets the sequence number from system properties", function (): void {
const testEventData = EventData.fromAmqpMessage(testMessage);
testEventData.sequenceNumber!.should.equal(testAnnotations["x-opt-sequence-number"]);
});
it("partitionKey gets the sequence number from system properties", function () {
it("partitionKey gets the sequence number from system properties", function (): void {
const testEventData = EventData.fromAmqpMessage(testMessage);
testEventData.partitionKey!.should.equal(testAnnotations["x-opt-partition-key"]);
});
});
});
});

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

@ -1,38 +1,36 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as chai from "chai";
import chai from "chai";
const should = chai.should();
import * as chaiAsPromised from "chai-as-promised";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
import * as debugModule from "debug";
import debugModule from "debug";
const debug = debugModule("azure:event-hubs:hubruntime-spec");
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
import { EventHubClient } from "../lib";
describe("RuntimeInformation", function () {
this.timeout(60000);
describe("RuntimeInformation", function (): void {
let client: EventHubClient;
const service = { connectionString: process.env.EVENTHUB_CONNECTION_STRING, path: process.env.EVENTHUB_NAME };
before("validate environment", function () {
before("validate environment", function (): void {
should.exist(process.env.EVENTHUB_CONNECTION_STRING,
"define EVENTHUB_CONNECTION_STRING in your environment before running integration tests.");
should.exist(process.env.EVENTHUB_NAME,
"define EVENTHUB_NAME in your environment before running integration tests.");
});
afterEach('close the connection', async function () {
afterEach('close the connection', async function (): Promise<void> {
await client.close();
});
function arrayOfIncreasingNumbersFromZero(length: any) {
return Array.apply(null, new Array(length)).map((x: any, i: any) => { return `${i}`; });
function arrayOfIncreasingNumbersFromZero(length: any): Array<string> {
return Array.apply(undefined, new Array(length)).map((x: any, i: any) => { return `${i}`; });
}
it("gets the hub runtime information", async function () {
it("gets the hub runtime information", async function (): Promise<void> {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path,
{ userAgent: "/js-event-processor-host=0.2.0" });
const hubRuntimeInfo = await client.getHubRuntimeInformation();
@ -44,7 +42,7 @@ describe("RuntimeInformation", function () {
hubRuntimeInfo.createdAt.should.be.instanceof(Date);
});
it("gets the partition runtime information with partitionId as a string", async function () {
it("gets the partition runtime information with partitionId as a string", async function (): Promise<void> {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
const partitionRuntimeInfo = await client.getPartitionInformation("0");
debug(partitionRuntimeInfo);
@ -56,7 +54,7 @@ describe("RuntimeInformation", function () {
should.exist(partitionRuntimeInfo.lastEnqueuedOffset);
});
it("gets the partition runtime information with partitionId as a number", async function () {
it("gets the partition runtime information with partitionId as a number", async function (): Promise<void> {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
const partitionRuntimeInfo = await client.getPartitionInformation(0);
debug(partitionRuntimeInfo);
@ -68,30 +66,30 @@ describe("RuntimeInformation", function () {
should.exist(partitionRuntimeInfo.lastEnqueuedOffset);
});
it("should fail the partition runtime information when partitionId is not a number or string", async function () {
it("should fail the partition runtime information when partitionId is not a number or string", async function (): Promise<void> {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
try {
const partitionRuntimeInfo = await client.getPartitionInformation(true as any);
await client.getPartitionInformation(true as any);
} catch (err) {
err.message.should.equal("'partitionId' is a required parameter and must be of type: 'string' | 'number'.");
}
});
it("should fail the partition runtime information when partitionId is empty string", async function () {
it("should fail the partition runtime information when partitionId is empty string", async function (): Promise<void> {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
try {
const partitionRuntimeInfo = await client.getPartitionInformation("");
await client.getPartitionInformation("");
} catch (err) {
err.message.should.match(/.*The specified partition is invalid for an EventHub partition sender or receiver.*/ig);
}
});
it("should fail the partition runtime information when partitionId is a negative number", async function () {
it("should fail the partition runtime information when partitionId is a negative number", async function (): Promise<void> {
client = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
try {
const partitionRuntimeInfo = await client.getPartitionInformation(-1);
await client.getPartitionInformation(-1);
} catch (err) {
err.message.should.match(/.*The specified partition is invalid for an EventHub partition sender or receiver.*/ig);
}
});
});
}).timeout(60000);

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

@ -1,34 +1,32 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as dotenv from "dotenv";
import * as chai from "chai";
import dotenv from "dotenv";
import chai from "chai";
const should = chai.should();
import * as chaiAsPromised from "chai-as-promised";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
import * as debugModule from "debug";
import debugModule from "debug";
const debug = debugModule("azure:event-hubs:iothub-spec");
import { EventHubClient } from "../lib";
dotenv.config();
describe("EventHub Client with iothub connection string", function () {
this.timeout(30000);
describe("EventHub Client with iothub connection string", function (): void {
const service = { connectionString: process.env.IOTHUB_CONNECTION_STRING };
let client: EventHubClient;
before("validate environment", async function () {
before("validate environment", async function (): Promise<void> {
should.exist(process.env.IOTHUB_CONNECTION_STRING,
"define IOTHUB_CONNECTION_STRING in your environment before running integration tests.");
});
afterEach("close the connection", async function () {
afterEach("close the connection", async function (): Promise<void> {
if (client) {
debug(">>> After Each, closing the client...");
await client.close();
}
});
it("should be able to get hub runtime info", async function () {
it("should be able to get hub runtime info", async function (): Promise<void> {
client = await EventHubClient.createFromIotHubConnectionString(service.connectionString!);
const runtimeInfo = await client.getHubRuntimeInformation();
debug(">>> RuntimeInfo: ", runtimeInfo);
@ -38,9 +36,9 @@ describe("EventHub Client with iothub connection string", function () {
runtimeInfo.partitionIds.length.should.be.greaterThan(0);
});
it("should be able to receive messages from the event hub", async function () {
it("should be able to receive messages from the event hub", async function (): Promise<void> {
client = await EventHubClient.createFromIotHubConnectionString(service.connectionString!);
const datas = await client.receiveBatch("0", 15, 10);
debug(">>>> Received events from partition %s, %O", "0", datas);
});
});
}).timeout(30000);

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

@ -1,27 +1,25 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as uuid from "uuid/v4";
import * as chai from "chai";
import * as assert from "assert";
import uuid from "uuid/v4";
import chai from "chai";
import assert from "assert";
const should = chai.should();
import * as chaiAsPromised from "chai-as-promised";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
import * as debugModule from "debug";
import debugModule from "debug";
const debug = debugModule("azure:event-hubs:misc-spec");
import { EventPosition, EventHubClient, EventData, EventHubRuntimeInformation } from "../lib";
import { BatchingReceiver } from "../lib/batchingReceiver";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
describe("Misc tests", function () {
this.timeout(60000);
describe("Misc tests", function (): void {
const service = { connectionString: process.env.EVENTHUB_CONNECTION_STRING, path: process.env.EVENTHUB_NAME };
let client: EventHubClient = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
const client: EventHubClient = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
let breceiver: BatchingReceiver;
let hubInfo: EventHubRuntimeInformation;
before("validate environment", async function () {
before("validate environment", async function (): Promise<void> {
should.exist(process.env.EVENTHUB_CONNECTION_STRING,
"define EVENTHUB_CONNECTION_STRING in your environment before running integration tests.");
should.exist(process.env.EVENTHUB_NAME,
@ -29,11 +27,11 @@ describe("Misc tests", function () {
hubInfo = await client.getHubRuntimeInformation();
});
after("close the connection", async function () {
after("close the connection", async function (): Promise<void> {
await client.close();
});
it("should be able to send and receive a large message correctly", async function () {
it("should be able to send and receive a large message correctly", async function (): Promise<void> {
const bodysize = 220 * 1024;
const partitionId = hubInfo.partitionIds[0];
const msgString = "A".repeat(220 * 1024);
@ -57,7 +55,7 @@ describe("Misc tests", function () {
should.not.exist((data[0].properties || {}).message_id);
});
it("should be able to send and receive a JSON object as a message correctly", async function () {
it("should be able to send and receive a JSON object as a message correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const msgBody = {
id: '123-456-789',
@ -88,7 +86,7 @@ describe("Misc tests", function () {
should.not.exist((data[0].properties || {}).message_id);
});
it("should be able to send and receive an array as a message correctly", async function () {
it("should be able to send and receive an array as a message correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const msgBody = [
{
@ -114,10 +112,10 @@ describe("Misc tests", function () {
data.length.should.equal(1);
debug("Received message: %O", data);
assert.deepEqual(data[0].body, msgBody);
assert.strictEqual(data[0].properties.message_id, obj.properties.message_id);
assert.strictEqual(data[0].properties!.message_id, obj.properties!.message_id);
});
it("should be able to send a boolean as a message correctly", async function () {
it("should be able to send a boolean as a message correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const msgBody = true;
const obj: EventData = { body: msgBody };
@ -137,7 +135,7 @@ describe("Misc tests", function () {
should.not.exist((data[0].properties || {}).message_id);
});
it("should be able to send and receive batched messages correctly", async function () {
it("should be able to send and receive batched messages correctly", async function (): Promise<void> {
try {
const partitionId = hubInfo.partitionIds[0];
const offset = (await client.getPartitionInformation(partitionId)).lastEnqueuedOffset;
@ -146,9 +144,9 @@ describe("Misc tests", function () {
let data = await breceiver.receive(5, 10);
data.length.should.equal(0);
const messageCount = 5;
let d: EventData[] = [];
const d: EventData[] = [];
for (let i = 0; i < messageCount; i++) {
let obj: EventData = { body: `Hello EH ${i}` };
const obj: EventData = { body: `Hello EH ${i}` };
d.push(obj);
}
d[0].partitionKey = 'pk1234656';
@ -169,7 +167,7 @@ describe("Misc tests", function () {
}
});
it("should be able to send and receive batched messages as JSON objects correctly", async function () {
it("should be able to send and receive batched messages as JSON objects correctly", async function (): Promise<void> {
try {
const partitionId = hubInfo.partitionIds[0];
const offset = (await client.getPartitionInformation(partitionId)).lastEnqueuedOffset;
@ -178,9 +176,9 @@ describe("Misc tests", function () {
let data = await breceiver.receive(5, 5);
data.length.should.equal(0);
const messageCount = 5;
let d: EventData[] = [];
const d: EventData[] = [];
for (let i = 0; i < messageCount; i++) {
let obj: EventData = {
const obj: EventData = {
body: {
id: '123-456-789',
count: i,
@ -211,7 +209,7 @@ describe("Misc tests", function () {
data[0].body.count.should.equal(0);
data.length.should.equal(5);
for (const [index, message] of data.entries()) {
assert.strictEqual(message.properties.message_id, d[index].properties.message_id);
assert.strictEqual(message.properties!.message_id, d[index].properties!.message_id);
}
} catch (err) {
debug("should not have happened, uber catch....", err);
@ -219,18 +217,18 @@ describe("Misc tests", function () {
}
});
it("should consistently send messages with partitionkey to a partitionId", async function () {
it("should consistently send messages with partitionkey to a partitionId", async function (): Promise<void> {
const msgToSendCount = 50;
let partitionOffsets: any = {};
const partitionOffsets: any = {};
debug("Discovering end of stream on each partition.");
const partitionIds = hubInfo.partitionIds;
for (let id of partitionIds) {
for (const id of partitionIds) {
const pInfo = await client.getPartitionInformation(id);
partitionOffsets[id] = pInfo.lastEnqueuedOffset;
debug(`Partition ${id} has last message with offset ${pInfo.lastEnqueuedOffset}.`);
}
debug("Sending %d messages.", msgToSendCount);
function getRandomInt(max: number) {
function getRandomInt(max: number): number {
return Math.floor(Math.random() * Math.floor(max));
}
for (let i = 0; i < msgToSendCount; i++) {
@ -238,13 +236,13 @@ describe("Misc tests", function () {
await client.send({ body: "Hello EventHub " + i, partitionKey: partitionKey.toString() });
}
debug("Starting to receive all messages from each partition.");
let partitionMap: any = {};
const partitionMap: any = {};
let totalReceived = 0;
for (let id of partitionIds) {
let data = await client.receiveBatch(id, 50, 10, { eventPosition: EventPosition.fromOffset(partitionOffsets[id]) });
for (const id of partitionIds) {
const data = await client.receiveBatch(id, 50, 10, { eventPosition: EventPosition.fromOffset(partitionOffsets[id]) });
debug(`Received ${data.length} messages from partition ${id}.`);
for (let d of data) {
debug(">>>> _raw_amqp_mesage: ", d._raw_amqp_mesage)
for (const d of data) {
debug(">>>> _raw_amqp_mesage: ", d._raw_amqp_mesage);
const pk = d.partitionKey as string;
debug("pk: ", pk);
if (partitionMap[pk] && partitionMap[pk] !== id) {
@ -258,4 +256,4 @@ describe("Misc tests", function () {
}
totalReceived.should.equal(msgToSendCount);
});
});
}).timeout(60000);

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

@ -1,27 +1,25 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as chai from "chai";
import * as uuid from "uuid/v4";
import chai from "chai";
import uuid from "uuid/v4";
const should = chai.should();
import * as chaiAsPromised from "chai-as-promised";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
import * as debugModule from "debug";
import debugModule from "debug";
const debug = debugModule("azure:event-hubs:receiver-spec");
import { EventPosition, EventHubClient, EventData, EventHubRuntimeInformation, delay } from "../lib";
import { BatchingReceiver } from "../lib/batchingReceiver"
import { EventPosition, EventHubClient, EventData, EventHubRuntimeInformation, MessagingError } from "../lib";
import { BatchingReceiver } from "../lib/batchingReceiver";
import { ReceiveHandler } from "../lib/streamingReceiver";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
describe("EventHub Receiver", function () {
this.timeout(60000);
describe("EventHub Receiver", function (): void {
const service = { connectionString: process.env.EVENTHUB_CONNECTION_STRING, path: process.env.EVENTHUB_NAME };
let client: EventHubClient = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
const client: EventHubClient = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
let breceiver: BatchingReceiver;
let hubInfo: EventHubRuntimeInformation;
before("validate environment", async function () {
before("validate environment", async function (): Promise<void> {
should.exist(process.env.EVENTHUB_CONNECTION_STRING,
"define EVENTHUB_CONNECTION_STRING in your environment before running integration tests.");
should.exist(process.env.EVENTHUB_NAME,
@ -29,30 +27,30 @@ describe("EventHub Receiver", function () {
hubInfo = await client.getHubRuntimeInformation();
});
after("close the connection", async function () {
after("close the connection", async function (): Promise<void> {
await client.close();
});
afterEach("close the sender link", async function () {
afterEach("close the sender link", async function (): Promise<void> {
if (breceiver) {
await breceiver.close();
debug("After each - Batching Receiver closed.");
}
});
describe("with partitionId 0 as number", function () {
it("should work for receiveBatch", async function () {
describe("with partitionId 0 as number", function (): void {
it("should work for receiveBatch", async function (): Promise<void> {
const result = await client.receiveBatch(0, 10, 20, { eventPosition: EventPosition.fromSequenceNumber(0) });
should.equal(true, Array.isArray(result));
});
it("should work for receive", function (done) {
let rcvHandler;
it("should work for receive", function (done: Mocha.Done): void {
let rcvHandler: ReceiveHandler;
let stopCalled = false;
const onError = (error) => {
const onError = (error: MessagingError | Error) => {
debug(">>>> An error occurred: %O", error);
}
const onMsg = (data) => {
};
const onMsg = (data: EventData) => {
debug(">>>> Received Data: %O", data);
if (!stopCalled) {
stopCalled = true;
@ -67,13 +65,13 @@ describe("EventHub Receiver", function () {
});
});
describe("with EventPosition specified as", function () {
it("'from end of stream' should receive messages correctly", async function () {
describe("with EventPosition specified as", function (): void {
it("'from end of stream' should receive messages correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
for (let i = 0; i < 10; i++) {
const ed: EventData = {
body: "Hello awesome world " + i
}
};
await client.send(ed, partitionId);
debug("sent message - " + i);
}
@ -87,7 +85,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid
}
}
};
await client.send(ed, partitionId);
debug(">>>>>>> Sent the new message after creating the receiver. We should only receive this message.");
const datas = await breceiver.receive(10, 5);
@ -99,7 +97,7 @@ describe("EventHub Receiver", function () {
datas2.length.should.equal(0);
});
it("after a particular offset' should receive messages correctly", async function () {
it("after a particular offset' should receive messages correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const pInfo = await client.getPartitionInformation(partitionId);
debug(`Creating new receiver with last enqueued offset: "${pInfo.lastEnqueuedOffset}".`);
@ -114,7 +112,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid
}
}
};
await client.send(ed, "0");
debug("Sent the new message after creating the receiver. We should only receive this message.");
const datas = await breceiver.receive(10, 10);
@ -126,7 +124,7 @@ describe("EventHub Receiver", function () {
datas2.length.should.equal(0);
});
it("after a particular offset with isInclusive true' should receive messages correctly", async function () {
it("after a particular offset with isInclusive true' should receive messages correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const uid = uuid();
const ed: EventData = {
@ -134,7 +132,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid
}
}
};
await client.send(ed, partitionId);
debug(`Sent message 1 with stamp: ${uid}.`);
const pInfo = await client.getPartitionInformation(partitionId);
@ -144,7 +142,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid2
}
}
};
await client.send(ed2, partitionId);
debug(`Sent message 2 with stamp: ${uid} after getting the enqueued offset.`);
debug(`Creating new receiver with last enqueued offset: "${pInfo.lastEnqueuedOffset}".`);
@ -160,7 +158,7 @@ describe("EventHub Receiver", function () {
datas2.length.should.equal(0);
});
it("'from a particular enqueued time' should receive messages correctly", async function () {
it("'from a particular enqueued time' should receive messages correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const pInfo = await client.getPartitionInformation(partitionId);
debug(`Creating new receiver with last enqueued time: "${pInfo.lastEnqueuedTimeUtc}".`);
@ -175,7 +173,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid
}
}
};
await client.send(ed, partitionId);
debug("Sent the new message after creating the receiver. We should only receive this message.");
const datas = await breceiver.receive(10, 10);
@ -183,11 +181,11 @@ describe("EventHub Receiver", function () {
datas.length.should.equal(1);
datas[0].applicationProperties!.stamp.should.equal(uid);
debug("Next receive on this partition should not receive any messages.");
const datas2 = await breceiver.receive(10, 5)
const datas2 = await breceiver.receive(10, 5);
datas2.length.should.equal(0);
});
it("'after the particular sequence number' should receive messages correctly", async function () {
it("'after the particular sequence number' should receive messages correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const pInfo = await client.getPartitionInformation(partitionId);
// send a new message. We should only receive this new message.
@ -197,7 +195,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid
}
}
};
await client.send(ed, partitionId);
debug("Sent the new message after getting the partition runtime information. We should only receive this message.");
debug(`Creating new receiver with last enqueued sequence number: "${pInfo.lastSequenceNumber}".`);
@ -211,7 +209,7 @@ describe("EventHub Receiver", function () {
datas2.length.should.equal(0);
});
it("'after the particular sequence number' with isInclusive true should receive messages correctly", async function () {
it("'after the particular sequence number' with isInclusive true should receive messages correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const uid = uuid();
const ed: EventData = {
@ -219,7 +217,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid
}
}
};
await client.send(ed, partitionId);
debug(`Sent message 1 with stamp: ${uid}.`);
const pInfo = await client.getPartitionInformation(partitionId);
@ -229,7 +227,7 @@ describe("EventHub Receiver", function () {
applicationProperties: {
stamp: uid2
}
}
};
await client.send(ed2, partitionId);
debug(`Sent message 2 with stamp: ${uid}.`);
debug(`Creating new receiver with last sequence number: "${pInfo.lastSequenceNumber}".`);
@ -246,8 +244,8 @@ describe("EventHub Receiver", function () {
});
});
describe("in batch mode", function () {
it("should receive messages correctly", async function () {
describe("in batch mode", function (): void {
it("should receive messages correctly", async function (): Promise<void> {
const partitionId = hubInfo.partitionIds[0];
const datas = await client.receiveBatch(partitionId, 5, 10);
debug("received messages: ", datas);
@ -255,8 +253,8 @@ describe("EventHub Receiver", function () {
});
});
// describe("with receiverRuntimeMetricEnabled", function () {
// it("should have ReceiverRuntimeInfo populated", async function () {
// describe("with receiverRuntimeMetricEnabled", function (): void {
// it("should have ReceiverRuntimeInfo populated", async function (): Promise<void> {
// const partitionId = hubInfo.partitionIds[0];
// sender = client.createSender(partitionId);
// for (let i = 0; i < 10; i++) {
@ -283,21 +281,22 @@ describe("EventHub Receiver", function () {
// });
// });
describe("with epoch", function () {
it("should behave correctly when a receiver with lower epoch value is connected after a receiver with higher epoch value to a partition in a consumer group", function (done) {
describe("with epoch", function (): void {
it("should behave correctly when a receiver with lower epoch value is connected after a receiver with higher epoch value to a partition in a consumer group", function (done: Mocha.Done): void {
const partitionId = hubInfo.partitionIds[0];
let epochRcvr1: ReceiveHandler, epochRcvr2: ReceiveHandler
const onError = (error) => {
let epochRcvr1: ReceiveHandler;
let epochRcvr2: ReceiveHandler;
const onError = (error: MessagingError | Error) => {
debug(">>>> epoch Receiver 1", error);
throw new Error("An Error should not have happened for epoch receiver with epoch value 2.");
};
const onMsg = (data) => {
const onMsg = (data: EventData) => {
debug(">>>> epoch Receiver 1", data);
};
epochRcvr1 = client.receive(partitionId, onMsg, onError, { epoch: 2, eventPosition: EventPosition.fromEnd() });
debug("Created epoch receiver 1 %s", epochRcvr1.name);
setTimeout(() => {
const onError2 = (error) => {
const onError2 = (error: MessagingError | Error) => {
debug(">>>> epoch Receiver 2", error);
should.exist(error);
should.equal(error.name, "ReceiverDisconnectedError");
@ -312,18 +311,19 @@ describe("EventHub Receiver", function () {
done();
});
};
const onMsg2 = (data) => {
const onMsg2 = (data: EventData) => {
debug(">>>> epoch Receiver 2", data);
};
epochRcvr2 = client.receive(partitionId, onMsg, onError2, { epoch: 1, eventPosition: EventPosition.fromEnd() });
epochRcvr2 = client.receive(partitionId, onMsg2, onError2, { epoch: 1, eventPosition: EventPosition.fromEnd() });
debug("Created epoch receiver 2 %s", epochRcvr2.name);
}, 3000);
});
it("should behave correctly when a receiver with higher epoch value is connected after a receiver with lower epoch value to a partition in a consumer group", function (done) {
it("should behave correctly when a receiver with higher epoch value is connected after a receiver with lower epoch value to a partition in a consumer group", function (done: Mocha.Done): void {
const partitionId = hubInfo.partitionIds[0];
let epochRcvr1: ReceiveHandler, epochRcvr2: ReceiveHandler
const onError = (error) => {
let epochRcvr1: ReceiveHandler;
let epochRcvr2: ReceiveHandler;
const onError = (error: MessagingError | Error) => {
debug(">>>> epoch Receiver 1", error);
should.exist(error);
should.equal(error.name, "ReceiverDisconnectedError");
@ -338,38 +338,38 @@ describe("EventHub Receiver", function () {
done();
});
};
const onMsg = (data) => {
const onMsg = (data: EventData) => {
debug(">>>> epoch Receiver 1", data);
};
epochRcvr1 = client.receive(partitionId, onMsg, onError, { epoch: 1, eventPosition: EventPosition.fromEnd() });
debug("Created epoch receiver 1 %s", epochRcvr1.name);
setTimeout(() => {
const onError2 = (error) => {
const onError2 = (error: MessagingError | Error) => {
debug(">>>> epoch Receiver 2", error);
throw new Error("An Error should not have happened for epoch receiver with epoch value 2.");
};
const onMsg2 = (data) => {
const onMsg2 = (data: EventData) => {
debug(">>>> epoch Receiver 2", data);
};
epochRcvr2 = client.receive(partitionId, onMsg, onError2, { epoch: 2, eventPosition: EventPosition.fromEnd() });
epochRcvr2 = client.receive(partitionId, onMsg2, onError2, { epoch: 2, eventPosition: EventPosition.fromEnd() });
debug("Created epoch receiver 2 %s", epochRcvr2.name);
}, 3000);
});
it("should behave correctly when a non epoch receiver is created after an epoch receiver", function (done) {
it("should behave correctly when a non epoch receiver is created after an epoch receiver", function (done: Mocha.Done): void {
const partitionId = hubInfo.partitionIds[0];
let epochRcvr: ReceiveHandler, nonEpochRcvr: ReceiveHandler;
let events: EventData[] = [];
const onerr1 = (error) => {
let epochRcvr: ReceiveHandler;
let nonEpochRcvr: ReceiveHandler;
const onerr1 = (error: MessagingError | Error) => {
debug(">>>> epoch Receiver ", error);
throw new Error("An Error should not have happened for epoch receiver with epoch value 1.");
};
const onmsg1 = (data) => {
const onmsg1 = (data: EventData) => {
debug(">>>> epoch Receiver ", data);
};
epochRcvr = client.receive(partitionId, onmsg1, onerr1, { epoch: 1, eventPosition: EventPosition.fromEnd() });
debug("Created epoch receiver %s", epochRcvr.name);
const onerr2 = (error) => {
const onerr2 = (error: MessagingError | Error) => {
debug(">>>> non epoch Receiver", error);
should.exist(error);
should.equal(error.name, "ReceiverDisconnectedError");
@ -384,18 +384,18 @@ describe("EventHub Receiver", function () {
done();
});
};
const onmsg2 = (data) => {
const onmsg2 = (data: EventData) => {
debug(">>>> non epoch Receiver", data);
};
nonEpochRcvr = client.receive(partitionId, onmsg2, onerr2, { eventPosition: EventPosition.fromEnd() });
debug("Created non epoch receiver %s", nonEpochRcvr.name);
});
it("should behave correctly when an epoch receiver is created after a non epoch receiver", function (done) {
it("should behave correctly when an epoch receiver is created after a non epoch receiver", function (done: Mocha.Done): void {
const partitionId = hubInfo.partitionIds[0];
let epochRcvr: ReceiveHandler, nonEpochRcvr: ReceiveHandler;
let events: EventData[] = [];
const onerr3 = (error) => {
let epochRcvr: ReceiveHandler;
let nonEpochRcvr: ReceiveHandler;
const onerr3 = (error: MessagingError | Error) => {
debug(">>>> non epoch Receiver", error);
should.exist(error);
should.equal(error.name, "ReceiverDisconnectedError");
@ -410,17 +410,17 @@ describe("EventHub Receiver", function () {
done();
});
};
const onmsg3 = (data) => {
const onmsg3 = (data: EventData) => {
debug(">>>> non epoch Receiver", data);
};
nonEpochRcvr = client.receive(partitionId, onmsg3, onerr3, { eventPosition: EventPosition.fromEnd() });
debug("Created non epoch receiver %s", nonEpochRcvr.name);
setTimeout(() => {
const onerr4 = (error) => {
const onerr4 = (error: MessagingError | Error) => {
debug(">>>> epoch Receiver ", error);
throw new Error("OnErr4 >> An Error should not have happened for epoch receiver with epoch value 1.");
};
const onmsg4 = (data) => {
const onmsg4 = (data: EventData) => {
debug(">>>> epoch Receiver ", data);
};
epochRcvr = client.receive(partitionId, onmsg4, onerr4, { epoch: 1, eventPosition: EventPosition.fromEnd() });
@ -429,12 +429,12 @@ describe("EventHub Receiver", function () {
});
});
describe("Negative scenarios", function () {
describe("Negative scenarios", function (): void {
describe("on invalid partition ids like", function () {
describe("on invalid partition ids like", function (): void {
const invalidIds = ["XYZ", "-1", "1000", "-"];
invalidIds.forEach(function (id) {
it(`"${id}" should throw an error`, async function () {
invalidIds.forEach(function (id: string): void {
it(`"${id}" should throw an error`, async function (): Promise<void> {
try {
debug("Created receiver and will be receiving messages from partition id ...", id);
const d = await client.receiveBatch(id, 10, 3);
@ -447,7 +447,7 @@ describe("EventHub Receiver", function () {
});
});
it(`" " should throw an invalid EventHub address error`, async function () {
it(`" " should throw an invalid EventHub address error`, async function (): Promise<void> {
try {
const id = " ";
debug("Created receiver and will be receiving messages from partition id ...", id);
@ -460,11 +460,11 @@ describe("EventHub Receiver", function () {
}
});
const invalidIds2 = ["", null];
invalidIds2.forEach(function (id) {
it(`"${id}" should throw an error`, async function () {
const invalidIds2 = [""];
invalidIds2.forEach(function (id: string): void {
it(`"${id}" should throw an error`, async function (): Promise<void> {
try {
const d = await client.receiveBatch(id, 10, 3);
await client.receiveBatch(id, 10, 3);
} catch (err) {
debug(`>>>> Received error - `, err);
should.exist(err);
@ -473,21 +473,21 @@ describe("EventHub Receiver", function () {
});
});
it("should receive 'QuotaExceededError' when attempting to connect more than 5 receivers to a partition in a consumer group", function (done) {
it("should receive 'QuotaExceededError' when attempting to connect more than 5 receivers to a partition in a consumer group", function (done: Mocha.Done): void {
const partitionId = hubInfo.partitionIds[0];
let rcvHndlrs: ReceiveHandler[] = [];
let rcvrs: any[] = [];
const rcvHndlrs: ReceiveHandler[] = [];
const rcvrs: any[] = [];
debug(">>> Receivers length: ", rcvHndlrs.length);
for (let i = 1; i <= 5; i++) {
const rcvrId = `rcvr-${i}`;
debug(rcvrId);
const onMsg = (data) => {
const onMsg = (data: EventData) => {
if (!rcvrs[i]) {
rcvrs[i] = rcvrId;
debug("receiver id %s", rcvrId);
}
};
const onError = (err) => {
const onError = (err: MessagingError | Error) => {
debug("@@@@ Error received by receiver %s", rcvrId);
debug(err);
};
@ -497,14 +497,14 @@ describe("EventHub Receiver", function () {
debug(">>> Attached message handlers to each receiver.");
setTimeout(() => {
debug(`Created 6th receiver - "rcvr-6"`);
const onmsg2 = (data) => {
//debug(data);
const onmsg2 = (data: EventData) => {
// debug(data);
};
const onerr2 = (err) => {
const onerr2 = (err: MessagingError | Error) => {
debug("@@@@ Error received by receiver rcvr-6");
debug(err);
should.equal(err.name, "QuotaExceededError");
let promises = [];
const promises = [];
for (const rcvr of rcvHndlrs) {
promises.push(rcvr.stop());
}
@ -515,10 +515,10 @@ describe("EventHub Receiver", function () {
debug("An error occurred while closing the receiver in the 'QuotaExceededError' test.", err);
done();
});
}
};
const failedRcvHandler = client.receive(partitionId, onmsg2, onerr2, { eventPosition: EventPosition.fromStart(), identifier: "rcvr-6" });
rcvHndlrs.push(failedRcvHandler);
}, 5000);
});
});
});
}).timeout(60000);

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

@ -1,59 +1,57 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import "mocha";
import * as chai from "chai";
import chai from "chai";
const should = chai.should();
import * as chaiAsPromised from "chai-as-promised";
import chaiAsPromised from "chai-as-promised";
chai.use(chaiAsPromised);
import * as debugModule from "debug";
import debugModule from "debug";
const debug = debugModule("azure:event-hubs:sender-spec");
import { EventHubClient, EventData } from "../lib";
import * as dotenv from "dotenv";
import dotenv from "dotenv";
dotenv.config();
describe("EventHub Sender", function () {
this.timeout(20000);
describe("EventHub Sender", function (): void {
const service = { connectionString: process.env.EVENTHUB_CONNECTION_STRING, path: process.env.EVENTHUB_NAME };
let client: EventHubClient = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
before("validate environment", function () {
const client: EventHubClient = EventHubClient.createFromConnectionString(service.connectionString!, service.path);
before("validate environment", function (): void {
should.exist(process.env.EVENTHUB_CONNECTION_STRING,
"define EVENTHUB_CONNECTION_STRING in your environment before running integration tests.");
should.exist(process.env.EVENTHUB_NAME,
"define EVENTHUB_NAME in your environment before running integration tests.");
});
after("close the connection", async function () {
after("close the connection", async function (): Promise<void> {
debug("Closing the client..");
await client.close();
});
describe("Single message", function () {
it("should be sent successfully.", async function () {
let data: EventData = {
describe("Single message", function (): void {
it("should be sent successfully.", async function (): Promise<void> {
const data: EventData = {
body: "Hello World"
}
};
const delivery = await client.send(data);
// debug(delivery);
delivery.format.should.equal(0);
delivery.settled.should.equal(true);
delivery.remote_settled.should.equal(true);
});
it("with partition key should be sent successfully.", async function () {
let data: EventData = {
it("with partition key should be sent successfully.", async function (): Promise<void> {
const data: EventData = {
body: "Hello World with partition key",
partitionKey: "p1234"
}
};
const delivery = await client.send(data);
// debug(delivery);
delivery.format.should.equal(0);
delivery.settled.should.equal(true);
delivery.remote_settled.should.equal(true);
});
it("should be sent successfully to a specific partition.", async function () {
let data: EventData = {
it("should be sent successfully to a specific partition.", async function (): Promise<void> {
const data: EventData = {
body: "Hello World"
}
};
const delivery = await client.send(data, "0");
// debug(delivery);
delivery.format.should.equal(0);
@ -62,9 +60,9 @@ describe("EventHub Sender", function () {
});
});
describe("Batch message", function () {
it("should be sent successfully.", async function () {
let data: EventData[] = [
describe("Batch message", function (): void {
it("should be sent successfully.", async function (): Promise<void> {
const data: EventData[] = [
{
body: "Hello World 1"
},
@ -78,8 +76,8 @@ describe("EventHub Sender", function () {
delivery.settled.should.equal(true);
delivery.remote_settled.should.equal(true);
});
it("with partition key should be sent successfully.", async function () {
let data: EventData[] = [
it("with partition key should be sent successfully.", async function (): Promise<void> {
const data: EventData[] = [
{
body: "Hello World 1",
partitionKey: "p1234"
@ -94,8 +92,8 @@ describe("EventHub Sender", function () {
delivery.settled.should.equal(true);
delivery.remote_settled.should.equal(true);
});
it("should be sent successfully to a specific partition.", async function () {
let data: EventData[] = [
it("should be sent successfully to a specific partition.", async function (): Promise<void> {
const data: EventData[] = [
{
body: "Hello World 1"
},
@ -111,9 +109,9 @@ describe("EventHub Sender", function () {
});
});
describe("Multiple messages", function () {
it("should be sent successfully in parallel", async function () {
let promises = [];
describe("Multiple messages", function (): void {
it("should be sent successfully in parallel", async function (): Promise<void> {
const promises = [];
for (let i = 0; i < 5; i++) {
promises.push(client.send({ body: `Hello World ${i}` }));
}
@ -126,15 +124,15 @@ describe("EventHub Sender", function () {
delivery.remote_settled.should.equal(true);
}
});
it("should be sent successfully in parallel by multiple senders", async function () {
it("should be sent successfully in parallel by multiple senders", async function (): Promise<void> {
const senderCount = 3;
try {
let promises = [];
const promises = [];
for (let i = 0; i < senderCount; i++) {
if (i == 0) {
if (i === 0) {
debug(">>>>> Sending a message to partition %d", i);
promises.push(client.send({ body: `Hello World ${i}` }, i));
} else if (i == 1) {
} else if (i === 1) {
debug(">>>>> Sending a message to partition %d", i);
promises.push(client.send({ body: `Hello World ${i}` }, i));
} else {
@ -156,10 +154,10 @@ describe("EventHub Sender", function () {
}
});
it("should fail when a message greater than 256 KB is sent and succeed when a normal message is sent after that on the same link.", async function () {
let data: EventData = {
it("should fail when a message greater than 256 KB is sent and succeed when a normal message is sent after that on the same link.", async function (): Promise<void> {
const data: EventData = {
body: Buffer.from("Z".repeat(300000))
}
};
try {
debug("Sendina message of 300KB...");
await client.send(data, "0");
@ -177,11 +175,11 @@ describe("EventHub Sender", function () {
});
});
describe("Negative scenarios", function () {
it("a message greater than 256 KB should fail.", async function () {
let data: EventData = {
describe("Negative scenarios", function (): void {
it("a message greater than 256 KB should fail.", async function (): Promise<void> {
const data: EventData = {
body: Buffer.from("Z".repeat(300000))
}
};
try {
await client.send(data);
} catch (err) {
@ -192,10 +190,11 @@ describe("EventHub Sender", function () {
}
});
describe("on invalid partition ids like", function () {
describe("on invalid partition ids like", function (): void {
// tslint:disable-next-line: no-null-keyword
const invalidIds = ["XYZ", "-1", "1000", "-", null];
invalidIds.forEach(function (id) {
it(`"${id}" should throw an error`, async function () {
invalidIds.forEach(function (id: string | null): void {
it(`"${id}" should throw an error`, async function (): Promise<void> {
try {
debug("Created sender and will be sending a message to partition id ...", id);
await client.send({ body: "Hello world!" }, id as any);
@ -209,8 +208,8 @@ describe("EventHub Sender", function () {
});
const invalidIds2 = ["", " "];
invalidIds2.forEach(function (id) {
it(`"${id}" should throw an invalid EventHub address error`, async function () {
invalidIds2.forEach(function (id: string): void {
it(`"${id}" should throw an invalid EventHub address error`, async function (): Promise<void> {
try {
debug("Created sender and will be sending a message to partition id ...", id);
await client.send({ body: "Hello world!" }, id as any);
@ -224,4 +223,4 @@ describe("EventHub Sender", function () {
});
});
});
});
}).timeout(20000);

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

@ -1,29 +1,45 @@
{
"compilerOptions": {
"module": "commonjs",
"preserveConstEnums": true,
"sourceMap": true,
"newLine": "LF",
"target": "es2015",
"importHelpers": true,
"moduleResolution": "node",
"noImplicitReturns": true,
"outDir": "dist",
"allowJs": false,
"noUnusedLocals":true,
"strict": true,
"declaration": true,
"declarationDir": "./typings"
/* Basic Options */
"target": "es6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
"module": "es6" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
"declaration": true /* Generates corresponding '.d.ts' file. */,
"declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
"outDir": "./dist-esm" /* Redirect output structure to the directory. */,
"declarationDir": "./typings", /* Output directory for generated declaration files.*/
"importHelpers": true /* Import emit helpers from 'tslib'. */,
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
/* Additional Checks */
"noUnusedLocals": true, /* Report errors on unused locals. */
/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
"allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */,
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
/* Experimental Options */
"forceConsistentCasingInFileNames": true,
/* Other options */
"newLine": "LF", /* Use the specified end of line sequence to be used when emitting files: "crlf" (windows) or "lf" (unix).*/
"allowJs": false, /* Don't allow JavaScript files to be compiled.*/
},
"compileOnSave": true,
"exclude": [
"node_modules",
"testhub",
"typings/**",
"processor"
"./examples/**/*.ts"
],
"include": [
"./lib/**/*.ts",
"./examples/**/*.ts"
"./tests/**/*.ts",
]
}
}

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

@ -36,36 +36,22 @@
"no-empty": true,
"no-invalid-this": true,
"no-null-keyword": true,
"no-string-literal": true,
"no-switch-case-fall-through": true,
"no-unsafe-finally": true,
"no-unused-expression": true,
"no-unused-variable": false,
"no-use-before-declare": true,
"no-var-keyword": true,
"no-floating-promises": true,
"triple-equals": [
true,
"allow-null-check",
"allow-undefined-check"
],
"no-return-await": true,
"triple-equals": [true, "allow-null-check", "allow-undefined-check"],
"use-isnan": true,
"eofline": true,
"indent": [
true,
"spaces"
],
"indent": [true, "spaces"],
"no-trailing-whitespace": true,
"arrow-parens": true,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"interface-name": [
true,
"never-prefix"
],
"comment-format": [true, "check-space"],
"interface-name": [true, "never-prefix"],
"jsdoc-format": true,
"new-parens": true,
"one-line": [
@ -75,18 +61,9 @@
"check-else",
"check-open-brace"
],
"one-variable-per-declaration": [
true,
"ignore-for-loop"
],
"semicolon": [
true,
"always"
],
"curly": [
true,
"ignore-same-line"
],
"one-variable-per-declaration": [true, "ignore-for-loop"],
"semicolon": [true, "always"],
"curly": [true, "ignore-same-line"],
"variable-name": [
true,
"check-format",
@ -103,4 +80,4 @@
"check-type"
]
}
}
}