Task 9901543: Remediate security vulnerabilities (#1590)

Task 9901523: Open Source Security Review
- Remove Legacy Code from master
This commit is contained in:
Nev 2021-06-23 12:43:50 -07:00 коммит произвёл GitHub
Родитель 01b98207d3
Коммит a7ee32c8b6
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
246 изменённых файлов: 217 добавлений и 54013 удалений

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

@ -1,4 +0,0 @@
cd legacy
npm install
grunt
grunt test

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

@ -8,7 +8,6 @@
"target": "es5",
"alwaysStrict": true,
"declaration": true,
"rootDir": "AISKU",
"out": "Tests/Selenium/appinsights-sdk.tests.js"
},
"include": [

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

@ -44,7 +44,7 @@
"grunt": "^1.3.0",
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"grunt-tslint": "^5.0.2",
"globby": "^11.0.0",
"magic-string": "^0.25.7",

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

@ -24,7 +24,7 @@
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"globby": "^11.0.0",
"magic-string": "^0.25.7",
"@rollup/plugin-commonjs": "^15.1.0",

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

@ -28,7 +28,7 @@
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"globby": "^11.0.0",
"magic-string": "^0.25.7",
"@rollup/plugin-commonjs": "^15.1.0",

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

@ -32,7 +32,7 @@
"@types/sinon": "4.3.3",
"grunt": "^1.3.0",
"grunt-contrib-qunit": "^3.1.0",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"tslint": "^5.19.0",
"tslint-config-prettier": "^1.18.0",
"tslint-microsoft-contrib": "^5.2.1",

3157
common/config/rush/npm-shrinkwrap.json сгенерированный

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

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

@ -41,7 +41,7 @@
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"tslint": "^5.19.0",
"tslint-config-prettier": "^1.18.0",
"qunit": "^2.9.1",

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

@ -33,7 +33,7 @@
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"tslint": "^5.19.0",
"tslint-config-prettier": "^1.18.0"
},

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

@ -30,7 +30,7 @@
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"globby": "^11.0.0",
"magic-string": "^0.25.7",
"@rollup/plugin-commonjs": "^15.1.0",

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

@ -30,7 +30,7 @@
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"globby": "^11.0.0",
"magic-string": "^0.25.7",
"@rollup/plugin-commonjs": "^15.1.0",

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

@ -31,7 +31,7 @@
"grunt-cli": "^1.3.2",
"grunt-contrib-qunit": "^3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"globby": "^11.0.0",
"magic-string": "^0.25.7",
"pako":"^2.0.3",

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

@ -24,7 +24,7 @@
"grunt-contrib-qunit": "^3.1.0",
"grunt-contrib-uglify": "3.1.0",
"grunt-run": "^0.8.1",
"grunt-ts": "^6.0.0-beta.22",
"@nevware21/grunt-ts-plugin": "^0.2.2",
"grunt-tslint": "^5.0.2",
"qunit": "^2.11.2",
"react": "16.13.1",

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

@ -20,15 +20,11 @@ module.exports = function (grunt) {
},
ts: {
options: {
comments: true
comments: true,
debug: true
},
default: {
tsconfig: './tsconfig.json',
src: [
'legacy/JavaScript/JavaScriptSDK.Interfaces/*.ts',
'legacy/JavaScript/JavaScriptSDK/*.ts',
],
out: 'legacy/bundle/ai.js',
},
core: {
tsconfig: './shared/AppInsightsCore/tsconfig.json'
@ -108,7 +104,7 @@ module.exports = function (grunt) {
},
propertiestests: {
tsconfig: './extensions/applicationinsights-properties-js/Tests/tsconfig.json',
src: './extensions/applicationinsights-properties-js/Tests/**/*.ts',
src: [ './extensions/applicationinsights-properties-js/Tests/**/*.ts' ],
out: './extensions/applicationinsights-properties-js/Tests/Selenium/prop.tests.js'
},
reactnative: {
@ -119,7 +115,7 @@ module.exports = function (grunt) {
},
reactnativetests: {
tsconfig: './extensions/applicationinsights-react-native/Tests/tsconfig.json',
src: './extensions/applicationinsights-react-native/Tests/**/*.ts',
src: [ './extensions/applicationinsights-react-native/Tests/**/*.ts' ],
out: './extensions/applicationinsights-react-native/Tests/Selenium/reactnativeplugin.tests.js'
},
deps: {
@ -189,89 +185,8 @@ module.exports = function (grunt) {
'./common/Tests/Framework/src/*.ts'
]
},
module: {
// Use a different tsconfig for building module in order to not generate a declaration file for module, while keeping declaration for other modules
tsconfig: './tsconfigmodule.json',
src: [
'legacy/JavaScript/JavaScriptSDK.Interfaces/*.ts',
'legacy/JavaScript/JavaScriptSDK.Module/*.ts',
],
out: 'legacy/bundle/ai.module.js'
},
types: {
tsconfig: './tsconfig.json',
src: [
'legacy/JavaScript/JavaScriptSDK.Tests/DefinitionTypes/*.ts'
],
out: 'legacy/bundle/test/ai.types.js'
},
test: {
tsconfig: './tsconfig.json',
src: [
'legacy/JavaScript/JavaScriptSDK.Tests/Selenium/*.ts'
],
out: 'legacy/JavaScript/JavaScriptSDK.Tests/Selenium/ai.tests.js'
},
testSchema: {
tsconfig: './tsconfig.json',
src: [
'legacy/JavaScript/JavaScriptSDK.Tests/Contracts/Generated/*.ts'
],
out: 'legacy/bundle/test/ai.schema.tests.js'
},
testE2E: {
tsconfig: './tsconfig.json',
files: [
{
src: 'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/DisableTelemetry.tests.ts',
dest: 'legacy/bundle/test/e2e/DisableTelemetry.tests.js'
},
{
src: 'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/PublicApi.tests.ts',
dest: 'legacy/bundle/test/e2e/PublicApiTests.tests.js'
},
{
src: 'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/SanitizerE2E.tests.ts',
dest: 'legacy/bundle/test/e2e/SanitizerE2E.tests.js'
},
{
src: 'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/SenderE2E.tests.ts',
dest: 'legacy/bundle/test/e2e/SenderE2E.tests.js'
},
{
src: 'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/Snippet.tests.ts',
dest: 'legacy/bundle/test/e2e/Snippet.tests.js'
},
{
src: 'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/ValidateApi.tests.ts',
dest: 'legacy/bundle/test/e2e/ValidateApi.tests.js'
}
],
outDir: 'legacy/bundle/test/e2e'
}
},
uglify: {
ai: {
files: {
'legacy/bundle/ai.0.js': ['legacy/bundle/ai.js'],
},
options: {
sourceMap: true,
sourceMapIncludeSources: true,
sourceMapIn: 'legacy/bundle/ai.js.map',
compress: {
ie8: true
},
mangle: {
ie8: true
}
},
},
snippet: {
files: {
'legacy/bundle/snippet/snippet.min.js': ['legacy/JavaScript/JavaScriptSDK/snippet.js']
}
},
snippetvNext: {
files: {
'AISKU/snippet/snippet.min.js': ['AISKU/snippet/snippet.js']
@ -292,20 +207,6 @@ module.exports = function (grunt) {
qunit: {
all: {
options: {
urls: [
'legacy/JavaScript/JavaScriptSDK.Tests/Selenium/Tests.html',
'legacy/JavaScript/JavaScriptSDK.Tests/Contracts/Schema.tests.htm',
'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/E2E.DisableTelemetry.tests.htm',
'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/E2E.PublicApi.tests.htm',
'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/E2E.SanitizerE2E.tests.htm',
'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/E2E.Sender.tests.htm',
'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/E2E.snippetTests.htm',
'legacy/JavaScript/JavaScriptSDK.Tests/E2ETests/E2E.ValidateApi.tests.htm'
],
timeout: 300 * 1000, // 5 min
console: false,
summaryOnly: true,
'--web-security': 'false' // we need this to allow CORS requests in PhantomJS
}
},
core: {
@ -444,7 +345,7 @@ module.exports = function (grunt) {
grunt.log.ok('Running test: ' + name);
});
grunt.loadNpmTasks("grunt-ts");
grunt.loadNpmTasks("@nevware21/grunt-ts-plugin");
grunt.loadNpmTasks('grunt-tslint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-qunit');

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

@ -1,578 +0,0 @@
<properties
pageTitle="Application Insights SDK JavaScript API"
description="Reference doc"
services="application-insights"
documentationCenter=".net"
authors="alancameronwills"
manager="douge"/>
<tags
ms.service="application-insights"
ms.workload="tbd"
ms.tgt_pltfrm="ibiza"
ms.devlang="na"
ms.topic="article"
ms.date="08/24/2015"
ms.author="awills"/>
# Application Insights SDK JavaScript API
The JavaScript SDK is loaded into your web page when you set up [web page tracking](https://azure.microsoft.com/documentation/articles/app-insights-javascript/) in [Application Insights](https://azure.microsoft.com/services/application-insights/).
You add a short snippet of code to the page, which pulls in the rest of the SDK.
* [How to set up web page tracking](https://azure.microsoft.com/documentation/articles/app-insights-javascript/)
* [Overview of the API and examples](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/)
* Non-minified built code: [ai.js](https://az416426.vo.msecnd.net/scripts/a/ai.js)
## class AppInsights
The shop front for the SDK, that sends telemetry to Application Insights.
In a web page where you have [set up web page tracking](https://azure.microsoft.com/documentation/articles/app-insights-javascript/), you can use the instance `appInsights`. For example:
```js
appInsights.trackPageView("page1");
```
### trackPageView
```ts
trackPageView(name?: string, url?: string, properties?:{[string]:string}, measurements?: {[string]:number}, duration?: number)
```
Logs that a page or similar container was displayed to the user.
Parameter | Description
---|---
`name` | The name used to identify the page in the portal. Defaults to the document title.
`url` | A relative or absolute URL that identifies the page or similar item. Defaults to the window location.
`properties` | Map of string to string: Additional data used to [filter pages](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/#properties) in the portal. Defaults to empty.
`measurements` | Map of string to number: Metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
`duration` | The number of milliseconds it took to load this page, displayed in Metrics Explorer on the portal. Defaults to empty. If empty, end of page view duration is recorded when browser page load event is called.
The standard snippet that you get from the portal includes a call to trackPageView. If you insert your own calls, consider
removing this default. An example where you might write your own calls is where your app is a single HTML page that has multiple
tabs, and you want to log a page view when each tab opens.
### startTrackPage
```ts
startTrackPage(name?: string)
```
Starts the timer for tracking a page view. Use this instead of ```trackPageView``` if you want to control when the page view timer starts and stops, but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call ```stopTrackPage``` to log the end of the page view and send the event.
Parameter | Description
---|---
`name` | The name used to identify the page in the portal. Defaults to the document title.
### stopTrackPage
```ts
stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; });
```
Stops the timer that was started by calling ```startTrackPage``` and sends the page view telemetry with the specified properties and measurements. The duration of the page view will be the time between calling ```startTrackPage``` and ```stopTrackPage```.
Parameter | Description
---|---
`name` | The name used to identify the page in the portal. Defaults to the document title.
`url` | A relative or absolute URL that identifies the page or similar item. Defaults to the window location.
`properties` | Map of string to string: Additional data used to [filter pages](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/#properties) in the portal. Defaults to empty.
`measurements` | Map of string to number: Metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
### trackEvent
```ts
trackEvent(name: string, properties?: {[string]:string}, measurements?: {[string]:number})
```
Log a user action or other occurrence.
Parameter | Description
---|---
`name` | Identifies the event. Events with the same name are counted and can be charted in [Metric Explorer](https://azure.microsoft.com/documentation/articles/app-insights-metrics-explorer/).
`properties` | Map of string to string: Additional data used to [filter events](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/#properties) in the portal. Defaults to empty.
`measurements` | Map of string to number: Metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
In the portal, you can select events by name, and [display charts that count them or display associated measurements](https://azure.microsoft.com/documentation/articles/app-insights-metrics-explorer/).
You can also search and [display individual events](https://azure.microsoft.com/documentation/articles/app-insights-diagnostic-search/).
### startTrackEvent
Start timing an extended event. Call [`stopTrackEvent`](#stoptrackevent) to log the event when it ends.
```ts
startTrackEvent(name: string)
```
Parameter | Description
---|---
`name` | Identifies the event. Events with the same name are counted and can be charted in [Metric Explorer](https://azure.microsoft.com/documentation/articles/app-insights-metrics-explorer/).
### stopTrackEvent
Log an extended event that you started timing with [`startTrackEvent`](#starttrackevent).
```ts
stopTrackEvent(name: string, properties?: {[key:string]: string}, measurements?: {[key:string]: number})
```
Parameter | Description
---|---
`name` | Identifies the event. Events with the same name are counted and can be charted in [Metric Explorer](https://azure.microsoft.com/documentation/articles/app-insights-metrics-explorer/).
`properties` | Map of string to string: Additional data used to [filter events](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/#properties) in the portal. Defaults to empty.
`measurements` | Map of string to number: Metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
### trackMetric
```ts
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: {[string]:string})
```
Log a positive numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.
Parameter | Description
---|---
`name` | A string that identifies the metric. In the portal, you can select metrics for display by name.
`average` | Either a single measurement, or the average of several measurements. Should be >=0 to be correctly displayed.
`sampleCount` | Count of measurements represented by the average. Defaults to 1. Should be >=1.
`min` | The smallest measurement in the sample. Defaults to the average. Should be >= 0.
`max` | The largest measurement in the sample. Defaults to the average. Should be >= 0.
`properties` | Map of string to string: Additional data used to [filter events](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/#properties) in the portal.
In the portal, you can select metrics by name to [chart their values over time](https://azure.microsoft.com/documentation/articles/app-insights-metrics-explorer/). You can't search or view individual trackMetric calls.
To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals.
### trackException
```ts
trackException(exception: Error, handledAt?: string, properties?: {[string]:string}, measurements?: {[string]:number}, severityLevel?: AI.SeverityLevel)
```
Log an exception you have caught. (Exceptions caught by the browser are also logged.)
Parameter | Description
---|---
`exception` | An Error from a catch clause.
`handledAt` | Deprecated. This argument is ignored. Please pass `null`.
`properties` | Map of string to string: Additional data used to [filter exceptions](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/#properties) in the portal. Defaults to empty.
`measurements` | Map of string to number: Metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
`severityLevel` | Supported values: [SeverityLevel.ts](https://github.com/microsoft/ApplicationInsights-JS/blob/master/legacy/JavaScript/JavaScriptSDK.Interfaces/Contracts/Generated/SeverityLevel.ts)
In the portal, you can [search on exception type and view](https://azure.microsoft.com/documentation/articles/app-insights-diagnostic-search/) the type, message, and stack trace of individual instances.
By default, uncaught browser exceptions are caught by the SDK and reported to the portal. To disable this behavior, insert the following line in the initialization snippet that you got from the portal. You can't set this anywhere else:
```ts
})({
instrumentationKey: "your instrumentation key",
disableExceptionTracking: true
});
```
### trackTrace
```ts
trackTrace(message: string, properties?: {[string]:string}, severityLevel?: AI.SeverityLevel)
```
Log a diagnostic event such as entering or leaving a method.
Parameter | Description
---|---
`message` | Diagnostic data. Can be much longer than a name.
`properties` | Map of string to string: Additional data used to [filter exceptions](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/#properties) in the portal. Defaults to empty.
`severityLevel` | Supported values: [SeverityLevel.ts](https://github.com/microsoft/ApplicationInsights-JS/blob/master/legacy/JavaScript/JavaScriptSDK.Interfaces/Contracts/Generated/SeverityLevel.ts)
In the portal, you can search on message content and [display individual trackTrace events](https://azure.microsoft.com/documentation/articles/app-insights-diagnostic-search/).
(Unlike `trackEvent`, you can't filter on the message content in the portal.)
### trackDependency
```ts
trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) {
```
Log a dependency call (for instance: ajax)
Parameter | Description
---|---
`id` | Unique id, this is used by the backend to correlate server requests. Use `Util.newId()` to generate a unique Id.
`method` | Represents request verb (GET, POST, etc.)
`absoluteUrl` | Absolute url used to make the dependency request
`pathName` | Path part of the absolute url
`totalTime` | Total request time
`success` | Indicates if the request was successful
`resultCode` | Response code returned by the dependency request
### flush
```ts
flush()
```
Immediately send all queued telemetry. Synchronous.
You don't usually have to use this, as it happens automatically on window closing.
<a name="setAuthenticatedUserContext"></a>
### setAuthenticatedUserContext
```ts
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie = false)
```
Set the authenticated user id and the account id. Use this when you have identified a specific signed-in user. Parameters must not contain spaces or ,;=|
The method will only set the `authenticatedUserId` and `accountId` for all events in the current page view. To set them for all events within the whole session, you should either call this method on every page view or set `storeInCookie = true`.
Parameter | Description
---|---
`authenticatedUserId` | An id that uniquely identifies a user of your app. No spaces, comma, semicolon, equals or vertical bar.
`accountId` | An optional account id, if your app groups users into accounts. No spaces, comma, semicolon, equals or vertical bar.
In the portal, this will add to the count of authenticated users. Authenticated users provide a more reliable count of the number of real users than the count of anonymous users.
The authenticated user id will be available as part of the context of the telemetry sent to the portal, so that you can filter and search on it. It will also be saved as a cookie and sent to the server, where the server SDK (if installed) will attach it to server telemetry.
### clearAuthenticatedUserContext
```ts
clearAuthenticatedUserContext ()
```
Clears the authenticated user id and the account id from the user context, and clears the associated cookie.
### config
```ts
config: IConfig
```
Values that control how the telemetry data is sent.
```ts
interface IConfig {
// The key of your Application Insights resource in Azure
instrumentationKey: string;
// The Application Insights server
endpointUrl: string;
accountId: string;
// A session is logged if the user is inactive for this time in milliseconds. Default 30 mins.
sessionRenewalMs: number;
// A session is logged if it has continued for this time in milliseconds. Default 24h.
sessionExpirationMs: number;
// Default 100k
maxBatchSizeInBytes: number;
// Default 15s
maxBatchInterval: number;
// If true, debugging data is thrown as an exception by the logger. Default false.
enableDebug: boolean;
// If true, telemetry data is not collected or sent. Default false.
disableTelemetry: boolean;
// If true, the SDK will log all internal errors (any severity) to the console. Default false
verboseLogging: boolean;
// Controls what percentage of events will be sent
// Default 100.
samplingPercentage: number;
// Default 10s
diagnosticLogInterval: number;
// If true, exceptions are not monitored.
disableExceptionTracking: boolean;
// If true, ajax calls are not monitored.
disableAjaxTracking: boolean;
// If true, default behavior of trackPageView is changed to record end of page view duration interval when
// trackPageView is called. If false and no custom duration is provided to trackPageView, the page view
// performance is calculated using the navigation timing API.
overridePageViewDuration: boolean;
// Default 500 - controls how many ajax calls will be monitored per page view.
// Set to -1 to monitor all ajax calls on the page.
maxAjaxCallsPerView: number;
// If true, the SDK will not store or read any data from cookies.
// Default: false
isCookieUseDisabled: boolean;
// Custom cookie domain. This is helpful if you want to share Application Insights cookies across subdomains.
cookieDomain: string;
// Default false. If true, flush method will not be called when onBeforeUnload event triggers.
disableFlushOnBeforeUnload: boolean;
// If true, the buffer with all unsent telemetry is stored in a session storage. The buffer is restored on page load.
// The feature is enable by default starting with v0.23.0.
enableSessionStorageBuffer: boolean;
// Is retry handler disabled. Default false.
// If enabled, retry on 206 (partial success), 408 (timeout), 429 (too many requests), 500 (internal server error) and 503 (service unavailable).
isRetryDisabled: boolean;
// The url from where the JS SDK will be downloaded.
// Default 'https://az416426.vo.msecnd.net/scripts/a/ai.0.js'
url: string;
// If true, the SDK will not store or read any data from local and session storage.
// Default: false
isStorageUseDisabled: boolean;
// If false, the SDK will add two headers ('Request-Id' and 'Request-Context') to all
// dependency requests to correlate them with corresponding requests on the server side.
// Default false.
disableCorrelationHeaders: boolean;
// If true, the SDK will send all telemetry using [Beacon API](https://www.w3.org/TR/beacon/)
// When Beacon API is enabled, then SessionStorageBuffer cannot be used and maxBatchSizeInBytes is limit too 64kb
// Default: true
isBeaconApiDisabled: boolean;
// Sets the sdk extension name. Only alphabetic characters are allowed.
// The extension name is added as a prefix to 'ai.internal.sdkVersion' tag (for instance 'ext_javascript:1.0.5')
// Default: null
sdkExtension: string;
// If true, the SDK will track all [Browser Link](https://docs.microsoft.com/en-us/aspnet/core/client-side/using-browserlink) requests.
// Default: false
isBrowserLinkTrackingEnabled: boolean;
// AppId is used for the correlation between AJAX dependencies happening on the client-side with the server-side requests.
// When Beacon API is enabled it can not be used automatically, but can be set manually in the configuration.
// Default: null
appId: string;
// If true, the SDK will add two headers ('Request-Id' and 'Request-Context') to all
// CORS requests to correlate outgoing AJAX dependencies with corresponding requests on the server side.
// Default false.
enableCorsCorrelation: boolean;
// Disable correlation headers for specific domains
correlationHeaderExcludedDomains: string[];
}
```
Set these values in [the snippet](https://azure.microsoft.com/documentation/articles/app-insights-javascript/) that you insert in your web pages.
Look for this line, and add more items:
```ts
})({
instrumentationKey: "000...000"
});
```
You can also read or write them dynamically:
```ts
appInsights.config.disableTelemetry = true;
```
### context
```ts
context: TelemetryContext
```
Information that the SDK attempts to extract from the environment about the device, location, and user.
## class TelemetryContext
### context.application
```ts
application: Context.Application
```
Details of the app you're monitoring.
```ts
context.application.ver: string
context.application.build : string
```
### context.device
```ts
device : Context.Device
```
The device the app is running on.
Property | Description
---|---
device.type | Type of device
device.id | unique ID
device.oemName |
device.model |
device.network | number - IANA interface type
device.resolution | screen res
device.locale | display language of the OS
device.ip |
device.language |
device.os | OS running on the device
device.osversion |
### context.user
```ts
user: Context.User
```
Data about the current user. Users are identified by cookie, so one person can look like
more than one user if they use different machines or browsers, or delete cookies.
Property | Description
---|---
`user.id` | Unique, cookie-based user id, automatically assigned.
`user.authenticatedId` | Id set by your app using [`setAuthenticatedUserContext`](#setAuthenticatedUserContext) when the user signs in.
`user.accountId` | Set by your app when the user signs in, if your app groups users into accounts.
`user.accountAcquisitionDate` |
`user.agent` |
`user.storeRegion` |
### context.session
```ts
session: Context.Session
```
The user session. A session represents a series of user actions. A session starts with a user action.
It ends at the last user activity when there is no more activity for sessionRenewalMs, or if it lasts longer than sessionExpirationMs.
Property | Description
---|---
`session.id` | Automatically assigned id
`session.isFirst` | Boolean. True if this is the first session for this user.
`session.acquisitionDate` | Number. The dateTime when this session was created.
`session.renewalDate` | Number. DateTime when telemetry was last sent with this session.
### context.location
```ts
location: Context.Location
```
Data from which the geographical location of the user's device can be guessed.
Property | Description
---|---
`location.ip` | IP address
### context.operation
```ts
operation: Context.Operation;
```
Represents the user request. Operation id is used to tie together related events in diagnostic search.
Property | Description
---|---
`id` | Unique id
`name` |
`parentId` |
`rootId` |
`syntheticSource` | String identifying the bot or test agent.
### track
```ts
public track(envelope: Telemetry.Common.Envelope) ;
```
Sends telemetry to the endpoint.
### addTelemetryInitializer
```ts
public addTelemetryInitializer(telemetryInitializer: (envelope: Telemetry.Common.Envelope) => boolean | void)
```
Adds a telemetry initializer to the collection. Telemetry initializers will be called one by one, in the order they were added,
before the telemetry item is pushed for sending.
If one of the telemetry initializers returns false then the telemetry item will not be sent.
If one of the telemetry initializers throws an error then the telemetry item will not be sent.
#### Example
Add this code immediately after the initialization snippet that you get from the portal.
```js
...
window.appInsights = appInsights;
// Add telemetry initializer
appInsights.queue.push(function () {
appInsights.context.addTelemetryInitializer(function (envelope) {
var telemetryItem = envelope.data.baseData;
// To check the telemetry items type:
if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType) {
// this statement removes url from all page view documents
telemetryItem.url = "URL CENSORED";
}
// To set custom properties:
telemetryItem.properties = telemetryItem.properties || {};
telemetryItem.properties["globalProperty"] = "boo";
// To set custom metrics:
telemetryItem.measurements = telemetryItem.measurements || {};
telemetryItem.measurements["globalMetric"] = 100;
});
});
// end of insertion
appInsights.trackPageView();
```
## class Envelope
```ts
public ver: number;
public name: string;
public time: string;
public sampleRate: number;
public seq: string;
public iKey: string;
public flags: number;
public deviceId: string;
public os: string;
public osVer: string;
public appId: string;
public appVer: string;
public userId: string;
public tags: any;
public data: Base; // PageView, Event, Exception etc
```
## Links
* Read or contribute to the [code for the SDK](https://github.com/microsoft/ApplicationInsights-js).
* [Overview of the API and examples](https://azure.microsoft.com/documentation/articles/app-insights-api-custom-events-metrics/)

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

@ -1,120 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This file (Global.props) must be included into all projects in all solutions of this product. -->
<!-- It defines common build paths and infrastructure. -->
<!-- Other products / repositories using the same build pattern will have an own copy of copy this file -->
<!-- Project file location for the Import statement: -->
<!-- * You MUST include this file towards the bottom of each respective project file, * -->
<!-- * BELOW all local definitions, RIGHT ABOVE the targets import. * -->
<!-- * For example, right above this line: * -->
<!-- * <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> * -->
<!-- There are two easy ways to import this file. The shortest way is to write something like: -->
<!-- <Import Project="..\..\Global.props" /> -->
<!-- However, you will need to match the number of "..\" segments to the respective location of each project file in -->
<!-- your sourcce tree. A more robust approach is to include the following code. It can stay the same regardless of -->
<!-- your project file location: -->
<!--
<PropertyGroup Label="Include_Common_Build_Properties">
<CommonBuildPropsLocation>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), 'EnlistmentRoot.marker'))</CommonBuildPropsLocation>
</PropertyGroup>
<ImportGroup Label="Include_Common_Build_Properties">
<Import Project="$(CommonBuildPropsLocation)\Global.props" />
</ImportGroup>
-->
<PropertyGroup>
<!-- The common project structure looks like this: -->
<!-- d:\DDGit\ -->
<!-- ServiceFoo\ -->
<!-- Bin\ -->
<!-- Obj\ -->
<!-- Packages\ -->
<!-- Src\ -->
<!-- .git\ -->
<!-- .nuget\ -->
<!-- Global.props -->
<!-- SomeProjectFolderA\ -->
<!-- NuGet.config -->
<!-- SomeProjectA.sln -->
<!-- ... -->
<!-- SomeProjectFolderB\ -->
<!-- ... -->
<!-- EnlistmentRoot.marker -->
<!-- ServiceBar\ -->
<!-- Bin\ -->
<!-- Obj\ -->
<!-- Packages\ -->
<!-- Src\ -->
<!-- ... -->
<!-- -->
<!-- The Bin folder contains ALL build output. -->
<!-- The Obj folder contains all intermediate build files (like the obj folder). -->
<!-- The Packages folder contains ALL packages downloaded by NuGet. -->
<!-- The above folders contain NOTHING that is checked in (they are not checked in themselves). -->
<!-- The Src folder contains EVERHYTHNG that is checked in and ALL that is checked in. -->
<!-- No build output or temp files should end up in the Src folder! (barring a few *small* VS temporaries) -->
<!-- -->
<!-- Src MUST contain the EnlistmentRoot.marker file which marks the EnlistmentRoot. -->
<!-- Src also contains the NuGet.config file which ensures that NuGet uses the NuGet.Packages folder. -->
<EnlistmentRoot>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), 'EnlistmentRoot.marker'))</EnlistmentRoot>
<BinRoot>$(EnlistmentRoot)\..\bin</BinRoot>
<BinRoot>$([System.IO.Path]::GetFullPath( $(BinRoot) ))</BinRoot>
<RelativeOutputPathBase>$(MSBuildProjectDirectory.Substring($(EnlistmentRoot.Length)))</RelativeOutputPathBase>
<BaseIntermediateOutputPath>$(EnlistmentRoot)\..\obj</BaseIntermediateOutputPath>
<BaseIntermediateOutputPath>$([System.IO.Path]::GetFullPath( $(BaseIntermediateOutputPath) ))</BaseIntermediateOutputPath>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<OutputPath>$(BinRoot)\$(Configuration)\$(RelativeOutputPathBase)</OutputPath>
<OutputPath>$([System.IO.Path]::GetFullPath( $(OutputPath) ))\</OutputPath>
<!-- Collect all NuGet packages in the same folder for convenience during testing -->
<PackageOutputDir>$(BinRoot)\$(Configuration)\NuGet</PackageOutputDir>
<AppxPackageDir>$(OutputPath)</AppxPackageDir>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)\$(Configuration)\$(RelativeOutputPathBase)</IntermediateOutputPath>
<IntermediateOutputPath>$([System.IO.Path]::GetFullPath( $(IntermediateOutputPath) ))\</IntermediateOutputPath>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(EnlistmentRoot)\</SolutionDir>
<PackagesDir>$(EnlistmentRoot)\..\packages</PackagesDir>
<PackagesDir>$([System.IO.Path]::GetFullPath( $(PackagesDir) ))</PackagesDir>
</PropertyGroup>
<PropertyGroup>
<!-- Enable NuGet package restore during build -->
<RestorePackages>true</RestorePackages>
<RequireRestoreConsent>false</RequireRestoreConsent>
<!-- Set the root namespace for all assemblies in this project hierarchy -->
<RootNamespace>Microsoft.ApplicationInsights</RootNamespace>
<!-- Disable StyleCop by default to prevent StyleCop.MSBuild package from slowing down the debug build -->
<StyleCopEnabled>false</StyleCopEnabled>
</PropertyGroup>
<!-- Generate AssemblyFileVersion and AssemblyVersion attributes. -->
<PropertyGroup>
<!--
Semantic Version. See http://semver.org for full details.
Update for every public release.
-->
<SemanticVersionMajor>1</SemanticVersionMajor>
<SemanticVersionMinor>0</SemanticVersionMinor>
<SemanticVersionPatch>20</SemanticVersionPatch>
<!--
Date when Semantic Version was changed.
Update for every public release.
-->
<SemanticVersionDate>2018-08-25</SemanticVersionDate>
<!--
Pre-release version is used to distinguish internally built NuGet packages.
Pre-release version = Minutes since semantic version was set, divided by 5 (to make it fit in a UInt16).
-->
<PreReleaseVersion>$([MSBuild]::Divide($([System.DateTime]::Now.Subtract($([System.DateTime]::Parse($(SemanticVersionDate)))).TotalMinutes), 5).ToString('F0'))</PreReleaseVersion>
<!-- Turn on dynamic assembly attribute generation -->
<AssemblyAttributesPath>$(IntermediateOutputPath)\AssemblyInfo.g.cs</AssemblyAttributesPath>
<GenerateAdditionalSources>true</GenerateAdditionalSources>
</PropertyGroup>
<ItemGroup>
<!--
AssemblyVersion and AssemblyFileVersion attributes are generated automatically for every build.
NuGet package version is derived from AssemblyFileVersion.
-->
<AssemblyAttributes Include="AssemblyVersion">
<_Parameter1>$(SemanticVersionMajor).$(SemanticVersionMinor).$(SemanticVersionPatch).$(PreReleaseVersion)</_Parameter1>
</AssemblyAttributes>
<AssemblyAttributes Include="AssemblyFileVersion">
<_Parameter1>$(SemanticVersionMajor).$(SemanticVersionMinor).$(SemanticVersionPatch).$(PreReleaseVersion)</_Parameter1>
</AssemblyAttributes>
</ItemGroup>
</Project>

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

@ -1,4 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Ignore this file. See https://github.com/grunt-ts/grunt-ts/issues/77

37
legacy/JavaScript/.gitignore поставляемый
Просмотреть файл

@ -1,37 +0,0 @@
# Ignore test file
/*/Selenium/*.js
# Ignore compiled SDK
/*/ai.full.*
# Ignore Chutzpah output
_Chutzpah.*
# Ignore Policheck targets
/*/*/policheck/targets/*
# Ignore node package
/Node/appInsights-0.1.5.tgz
# Ignore modules
/*/node_modules/**
# Ignore minified scripts
/*/min/*.js
/*/min/*.d.ts
/*/min/*.js.map
/*/min/*.html
# Ignore standalone test output
/*/E2ETests/*.js
/*/E2ETests/*.html
/*/Selenium/testPageWithAppInsights.html
# Ignore map files
*.map
# Ignore JS files and d.ts files in Interfaces and Module project
JavaScriptSDK.Interfaces/**/*.js
JavaScriptSDK.Interfaces/**/*.d.ts
JavaScriptSDK.Module/**/*.js
JavaScriptSDK.Module/**/*.d.ts

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

@ -1,7 +0,0 @@
# NPM Ignore
# ignore everything
*
# ... but these files
!/JavaScriptSDK.Module/AppInsightsModule.js
!/JavaScriptSDK/snippet.js

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

@ -1,19 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface IApplication {
/**
* The application version.
*/
ver: string;
/**
* The application build version.
*/
build: string;
}
}

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

@ -1,64 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface IDevice {
/**
* The type for the current device.
*/
type: string;
/**
* A device unique ID.
*/
id: string;
/**
* The device OEM for the current device.
*/
oemName: string;
/**
* The device model for the current device.
*/
model: string;
/**
* The IANA interface type for the internet connected network adapter.
*/
network: number;
/**
* The application screen resolution.
*/
resolution: string;
/**
* The current display language of the operating system.
*/
locale: string;
/**
* The IP address.
*/
ip: string;
/**
* The device language.
*/
language: string;
/**
* The OS name.
*/
os: string;
/**
* The OS version.
*/
osversion: string;
}
}

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

@ -1,19 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface IInternal {
/**
* The SDK version used to create this telemetry item.
*/
sdkVersion: string;
/**
* The SDK agent version.
*/
agentVersion: string;
}
}

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

@ -1,14 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface ILocation {
/**
* Client IP address for reverse lookup
*/
ip: string;
}
}

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

@ -1,34 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface IOperation {
/**
* Operation id
*/
id: string;
/**
* Operation name
*/
name: string;
/**
* Parent operation id
*/
parentId: string;
/**
* Root operation id
*/
rootId: string;
/**
* Synthetic source of the operation
*/
syntheticSource: string;
}
}

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

@ -1,14 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface ISample {
/**
* Sample rate
*/
sampleRate: number;
}
}

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

@ -1,32 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface ISession {
/**
* The session ID.
*/
id: string;
/**
* The true if this is the first session
*/
isFirst: boolean;
/**
* The date at which this guid was genereated.
* Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds ellapse from this time.
*/
acquisitionDate: number;
/**
* The date at which this session ID was last reported.
* This value should be updated whenever telemetry is sent using this ID.
* Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity.
*/
renewalDate: number;
}
}

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

@ -1,44 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights.Context {
"use strict";
export interface IUser {
/**
* The telemetry configuration.
*/
config: any;
/**
* The user ID.
*/
id: string;
/**
* Authenticated user id
*/
authenticatedId: string;
/**
* The account ID.
*/
accountId: string;
/**
* The account acquisition date.
*/
accountAcquisitionDate: string;
/**
* The user agent string.
*/
agent: string;
/**
* The store region.
*/
storeRegion: string;
}
}

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

@ -1,70 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Domain.ts" />
module AI
{
"use strict";
/**
* Instances of AvailabilityData represent the result of executing an availability test.
*/
export class AvailabilityData extends Microsoft.Telemetry.Domain
{
/**
* Schema version
*/
public ver: number;
/**
* Identifier of a test run. Use it to correlate steps of test run and telemetry generated by the service.
*/
public id: string;
/**
* Name of the test that these availability results represent.
*/
public name: string;
/**
* Duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days.
*/
public duration: string;
/**
* Success flag.
*/
public success: boolean;
/**
* Name of the location where the test was run from.
*/
public runLocation: string;
/**
* Diagnostic message for the result.
*/
public message: string;
/**
* Collection of custom properties.
*/
public properties: any;
/**
* Collection of custom measurements.
*/
public measurements: any;
constructor()
{
super();
this.ver = 2;
this.properties = {};
this.measurements = {};
}
}
}

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

@ -1,24 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module Microsoft.Telemetry
{
"use strict";
/**
* Data struct to contain only C section with custom fields.
*/
export class Base
{
/**
* Name of item (B section) if any. If telemetry data is derived straight from this, this should be null.
*/
public baseType: string;
constructor()
{
}
}
}

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

@ -1,265 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module AI
{
"use strict";
export class ContextTagKeys
{
/**
* Application version. Information in the application context fields is always about the application that is sending the telemetry.
*/
public applicationVersion: string;
/**
* Application build.
*/
public applicationBuild: string;
/**
* Application type id.
*/
public applicationTypeId: string;
/**
* Application id.
*/
public applicationId: string;
/**
* Application layer.
*/
public applicationLayer: string;
/**
* Unique client device id. Computer name in most cases.
*/
public deviceId: string;
public deviceIp: string;
public deviceLanguage: string;
/**
* Device locale using <language>-<REGION> pattern, following RFC 5646. Example 'en-US'.
*/
public deviceLocale: string;
/**
* Model of the device the end user of the application is using. Used for client scenarios. If this field is empty then it is derived from the user agent.
*/
public deviceModel: string;
public deviceFriendlyName: string;
public deviceNetwork: string;
public deviceNetworkName: string;
/**
* Client device OEM name taken from the browser.
*/
public deviceOEMName: string;
public deviceOS: string;
/**
* Operating system name and version of the device the end user of the application is using. If this field is empty then it is derived from the user agent. Example 'Windows 10 Pro 10.0.10586.0'
*/
public deviceOSVersion: string;
/**
* Name of the instance where application is running. Computer name for on-premisis, instance name for Azure.
*/
public deviceRoleInstance: string;
/**
* Name of the role application is part of. Maps directly to the role name in azure.
*/
public deviceRoleName: string;
public deviceScreenResolution: string;
/**
* The type of the device the end user of the application is using. Used primarily to distinguish JavaScript telemetry from server side telemetry. Examples: 'PC', 'Phone', 'Browser'. 'PC' is the default value.
*/
public deviceType: string;
public deviceMachineName: string;
public deviceVMName: string;
public deviceBrowser: string;
/**
* The browser name and version as reported by the browser.
*/
public deviceBrowserVersion: string;
/**
* The IP address of the client device. IPv4 and IPv6 are supported. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
public locationIp: string;
/**
* The country of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
public locationCountry: string;
/**
* The province/state of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
public locationProvince: string;
/**
* The city of the client device. If any of Country, Province, or City is specified, those values will be preferred over geolocation of the IP address field. Information in the location context fields is always about the end user. When telemetry is sent from a service, the location context is about the user that initiated the operation in the service.
*/
public locationCity: string;
/**
* A unique identifier for the operation instance. The operation.id is created by either a request or a page view. All other telemetry sets this to the value for the containing request or page view. Operation.id is used for finding all the telemetry items for a specific operation instance.
*/
public operationId: string;
/**
* The name (group) of the operation. The operation.name is created by either a request or a page view. All other telemetry items set this to the value for the containing request or page view. Operation.name is used for finding all the telemetry items for a group of operations (i.e. 'GET Home/Index').
*/
public operationName: string;
/**
* The unique identifier of the telemetry item's immediate parent.
*/
public operationParentId: string;
public operationRootId: string;
/**
* Name of synthetic source. Some telemetry from the application may represent a synthetic traffic. It may be web crawler indexing the web site, site availability tests or traces from diagnostic libraries like Application Insights SDK itself.
*/
public operationSyntheticSource: string;
/**
* The correlation vector is a light weight vector clock which can be used to identify and order related events across clients and services.
*/
public operationCorrelationVector: string;
/**
* Session ID - the instance of the user's interaction with the app. Information in the session context fields is always about the end user. When telemetry is sent from a service, the session context is about the user that initiated the operation in the service.
*/
public sessionId: string;
/**
* Boolean value indicating whether the session identified by ai.session.id is first for the user or not.
*/
public sessionIsFirst: string;
public sessionIsNew: string;
public userAccountAcquisitionDate: string;
/**
* In multi-tenant applications this is the account ID or name which the user is acting with. Examples may be subscription ID for Azure portal or blog name blogging platform.
*/
public userAccountId: string;
/**
* The browser's user agent string as reported by the browser. This property will be used to extract informaiton regarding the customer's browser but will not be stored. Use custom properties to store the original user agent.
*/
public userAgent: string;
/**
* Anonymous user id. Represents the end user of the application. When telemetry is sent from a service, the user context is about the user that initiated the operation in the service.
*/
public userId: string;
/**
* Store region for UWP applications.
*/
public userStoreRegion: string;
/**
* Authenticated user id. The opposite of ai.user.id, this represents the user with a friendly name. Since it's PII information it is not collected by default by most SDKs.
*/
public userAuthUserId: string;
public userAnonymousUserAcquisitionDate: string;
public userAuthenticatedUserAcquisitionDate: string;
public cloudName: string;
/**
* Name of the role the application is a part of. Maps directly to the role name in azure.
*/
public cloudRole: string;
public cloudRoleVer: string;
/**
* Name of the instance where the application is running. Computer name for on-premisis, instance name for Azure.
*/
public cloudRoleInstance: string;
public cloudEnvironment: string;
public cloudLocation: string;
public cloudDeploymentUnit: string;
/**
* SDK version. See https://github.com/microsoft/ApplicationInsights-Home/blob/master/SDK-AUTHORING.md#sdk-version-specification for information.
*/
public internalSdkVersion: string;
/**
* Agent version. Used to indicate the version of StatusMonitor installed on the computer if it is used for data collection.
*/
public internalAgentVersion: string;
/**
* This is the node name used for billing purposes. Use it to override the standard detection of nodes.
*/
public internalNodeName: string;
constructor()
{
this.applicationVersion = "ai.application.ver";
this.applicationBuild = "ai.application.build";
this.applicationTypeId = "ai.application.typeId";
this.applicationId = "ai.application.applicationId";
this.applicationLayer = "ai.application.layer";
this.deviceId = "ai.device.id";
this.deviceIp = "ai.device.ip";
this.deviceLanguage = "ai.device.language";
this.deviceLocale = "ai.device.locale";
this.deviceModel = "ai.device.model";
this.deviceFriendlyName = "ai.device.friendlyName";
this.deviceNetwork = "ai.device.network";
this.deviceNetworkName = "ai.device.networkName";
this.deviceOEMName = "ai.device.oemName";
this.deviceOS = "ai.device.os";
this.deviceOSVersion = "ai.device.osVersion";
this.deviceRoleInstance = "ai.device.roleInstance";
this.deviceRoleName = "ai.device.roleName";
this.deviceScreenResolution = "ai.device.screenResolution";
this.deviceType = "ai.device.type";
this.deviceMachineName = "ai.device.machineName";
this.deviceVMName = "ai.device.vmName";
this.deviceBrowser = "ai.device.browser";
this.deviceBrowserVersion = "ai.device.browserVersion";
this.locationIp = "ai.location.ip";
this.locationCountry = "ai.location.country";
this.locationProvince = "ai.location.province";
this.locationCity = "ai.location.city";
this.operationId = "ai.operation.id";
this.operationName = "ai.operation.name";
this.operationParentId = "ai.operation.parentId";
this.operationRootId = "ai.operation.rootId";
this.operationSyntheticSource = "ai.operation.syntheticSource";
this.operationCorrelationVector = "ai.operation.correlationVector";
this.sessionId = "ai.session.id";
this.sessionIsFirst = "ai.session.isFirst";
this.sessionIsNew = "ai.session.isNew";
this.userAccountAcquisitionDate = "ai.user.accountAcquisitionDate";
this.userAccountId = "ai.user.accountId";
this.userAgent = "ai.user.userAgent";
this.userId = "ai.user.id";
this.userStoreRegion = "ai.user.storeRegion";
this.userAuthUserId = "ai.user.authUserId";
this.userAnonymousUserAcquisitionDate = "ai.user.anonUserAcquisitionDate";
this.userAuthenticatedUserAcquisitionDate = "ai.user.authUserAcquisitionDate";
this.cloudName = "ai.cloud.name";
this.cloudRole = "ai.cloud.role";
this.cloudRoleVer = "ai.cloud.roleVer";
this.cloudRoleInstance = "ai.cloud.roleInstance";
this.cloudEnvironment = "ai.cloud.environment";
this.cloudLocation = "ai.cloud.location";
this.cloudDeploymentUnit = "ai.cloud.deploymentUnit";
this.internalSdkVersion = "ai.internal.sdkVersion";
this.internalAgentVersion = "ai.internal.agentVersion";
this.internalNodeName = "ai.internal.nodeName";
}
}
}

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

@ -1,32 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Base.ts" />
module Microsoft.Telemetry
{
"use strict";
/**
* Data struct to contain both B and C sections.
*/
export class Data<TDomain> extends Microsoft.Telemetry.Base
{
/**
* Name of item (B section) if any. If telemetry data is derived straight from this, this should be null.
*/
public baseType: string;
/**
* Container for data item (B section).
*/
public baseData: TDomain;
constructor()
{
super();
}
}
}

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

@ -1,56 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="DataPointType.ts" />
module AI
{
"use strict";
/**
* Metric data single measurement.
*/
export class DataPoint
{
/**
* Name of the metric.
*/
public name: string;
/**
* Metric type. Single measurement or the aggregated value.
*/
public kind: AI.DataPointType;
/**
* Single value for measurement. Sum of individual measurements for the aggregation.
*/
public value: number;
/**
* Metric weight of the aggregated metric. Should not be set for a measurement.
*/
public count: number;
/**
* Minimum value of the aggregated metric. Should not be set for a measurement.
*/
public min: number;
/**
* Maximum value of the aggregated metric. Should not be set for a measurement.
*/
public max: number;
/**
* Standard deviation of the aggregated metric. Should not be set for a measurement.
*/
public stdDev: number;
constructor()
{
this.kind = AI.DataPointType.Measurement;
}
}
}

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

@ -1,17 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module AI
{
"use strict";
/**
* Type of the metric data measurement.
*/
export enum DataPointType
{
Measurement = 0,
Aggregation = 1,
}
}

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

@ -1,18 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module AI
{
"use strict";
/**
* Identifies the type of dependency.
*/
export enum DependencyKind
{
SQL = 0,
Http = 1,
Other = 2,
}
}

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

@ -1,18 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module AI
{
"use strict";
/**
* Identifies the source of the dependency.
*/
export enum DependencySourceType
{
Undefined = 0,
Aic = 1,
Apmc = 2,
}
}

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

@ -1,19 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module Microsoft.Telemetry
{
"use strict";
/**
* The abstract common base of all domains.
*/
export class Domain
{
constructor()
{
}
}
}

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

@ -1,63 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Base.ts" />
module Microsoft.Telemetry
{
"use strict";
/**
* System variables for a telemetry item.
*/
export class Envelope
{
/**
* Envelope version. For internal use only. By assigning this the default, it will not be serialized within the payload unless changed to a value other than #1.
*/
public ver: number;
/**
* Type name of telemetry data item.
*/
public name: string;
/**
* Event date time when telemetry item was created. This is the wall clock time on the client when the event was generated. There is no guarantee that the client's time is accurate. This field must be formatted in UTC ISO 8601 format, with a trailing 'Z' character, as described publicly on https://en.wikipedia.org/wiki/ISO_8601#UTC. Note: the number of decimal seconds digits provided are variable (and unspecified). Consumers should handle this, i.e. managed code consumers should not use format 'O' for parsing as it specifies a fixed length. Example: 2009-06-15T13:45:30.0000000Z.
*/
public time: string;
/**
* Sampling rate used in application. This telemetry item represents 1 / sampleRate actual telemetry items.
*/
public sampleRate: number;
/**
* Sequence field used to track absolute order of uploaded events.
*/
public seq: string;
/**
* The application's instrumentation key. The key is typically represented as a GUID, but there are cases when it is not a guid. No code should rely on iKey being a GUID. Instrumentation key is case insensitive.
*/
public iKey: string;
/**
* Key/value collection of context properties. See ContextTagKeys for information on available properties.
*/
public tags: any;
/**
* Telemetry data item.
*/
public data: Base;
constructor()
{
this.ver = 1;
this.sampleRate = 100.0;
this.tags = {};
}
}
}

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

@ -1,45 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Domain.ts" />
module AI
{
"use strict";
/**
* Instances of Event represent structured event records that can be grouped and searched by their properties. Event data item also creates a metric of event count by name.
*/
export class EventData extends Microsoft.Telemetry.Domain
{
/**
* Schema version
*/
public ver: number;
/**
* Event name. Keep it low cardinality to allow proper grouping and useful metrics.
*/
public name: string;
/**
* Collection of custom properties.
*/
public properties: any;
/**
* Collection of custom measurements.
*/
public measurements: any;
constructor()
{
super();
this.ver = 2;
this.properties = {};
this.measurements = {};
}
}
}

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

@ -1,53 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Domain.ts" />
/// <reference path="SeverityLevel.ts" />
/// <reference path="ExceptionDetails.ts" />
module AI
{
"use strict";
/**
* An instance of Exception represents a handled or unhandled exception that occurred during execution of the monitored application.
*/
export class ExceptionData extends Microsoft.Telemetry.Domain
{
/**
* Schema version
*/
public ver: number;
/**
* Exception chain - list of inner exceptions.
*/
public exceptions: ExceptionDetails[];
/**
* Severity level. Mostly used to indicate exception severity level when it is reported by logging library.
*/
public severityLevel: AI.SeverityLevel;
/**
* Collection of custom properties.
*/
public properties: any;
/**
* Collection of custom measurements.
*/
public measurements: any;
constructor()
{
super();
this.ver = 2;
this.exceptions = [];
this.properties = {};
this.measurements = {};
}
}
}

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

@ -1,56 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module AI
{
"use strict";
/**
* Exception details of the exception in a chain.
*/
export class ExceptionDetails
{
/**
* In case exception is nested (outer exception contains inner one), the id and outerId properties are used to represent the nesting.
*/
public id: number;
/**
* The value of outerId is a reference to an element in ExceptionDetails that represents the outer exception
*/
public outerId: number;
/**
* Exception type name.
*/
public typeName: string;
/**
* Exception message.
*/
public message: string;
/**
* Indicates if full exception stack is provided in the exception. The stack may be trimmed, such as in the case of a StackOverflow exception.
*/
public hasFullStack: boolean;
/**
* Text describing the stack. Either stack or parsedStack should have a value.
*/
public stack: string;
/**
* List of stack frames. Either stack or parsedStack should have a value.
*/
public parsedStack: StackFrame[];
constructor()
{
this.hasFullStack = true;
this.parsedStack = [];
}
}
}

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

@ -1,45 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Domain.ts" />
/// <reference path="SeverityLevel.ts" />
module AI
{
"use strict";
/**
* Instances of Message represent printf-like trace statements that are text-searched. Log4Net, NLog and other text-based log file entries are translated into intances of this type. The message does not have measurements.
*/
export class MessageData extends Microsoft.Telemetry.Domain
{
/**
* Schema version
*/
public ver: number;
/**
* Trace message
*/
public message: string;
/**
* Trace severity level.
*/
public severityLevel: AI.SeverityLevel;
/**
* Collection of custom properties.
*/
public properties: any;
constructor()
{
super();
this.ver = 2;
this.properties = {};
}
}
}

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

@ -1,41 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Domain.ts" />
/// <reference path="DataPoint.ts" />
module AI
{
"use strict";
/**
* An instance of the Metric item is a list of measurements (single data points) and/or aggregations.
*/
export class MetricData extends Microsoft.Telemetry.Domain
{
/**
* Schema version
*/
public ver: number;
/**
* List of metrics. Only one metric in the list is currently supported by Application Insights storage. If multiple data points were sent only the first one will be used.
*/
public metrics: DataPoint[];
/**
* Collection of custom properties.
*/
public properties: any;
constructor()
{
super();
this.ver = 2;
this.metrics = [];
this.properties = {};
}
}
}

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

@ -1,60 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="EventData.ts" />
module AI
{
"use strict";
/**
* An instance of PageView represents a generic action on a page like a button click. It is also the base type for PageView.
*/
export class PageViewData extends AI.EventData
{
/**
* Schema version
*/
public ver: number;
/**
* Request URL with all query string parameters
*/
public url: string;
/**
* Event name. Keep it low cardinality to allow proper grouping and useful metrics.
*/
public name: string;
/**
* Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days.
*/
public duration: string;
/**
* Identifier of a page view instance. Used for correlation between page view and other telemetry items.
*/
public id: string;
/**
* Collection of custom properties.
*/
public properties: any;
/**
* Collection of custom measurements.
*/
public measurements: any;
constructor()
{
super();
this.ver = 2;
this.properties = {};
this.measurements = {};
}
}
}

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

@ -1,80 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="PageViewData.ts" />
module AI
{
"use strict";
/**
* An instance of PageViewPerf represents: a page view with no performance data, a page view with performance data, or just the performance data of an earlier page request.
*/
export class PageViewPerfData extends AI.PageViewData
{
/**
* Schema version
*/
public ver: number;
/**
* Request URL with all query string parameters
*/
public url: string;
/**
* Performance total in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff
*/
public perfTotal: string;
/**
* Event name. Keep it low cardinality to allow proper grouping and useful metrics.
*/
public name: string;
/**
* Request duration in format: DD.HH:MM:SS.MMMMMM. For a page view (PageViewData), this is the duration. For a page view with performance information (PageViewPerfData), this is the page load time. Must be less than 1000 days.
*/
public duration: string;
/**
* Network connection time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff
*/
public networkConnect: string;
/**
* Sent request time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff
*/
public sentRequest: string;
/**
* Received response time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff
*/
public receivedResponse: string;
/**
* DOM processing time in TimeSpan 'G' (general long) format: d:hh:mm:ss.fffffff
*/
public domProcessing: string;
/**
* Collection of custom properties.
*/
public properties: any;
/**
* Collection of custom measurements.
*/
public measurements: any;
constructor()
{
super();
this.ver = 2;
this.properties = {};
this.measurements = {};
}
}
}

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

@ -1,81 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Domain.ts" />
module AI
{
"use strict";
/**
* An instance of Remote Dependency represents an interaction of the monitored component with a remote component/service like SQL or an HTTP endpoint.
*/
export class RemoteDependencyData extends Microsoft.Telemetry.Domain
{
/**
* Schema version
*/
public ver: number;
/**
* Name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template.
*/
public name: string;
/**
* Identifier of a dependency call instance. Used for correlation with the request telemetry item corresponding to this dependency call.
*/
public id: string;
/**
* Result code of a dependency call. Examples are SQL error code and HTTP status code.
*/
public resultCode: string;
/**
* Request duration in format: DD.HH:MM:SS.MMMMMM. Must be less than 1000 days.
*/
public duration: string;
/**
* Indication of successfull or unsuccessfull call.
*/
public success: boolean;
/**
* Command initiated by this dependency call. Examples are SQL statement and HTTP URL's with all query parameters.
*/
public data: string;
/**
* Target site of a dependency call. Examples are server name, host address.
*/
public target: string;
/**
* Dependency type name. Very low cardinality value for logical grouping of dependencies and interpretation of other fields like commandName and resultCode. Examples are SQL, Azure table, and HTTP.
*/
public type: string;
/**
* Collection of custom properties.
*/
public properties: any;
/**
* Collection of custom measurements.
*/
public measurements: any;
constructor()
{
super();
this.ver = 2;
this.success = true;
this.properties = {};
this.measurements = {};
}
}
}

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

@ -1,65 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
/// <reference path="Domain.ts" />
module AI
{
"use strict";
/**
* An instance of Request represents completion of an external request to the application to do work and contains a summary of that request execution and the results.
*/
export class RequestData extends Microsoft.Telemetry.Domain
{
/**
* Schema version
*/
public ver: number;
/**
* Identifier of a request call instance. Used for correlation between request and other telemetry items.
*/
public id: string;
/**
* Source of the request. Examples are the instrumentation key of the caller or the ip address of the caller.
*/
public source: string;
/**
* Name of the request. Represents code path taken to process request. Low cardinality value to allow better grouping of requests. For HTTP requests it represents the HTTP method and URL path template like 'GET /values/{id}'.
*/
public name: string;
/**
* Indication of successfull or unsuccessfull call.
*/
public success: boolean;
/**
* Request URL with all query string parameters.
*/
public url: string;
/**
* Collection of custom properties.
*/
public properties: any;
/**
* Collection of custom measurements.
*/
public measurements: any;
constructor()
{
super();
this.ver = 2;
this.properties = {};
this.measurements = {};
}
}
}

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

@ -1,20 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module AI
{
"use strict";
/**
* Defines the level of severity for the event.
*/
export enum SeverityLevel
{
Verbose = 0,
Information = 1,
Warning = 2,
Error = 3,
Critical = 4,
}
}

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

@ -1,44 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// THIS FILE WAS AUTOGENERATED
module AI
{
"use strict";
/**
* Stack frame information.
*/
export class StackFrame
{
/**
* Level in the call stack. For the long stacks SDK may not report every function in a call stack.
*/
public level: number;
/**
* Method name.
*/
public method: string;
/**
* Name of the assembly (dll, jar, etc.) containing this function.
*/
public assembly: string;
/**
* File name or URL of the method implementation.
*/
public fileName: string;
/**
* Line number of the code implementation.
*/
public line: number;
constructor()
{
}
}
}

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

@ -1,156 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/// <reference path="./IConfig.ts" />
/// <reference path="./ITelemetryContext.ts" />
/// <reference path="./Contracts/Generated/SeverityLevel.ts" />
module Microsoft.ApplicationInsights {
"use strict";
export interface IAppInsights {
/*
* Config object used to initialize AppInsights
*/
config: IConfig;
context: ITelemetryContext;
/*
* Initialization queue. Contains functions to run when appInsights initializes
*/
queue: Array<() => void>;
/**
* Starts timing how long the user views a page or other item. Call this when the page opens.
* This method doesn't send any telemetry. Call `stopTrackPage` to log the page when it closes.
* @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title.
*/
startTrackPage(name?: string);
/**
* Logs how long a page or other item was visible, after `startTrackPage`. Call this when the page closes.
* @param name The string you used as the name in startTrackPage. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; });
/**
* Logs that a page or other item was viewed.
* @param name The string you used as the name in `startTrackPage`. Defaults to the document title.
* @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location.
* @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty.
* @param duration number - the number of milliseconds it took to load the page. Defaults to undefined. If set to default value, page load time is calculated internally.
*/
trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number);
/**
* Start timing an extended event. Call `stopTrackEvent` to log the event when it ends.
* @param name A string that identifies this event uniquely within the document.
*/
startTrackEvent(name: string);
/**
* Log an extended event that you started timing with `startTrackEvent`.
* @param name The string you used to identify this event in `startTrackEvent`.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; });
/**
* Log a user action or other occurrence.
* @param name A string to identify this event in the portal.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; });
/**
* Log a dependency call
* @param id unique id, this is used by the backend o correlate server requests. Use Util.newId() to generate a unique Id.
* @param method represents request verb (GET, POST, etc.)
* @param absoluteUrl absolute url used to make the dependency request
* @param pathName the path part of the absolute url
* @param totalTime total request time
* @param success indicates if the request was sessessful
* @param resultCode response code returned by the dependency request
*/
trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number);
/**
* Log an exception you have caught.
* @param exception An Error from a catch clause, or the string error message.
* @param handledAt Not used
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
* @param severityLevel AI.SeverityLevel - severity level
*/
trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel);
/**
* Log a numeric value that is not associated with a specific event. Typically used to send regular reports of performance indicators.
* To send a single measurement, use just the first two parameters. If you take measurements very frequently, you can reduce the
* telemetry bandwidth by aggregating multiple measurements and sending the resulting average at intervals.
* @param name A string that identifies the metric.
* @param average Number representing either a single measurement, or the average of several measurements.
* @param sampleCount The number of measurements represented by the average. Defaults to 1.
* @param min The smallest measurement in the sample. Defaults to the average.
* @param max The largest measurement in the sample. Defaults to the average.
*/
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; });
/**
* Log a diagnostic message.
* @param message A message string
* @param properties map[string, string] - additional data used to filter traces in the portal. Defaults to empty.
* @param severityLevel AI.SeverityLevel - severity level
*/
trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: AI.SeverityLevel);
/**
* Immediately send all queued telemetry.
* @param {boolean} async - If flush should be call asynchronously
*/
flush(async?: boolean);
/**
* Sets the authenticated user id and the account id in this session.
* User auth id and account id should be of type string. They should not contain commas, semi-colons, equal signs, spaces, or vertical-bars.
*
* @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service.
* @param accountId {string} - An optional string to represent the account associated with the authenticated user.
*/
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string);
/**
* Clears the authenticated user id and the account id from the user context.
*/
clearAuthenticatedUserContext();
/*
* Downloads and initializes AppInsights. You can override default script download location by specifying url property of `config`.
*/
downloadAndSetup?(config: Microsoft.ApplicationInsights.IConfig): void;
/**
* The custom error handler for Application Insights
* @param {string} message - The error message
* @param {string} url - The url where the error was raised
* @param {number} lineNumber - The line number where the error was raised
* @param {number} columnNumber - The column number for the line where the error was raised
* @param {Error} error - The Error object
*/
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error);
}
}

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

@ -1,44 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights {
"use strict";
export interface IConfig {
instrumentationKey?: string;
endpointUrl?: string;
emitLineDelimitedJson?: boolean;
accountId?: string;
sessionRenewalMs?: number;
sessionExpirationMs?: number;
maxBatchSizeInBytes?: number;
maxBatchInterval?: number;
enableDebug?: boolean;
disableExceptionTracking?: boolean;
disableTelemetry?: boolean;
verboseLogging?: boolean;
diagnosticLogInterval?: number;
samplingPercentage?: number;
autoTrackPageVisitTime?: boolean;
disableAjaxTracking?: boolean;
overridePageViewDuration?: boolean;
maxAjaxCallsPerView?: number;
disableDataLossAnalysis?: boolean;
disableCorrelationHeaders?: boolean;
correlationHeaderExcludedDomains?: string[];
correlationHeaderExcludePatterns?: RegExp[];
disableFlushOnBeforeUnload?: boolean;
enableSessionStorageBuffer?: boolean;
isCookieUseDisabled?: boolean;
cookieDomain?: string;
isRetryDisabled?: boolean;
url?: string;
isStorageUseDisabled?: boolean;
isBeaconApiDisabled?: boolean;
sdkExtension?: string;
isBrowserLinkTrackingEnabled?: boolean;
appId?: string;
enableCorsCorrelation?: boolean;
}
}

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

@ -1,74 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/// <reference path="./Contracts/Generated/Envelope.ts" />
/// <reference path="./Context/IApplication.ts"/>
/// <reference path="./Context/IDevice.ts"/>
/// <reference path="./Context/IInternal.ts"/>
/// <reference path="./Context/ILocation.ts"/>
/// <reference path="./Context/IOperation.ts"/>
/// <reference path="./Context/ISample.ts"/>
/// <reference path="./Context/IUser.ts"/>
/// <reference path="./Context/ISession.ts"/>
/// <reference path="./Telemetry/IEnvelope.ts"/>
module Microsoft.ApplicationInsights {
"use strict";
export interface ITelemetryContext {
/**
* The object describing a component tracked by this object.
*/
application: Context.IApplication;
/**
* The object describing a device tracked by this object.
*/
device: Context.IDevice;
/**
* The object describing internal settings.
*/
internal: Context.IInternal;
/**
* The object describing a location tracked by this object.
*/
location: Context.ILocation;
/**
* The object describing a operation tracked by this object.
*/
operation: Context.IOperation;
/**
* The object describing sampling settings.
*/
sample: Context.ISample;
/**
* The object describing a user tracked by this object.
*/
user: Context.IUser;
/**
* The object describing a session tracked by this object.
*/
session: Context.ISession;
/**
* Adds a telemetry initializer to the collection. Telemetry initializers will be called one by one,
* in the order they were added, before the telemetry item is pushed for sending.
* If one of the telemetry initializers returns false or throws an error then the telemetry item will not be sent.
* If it returns true or doesn't return any value the event will be passed to the next telemetry initializer and
* send to the cloud (if not rejected by other initializers).
*/
addTelemetryInitializer(telemetryInitializer: (envelope: Microsoft.ApplicationInsights.IEnvelope) => boolean | void);
/**
* Tracks telemetry object.
*/
track(envelope: Microsoft.ApplicationInsights.IEnvelope);
}
}

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

@ -1,97 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.Default.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<ProjectGuid>{FAD54375-9834-4265-BAAC-77B64A6AEEC1}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<OutputPath>bin</OutputPath>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
<TypeScriptToolsVersion>1.8</TypeScriptToolsVersion>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<UseGlobalApplicationHostFile />
</PropertyGroup>
<ItemGroup>
<Service Include="{4A0DDDB5-7A95-4FBF-97CC-616D07737A77}" />
</ItemGroup>
<ItemGroup>
<TypeScriptCompile Include="Context\IApplication.ts" />
<TypeScriptCompile Include="Context\IDevice.ts" />
<TypeScriptCompile Include="Context\IInternal.ts" />
<TypeScriptCompile Include="Context\ILocation.ts" />
<TypeScriptCompile Include="Context\IOperation.ts" />
<TypeScriptCompile Include="Context\ISample.ts" />
<TypeScriptCompile Include="Context\ISession.ts" />
<TypeScriptCompile Include="Context\IUser.ts" />
<TypeScriptCompile Include="Contracts\Generated\AjaxCallData.ts" />
<TypeScriptCompile Include="Contracts\Generated\Base.ts" />
<TypeScriptCompile Include="Contracts\Generated\ContextTagKeys.ts" />
<TypeScriptCompile Include="Contracts\Generated\Data.ts" />
<TypeScriptCompile Include="Contracts\Generated\DataPoint.ts" />
<TypeScriptCompile Include="Contracts\Generated\DataPointType.ts" />
<TypeScriptCompile Include="Contracts\Generated\DependencyKind.ts" />
<TypeScriptCompile Include="Contracts\Generated\DependencySourceType.ts" />
<TypeScriptCompile Include="Contracts\Generated\Domain.ts" />
<TypeScriptCompile Include="Contracts\Generated\Envelope.ts" />
<TypeScriptCompile Include="Contracts\Generated\EventData.ts" />
<TypeScriptCompile Include="Contracts\Generated\ExceptionData.ts" />
<TypeScriptCompile Include="Contracts\Generated\ExceptionDetails.ts" />
<TypeScriptCompile Include="Contracts\Generated\MessageData.ts" />
<TypeScriptCompile Include="Contracts\Generated\MetricData.ts" />
<TypeScriptCompile Include="Contracts\Generated\PageViewData.ts" />
<TypeScriptCompile Include="Contracts\Generated\PageViewPerfData.ts" />
<TypeScriptCompile Include="Contracts\Generated\RemoteDependencyData.ts" />
<TypeScriptCompile Include="Contracts\Generated\RequestData.ts" />
<TypeScriptCompile Include="Contracts\Generated\SessionState.ts" />
<TypeScriptCompile Include="Contracts\Generated\SessionStateData.ts" />
<TypeScriptCompile Include="Contracts\Generated\SeverityLevel.ts" />
<TypeScriptCompile Include="Contracts\Generated\StackFrame.ts" />
<TypeScriptCompile Include="IAppInsights.ts" />
<TypeScriptCompile Include="IConfig.ts" />
<TypeScriptCompile Include="ITelemetryContext.ts" />
<TypeScriptCompile Include="Telemetry\IEnvelope.ts" />
<TypeScriptCompile Include="Telemetry\ISerializable.ts" />
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">12.0</VisualStudioVersion>
</PropertyGroup>
<PropertyGroup>
<RootNamespace>JavaScriptSDK.Interfaces</RootNamespace>
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\WebApplications\Microsoft.WebApplication.targets')" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>True</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>1158</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:1158/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<TypeScriptRemoveComments>false</TypeScriptRemoveComments>
<TypeScriptSourceMap>true</TypeScriptSourceMap>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<TypeScriptRemoveComments>true</TypeScriptRemoveComments>
<TypeScriptSourceMap>false</TypeScriptSourceMap>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\TypeScript\Microsoft.TypeScript.targets')" />
</Project>

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

@ -1,20 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/// <reference path="./ISerializable.ts" />
module Microsoft.ApplicationInsights {
"use strict";
export interface IEnvelope extends ISerializable {
ver: number;
name: string;
time: string;
sampleRate: number;
seq: string;
iKey: string;
tags: { [name: string]: any };
data: any;
}
}

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

@ -1,16 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
module Microsoft.ApplicationInsights {
"use strict";
export interface ISerializable {
/**
* The set of fields for a serializable object.
* This defines the serialization order and a value of true/false
* for each field defines whether the field is required or not.
*/
aiDataContract: any;
}
}

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

@ -1,142 +0,0 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
/// <reference path="../JavaScriptSDK.Interfaces/IConfig.ts"/>
/// <reference path="../JavaScriptSDK.Interfaces/IAppInsights.ts"/>
/// <reference path="../JavaScriptSDK/UtilHelpers.ts"/>
"use strict";
class AppInsightsModule {
private static appInsightsInitialized: boolean = false;
private static appInsightsName = "appInsights";
private static _createLazyMethod(name) {
var aiObject = window[AppInsightsModule.appInsightsName];
// Define a temporary method that queues-up a the real method call
aiObject[name] = function () {
// Capture the original arguments passed to the method
var originalArguments = arguments;
// If the queue is available, it means that the function wasn't yet replaced with actual function value
if (aiObject.queue) {
aiObject.queue.push(() => aiObject[name].apply(aiObject, originalArguments));
}
else {
// otherwise execute the function
aiObject[name].apply(aiObject, originalArguments);
}
}
};
private static _defineLazyMethods() {
var aiObject = window[AppInsightsModule.appInsightsName];
// capture initial cookie if possible
try {
(<any>aiObject).cookie = document.cookie;
}
catch (e) {
}
aiObject.queue = [];
var method = [
"clearAuthenticatedUserContext",
"flush",
"setAuthenticatedUserContext",
"startTrackEvent",
"startTrackPage",
"stopTrackEvent",
"stopTrackPage",
"trackDependency",
"trackEvent",
"trackException",
"trackMetric",
"trackPageView",
"trackTrace"
];
while (method.length) {
AppInsightsModule._createLazyMethod(method.pop());
}
}
private static _download(aiConfig: Microsoft.ApplicationInsights.IConfig) {
AppInsightsModule.getAppInsightsInstance().config = aiConfig;
var aiObject = window[AppInsightsModule.appInsightsName];
// if script was previously downloaded and initialized, queue will be deleted, reinitialize it
if (!aiObject.queue) {
aiObject.queue = [];
}
setTimeout(function () {
var scriptElement = document.createElement("script");
scriptElement.src = aiConfig.url || "https://az416426.vo.msecnd.net/scripts/a/ai.0.js";
document.head.appendChild(scriptElement);
});
// collect global errors by wrapping the window.onerror method
if (!aiConfig.disableExceptionTracking) {
let method = "onerror";
AppInsightsModule._createLazyMethod("_" + method);
var originalOnError = window[method];
window[method] = function (message, url, lineNumber, columnNumber, error) {
var handled = originalOnError && originalOnError(message, url, lineNumber, columnNumber, error);
if (handled !== true) {
aiObject["_" + method](message, url, lineNumber, columnNumber, error);
}
return handled;
};
}
}
/**
* This property returns the current instance of the appInsights, the property is optional as
* it will only defined when running in an ES5+ browser, if your users are using an ES3 browser
* (IE8) you should use the function getter(getAppInsightsInstance()) instead.
* This change was added in Nov'19 and may not be published -- check your deployed version
*/
public static readonly appInsightsInstance?: Microsoft.ApplicationInsights.IAppInsights;
public static getAppInsightsInstance(): Microsoft.ApplicationInsights.IAppInsights {
if (typeof window === 'undefined') {
return;
}
if (!window[AppInsightsModule.appInsightsName]) {
window[AppInsightsModule.appInsightsName] = {
downloadAndSetup: AppInsightsModule._download,
// exposing it for unit tests only, not part of interface
_defineLazyMethods: AppInsightsModule._defineLazyMethods
};
AppInsightsModule._defineLazyMethods();
}
return window[AppInsightsModule.appInsightsName];
}
/**
* Static constructor, attempt to ES5 get accessor
*/
private static _staticInit = (() => {
// Dynamically create get/set property accessors
let defineProp = Object["defineProperty"];
try {
defineProp && defineProp(AppInsightsModule.prototype, "appInsightsInstance", {
get: AppInsightsModule.getAppInsightsInstance,
enumerable: true,
configurable: true
});
} catch (e) {
// IE8 Defines a defineProperty on Object but it's only supported for DOM elements so it will throw
// We will just ignore this here.
}
})();
}
export var AppInsights: Microsoft.ApplicationInsights.IAppInsights = AppInsightsModule.getAppInsightsInstance();
export var Util: typeof Microsoft.ApplicationInsights.UtilHelpers;

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

@ -1,65 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<ProjectGuid>{9efeed47-7841-4356-8a6f-ad16ff9a28e4}</ProjectGuid>
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<OutputPath>bin</OutputPath>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<DebugType>full</DebugType>
<DebugSymbols>true</DebugSymbols>
<UseIISExpress>true</UseIISExpress>
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<RootNamespace>ApplicationInsights.Javascript</RootNamespace>
<TypeScriptGeneratesDeclarations>True</TypeScriptGeneratesDeclarations>
<TypeScriptModuleKind>AMD</TypeScriptModuleKind>
<TypeScriptTarget>ES5</TypeScriptTarget>
<!-- Suppress the "CS2008: No source files specified" warning -->
<NoWarn>2008</NoWarn>
<UseGlobalApplicationHostFile />
</PropertyGroup>
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
<Import Project="..\..\..\packages\AjaxMin.5.5.5091.22839\tools\net40\AjaxMin.targets" Condition="Exists('..\..\..\packages\AjaxMin.5.5.5091.22839\tools\net40\AjaxMin.targets')" />
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<UseIIS>False</UseIIS>
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>52143</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:52102/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl>
</CustomServerUrl>
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptRemoveComments>false</TypeScriptRemoveComments>
<TypeScriptSourceMap>true</TypeScriptSourceMap>
<TypeScriptModuleKind>AMD</TypeScriptModuleKind>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<TypeScriptTarget>ES5</TypeScriptTarget>
<TypeScriptRemoveComments>true</TypeScriptRemoveComments>
<TypeScriptSourceMap>false</TypeScriptSourceMap>
<TypeScriptModuleKind>AMD</TypeScriptModuleKind>
</PropertyGroup>
<ItemGroup>
<TypeScriptCompile Include="AppInsightsModule.ts" />
</ItemGroup>
<Import Project="$(VSToolsPath)\TypeScript\Microsoft.TypeScript.targets" Condition="Exists('$(VSToolsPath)\TypeScript\Microsoft.TypeScript.targets')" />
</Project>

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

@ -1,115 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
import {AppInsights, Util} from "../../JavaScriptSDK.Module/AppInsightsModule"
export default class AppInsightsModuleTests extends TestClass {
private static expectedMethods = [
"clearAuthenticatedUserContext",
"flush",
"setAuthenticatedUserContext",
"startTrackEvent",
"startTrackPage",
"stopTrackEvent",
"stopTrackPage",
"trackDependency",
"trackEvent",
"trackException",
"trackMetric",
"trackPageView",
"trackTrace"
];
private static getUncachedScriptUrl() {
return "https://az416426.vo.msecnd.net/scripts/a/ai.0.js?s=" + (new Date()).getTime().toString();
}
public testInitialize() {
// this is a workaround to force re-initialized of imported variable
AppInsights["_defineLazyMethods"]();
}
public registerTests() {
this.useFakeTimers = false;
this.testCaseAsync({
name: "AppInsightsModuleTests: downloadAndSetup",
steps: [
() => {
Assert.ok(AppInsights.queue, "Queue should initially be defined");
// need to override the url, otherwise file:// is used for local test runs.
AppInsights.downloadAndSetup({ instrumentationKey: "test", url: AppInsightsModuleTests.getUncachedScriptUrl()});
},
<() => void>
PollingAssert.createPollingAssert(
() => !AppInsights.queue,
"Queue object is cleaned and removed after script loads")
],
stepDelay: 0
});
this.testCase({
name: "AppInsightsModuleTests: verify methods are registered",
test: () => {
AppInsights.downloadAndSetup({ instrumentationKey: "test" });
for (var i = 0; i < AppInsightsModuleTests.expectedMethods.length; i++) {
Assert.ok(AppInsights[AppInsightsModuleTests.expectedMethods[i]], AppInsightsModuleTests.expectedMethods[i] + " should be defined");
}
}
});
this.testCaseAsync({
name: "AppInsightsModuleTests: verifying queue is flushed when loading",
steps: [
() => {
AppInsights.downloadAndSetup({ instrumentationKey: "test", url: AppInsightsModuleTests.getUncachedScriptUrl() });
AppInsights.queue.push(() => this["queueFlushed"] = true);
this["queueFlushed"] = false;
},
<() => void>
PollingAssert.createPollingAssert(
() => this["queueFlushed"] === true,
"Actions in the queue are executed when queue is flushed")
],
stepDelay: 0
});
this.testCase({
name: "AppInsightsModuleTests: verify track* methods are defined before calling downloadAndSetup",
test: () => {
for (var i = 0; i < AppInsightsModuleTests.expectedMethods.length; i++) {
Assert.ok(AppInsights[AppInsightsModuleTests.expectedMethods[i]], AppInsightsModuleTests.expectedMethods[i] + " should be defined");
}
}
});
this.testCase({
name: "AppInsightsModuleTests: verify track* method calls called before downloadAndSetup end up in the queue",
test: () => {
AppInsights.trackTrace("");
AppInsights.trackEvent("");
AppInsights.trackTrace("");
Assert.equal(3, AppInsights.queue.length);
AppInsights.downloadAndSetup({ instrumentationKey: "test", url: AppInsightsModuleTests.getUncachedScriptUrl() });
Assert.equal(3, AppInsights.queue.length);
}
});
this.testCase({
name: "UtilHelpers: exposed Util.newId() generates unique GUIDs",
test: () => {
var results = [];
for (var i = 0; i < 100; i++) {
var newId = Util.newId();
for (var j = 0; j < results.length; j++) {
Assert.notEqual(newId, results[j]);
}
results.push(newId);
}
}
});
}
}

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

@ -1,81 +0,0 @@
/// <reference path="../../../JavaScriptSDK/AppInsights.ts" />
/// <reference path="../../../JavaScriptSDK/Util.ts" />
/// <reference path="../../../JavaScriptSDK/HashCodeScoreGenerator.ts" />
/// <reference path="../../TestFramework/Common.ts" />
class HashCodeScoreGeneratorTests extends TestClass {
private originalDocument;
private results: any[];
/** Method called before the start of each test method */
public testInitialize() {
this.results = [];
}
/** Method called after each test method has completed */
public testCleanup() {
this.results = [];
}
public registerTests() {
var contextKeys = new AI.ContextTagKeys();
this.testCase({
name: "HashCodeGeneratorTests: results consistent with .net implementation",
test: () => {
// test array is produced by .net sdk test
var testArray = [
["ss", 1179811869],
["kxi", 34202699],
["wr", 1281077591],
["ynehgfhyuiltaiqovbpyhpm", 2139623659],
["iaxxtklcw", 1941943012],
["hjwvqjiiwhoxrtsjma", 1824011880],
["rpiauyg", 251412007],
["jekvjvh", 9189387],
["hq", 1807146729],
["kgqxrftjhefkwlufcxibwjcy", 270215819],
["lkfc", 1228617029],
["skrnpybqqu", 223230949],
["px", 70671963],
["dtn", 904623389],
["nqfcxobaequ", 397313566],
["togxlt", 948170633],
["jvvdkhnahkaujxarkd", 1486894898],
["mcloukvkamiaqja", 56804453],
["ornuu", 1588005865],
["otodvlhtvu", 1544494884],
["uhpwhasnvmnykjkitla", 981289895],
["itbnryqnjcgpmgivlghqtg", 1923061690],
["wauetkdnivwlafbfhiedsfx", 2114415420],
["fniwmeidbvd", 508699380],
["vuwdgoxspstvj", 1821547235],
["y", 1406544563],
["pceqcixfb", 1282453766],
["aentke", 255756533],
["ni", 1696510239],
["lbwehevltlnl", 1466602040],
["ymxql", 1974582171],
["mvqbaosfuip", 1560556398],
["urmwofajwmmlornynglm", 701710403],
["buptyvonyacerrt", 1315240646],
["cxsqcnyieliatqnwc", 76148095],
["svvco", 1849105799],
["luwmjhwyt", 553630912],
["lisvmmug", 822987687],
["mmntilfbmxwuyij", 882214597],
["hqmyv", 1510970959],
];
var sut = new Microsoft.ApplicationInsights.HashCodeScoreGenerator();
for (var i = 0; i < testArray.length; ++i) {
var res = sut.getHashCode(<string>testArray[i][0]);
Assert.equal(<number>testArray[i][1], res);
}
}
});
}
}
new HashCodeScoreGeneratorTests().registerTests();

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

@ -1,163 +0,0 @@
/// <reference path="../../../JavaScriptSDK/AppInsights.ts" />
/// <reference path="../../../JavaScriptSDK/Context/Sample.ts" />
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../Util.tests.ts"/>
class SampleContextTests extends TestClass {
private originalDocument;
private results: any[];
/** Method called before the start of each test method */
public testInitialize() {
this.results = [];
}
/** Method called after each test method has completed */
public testCleanup() {
this.results = [];
}
public registerTests() {
var contextKeys = new AI.ContextTagKeys();
this.testCase({
name: "Sampling: isSampledIn returns true for 100 sampling rate",
test: () => {
// setup
var sample = new Microsoft.ApplicationInsights.Context.Sample(100);
var envelope = this.getEnvelope();
envelope.tags[contextKeys.userId] = null;
envelope.tags[contextKeys.operationId] = null;
// act
var isSampledIn = sample.isSampledIn(envelope);
// assert
Assert.ok(isSampledIn);
}
});
this.testCase({
name: "Sampling: hashing is based on user id even if operation id is provided",
test: () => {
// setup
var sample = new Microsoft.ApplicationInsights.Context.Sample(33);
var userid = "asdf";
var envelope1 = this.getEnvelope();
envelope1.tags[contextKeys.userId] = userid;
envelope1.tags[contextKeys.operationId] = "operation 1";
var envelope2 = this.getEnvelope();
envelope2.tags[contextKeys.userId] = userid;
envelope2.tags[contextKeys.operationId] = "operation 2";
// act
var isSampledIn1 = sample.isSampledIn(envelope1);
var isSampledIn2 = sample.isSampledIn(envelope2);
// assert
Assert.equal(isSampledIn1, isSampledIn2);
}
});
this.testCase({
name: "Sampling: hashing is based on operation id if no user id is provided",
test: () => {
// setup
var sample = new Microsoft.ApplicationInsights.Context.Sample(33);
var operationid = "operation id";
var envelope1 = this.getEnvelope();
envelope1.tags[contextKeys.userId] = null;
envelope1.tags[contextKeys.operationId] = operationid;
var envelope2 = this.getEnvelope();
envelope2.tags[contextKeys.userId] = null;
envelope2.tags[contextKeys.operationId] = operationid;
var envelope3 = this.getEnvelope();
envelope3.tags[contextKeys.userId] = undefined;
envelope3.tags[contextKeys.operationId] = operationid;
var envelope4 = this.getEnvelope();
envelope4.tags[contextKeys.userId] = "";
envelope4.tags[contextKeys.operationId] = operationid;
// act
var isSampledIn1 = sample.isSampledIn(envelope1);
var isSampledIn2 = sample.isSampledIn(envelope2);
var isSampledIn3 = sample.isSampledIn(envelope3);
var isSampledIn4 = sample.isSampledIn(envelope4);
// assert
Assert.equal(isSampledIn1, isSampledIn2);
Assert.equal(isSampledIn1, isSampledIn3);
Assert.equal(isSampledIn1, isSampledIn4);
}
});
this.testCase({
name: "Sampling: hashing is random if no user id nor operation id provided",
test: () => {
// setup
var sample = new Microsoft.ApplicationInsights.Context.Sample(33);
var envelope1 = this.getEnvelope();
envelope1.tags[contextKeys.userId] = null;
envelope1.tags[contextKeys.operationId] = null;
var mathRandomSpy = this.sandbox.spy(Math, "random");
// act
sample.isSampledIn(envelope1);
// assert
Assert.ok(mathRandomSpy.calledOnce);
}
});
this.testCase({
name: "Sampling: actual sampling rate should fall into 5% error range",
test: () => {
// setup
var errorRange = 5;
var totalItems = 1000;
var ids = [];
for (var i = 0; i < totalItems; ++i) {
ids.push(Microsoft.ApplicationInsights.Util.newId());
}
var sampleRates = [50, 33, 25, 20, 16, 10];
// act
sampleRates.forEach((sampleRate) => {
var sut = new Microsoft.ApplicationInsights.HashCodeScoreGenerator();
var countOfSampledItems = 0;
ids.forEach(function (id) {
if (sut.getHashCodeScore(id) < sampleRate)++countOfSampledItems;
});
// Assert
var actualSampleRate = 100 * countOfSampledItems / totalItems;
Assert.ok(Math.abs(actualSampleRate - sampleRate) < errorRange,
"Actual sampling (" + actualSampleRate + ") does not fall into +-2% range from expected rate (" + sampleRate + ")");
});
}
});
}
private getEnvelope(): Microsoft.ApplicationInsights.Telemetry.Common.Envelope {
var pageView = new Microsoft.ApplicationInsights.Telemetry.PageView();
var data = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageView>(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageView);
return new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType);
}
}
new SampleContextTests().registerTests();

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

@ -1,524 +0,0 @@
/// <reference path="../../../JavaScriptSDK/TelemetryContext.ts" />
/// <reference path="../../../JavaScriptSDK/Context/Session.ts" />
/// <reference path="../../../JavaScriptSDK/Context/User.ts" />
/// <reference path="../../../JavaScriptSDK/ajax/ajaxUtils.ts" />
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../Util.tests.ts"/>
class SessionContextTests extends TestClass {
private originalDocument = Microsoft.ApplicationInsights.Util["document"];
private results: any[];
private dateTimeNowObj = Microsoft.ApplicationInsights.dateTime.Now;
/** Method called before the start of each test method */
public testInitialize() {
this.results = [];
this.resetStorage();
this.restoreFakeCookie();
// SinonFakeTimers doesn't mock "performance.now" - https://github.com/sinonjs/lolex/issues/82
// this is a hack to mock the clock
Microsoft.ApplicationInsights.dateTime.Now = Date.now;
}
/** Method called after each test method has completed */
public testCleanup() {
this.results = [];
this.resetStorage();
this.restoreFakeCookie();
// restore original dateTime.Now object
Microsoft.ApplicationInsights.dateTime.Now = this.dateTimeNowObj;
}
public registerTests() {
this.testCase({
name: "SessionContext: session manager does not initialize automatic session in constructor",
test: () => {
// no cookie, isNew should be true
Microsoft.ApplicationInsights.Util["document"] = <any>{
cookie: ""
};
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
Assert.ok(!sessionManager.automaticSession.isFirst, "isFirst");
Assert.ok(!sessionManager.automaticSession.id, "id");
Assert.ok(!sessionManager.automaticSession.acquisitionDate, "acquisitionDate");
Assert.ok(!sessionManager.automaticSession.renewalDate, "renewalDate");
}
});
this.testCase({
name: "SessionContext: session manager updates isFirst field correctly",
test: () => {
// no cookie, isNew should be true
Microsoft.ApplicationInsights.Util["document"] = <any>{
cookie: ""
};
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
// after first update, should be true
this.clock.tick(10);
sessionManager.update();
Assert.ok(sessionManager.automaticSession.isFirst, "isFirst should be true after 1st update");
// after second update also true
sessionManager.update();
Assert.ok(sessionManager.automaticSession.isFirst, "isFirst should be true after 2st update");
// after renewal, should be false
this.clock.tick(Microsoft.ApplicationInsights.Context._SessionManager.renewalSpan + 1);
sessionManager.update();
Assert.ok(!sessionManager.automaticSession.isFirst, "isFirst should be false after renewal");
}
});
this.testCase({
name: "SessionContext: when sessionmanager initailzes it sets isFirst to false if cookie is present",
test: () => {
// no cookie, isNew should be true
Microsoft.ApplicationInsights.Util["document"] = <any>{
cookie: ""
};
this.clock.tick(10);
var sessionManager1 = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager1.update();
this.clock.tick(Microsoft.ApplicationInsights.Context._SessionManager.renewalSpan + 1);
// Creating one more instance immulate that browser was closed
var sessionManager2 = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager2.update();
Assert.ok(!sessionManager2.automaticSession.isFirst, "isFirst should be false because it is same browser/user");
}
});
this.testCase({
name: "ai_session cookie has correct structure",
test: () => {
// setup
var actualCookieName: string;
var actualCookieValue: string;
var newIdStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "newId", () => "newId");
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => "");
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie", (cookieName, cookieValue) => {
actualCookieName = cookieName;
actualCookieValue = cookieValue;
});
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
// verify
Assert.equal("ai_session", actualCookieName, "ai_session cookie is set");
var cookieValueParts = actualCookieValue.split(';');
Assert.equal(2, cookieValueParts.length, "Cookie value should have actual value and expiration");
Assert.equal(3, cookieValueParts[0].split('|').length, "Cookie value before expiration should include user id, acq date and renew date");
Assert.equal("newId", cookieValueParts[0].split('|')[0], "First part of cookie value should be new user id guid");
// The cookie should expire 30 minutes after activity by default
var expiration = cookieValueParts[1];
Assert.equal(true, expiration.substr(0, "expires=".length) === "expires=", "Cookie expiration part should start with expires=");
var expirationDate = new Date(expiration.substr("expires=".length));
Assert.equal(30, expirationDate.getTime() / 1000 / 60, "cookie expiration should be in 30 minutes");
}
});
this.testCase({
name: "ai_session local storage has correct structure",
test: () => {
if (Microsoft.ApplicationInsights.Util.canUseLocalStorage()) {
// setup
var actualCookieName: string;
var actualCookieValue: string;
var newIdStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "newId", () => "newId");
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie",() => "");
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie",(cookieName, cookieValue) => { });
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
sessionManager.backup();
// verify
Assert.ok(localStorage["ai_session"], "ai_session storage is set");
Assert.equal(3, localStorage["ai_session"].split('|').length, "Cookie value before expiration should include user id, acq date and renew date");
Assert.equal("newId", localStorage["ai_session"].split('|')[0], "First part of cookie value should be new user id guid");
} else {
// this might happen on IE when using a file:// url
Assert.ok(true, "browser does not support local storage in current environment");
}
}
});
this.testCase({
name: "SessionContext: session manager can back up session when localStorage is available",
test: () => {
var cookies = {};
var storage = {};
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie",(name) => cookies[name]);
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie",(name, value) => {
cookies[name] = value;
});
var getStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getStorage",(name) => storage[name]);
var setStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setStorage",(name, value) => {
storage[name] = value;
});
// Initialize our user and session cookies
var sessionId = "SESSID";
var curDate = Microsoft.ApplicationInsights.dateTime.Now();
cookies['ai_user'] = 'user';
cookies['ai_session'] = this.generateFakeSessionCookieData(sessionId, curDate, curDate);
// Ensure session manager backs up properly
new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
sessionManager.backup();
Assert.ok(storage['ai_session'], "session cookie should be backed up in local storage");
}
});
this.testCase({
name: "SessionContext: session manager can recover old session id and isFirst state from lost cookies when localStorage is available",
test: () => {
var cookies = {};
var storage = {};
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie",(name) => cookies[name]);
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie",(name, value) => {
cookies[name] = value;
});
var getStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getStorage",(name) => storage[name]);
var setStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setStorage",(name, value) => {
storage[name] = value;
});
// Initialize our user cookie and local storage
// Note there is no session cookie
var sessionId = "SESSID";
var curDate = Microsoft.ApplicationInsights.dateTime.Now();
cookies['ai_user'] = 'user';
storage['ai_session'] = this.generateFakeSessionCookieData(sessionId, curDate, curDate);
// Initalize the session manager
new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
sessionManager.backup();
// We should recover
Assert.equal(sessionId, sessionManager.automaticSession.id, "session id should be consistent with value before losing session cookie");
Assert.ok(!sessionManager.automaticSession.isFirst, "the isFirst state should be conserved after losing the session cookie");
}
});
this.testCase({
name: "SessionContext: session manager uses a new session when user cookie is deleted despite local storage being available",
test: () => {
var cookies = {};
var storage = {};
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie",(name) => cookies[name]);
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie",(name, value) => {
cookies[name] = value;
});
var getStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getStorage",(name) => storage[name]);
var setStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setStorage",(name, value) => {
storage[name] = value;
});
var removeStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "removeStorage",(name, value) => {
storage[name] = undefined;
});
// Initialize our local storage
// Note no cookies are available
var sessionId = "SESSID";
var curDate = Microsoft.ApplicationInsights.dateTime.Now();
storage['ai_session'] = this.generateFakeSessionCookieData(sessionId, curDate, curDate);
// Initialize the session manager
new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
// Verify the backup was lost
Assert.ok(!storage['ai_session'], "the local storage backup should be removed");
// Everything should be reset with the backup removed
Assert.notEqual(sessionId, sessionManager.automaticSession.id, "a new session id should be given after losing all ai cookies");
Assert.ok(sessionManager.automaticSession.isFirst, "the isFirst state should be reset after losing all ai cookies");
}
});
this.testCase({
name: "SessionContext: session manager cannot recover old session id and isFirst state from lost cookies when localStorage is unavailable",
test: () => {
var cookies = {};
var storage = {};
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie",(name) => cookies[name]);
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie",(name, value) => {
cookies[name] = value;
});
var getStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getStorage",(name) => null);
var setStorageStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setStorage",(name, value) => false);
// Initialize our user and session cookies
var sessionId = "SESSID";
var curDate = Microsoft.ApplicationInsights.dateTime.Now();
cookies['ai_user'] = 'user';
cookies['ai_session'] = this.generateFakeSessionCookieData(sessionId, curDate, curDate);
// Back up the session
new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
sessionManager.backup();
// Lose the session cookie but not the user cookie
cookies['ai_session'] = undefined;
new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
sessionManager.backup();
// The lost cookie should not be recovered from
Assert.notEqual(sessionId, sessionManager.automaticSession.id, "a new session id should be given after losing the session cookie");
Assert.ok(sessionManager.automaticSession.isFirst, "the isFirst state should be reset after losing the session cookie");
}
});
this.testCase({
name: "SessionContext: session manager sets the isFirst to false if cookie was present",
test: () => {
// no cookie, isNew should be true
Microsoft.ApplicationInsights.Util["document"] = <any>{
cookie: ""
};
var testGuid = "00000000-0000-0000-0000-000000000000";
var acquisitionDate = Microsoft.ApplicationInsights.dateTime.Now();
var renewalDate = Microsoft.ApplicationInsights.dateTime.Now();
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
Assert.ok(!sessionManager.automaticSession.isFirst, "isFirst is false when an existing session was set");
}
});
this.testCase({
name: "SessionContext: session manager honors session from the cookie",
test: () => {
// setup
var testGuid = "00000000-0000-0000-0000-000000000000";
var acquisitionDate = Microsoft.ApplicationInsights.dateTime.Now();
var renewalDate = Microsoft.ApplicationInsights.dateTime.Now();
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
// verify
Assert.equal(testGuid, sessionManager.automaticSession.id, "cookie session id was used");
Assert.equal(+new Date(acquisitionDate), sessionManager.automaticSession.acquisitionDate, "cookie acquisitionDate was used");
Assert.equal(+new Date(renewalDate), sessionManager.automaticSession.renewalDate, "cookie renewalDate was used");
}
});
this.testCase({
name: "SessionContext: session manager renews when renewal date has expired",
test: () => {
// setup
var testGuid = "00000000-0000-0000-0000-000000000000";
var delta = (Microsoft.ApplicationInsights.Context._SessionManager.renewalSpan + 1);
this.clock.tick(delta); // safari crashes without this
var cookieTime = +new Date - delta;
var acquisitionDate = +new Date(cookieTime);
var renewalDate = +new Date(cookieTime);
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
// verify
Assert.notEqual(testGuid, sessionManager.automaticSession.id, "cookie session id was renewed");
Assert.equal(delta, sessionManager.automaticSession.acquisitionDate, "cookie acquisitionDate was updated");
Assert.equal(delta, sessionManager.automaticSession.renewalDate, "cookie renewalDate was updated");
}
});
this.testCase({
name: "SessionContext: session manager renews when acquisition date has expired",
test: () => {
// setup
var testGuid = "00000000-0000-0000-0000-000000000000";
var delta = (Microsoft.ApplicationInsights.Context._SessionManager.acquisitionSpan + 1);
this.clock.tick(delta); // safari crashes without this
var cookieTime = +new Date - delta;
var acquisitionDate = +new Date(cookieTime);
var renewalDate = Microsoft.ApplicationInsights.dateTime.Now();
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
sessionManager.update();
// verify
Assert.notEqual(testGuid, sessionManager.automaticSession.id, "cookie session id was renewed");
Assert.equal(delta, sessionManager.automaticSession.acquisitionDate, "cookie acquisitionDate was updated");
Assert.equal(delta, sessionManager.automaticSession.renewalDate, "cookie renewalDate was updated");
}
});
this.testCase({
name: "SessionContext: the cookie is not updated more often than cookieUpdateInterval",
test: () => {
var cookieInterval = Microsoft.ApplicationInsights.Context._SessionManager.cookieUpdateInterval;
// setup
var testGuid = "00000000-0000-0000-0000-000000000000";
var acquisitionDate = Microsoft.ApplicationInsights.dateTime.Now();
var renewalDate = Microsoft.ApplicationInsights.dateTime.Now();
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// create session manager and call update to set the cookie
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
var setCookieSpy = this.sandbox.spy(sessionManager, "setCookie");
this.clock.tick(10);
sessionManager.update();
// verify
Assert.equal(1, setCookieSpy.callCount, "setCookie should be called only once");
Assert.equal(10, sessionManager.automaticSession.renewalDate, "cookie renewalDate was updated");
// try updating the cookie before the cookieUpdateInterval elapsed
this.clock.tick(cookieInterval - 1);
sessionManager.update();
// verify
Assert.equal(1, setCookieSpy.callCount, "setCookie should not be colled before cookieUpdateInterval elapsed");
Assert.equal(10, sessionManager.automaticSession.renewalDate, "cookie renewalDate was NOT updated");
// wait few more milliseconds till the cookieUpdateInterval elapsed
this.clock.tick(2);
sessionManager.update();
Assert.equal(2, setCookieSpy.callCount, "setCookie should be called after the cookieUpdateInterval elapsed");
Assert.equal(cookieInterval + 10 + 1, sessionManager.automaticSession.renewalDate, "cookie renewalDate was updated");
}
});
this.testCase({
name: "SessionContext: session manager updates renewal date when updated",
test: () => {
// setup
var testGuid = "00000000-0000-0000-0000-000000000000";
var acquisitionDate = Microsoft.ApplicationInsights.dateTime.Now();
var renewalDate = Microsoft.ApplicationInsights.dateTime.Now();
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null);
this.clock.tick(10);
sessionManager.update();
// verify
Assert.equal(testGuid, sessionManager.automaticSession.id, "cookie session id was not renewed");
Assert.equal(0, sessionManager.automaticSession.acquisitionDate, "cookie acquisitionDate was updated");
Assert.equal(10, sessionManager.automaticSession.renewalDate, "cookie renewalDate was updated");
}
});
this.testCase({
name: "SessionContext: config overrides work",
test: () => {
// setup
var sessionRenewalMs = 5;
var sessionExpirationMs = 10;
var config: Microsoft.ApplicationInsights.Context.ISessionConfig = {
sessionRenewalMs: () => sessionRenewalMs,
sessionExpirationMs: () => sessionExpirationMs,
cookieDomain: () => undefined
};
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(config);
// verify
Assert.equal(sessionRenewalMs, sessionManager.config.sessionRenewalMs(), "config sessionRenewalMs is set correctly");
Assert.equal(sessionExpirationMs, sessionManager.config.sessionExpirationMs(), "config sessionExpirationMs is set correctly");
// act
sessionRenewalMs = 6;
sessionExpirationMs = 11;
// verify
Assert.equal(sessionRenewalMs, sessionManager.config.sessionRenewalMs(), "config sessionRenewalMs is updated correctly");
Assert.equal(sessionExpirationMs, sessionManager.config.sessionExpirationMs(), "config sessionExpirationMs is updated correctly");
}
});
}
private setFakeCookie(id, acqDate, renewalDate) {
this.originalDocument = Microsoft.ApplicationInsights.Util["document"];
Microsoft.ApplicationInsights.Util["document"] = <any>{
cookie: "ai_user=user; ai_session="+this.generateFakeSessionCookieData(id, acqDate, renewalDate)
};
}
private generateFakeSessionCookieData(id, acqDate, renewalDate) {
return [id, acqDate, renewalDate].join("|");
}
private restoreFakeCookie() {
Microsoft.ApplicationInsights.Util["document"] = this.originalDocument;
}
private resetStorage() {
if (Microsoft.ApplicationInsights.Util.canUseLocalStorage()) {
window.localStorage.clear();
}
}
private getEmptyConfig(): Microsoft.ApplicationInsights.ITelemetryConfig {
return {
instrumentationKey: () => null,
accountId: () => null,
sessionRenewalMs: () => null,
sessionExpirationMs: () => null,
sampleRate: () => null,
endpointUrl: () => null,
cookieDomain: () => null,
emitLineDelimitedJson: () => null,
maxBatchSizeInBytes: () => null,
maxBatchInterval: () => null,
disableTelemetry: () => null,
enableSessionStorageBuffer: () => null,
isRetryDisabled: () => null,
isBeaconApiDisabled: () => null,
sdkExtension: () => null,
isBrowserLinkTrackingEnabled: () => null,
appId: () => null,
};
}
}
new SessionContextTests().registerTests();

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

@ -1,421 +0,0 @@
/// <reference path="../../../JavaScriptSDK/Context/User.ts" />
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../Util.tests.ts"/>
class UserContextTests extends TestClass {
constructor() {
super("UserContext");
}
/** Method called before the start of each test method */
public testInitialize() {
}
/** Method called after each test method has completed */
public testCleanup() {
}
public registerTests() {
this.testCase({
name: "Types: user context initializes from cookie when possible",
test: () => {
// setup
var id = "userId";
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => id + "||||");
// act
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// verify
Assert.equal(id, user.id, "user id was set from cookie");
}
});
this.testCase({
name: "ai_user cookie is set with acq date and year expiration",
test: () => {
// setup
var id = "userId";
var actualCookieName: string;
var actualCookieValue: string;
var newIdStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "newId", () => "newId");
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => "");
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie", (cookieName, cookieValue) => {
actualCookieName = cookieName;
actualCookieValue = cookieValue;
});
// act
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// verify
Assert.equal("ai_user", actualCookieName, "ai_user cookie is set");
var cookieValueParts = actualCookieValue.split(';');
Assert.equal(2, cookieValueParts.length, "ai_user cookie value should have actual value and expiration");
Assert.equal(2, cookieValueParts[0].split('|').length, "ai_user cookie value before expiration should include user id and acq date");
Assert.equal("newId", cookieValueParts[0].split('|')[0], "First part of ai_user cookie value should be new user id guid");
Assert.equal(new Date().toString(), (new Date(cookieValueParts[0].split('|')[1])).toString(), "Second part of ai_user cookie should be parsable as date");
var expiration = cookieValueParts[1];
Assert.equal(true, expiration.substr(0, "expires=".length) === "expires=", "ai_user cookie expiration part should start with expires=");
var expirationDate = new Date(expiration.substr("expires=".length));
Assert.equal(true, expirationDate > (new Date), "ai_user cookie expiration should be in the future");
}
});
this.testCase({
name: "ai_user cookie is set with acq date and year expiration",
test: () => {
// setup
var id = "userId"
var actualCookieName: string;
var actualCookieValue: string;
var newIdStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "newId", () => "newId");
var getCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => "");
var setCookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie", (cookieName, cookieValue) => {
actualCookieName = cookieName;
actualCookieValue = cookieValue;
});
// act
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// verify
Assert.equal("ai_user", actualCookieName, "ai_user cookie is set");
var cookieValueParts = actualCookieValue.split(';');
Assert.equal(2, cookieValueParts.length, "ai_user cookie value should have actual value and expiration");
Assert.equal(2, cookieValueParts[0].split('|').length, "ai_user cookie value before expiration should include user id and acq date");
Assert.equal("newId", cookieValueParts[0].split('|')[0], "First part of ai_user cookie value should be new user id guid");
Assert.equal(new Date().toString(), (new Date(cookieValueParts[0].split('|')[1])).toString(), "Second part of ai_user cookie should be parsable as date");
var expiration = cookieValueParts[1];
Assert.equal(true, expiration.substr(0, "expires=".length) === "expires=", "ai_user cookie expiration part should start with expires=");
var expirationDate = new Date(expiration.substr("expires=".length));
Assert.equal(true, expirationDate > (new Date), "ai_user cookie expiration should be in the future");
}
});
this.testCase({
name: "Ctor: auth and account id initialize from cookie",
test: () => {
// setup
var authId = "bla@bla.com";
var accountId = "Contoso";
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => authId + "|" + accountId);
// act
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig()
);
// verify
Assert.equal(authId, user.authenticatedId, "user auth id was set from cookie");
Assert.equal(accountId, user.accountId, "user account id was not set from cookie");
}
});
this.testCase({
name: "Ctor: auth id initializes from cookie (without account id)",
test: () => {
// setup
var authId = "bla@bla.com";
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => authId);
// act
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// verify
Assert.equal(authId, user.authenticatedId, "user auth id was set from cookie");
}
});
this.testCase({
name: "Ctor: auth user context handles empty cookie",
test: () => {
// setup
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => "");
// act
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was not set");
Assert.equal(undefined, user.accountId, "user account id was not set");
}
});
this.testCase({
name: "Ctor: auth user context handles empty cookie with accountId backward compatibility",
test: () => {
// setup
var config = this.getEmptyConfig();
config.accountId = () => "account17";
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => null);
// act
var user = new Microsoft.ApplicationInsights.Context.User(config);
// verify
Assert.equal(config.accountId(), user.accountId, "user account id was set from back compat");
}
});
this.testCase({
name: "setAuthenticatedUserContext: auth id and account id is set (not in the cookie)",
test: () => {
// setup
var authAndAccountId = ['bla@bla.com', 'contoso'];
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
// act
user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1]);
// verify
Assert.equal('bla@bla.com', user.authenticatedId, "user auth id was not set");
Assert.equal('contoso', user.accountId, "user account id was not set");
Assert.equal(cookieStub.notCalled, true, "cookie was not set");
}
});
this.testCase({
name: "setAuthenticatedUserContext: auth user set in cookie without account id",
test: () => {
// setup
var authAndAccountId = ["bla@bla.com"];
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// act
user.setAuthenticatedUserContext(authAndAccountId[0], null, true);
// verify
Assert.equal(authAndAccountId[0], user.authenticatedId, "user auth id was set");
Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId.join('|')), null), true, "user auth id and account id cookie was set");
}
});
this.testCase({
name: "setAuthenticatedUserContext: auth user and account id set in cookie ",
test: () => {
// setup
var authAndAccountId = ['bla@bla.com', 'contoso'];
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// act
user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1], true);
// verify
Assert.equal(authAndAccountId[0], user.authenticatedId, "user auth id was set");
Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId.join('|')), null), true, "user auth id cookie was set");
}
});
this.testCase({
name: "setAuthenticatedUserContext: handles only auth user id correctly",
test: () => {
// setup
var authAndAccountId = ['bla@bla.com'];
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
// act
user.setAuthenticatedUserContext(authAndAccountId[0], null, true);
// verify
Assert.equal(authAndAccountId[0], user.authenticatedId, "user auth id was set");
Assert.equal(null, user.accountId, "user account id was not set");
Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId[0]), null), true, "user auth id cookie was set");
}
});
this.testCase({
name: "setAuthenticatedUserContext: handles null correctly",
test: () => {
// setup
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var loggingStub = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
cookieStub.reset();
loggingStub.reset();
// act
user.setAuthenticatedUserContext(null);
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was not set");
Assert.equal(undefined, user.accountId, "user account id was not set");
Assert.equal(cookieStub.notCalled, true, "cookie was not set");
Assert.equal(loggingStub.calledOnce, true, "Warning was logged");
}
});
this.testCase({
name: "setAuthenticatedUserContext: handles undefined correctly",
test: () => {
// setup
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var loggingStub = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
cookieStub.reset();
loggingStub.reset();
// act
user.setAuthenticatedUserContext(undefined, undefined);
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was not set");
Assert.equal(undefined, user.accountId, "user account id was not set");
Assert.equal(cookieStub.notCalled, true, "cookie was not set");
Assert.equal(loggingStub.calledOnce, true, "Warning was logged");
}
});
this.testCase({
name: "setAuthenticatedUserContext: handles only accountID correctly",
test: () => {
// setup
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var loggingStub = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
cookieStub.reset();
loggingStub.reset();
// act
user.setAuthenticatedUserContext(undefined, '1234');
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was not set");
Assert.equal(undefined, user.accountId, "user account id was not set");
Assert.equal(cookieStub.notCalled, true, "cookie was not set");
Assert.equal(loggingStub.calledOnce, true, "Warning was logged");
}
});
this.testCase({
name: "setAuthenticatedUserContext: handles authId special characters correctly",
test: () => {
// setup
var authAndAccountId = ['my|||special;id', '1234'];
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var loggingStub = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
// act
user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1], true);
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was not set");
Assert.equal(undefined, user.accountId, "user account id was not set");
Assert.equal(cookieStub.notCalled, true, "cookie was not set");
Assert.equal(loggingStub.calledOnce, true, "Warning was logged");
}
});
this.testCase({
name: "setAuthenticatedUserContext: handles accountId special characters correctly",
test: () => {
// setup
var authAndAccountId = ['myid', '1234 5678'];
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
user.clearAuthenticatedUserContext();
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var loggingStub = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
// act
user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1]);
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was not set");
Assert.equal(undefined, user.accountId, "user account id was not set");
Assert.equal(cookieStub.notCalled, true, "cookie was not set");
Assert.equal(loggingStub.calledOnce, true, "Warning was logged");
}
});
this.testCase({
name: "setAuthenticatedUserContext: handles non-ascii unicode characters correctly",
test: () => {
// setup
var authAndAccountId = ["\u05D0", "\u05D1"]; // Hebrew characters
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "setCookie");
var loggingStub = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
// act
user.setAuthenticatedUserContext(authAndAccountId[0], authAndAccountId[1], true);
// verify
Assert.equal(authAndAccountId[0], user.authenticatedId, "user auth id was set");
Assert.equal(authAndAccountId[1], user.accountId, "user account id was set");
Assert.equal(cookieStub.calledWithExactly('ai_authUser', encodeURI(authAndAccountId.join('|')), null), true, "user auth id cookie was set");
Assert.equal(loggingStub.notCalled, true, "No warnings");
}
});
this.testCase({
name: "clearAuthenticatedUserContext: auth user and account cleared in context and cookie ",
test: () => {
// setup
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
user.setAuthenticatedUserContext("bla", "123");
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "deleteCookie");
// act
user.clearAuthenticatedUserContext();
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was cleared");
Assert.equal(undefined, user.accountId, "user account id was cleared");
Assert.equal(cookieStub.calledWithExactly('ai_authUser'), true, "cookie was deleted");
}
});
this.testCase({
name: "clearAuthenticatedUserContext: works correctly when auth id and account id were never set",
test: () => {
// setup
var user = new Microsoft.ApplicationInsights.Context.User(this.getEmptyConfig());
var cookieStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "deleteCookie");
// act
user.clearAuthenticatedUserContext();
// verify
Assert.equal(undefined, user.authenticatedId, "user auth id was cleared");
Assert.equal(undefined, user.accountId, "user account id was cleared");
Assert.equal(cookieStub.calledWithExactly('ai_authUser'), true, "cookie was deleted");
}
});
}
private getEmptyConfig(): Microsoft.ApplicationInsights.ITelemetryConfig {
return {
instrumentationKey: () => null,
accountId: () => null,
sessionRenewalMs: () => null,
sessionExpirationMs: () => null,
sampleRate: () => null,
endpointUrl: () => null,
cookieDomain: () => null,
emitLineDelimitedJson: () => null,
maxBatchSizeInBytes: () => null,
maxBatchInterval: () => null,
disableTelemetry: () => null,
enableSessionStorageBuffer: () => null,
isRetryDisabled: () => null,
isBeaconApiDisabled: () => null,
sdkExtension: () => null,
isBrowserLinkTrackingEnabled: () => null,
appId: () => null,
};
}
}
new UserContextTests().registerTests();

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

@ -1,175 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Util.ts" />
class CorrelationIdHelperTests extends TestClass {
public registerTests() {
var CorrelationIdHelper = Microsoft.ApplicationInsights.CorrelationIdHelper;
this.testCase({
name: "CorrelationIdHelper: test for missing arguments",
test: () => {
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(null, null, null));
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader({}, null, null));
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader({
enableCorsCorrelation: false
}, null, null));
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader({
enableCorsCorrelation: false
}, "url", null));
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader({
enableCorsCorrelation: false
}, null, "host"));
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader({
enableCorsCorrelation: true,
correlationHeaderExcludedDomains: []
}, null, null));
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(null, "url1", "url2"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return false for CORS if disableCorrelationHeaders set to true",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
disableCorrelationHeaders: true
};
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, "some", "some"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return false for CORS if enableCorsCorrelation set to false",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
disableCorrelationHeaders: false,
enableCorsCorrelation: false
};
let url = "http://bing.com/search?q=example.com";
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "diffHost"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return false for different port number if enableCorsCorrelation set to false",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
disableCorrelationHeaders: false,
enableCorsCorrelation: false
};
let url = "http://bing.com/search?q=example.com";
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "bing.com:8080"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return true for same domain if enableCorsCorrelation set to false",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
disableCorrelationHeaders: false,
enableCorsCorrelation: false
};
let url = "http://bing.com/search?q=example.com";
Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "bing.com"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return true for same domain (case sensitive) if enableCorsCorrelation set to false",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
disableCorrelationHeaders: false,
enableCorsCorrelation: false
};
let url = "http://Bing.com/search?q=example.com";
Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "bing.com"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return true if domain is not on the excluded list",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
correlationHeaderExcludedDomains: ["example.com", "bing.net", "abc.bing.com"],
disableCorrelationHeaders: false,
enableCorsCorrelation: true
};
let url = "http://bing.com/search?q=example.com";
Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "diffHost"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return false if domain is on the excluded list",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
correlationHeaderExcludedDomains: ["bing.com", "bing.net"],
disableCorrelationHeaders: false,
enableCorsCorrelation: true
};
let url = "http://bing.com/search?q=node";
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "diffHost"));
let urlSecure = "https://bing.com/search?q=node";
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, urlSecure, "diffHost"));
let secondDomainUrl = "http://bing.net/search?q=node";
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, secondDomainUrl, "diffHost"));
}
});
this.testCase({
name: "CorrelationIdHelper: can take wildcards in the excluded domain list",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
correlationHeaderExcludedDomains: ["*.bing.com"],
disableCorrelationHeaders: false,
enableCorsCorrelation: true
};
let url = "https://abc.bing.com";
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "diffHost"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return false if url is on the excluded pattern match list",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
correlationHeaderExcludePatterns: [/.*locales.*\.json/i],
disableCorrelationHeaders: false,
enableCorsCorrelation: true
};
let url = "https://abc.bing.com/locales/test/test2.json";
Assert.equal(false, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "diffHost"));
}
});
this.testCase({
name: "CorrelationIdHelper: should return true if url is not on the excluded pattern match list",
test: () => {
var config: Microsoft.ApplicationInsights.IConfig = {
correlationHeaderExcludePatterns: [/.*locales.*\.json/i],
disableCorrelationHeaders: false,
enableCorsCorrelation: true
};
let url = "https://abc.bing.com/locales/test/test2.jsoan";
Assert.equal(true, CorrelationIdHelper.canIncludeCorrelationHeader(config, url, "diffHost"));
}
});
}
}
new CorrelationIdHelperTests().registerTests();

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

@ -1,93 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/DataLossAnalyzer.ts" />
class DataLossAnalyzerTests extends TestClass {
public testCleanup() {
Microsoft.ApplicationInsights.DataLossAnalyzer.enabled = false;
}
public testInitialize() {
if (Microsoft.ApplicationInsights.Util.canUseSessionStorage()) {
sessionStorage.clear();
}
}
public registerTests() {
this.testCase({
name: "SenderTests: data loss analyzer - result 1; reported 1",
test: () => {
// setup
Microsoft.ApplicationInsights.DataLossAnalyzer.enabled = true;
Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights = <any>{ trackTrace: (message) => { }, flush: () => { } };
var loggerSpy = this.sandbox.spy(Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights, "trackTrace");
// act
Microsoft.ApplicationInsights.DataLossAnalyzer.incrementItemsQueued();
Microsoft.ApplicationInsights.DataLossAnalyzer.reportLostItems();
// Validate
Assert.ok(loggerSpy.calledOnce);
Assert.equal(
"AI (Internal): Internal report DATALOSS: 1",
loggerSpy.args[0][0]
);
}
});
this.testCase({
name: "SenderTests: data loss analyzer - result 0; didn't report loss",
test: () => {
// setup
Microsoft.ApplicationInsights.DataLossAnalyzer.enabled = true;
Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights = <any>{ trackTrace: (message) => { }, flush: () => { } };
var loggerSpy = this.sandbox.spy(Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights, "trackTrace");
// act
Microsoft.ApplicationInsights.DataLossAnalyzer.reportLostItems();
// Validate
Assert.ok(loggerSpy.notCalled);
}
});
this.testCase({
name: "SenderTests: data loss analyzer - restores to 0 after reporting data loss",
test: () => {
// setup
Microsoft.ApplicationInsights.DataLossAnalyzer.enabled = true;
Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights = <any>{ trackTrace: (message) => { }, flush: () => { } };
var loggerSpy = this.sandbox.spy(Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights, "trackTrace");
// act
Microsoft.ApplicationInsights.DataLossAnalyzer.incrementItemsQueued();
Microsoft.ApplicationInsights.DataLossAnalyzer.reportLostItems();
// Validate
Assert.equal(0, Microsoft.ApplicationInsights.DataLossAnalyzer.getNumberOfLostItems(), "Expected to reset to 0");
}
});
this.testCase({
name: "DataLossAnalyzer: no more than 10 data loss trace messages per browser session",
test: () => {
// setup
Microsoft.ApplicationInsights.DataLossAnalyzer.enabled = true;
Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights = <any>{ trackTrace: (message) => { }, flush: () => { } };
var loggerSpy = this.sandbox.spy(Microsoft.ApplicationInsights.DataLossAnalyzer.appInsights, "trackTrace");
// act
for (var i = 0; i < 100; ++i) {
Microsoft.ApplicationInsights.DataLossAnalyzer.incrementItemsQueued();
Microsoft.ApplicationInsights.DataLossAnalyzer.reportLostItems();
}
// Validate
Assert.equal(10, loggerSpy.callCount);
}
});
}
}
// Uncomment if you want to use DataLossanalyzer
// new DataLossAnalyzerTests().registerTests();

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

@ -1,289 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Initialization.ts" />
/// <reference path="../../JavaScriptSDK/AppInsights.ts" />
class InitializationTests extends TestClass {
public testInitialize() {
window['queueTest'] = function () { };
}
private getAppInsightsSnippet() {
var snippet: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: "ffffffff-ffff-ffff-ffff-ffffffffffff",
endpointUrl: "https://dc.services.visualstudio.com/v2/track",
emitLineDelimitedJson: false,
accountId: undefined,
sessionRenewalMs: 10,
sessionExpirationMs: 10,
maxBatchSizeInBytes: 1000000,
maxBatchInterval: 1,
enableDebug: true,
disableExceptionTracking: false,
disableTelemetry: false,
verboseLogging: true,
diagnosticLogInterval: 1,
autoTrackPageVisitTime: false,
samplingPercentage: 33,
disableAjaxTracking: true,
overridePageViewDuration: false,
maxAjaxCallsPerView: 44,
disableDataLossAnalysis: true,
disableCorrelationHeaders: false,
disableFlushOnBeforeUnload: false,
cookieDomain: undefined,
enableSessionStorageBuffer: false,
enableCorsCorrelation: false
};
// set default values
return snippet;
}
public registerTests() {
this.testCase({
name: "InitializationTests: constructor throws if Instrumentation Key is not set",
test: () => {
var snippet = <any>{};
var msg = "";
try {
var init = new Microsoft.ApplicationInsights.Initialization(snippet);
}
catch (err) {
msg = err.message;
}
Assert.equal("Cannot load Application Insights SDK, no instrumentationKey was provided.", msg);
}
});
this.testCase({
name: "InitializationTests: constructor sets defaults",
test: () => {
var emptyConfig = <Microsoft.ApplicationInsights.IConfig>{
instrumentationKey: "ffffffff-ffff - ffff - ffff - ffffffffffff",
endpointUrl: undefined,
accountId: undefined,
sessionRenewalMs: undefined,
sessionExpirationMs: undefined,
maxBatchSizeInBytes: undefined,
maxBatchInterval: undefined,
enableDebug: undefined,
disableExceptionTracking: undefined,
disableTelemetry: undefined,
verboseLogging: undefined,
diagnosticLogInterval: undefined,
samplingPercentage: undefined,
maxAjaxCallsPerView: undefined
};
var snippet = <Microsoft.ApplicationInsights.Snippet>{
config: emptyConfig,
queue: []
}
var init = new Microsoft.ApplicationInsights.Initialization(snippet);
Assert.equal("https://dc.services.visualstudio.com/v2/track", init.config.endpointUrl);
Assert.equal(30 * 60 * 1000, init.config.sessionRenewalMs);
Assert.equal(24 * 60 * 60 * 1000, init.config.sessionExpirationMs);
Assert.equal(102400, init.config.maxBatchSizeInBytes);
Assert.equal(15000, init.config.maxBatchInterval);
Assert.ok(!init.config.enableDebug);
Assert.ok(!init.config.disableExceptionTracking);
Assert.equal(15000, init.config.maxBatchInterval);
Assert.ok(!init.config.verboseLogging);
Assert.equal(10000, init.config.diagnosticLogInterval);
Assert.equal(100, init.config.samplingPercentage);
Assert.equal(500, init.config.maxAjaxCallsPerView);
}
});
this.testCase({
name: "InitializationTests: constructor takes the user specified values",
test: () => {
var userConfig = this.getAppInsightsSnippet();
var snippet = <Microsoft.ApplicationInsights.Snippet>{
config: userConfig,
queue: []
}
var init = new Microsoft.ApplicationInsights.Initialization(snippet);
Assert.equal(userConfig.endpointUrl, init.config.endpointUrl);
Assert.equal(userConfig.sessionRenewalMs, init.config.sessionRenewalMs);
Assert.equal(userConfig.sessionExpirationMs, init.config.sessionExpirationMs);
Assert.equal(userConfig.maxBatchSizeInBytes, init.config.maxBatchSizeInBytes);
Assert.equal(userConfig.maxBatchInterval, init.config.maxBatchInterval);
Assert.ok(init.config.enableDebug);
Assert.ok(!init.config.disableExceptionTracking);
Assert.equal(1, init.config.maxBatchInterval);
Assert.ok(init.config.verboseLogging);
Assert.equal(1, init.config.diagnosticLogInterval);
Assert.equal(33, init.config.samplingPercentage);
Assert.equal(44, init.config.maxAjaxCallsPerView);
}
});
this.testCase({
name: "InitializationTests: invalid sampling values are treated as sampling OFF (sampling percentage gets set to 100)",
test: () => {
var res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: 0 });
Assert.equal(100, res.samplingPercentage);
res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: "" });
Assert.equal(100, res.samplingPercentage);
res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: null });
Assert.equal(100, res.samplingPercentage);
res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: undefined });
Assert.equal(100, res.samplingPercentage);
res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: false });
Assert.equal(100, res.samplingPercentage);
res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: -123 });
Assert.equal(100, res.samplingPercentage);
res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: 123 });
Assert.equal(100, res.samplingPercentage);
// "50" is treated as correct number and doesn't reset sampling percentage to 100.
res = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>{ samplingPercentage: "50" });
Assert.equal(50, res.samplingPercentage);
}
});
this.testCase({
name: "InitializationTests: polling for log messages",
test: () => {
var userConfig = this.getAppInsightsSnippet();
var snippet = <Microsoft.ApplicationInsights.Snippet>{
config: userConfig,
queue: []
}
var init = new Microsoft.ApplicationInsights.Initialization(snippet);
var appInsightsLocal = init.loadAppInsights();
var trackTraceSpy = this.sandbox.stub(appInsightsLocal, "trackTrace");
var queue: Array<Microsoft.ApplicationInsights._InternalLogMessage> = Microsoft.ApplicationInsights._InternalLogging["queue"];
var length = queue.length;
for (var i = 0; i < length; i++) {
queue.shift();
}
queue.push(new Microsoft.ApplicationInsights._InternalLogMessage(1, "Hello1"));
queue.push(new Microsoft.ApplicationInsights._InternalLogMessage(2, "Hello2"));
init.loadAppInsights();
var poller = init.pollInteralLogs(appInsightsLocal);
this.clock.tick(2);
var data1 = trackTraceSpy.args[0][0];
Assert.ok("Hello1", data1.message);
var data2 = trackTraceSpy.args[1][0];
Assert.ok("Hello2", data2.message);
clearInterval(poller);
}
});
this.testCase({
name: "InitializationTests: in config - 'false' string is treated as a boolean false",
test: () => {
var userConfig = {
enableDebug: "false",
disableExceptionTracking: "false",
disableTelemetry: "false",
verboseLogging: "false",
emitLineDelimitedJson: "false",
};
var config = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>userConfig);
Assert.ok(!config.enableDebug);
Assert.ok(!config.disableExceptionTracking);
Assert.ok(!config.disableTelemetry);
Assert.ok(!config.verboseLogging);
Assert.ok(!config.emitLineDelimitedJson);
}
});
this.testCase({
name: "InitializationTests: in config - 'true' string is treated as a boolean true",
test: () => {
var userConfig = {
enableDebug: "true",
disableExceptionTracking: "true",
disableTelemetry: "true",
verboseLogging: "true",
emitLineDelimitedJson: "true",
};
var config = Microsoft.ApplicationInsights.Initialization.getDefaultConfig(<any>userConfig);
Assert.ok(config.enableDebug);
Assert.ok(config.disableExceptionTracking);
Assert.ok(config.disableTelemetry);
Assert.ok(config.verboseLogging);
Assert.ok(config.emitLineDelimitedJson);
}
});
this.testCase({
name: "InitializationTests: beforeunload handler is appropriately added",
test: () => {
// Assemble
var userConfig = this.getAppInsightsSnippet();
var snippet = <Microsoft.ApplicationInsights.Snippet>{
config: userConfig,
queue: []
};
var addEventHandlerStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, 'addEventHandler').returns(true);
var init = new Microsoft.ApplicationInsights.Initialization(snippet);
var appInsightsLocal = init.loadAppInsights();
// Act
init.addHousekeepingBeforeUnload(appInsightsLocal);
// Assert
Assert.ok(addEventHandlerStub.calledOnce);
Assert.equal(addEventHandlerStub.getCall(0).args[0], 'beforeunload');
Assert.ok(addEventHandlerStub.getCall(0).args[1] !== undefined, 'addEventHandler was called with undefined callback');
}
});
this.testCase({
name: "InitializationTests: disableFlushOnBeforeUnload switch works",
test: () => {
// Assemble
var userConfig = this.getAppInsightsSnippet();
userConfig.disableFlushOnBeforeUnload = true;
var snippet = <Microsoft.ApplicationInsights.Snippet>{
config: userConfig,
queue: []
};
var addEventHandlerStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, 'addEventHandler').returns(true);
var init = new Microsoft.ApplicationInsights.Initialization(snippet);
var appInsightsLocal = init.loadAppInsights();
// Act
init.addHousekeepingBeforeUnload(appInsightsLocal);
// Assert
Assert.ok(addEventHandlerStub.notCalled);
}
});
}
}
new InitializationTests().registerTests();

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

@ -1,467 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Logging.ts" />
/// <reference path="../../JavaScriptSDK/AppInsights.ts" />
class LoggingTests extends TestClass {
InternalLogging = Microsoft.ApplicationInsights._InternalLogging;
InternalLoggingMessage = Microsoft.ApplicationInsights._InternalLogMessage;
enableDebugExceptionsDefaultValue = Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions();
verboseLoggingDefaultValue = Microsoft.ApplicationInsights._InternalLogging.verboseLogging();
public testInitialize() {
this.InternalLogging.setMaxInternalMessageLimit(Number.MAX_VALUE);
}
public testCleanup() {
// Clear the queue
this.clearInternalLoggingQueue();
// Reset the internal event throttle
this.InternalLogging.resetInternalMessageCount();
// Reset the internal throttle max limit
this.InternalLogging.setMaxInternalMessageLimit(Number.MAX_VALUE);
// Clear records indicating what internal message types were already logged
this.InternalLogging.clearInternalMessageLoggedTypes();
// Reset to a default state
this.InternalLogging.enableDebugExceptions = () => this.enableDebugExceptionsDefaultValue;
this.InternalLogging.verboseLogging = () => this.verboseLoggingDefaultValue;
}
/**
* Clears the internal logging queue
*/
private clearInternalLoggingQueue() {
var length = this.InternalLogging.queue.length;
for (var i = 0; i < length; i++) {
this.InternalLogging.queue.shift();
}
}
public registerTests() {
this.testCase({
name: "LoggingTests: enableDebugExceptions enables exceptions",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = this.sandbox.spy(console, "warn");
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies \n" + e.toString());
}
var i = 0;
// verify
Assert.ok(!this.InternalLogging.enableDebugExceptions(), "enableDebugExceptions is false by default");
// act
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, ++i, "error!", null, true);
// verify
Assert.ok(!throwSpy || throwSpy.calledOnce, "console.warn was called instead of throwing while enableDebugExceptions is false");
// act
this.InternalLogging.enableDebugExceptions = () => true;
// verify
Assert.throws(() =>
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, ++i, "error!", null, true),
"error is thrown when enableDebugExceptions is true");
Assert.ok(!throwSpy || throwSpy.calledOnce, "console.warn was not called when the error was thrown");
}
});
this.testCase({
name: "LoggingTests: verboseLogging collects all logs",
test: () => {
// setup
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.verboseLogging = () => true;
var i = 2;
// act
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, ++i, "error!");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, ++i, "error!", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, ++i, "error!");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, ++i, "error!", null, true);
//verify
Assert.equal(4, this.InternalLogging.queue.length);
Assert.equal("AI (Internal): " + "BrowserCannotWriteLocalStorage message:\"error!\"", this.InternalLogging.queue[0].message);
Assert.equal("AI: " + "BrowserCannotWriteSessionStorage message:\"error!\"", this.InternalLogging.queue[1].message);
Assert.equal("AI (Internal): " + "BrowserFailedRemovalFromLocalStorage message:\"error!\"", this.InternalLogging.queue[2].message);
Assert.equal("AI: " + "BrowserFailedRemovalFromSessionStorage message:\"error!\"", this.InternalLogging.queue[3].message);
}
});
this.testCase({
name: "LoggingTests: Logging only collects CRITICAL logs by default",
test: () => {
// setup
this.InternalLogging.enableDebugExceptions = () => false;
var i = 0;
// act
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, ++i, "error!");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, ++i, "error!", null, true);
Assert.equal(0, this.InternalLogging.queue.length);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, ++i, "error!");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, ++i, "error!", null, true);
//verify
Assert.equal(2, this.InternalLogging.queue.length);
Assert.equal("AI (Internal): " + "BrowserCannotWriteLocalStorage message:\"error!\"", this.InternalLogging.queue[0].message);
Assert.equal("AI: " + "BrowserCannotWriteSessionStorage message:\"error!\"", this.InternalLogging.queue[1].message);
}
});
this.testCase({
name: "LoggingTests: throwInternal adds to the queue and calls console.warn",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = this.sandbox.spy(console, "warn");
// act
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!", null, true);
// verify
Assert.ok(throwSpy.calledOnce, "console.warn was not called while debug mode was false");
Assert.equal(1, this.InternalLogging.queue.length);
Assert.equal("AI: " + "BrowserCannotReadLocalStorage message:\"error!\"", this.InternalLogging.queue[0].message);
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: throwInternal adds to the queue and calls console.warn",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = this.sandbox.spy(console, "warn");
// act
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.verboseLogging = () => true;
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!");
// verify
Assert.ok(throwSpy.calledOnce, "console.warn was not called while debug mode was false");
Assert.equal(1, this.InternalLogging.queue.length);
Assert.equal("AI (Internal): " + "BrowserCannotReadLocalStorage message:\"error!\"", this.InternalLogging.queue[0].message);
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: throwInternal does not call console.warn without verboseLogging",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = this.sandbox.spy(console, "warn");
// act
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.verboseLogging = () => false;
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!");
// verify
Assert.ok(throwSpy.notCalled, "console.warn was called while verboseLogging mode was false");
Assert.equal(1, this.InternalLogging.queue.length);
Assert.equal("AI (Internal): " + "BrowserCannotReadLocalStorage message:\"error!\"", this.InternalLogging.queue[0].message);
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: throwInternal (userActionable) logs only one message of a given type to console (without verboseLogging)",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = this.sandbox.spy(console, "warn");
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.verboseLogging = () => false;
// act
// send 4 messages, with 2 distinct types
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 2, "error 2!", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 2, "error 2!", null, true);
// verify
Assert.ok(throwSpy.calledTwice, "console.warn was called only once per each message type");
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: throwInternal (userActionable) always log to console with verbose logging",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = this.sandbox.spy(console, "warn");
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.verboseLogging = () => true;
// act
// send 4 messages, with 2 distinct types
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 2, "error 2!", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 2, "error 2!", null, true);
// verify
Assert.equal(4, throwSpy.callCount, "console.warn was called for each message");
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: warnToConsole does not add to the queue ",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = this.sandbox.spy(console, "warn");
// act
var message = "error!";
this.InternalLogging.warnToConsole(message);
// verify
Assert.ok(throwSpy.calledOnce, "console.warn was called once");
Assert.equal(0, this.InternalLogging.queue.length);
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: console.warn falls back to console.log",
test: () => {
// setup
var throwSpy = null;
var warn = console.warn;
try {
console.warn = undefined;
throwSpy = this.sandbox.spy(console, "log");
// act
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "error!", null, true);
// verify
Assert.ok(throwSpy.calledOnce, "console.log was called when console.warn was not present");
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
} finally {
console.warn = warn;
}
}
});
this.testCase({
name: "LoggingTests: logInternalMessage throttles messages when the throttle limit is reached",
test: () => {
var maxAllowedInternalMessages = 2;
// setup
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.setMaxInternalMessageLimit(maxAllowedInternalMessages);
this.InternalLogging.resetInternalMessageCount();
// act
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadLocalStorage, "");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadSessionStorage, "");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotWriteLocalStorage, "");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotWriteSessionStorage, "");
// verify
Assert.equal(maxAllowedInternalMessages + 1, this.InternalLogging.queue.length); // Since we always send one "extra" event to denote that limit was reached
Assert.equal(this.InternalLogging.queue[0].message, "AI (Internal): BrowserCannotReadLocalStorage");
Assert.equal(this.InternalLogging.queue[1].message, "AI (Internal): BrowserCannotReadSessionStorage");
Assert.equal(this.InternalLogging.queue[2].message, "AI (Internal): MessageLimitPerPVExceeded message:\"Internal events throttle limit per PageView reached for this app.\"");
}
});
this.testCase({
name: "LoggingTests: throwInternal should call logInternalMessage",
test: () => {
var maxAllowedInternalMessages = 2;
var logInternalMessageStub = this.sandbox.stub(this.InternalLogging, 'logInternalMessage');
// setup
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.resetInternalMessageCount();
// act
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, 1, "");
// verify
Assert.ok(logInternalMessageStub.calledOnce, 'logInternalMessage was not called by throwInternal');
}
});
this.testCase({
name: "LoggingTests: only single message of specific type can be sent within the same session",
test: () => {
var maxAllowedInternalMessages = 2;
// setup
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.resetInternalMessageCount();
this.InternalLogging.clearInternalMessageLoggedTypes();
var id1 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadLocalStorage;
var id2 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadSessionStorage;
// act
// send 4 messages, with 2 distinct types
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id1, "1");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id2, "2");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id1, "1");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id2, "2");
// verify
// only two messages should be in the queue, because we have to distinct types
Assert.equal(2, this.InternalLogging.queue.length);
Assert.equal(this.InternalLogging.queue[0].message, "AI (Internal): BrowserCannotReadLocalStorage message:\"1\"");
Assert.equal(this.InternalLogging.queue[1].message, "AI (Internal): BrowserCannotReadSessionStorage message:\"2\"");
}
});
this.testCase({
name: "LoggingTests: only single message of specific type can be sent within the same page view when session storage is not available",
test: () => {
var maxAllowedInternalMessages = 2;
var id1 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadLocalStorage;
var id2 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadSessionStorage;
// disable session storage
var utilCanUseSession = Microsoft.ApplicationInsights.Util.canUseSessionStorage;
Microsoft.ApplicationInsights.Util.canUseSessionStorage = () => {
return false;
};
// setup
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.resetInternalMessageCount();
this.InternalLogging.clearInternalMessageLoggedTypes();
// act
// send 4 messages, with 2 distinct types
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id1, "1");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id2, "2");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id1, "1");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id2, "2");
// verify
// only two messages should be in the queue, because we have to distinct types
Assert.equal(2, this.InternalLogging.queue.length);
Assert.equal(this.InternalLogging.queue[0].message, "AI (Internal): BrowserCannotReadLocalStorage message:\"1\"");
Assert.equal(this.InternalLogging.queue[1].message, "AI (Internal): BrowserCannotReadSessionStorage message:\"2\"");
// clean up - reset session storage
Microsoft.ApplicationInsights.Util.canUseSessionStorage = utilCanUseSession;
}
});
this.testCase({
name: "LoggingTests: throwInternal (user actionable) should call logInternalMessage",
test: () => {
var maxAllowedInternalMessages = 2;
var logInternalMessageStub = this.sandbox.stub(this.InternalLogging, 'logInternalMessage');
var id1 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadLocalStorage;
// setup
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.resetInternalMessageCount();
// act
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id1, "Internal Test Event", null, true);
// verify
Assert.ok(logInternalMessageStub.calledOnce, 'logInternalMessage was not called by throwInternal');
}
});
this.testCase({
name: "LoggingTests: logInternalMessage will log events when the throttle is reset",
test: () => {
var maxAllowedInternalMessages = 2;
var id1 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadLocalStorage;
var id2 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotReadSessionStorage;
var id3 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotWriteLocalStorage;
var id4 = Microsoft.ApplicationInsights._InternalMessageId.BrowserCannotWriteSessionStorage;
// setup
this.InternalLogging.enableDebugExceptions = () => false;
this.InternalLogging.setMaxInternalMessageLimit(maxAllowedInternalMessages);
this.InternalLogging.resetInternalMessageCount();
this.InternalLogging.clearInternalMessageLoggedTypes();
// act
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id1, "1");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id2, "2", null, true);
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id3, "3");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id4, "4", null, true);
// verify that internal events are throttled
Assert.equal(this.InternalLogging.queue.length, maxAllowedInternalMessages + 1); // Since we always send one "extra" event to denote that limit was reached
// act again
this.clearInternalLoggingQueue();
// reset the message count
this.InternalLogging.resetInternalMessageCount();
this.InternalLogging.clearInternalMessageLoggedTypes();
// Send some internal messages
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id1, "1");
this.InternalLogging.throwInternal(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, id2, "2");
// verify again
Assert.equal(this.InternalLogging.queue.length, maxAllowedInternalMessages + 1); // Since we always send one "extra" event to denote that limit was reached
Assert.equal(this.InternalLogging.queue[0].message, "AI (Internal): BrowserCannotReadLocalStorage message:\"1\"");
Assert.equal(this.InternalLogging.queue[1].message, "AI (Internal): BrowserCannotReadSessionStorage message:\"2\"");
}
});
}
}
new LoggingTests().registerTests();

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

@ -1,176 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Telemetry/PageVisitTimeManager.ts" />
class PageVisitTimeManagerTests extends TestClass {
private throwInternal;
private getStorageObjectStub;
/** Method called before the start of each test method */
public testInitialize() {
var storage = this.getMockStorage();
this.getStorageObjectStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "_getSessionStorageObject",() => storage);
this.throwInternal = this.sandbox.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
}
public registerTests() {
var testValues = {
page1Name: "page1",
page1Url: "page1Url",
page1ViewTime: 10,
page2Name: "page2",
page2Url: "page2Url",
page2ViewTime: 20,
page3Name: "page3",
page3Url: "page3Url",
page3ViewTime: 30
};
this.testCase({
name: "PageVisitTimeManager: When trackPreviousPageVisit is called once, the tracking delegate is not called since there are no previous pages",
test: () => {
//setup
var object = { method: function () { } };
var spy = this.sandbox.spy(object, "method");
var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(spy);
//act
pageVisitTimeManager.trackPreviousPageVisit(testValues.page1Name, testValues.page1Url);
this.clock.tick(testValues.page1ViewTime);
// verify
Assert.ok(spy.notCalled, "telemetry wasn't sent");
}
});
this.testCase({
name: "PageVisitTimeManager: When trackPreviousPageVisit is called twice, the tracking delegate is called once with correct details",
test: () => {
//setup
var object = { method: function () { } };
var spy = this.sandbox.spy(object, "method");
var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(spy);
//act
pageVisitTimeManager.trackPreviousPageVisit(testValues.page1Name, testValues.page1Url);
this.clock.tick(testValues.page1ViewTime);
pageVisitTimeManager.trackPreviousPageVisit(testValues.page2Name, testValues.page2Url);
// verify
Assert.ok(spy.calledOnce, "telemetry sent once");
Assert.ok(spy.calledWith(testValues.page1Name, testValues.page1Url, testValues.page1ViewTime));
}
});
this.testCase({
name: "PageVisitTimeManager: consecutive calls to start and stop returns expected information",
test: () => {
//setup
var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => {});
//act
pageVisitTimeManager.startPageVisitTimer(testValues.page1Name, testValues.page1Url);
this.clock.tick(testValues.page1ViewTime);
var page1VisitData = pageVisitTimeManager.stopPageVisitTimer();
//verify
Assert.equal(testValues.page1Name, page1VisitData.pageName);
Assert.equal(testValues.page1Url, page1VisitData.pageUrl);
Assert.equal(testValues.page1ViewTime, page1VisitData.pageVisitTime);
}
});
this.testCase({
name: "PageVisitTimeManager: first call to restart returns null",
test: () => {
//setup
var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => { });
//act
var nullPageData = pageVisitTimeManager.restartPageVisitTimer(testValues.page1Name, testValues.page1Url);
//verify
Assert.equal(null, nullPageData);
}
});
this.testCase({
name: "PageVisitTimeManager: consecutive calls to restart returns expected information",
test: () => {
//setup
var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => { });
//act
pageVisitTimeManager.restartPageVisitTimer(testValues.page1Name, testValues.page1Url);
this.clock.tick(testValues.page1ViewTime);
var page1VisitData = pageVisitTimeManager.restartPageVisitTimer(testValues.page2Name, testValues.page2Url);
//verify
Assert.equal(testValues.page1Name, page1VisitData.pageName);
Assert.equal(testValues.page1Url, page1VisitData.pageUrl);
Assert.equal(testValues.page1ViewTime, page1VisitData.pageVisitTime);
}
});
this.testCase({
name: "PageVisitTimeManager: stopPageVisitTimer returns null if start has not been called",
test: () => {
//setup
// Mock storage so this will work in all browsers for tests
var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => { });
//act
var retval = pageVisitTimeManager.stopPageVisitTimer();
Assert.equal(null, retval);
}
});
this.testCase({
name: "PageVisitTimeManager: startPageVisitTime fails silently if called twice without a call to stop",
test: () => {
//setup
var pageVisitTimeManager = new Microsoft.ApplicationInsights.Telemetry.PageVisitTimeManager(() => {});
//act
try {
pageVisitTimeManager.startPageVisitTimer(testValues.page1Name, testValues.page1Url);
pageVisitTimeManager.startPageVisitTimer(testValues.page1Name, testValues.page1Url);
Assert.ok(true);
} catch (e) {
Assert.ok(false);
}
}
});
}
private getMockStorage() {
var storage = <any>{};
storage.getItem = (name) => storage[name];
storage.setItem = (name, value) => (storage[name] = value);
storage.removeItem = (name, value) => (storage[name] = undefined);
return storage;
}
}
new PageVisitTimeManagerTests().registerTests();

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

@ -1,421 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Sender.ts" />
/// <reference path="../../JavaScriptSDK/AppInsights.ts" />
class SendBufferTests extends TestClass {
private getArraySendBuffer: (emitLineDelimitedJson?: boolean) => Microsoft.ApplicationInsights.ArraySendBuffer;
private getSessionStorageSendBuffer: (emitLineDelimitedJson?: boolean) => Microsoft.ApplicationInsights.SessionStorageSendBuffer;
public testInitialize() {
if (Microsoft.ApplicationInsights.Util.canUseSessionStorage()) {
sessionStorage.clear();
}
var config: Microsoft.ApplicationInsights.ISenderConfig = {
emitLineDelimitedJson: () => false,
enableSessionStorageBuffer: () => false,
endpointUrl: () => null,
maxBatchSizeInBytes: () => null,
maxBatchInterval: () => null,
disableTelemetry: () => null,
isRetryDisabled: () => null,
isBeaconApiDisabled: () => true
};
this.getArraySendBuffer = (emitLineDelimitedJson?: boolean) => {
if (emitLineDelimitedJson) {
config.emitLineDelimitedJson = () => emitLineDelimitedJson;
}
return new Microsoft.ApplicationInsights.ArraySendBuffer(config);
}
this.getSessionStorageSendBuffer = (emitLineDelimitedJson?: boolean) => {
if (emitLineDelimitedJson) {
config.emitLineDelimitedJson = () => emitLineDelimitedJson;
}
return new Microsoft.ApplicationInsights.SessionStorageSendBuffer(config);
}
}
public testCleanup() {
// reset enableDebugger to a default value
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
}
private BUFFER_KEY = "AI_buffer";
private SENT_BUFFER_KEY = "AI_sentBuffer";
public registerTests() {
this.testCase({
name: "ArraySendBuffer: initialize",
test: () => {
var buffer = this.getArraySendBuffer();
this.Test_Initialize(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: initialize",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
this.Test_Initialize(buffer);
}
});
this.testCase({
name: "ArraySendBuffer: can enqueue and clear the buffer",
test: () => {
var buffer = this.getArraySendBuffer();
this.Test_CanEnqueueAndClearTheBuffer(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: can enqueue and clear the buffer",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
this.Test_CanEnqueueAndClearTheBuffer(buffer);
}
});
this.testCase({
name: "ArraySendBuffer: can clear empty buffer",
test: () => {
var buffer = this.getArraySendBuffer();
this.Test_CanClearEmptyBuffer(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: can clear empty buffer",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
this.Test_CanClearEmptyBuffer(buffer);
}
});
this.testCase({
name: "ArraySendBuffer: call batchPayloads when a buffer is empty",
test: () => {
var buffer = this.getArraySendBuffer();
this.Test_CanClearEmptyBuffer(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: call batchPayloads when a buffer is empty",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
this.Test_CanClearEmptyBuffer(buffer);
}
});
this.testCase({
name: "ArraySendBuffer: call batchPayloads when a buffer has one element",
test: () => {
var buffer = this.getArraySendBuffer();
this.Test_CallBatchPayloadsWithOneElement(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: call batchPayloads when a buffer has one element",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
this.Test_CallBatchPayloadsWithOneElement(buffer);
}
});
this.testCase({
name: "ArraySendBuffer: call batchPayloads when a buffer has two elements",
test: () => {
var buffer = this.getArraySendBuffer();
this.Test_CallBatchPayloadsWithTwoElements(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: call batchPayloads when a buffer has two elements",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
this.Test_CallBatchPayloadsWithTwoElements(buffer);
}
});
this.testCase({
name: "ArraySendBuffer: call batchPayloads when a buffer has two elements - emitLineDelimitedJson",
test: () => {
var buffer = this.getArraySendBuffer(true);
this.Test_CallBatchPayloadsWithTwoElements_EmitLineDelimitedJson(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: call batchPayloads when a buffer has two elements - emitLineDelimitedJson",
test: () => {
var buffer = this.getSessionStorageSendBuffer(true);
this.Test_CallBatchPayloadsWithTwoElements_EmitLineDelimitedJson(buffer);
}
});
this.testCase({
name: "SessionStorageSendBuffer: is restored from the Session storage in constructor",
test: () => {
// setup
var buffer = this.getSessionStorageSendBuffer(true);
var payload1 = "{ test: test1 }";
var payload2 = "{ test: test2 }";
var payload3 = "{ test: test3 }";
// act
buffer.enqueue(payload1);
buffer.enqueue(payload2);
buffer.enqueue(payload3);
var sent = [payload1, payload2];
buffer.markAsSent(sent);
var delivered = [payload1];
buffer.clearSent(delivered);
var buffer2 = this.getSessionStorageSendBuffer(true);
// verify
Assert.equal(2, buffer2.count(), "there should be two elements in the buffer");
}
});
this.testCase({
name: "SessionStorageSendBuffer: markAsSent saves items in the SENT_BUFFER",
test: () => {
// setup
var buffer = this.getSessionStorageSendBuffer(true);
// act
var payload1 = "{ test: test }";
var payload2 = "{ test: test }";
buffer.enqueue(payload1);
buffer.enqueue(payload2);
// verify
Assert.equal(2, buffer.count(), "there should be two elements in the buffer");
// act
var payload = buffer.getItems();
buffer.markAsSent(payload);
// verify
Assert.equal(0, buffer.count(), "There shouldn't be any items in the buffer");
var sentBuffer = this.getBuffer(this.SENT_BUFFER_KEY);
Assert.equal(2, sentBuffer.length, "There should be 2 items in the sent buffer");
}
});
this.testCase({
name: "SessionStorageSendBuffer: markAsSent removes only sent items from the buffer",
test: () => {
// setup
var buffer = this.getSessionStorageSendBuffer(true);
// act
var payload1 = "{ test: test1 }";
var payload2 = "{ test: test2 }";
var payload3 = "{ test: test3 }";
buffer.enqueue(payload1);
buffer.enqueue(payload2);
buffer.enqueue(payload3);
// verify
Assert.equal(3, buffer.count(), "there should be three elements in the buffer");
// act
var payload = [payload1, payload2];
buffer.markAsSent(payload);
// verify
Assert.equal(1, buffer.count(), "There should be one notsent item left in the buffer");
var sentBuffer = this.getBuffer(this.SENT_BUFFER_KEY);
Assert.equal(2, sentBuffer.length, "There should be 2 items in the sent buffer");
}
});
this.testCase({
name: "SessionStorageSendBuffer: clearSent clears the SENT_BUFFER",
test: () => {
// setup
var buffer = this.getSessionStorageSendBuffer(true);
var payload1 = "{ test: test1 }";
var payload2 = "{ test: test2 }";
buffer.enqueue(payload1);
buffer.enqueue(payload2);
var payload = buffer.getItems();
buffer.markAsSent(payload);
// act
buffer.clearSent(payload);
// verify
var sentBuffer = this.getBuffer(this.SENT_BUFFER_KEY);
Assert.equal(0, sentBuffer.length, "There should be 0 items in the sent buffer");
}
});
this.testCase({
name: "SessionStorageSendBuffer: does not store more than 2000 elements",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
for (var i = 0; i < 2000; i++) {
buffer.enqueue("i=" + i);
}
Assert.equal(2000, buffer.count(), "Buffer has 100 elements");
buffer.enqueue("I don't fit!");
Assert.equal(2000, buffer.count(), "Buffer should not allow to enqueue 101th element");
}
});
this.testCase({
name: "SessionStorageSendBuffer: logs a warning if the buffer is full",
test: () => {
var buffer = this.getSessionStorageSendBuffer();
var loggingSpy = this.sandbox.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
for (var i = 0; i < 2000; i++) {
buffer.enqueue("i=" + i);
}
Assert.equal(2000, buffer.count(), "Buffer has 100 elements");
buffer.enqueue("I don't fit!");
Assert.ok(loggingSpy.calledOnce, "BufferFull warning logged to console");
buffer.enqueue("I don't fit!");
Assert.ok(loggingSpy.calledOnce, "BufferFull warning should be logged only once.");
}
});
}
private getBuffer(key: string): string[] {
var bufferJson = Microsoft.ApplicationInsights.Util.getSessionStorage(key);
if (bufferJson) {
var buffer: string[] = JSON.parse(bufferJson);
if (buffer) {
return buffer;
}
}
return [];
}
private Test_Initialize(buffer: Microsoft.ApplicationInsights.ISendBuffer) {
// verify
Assert.equal(0, buffer.count(), "new buffer should be empty");
}
private Test_CanEnqueueAndClearTheBuffer(buffer: Microsoft.ApplicationInsights.ISendBuffer) {
// act
buffer.enqueue("");
// verify
Assert.equal(1, buffer.count(), "one item expected");
// act
buffer.enqueue("");
// verify
Assert.equal(2, buffer.count(), "two items expected");
//act
buffer.clear();
// verify
Assert.equal(0, buffer.count(), "buffer should be empty");
}
private Test_CanClearEmptyBuffer(buffer: Microsoft.ApplicationInsights.ISendBuffer) {
//verify
Assert.equal(0, buffer.count(), "buffer should be empty");
// act
buffer.clear();
// verify
Assert.equal(0, buffer.count(), "buffer should be empty");
}
private Test_CallBatchPayloadsWhenABufferIsEmpty(buffer: Microsoft.ApplicationInsights.ISendBuffer) {
// act
var batch = buffer.batchPayloads(null);
// verify
Assert.equal(null, batch, "expecting null");
}
private Test_CallBatchPayloadsWithOneElement(buffer: Microsoft.ApplicationInsights.ISendBuffer) {
// act
var payload = "{ test: test }";
var batch = buffer.batchPayloads([payload]);
// verify
Assert.equal("[" + payload + "]", batch, "invalid batch");
}
private Test_CallBatchPayloadsWithTwoElements(buffer: Microsoft.ApplicationInsights.ISendBuffer) {
// act
var payload1 = "{ test: test }";
var payload2 = "{ }";
var batch = buffer.batchPayloads([payload1, payload2]);
// verify
Assert.equal(['[', payload1, ',', payload2, ']'].join(''), batch, "invalid batch");
}
private Test_CallBatchPayloadsWithTwoElements_EmitLineDelimitedJson(buffer: Microsoft.ApplicationInsights.ISendBuffer) {
// act
var payload1 = "{ test: test }";
var payload2 = "{ test: test }";
var batch = buffer.batchPayloads([payload1, payload2]);
// verify
Assert.equal(payload1 + "\n" + payload2, batch, "invalid batch");
}
}
new SendBufferTests().registerTests();

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

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

@ -1,329 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Serializer.ts" />
class SerializerTests extends TestClass {
private throwInternal;
/** Method called before the start of each test method */
public testInitialize() {
this.throwInternal = this.sandbox.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
}
public registerTests() {
this.testCase({
name: "SerializerTests: empty input",
test: () => {
// act
Microsoft.ApplicationInsights.Serializer.serialize(null);
// verify
Assert.ok(this.throwInternal.calledOnce, "throw internal when input is null");
}
});
this.testCase({
name: "SerializerTests: objects without a contract are serialized",
test: () => {
// act
var obj = {
str: "str",
noContract: {
stillSerializable: "yep"
},
aiDataContract: {
str: Microsoft.ApplicationInsights.FieldType.Required,
noContract: Microsoft.ApplicationInsights.FieldType.Required
}
};
var expected = '{"str":"str","noContract":{"stillSerializable":"yep"}}';
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
Assert.ok(this.throwInternal.calledOnce, "warning when contract is omitted");
}
});
this.testCase({
name: "SerializerTests: required objects that are not present throw",
test: () => {
// act
var obj = {
aiDataContract: {
str: Microsoft.ApplicationInsights.FieldType.Required
}
};
var expected = "{}";
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
Assert.ok(this.throwInternal.calledOnce, "broken contracts throw");
}
});
this.testCase({
name: "SerializerTests: serialize an item with an array",
test: () => {
// act
var noCycle = { value: "value", aiDataContract: { value: Microsoft.ApplicationInsights.FieldType.Required } };
var obj = {
arr: [
noCycle,
noCycle,
noCycle
],
aiDataContract: { arr: Microsoft.ApplicationInsights.FieldType.Array }
};
var expected = '{"arr":[{"value":"value"},{"value":"value"},{"value":"value"}]}';
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
Assert.ok(this.throwInternal.notCalled, "no errors");
}
});
this.testCase({
name: "SerializerTests: serialize an item which claims to have an array but does not",
test: () => {
// act
var obj = {
arr: {},
aiDataContract: { arr: Microsoft.ApplicationInsights.FieldType.Array }
};
Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.ok(this.throwInternal.calledOnce, "one error");
}
});
this.testCase({
name: "SerializerTests: hidden fields are not serialized",
test: () => {
// act
var obj = {
str: "yes!",
hiddenStr: "im the invisible man",
hiddenStrRequired: "required fields can also be marked as hidden",
aiDataContract: {
str: Microsoft.ApplicationInsights.FieldType.Required,
hiddenStr: Microsoft.ApplicationInsights.FieldType.Hidden,
hiddenStrRequired: Microsoft.ApplicationInsights.FieldType.Required | Microsoft.ApplicationInsights.FieldType.Hidden,
}
};
var expected = '{"str":"yes!"}';
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
}
});
this.testCase({
name: "SerializerTests: serialize a field which has a dynamic required state",
test: () => {
// act
var obj = {
str: "required",
strOptional: "optional",
aiDataContract: {
str: { isRequired: () => { return Microsoft.ApplicationInsights.FieldType.Required; } },
strOptional: { isRequired: () => { return Microsoft.ApplicationInsights.FieldType.Default; } }
}
};
var expected = '{"str":"required","strOptional":"optional"}';
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
}
});
this.testCase({
name: "SerializerTests: cycles without contracts are handled",
test: () => {
// act
var cyclePt1 = { value: undefined, aiDataContract: { value: Microsoft.ApplicationInsights.FieldType.Required } };
var cyclePt2 = { value: cyclePt1, aiDataContract: { value: Microsoft.ApplicationInsights.FieldType.Required } };
cyclePt1.value = cyclePt2;
var obj = {
noContractWithCycle: {
notSerializable: cyclePt1
},
aiDataContract: {
noContractWithCycle: Microsoft.ApplicationInsights.FieldType.Required,
}
};
Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.ok(this.throwInternal.calledTwice, "user actionable error is thrown");
var error = this.throwInternal.args[0][2];
Assert.equal("Attempting to serialize an object which does not implement ISerializable", error);
}
});
this.testCase({
name: "SerializerTests: cycles with contracts are handled",
test: () => {
// act
var cyclePt1 = { value: undefined, aiDataContract: { value: Microsoft.ApplicationInsights.FieldType.Required } };
var cyclePt2 = { value: cyclePt1, aiDataContract: { value: Microsoft.ApplicationInsights.FieldType.Required } };
cyclePt1.value = cyclePt2;
var obj = {
aCycleWithContract: cyclePt1,
aiDataContract: {
aCycleWithContract: Microsoft.ApplicationInsights.FieldType.Required,
}
};
Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.ok(this.throwInternal.calledOnce, "error is thrown");
var error = this.throwInternal.args[0][2];
Assert.equal("Circular reference detected while serializing object", error, "invalid error message");
}
});
this.testCase({
name: "SerializerTests: object not present in the contract are not serialized",
test: () => {
// act
var obj = {
str: "str",
notInContract: "notInContract",
aiDataContract: {
str: Microsoft.ApplicationInsights.FieldType.Required,
}
};
var expected = '{"str":"str"}';
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
}
});
this.testCase({
name: "SerializerTests: cycle detection does not modify input",
test: () => {
// act
var obj = {
str: "str",
aiDataContract: {
str: Microsoft.ApplicationInsights.FieldType.Required
}
};
var expectedFields = {};
for (var field in obj) {
expectedFields[field] = true;
}
var expected = '{"str":"str"}';
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
for (var xField in obj) {
Assert.ok(expectedFields[xField], "unexpected field present after serialization: '" + xField + "'");
}
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
Assert.ok(this.throwInternal.notCalled, "no errors");
}
});
this.testCase({
name: "SerializerTests: properties will be serialized as string:string, measurements will be serilized as string:number",
test: () => {
var goodProperties = { a: "1", b: "test" };
var badProperties = { a: 1, b: { a: "a", b: "b" }, c: [1, 2, 3] };
var goodMeasurements = { a: 1, b: 2 };
var badMeasurements = { a: "1", b: "2" };
var test = (props, meas, message) => {
var obj = {
properties: props,
measurements: meas,
aiDataContract: {
properties: Microsoft.ApplicationInsights.FieldType.Default,
measurements: Microsoft.ApplicationInsights.FieldType.Default
}
};
this.throwInternal.reset();
var result = Microsoft.ApplicationInsights.Serializer.serialize(obj);
Assert.ok(result.indexOf("invalid field") < 0, message);
Assert.ok(this.throwInternal.notCalled, "no errors");
};
test(goodProperties, goodMeasurements, "properties and measurements");
test(goodProperties, badMeasurements, "properties and string measurements are parsed to floats");
test(badProperties, goodMeasurements, "bad properties and measurements");
test(badProperties, badMeasurements, "bad properties and string measurements are parsed to floatss");
test(goodProperties, undefined, "properties");
test(badProperties, undefined, "bad properties");
test(undefined, goodMeasurements, "measurements");
test(undefined, badMeasurements, "string measurements are parsed to floats");
test({ "p1": null, "p2": undefined }, { "m1": null, "m2:": undefined }, "null/undefined check for properties/measurements");
}
});
this.testCase({
name: "SerializerTests: verifying that null and undefined inputs return expected output",
test: () => {
var test = (props, meas, expectedOutput) => {
var obj = {
properties: props,
measurements: meas,
aiDataContract: {
properties: Microsoft.ApplicationInsights.FieldType.Default,
measurements: Microsoft.ApplicationInsights.FieldType.Default,
}
};
this.throwInternal.reset();
var result = Microsoft.ApplicationInsights.Serializer.serialize(obj);
Assert.equal(expectedOutput, result);
Assert.ok(this.throwInternal.notCalled, "no user actionable errors");
};
test({ "p1": null, "p2": undefined }, { "m1": null, "m2": undefined, "m3": "notanumber" }, "{\"properties\":{\"p1\":\"null\",\"p2\":\"undefined\"},\"measurements\":{\"m1\":\"null\",\"m2\":\"undefined\",\"m3\":\"NaN\"}}");
var brokenObject = {};
brokenObject.toString = undefined;
test({ "p1": brokenObject }, { "m1": 2 }, "{\"properties\":{\"p1\":\"invalid field: toString() is not defined.\"},\"measurements\":{\"m1\":2}}");
}
});
}
}
new SerializerTests().registerTests();

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

@ -1,47 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Util.ts" />
/// <reference path="../../JavaScriptSDK/SplitTest.ts" />
class SplitTestTests extends TestClass {
public registerTests() {
var getGuids = (count: number): Array<string> => {
var guids = [];
for (var i = 0; i < count; ++i) {
guids.push(Microsoft.ApplicationInsights.Util.newId());
}
return guids;
}
this.testCase({
name: "SplitTestTests: ",
test: () => {
var sut = new Microsoft.ApplicationInsights.SplitTest();
var guids = getGuids(10000);
var enabledPercent = 20;
var acceptedErrorPercent = 2;
// Act
var totalCount = guids.length;
var enabledCount = 0;
guids.forEach((guid) => {
if (sut.isEnabled(guid, enabledPercent))
++enabledCount;
});
// Assert.ok(false);
// Validate
var actualEnabledPercent = (enabledCount / totalCount) * 100;
Assert.ok(
(actualEnabledPercent < enabledPercent + acceptedErrorPercent) &&
(actualEnabledPercent > enabledPercent - acceptedErrorPercent),
"Enabled percent does not fall into expected range (" + enabledPercent + " +- " + acceptedErrorPercent + "): " + actualEnabledPercent);
}
});
}
}
new SplitTestTests().registerTests();

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

@ -1,231 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/Common/DataSanitizer.ts" />
/// <reference path="../../../JavaScriptSDK/Util.ts"/>
class DataSanitizerTests extends TestClass {
private origMaxNameLength: number;
private origMaxStringLength: number;
private origMaxUrlLength: number;
private origMaxMessageLength: number;
private origMaxExceptionLength: number;
public testInitialize() {
this.origMaxNameLength = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_NAME_LENGTH"];
this.origMaxStringLength = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_STRING_LENGTH"];
this.origMaxUrlLength = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_URL_LENGTH"];
this.origMaxMessageLength = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_MESSAGE_LENGTH"];
this.origMaxExceptionLength = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_EXCEPTION_LENGTH"];
}
public testCleanup() {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_NAME_LENGTH"] = this.origMaxNameLength;
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_STRING_LENGTH"] = this.origMaxStringLength;
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_URL_LENGTH"] = this.origMaxUrlLength;
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_MESSAGE_LENGTH"] = this.origMaxMessageLength;
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_EXCEPTION_LENGTH"] = this.origMaxExceptionLength;
}
public registerTests() {
this.testCase({
name: "DataSanitizerTests: Validate key with leading and trailing spaces is trimmed",
test: () => {
var expectedName = "Hello World";
var name = " \t\r\n" + expectedName + "\r\n\t ";
var validatedName = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeKey(name);
Assert.equal(expectedName, validatedName);
}
});
this.testCase({
name: "DataSanitizerTests: Validate key is truncated after max length",
test: () => {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_NAME_LENGTH"] = 5;
var expectedName = "Hello";
var name = "HelloWorld";
var validatedName = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeKey(name);
Assert.equal(expectedName, validatedName);
}
});
this.testCase({
name: "DataSanitizerTests: Validate string is truncated after max length ",
test: () => {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_STRING_LENGTH"] = 5;
var expectedValue = "Hello";
var value = "HelloWorld";
var validatedValue = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(value);
Assert.equal(expectedValue, validatedValue);
}
});
this.testCase({
name: "DataSanitizerTests: Validate object.toString is truncated if object passed to sanitizeString",
test: () => {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_STRING_LENGTH"] = 5;
var expectedValue = "[obje";
var value = { greeting: "Hello", place: "World" };
var validatedValue = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(value);
Assert.equal(expectedValue, validatedValue);
}
});
this.testCase({
name: "DataSanitizerTests: Validate url is truncated after max length ",
test: () => {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_URL_LENGTH"] = 5;
var expectedUrl = "Hello";
var url = "HelloWorld";
var validatedUrl = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeUrl(url);
Assert.equal(expectedUrl, validatedUrl);
}
});
this.testCase({
name: "DataSanitizerTests: Validate message is truncated after max length ",
test: () => {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_MESSAGE_LENGTH"] = 5;
var expectedMessage = "Hello";
var message = "HelloWorld";
var validatedMessage = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMessage(message);
Assert.equal(expectedMessage, validatedMessage);
}
});
this.testCase({
name: "DataSanitizerTests: Validate exception is truncated after max length ",
test: () => {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_EXCEPTION_LENGTH"] = 5;
var expectedException = "Hello";
var exception = "HelloWorld";
var validatedException = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeException(exception);
Assert.equal(expectedException, validatedException);
}
});
this.testCase({
name: "DataSanitizerTests: Validate measurement map is truncated after max length and maintains uniqueness",
test: () => {
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_NAME_LENGTH"] = 5;
var map = {
"hello1": 1,
"hello2": 2,
"hello3": 3,
"hello4": 4,
"hello5": 5
}
var expectedMap = {
"hello": 1,
"he001": 2,
"he002": 3,
"he003": 4,
"he004": 5
}
var validatedMap = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(map);
Assert.deepEqual(expectedMap, validatedMap);
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizeString trims whitespaces",
test: () => {
var expected = "NoWhiteSpaces";
var input = " NoWhiteSpaces ";
var actual = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(input);
Assert.equal(expected, actual);
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizestring defaults to DataSanitizer.MAX_STRING_LENGTH length",
test: () => {
var expected = "247E5792-7F2";
var input = "247E5792-7F2A-49DE-81EB-17D868775A06";
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_STRING_LENGTH"] = 12;
var actual = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(input);
Assert.equal(expected, actual);
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizestring checks against input max length",
test: () => {
var expected = "24";
var input = "247E5792-7F2A-49DE-81EB-17D868775A06";
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_STRING_LENGTH"] = 12;
var actual = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(input, 2);
Assert.equal(expected, actual);
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizeProperties trims whitespaces in properties names and values",
test: () => {
var expected = "NoWhiteSpaces";
var input = " NoWhiteSpaces ";
var testProps = { " prop1 ": " val ", " prop2 ": " val " };
var actual = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeProperties(testProps);
Assert.equal("val", actual["prop1"]);
Assert.equal("val", actual["prop2"]);
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizeId trims to valid size",
test: () => {
var expected = "247E5";
var input = "247E5792-7F2A-49DE-81EB-17D868775A06";
Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer["MAX_ID_LENGTH"] = 5;
var actual = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeId(input);
Assert.equal(expected, actual);
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizeString handles null and undefined",
test: () => {
Assert.ok(null === Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(null));
Assert.ok(undefined === Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeString(undefined));
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizeInput trims when data exceeds allowed maxlength",
test: () => {
var expected = "247E5792-"; // length 9
var input = "247E5792-7F2A-49DE-81EB-17D868775A06";
var actual = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeInput(input, 9, Microsoft.ApplicationInsights._InternalMessageId. IdTooLong);
Assert.equal(expected, actual);
}
});
this.testCase({
name: "DataSanitizerTests: Validate sanitizeInput trims input data",
test: () => {
var expected = "247E5792-"; // length 9
var input = " 247E5792- ";
var actual = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeInput(input, 9, Microsoft.ApplicationInsights._InternalMessageId. IdTooLong);
Assert.equal(expected, actual);
}
});
}
}
new DataSanitizerTests().registerTests();

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

@ -1,45 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../TestFramework/ContractTestHelper.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/Event.ts" />
class EventTelemetryTests extends ContractTestHelper {
constructor() {
super(() => new Microsoft.ApplicationInsights.Telemetry.Event("test"), "EventTelemetryTests");
}
/** Method called before the start of each test method */
public testInitialize() {
delete Microsoft.ApplicationInsights.Telemetry.Event["__extends"];
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name + "Constructor initializes the name",
test: () => {
var eventName = "test";
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Event(eventName);
Assert.equal(eventName, telemetry.name, "event name is set correctly");
}
});
this.testCase({
name: name + "Constructor sanitizes the name",
test: () => {
var char10 = "1234567890";
var eventName = char10;
for (var i = 0; i <= 200; i++) {
eventName += char10;
}
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Event(eventName);
Assert.equal(1024, telemetry.name.length, "event name is too long");
}
});
}
}
new EventTelemetryTests().registerTests();

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

@ -1,201 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../TestFramework/ContractTestHelper.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/Exception.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/SeverityLevel.ts" />
class ExceptionTelemetryTests extends ContractTestHelper {
private exception;
constructor() {
super(() => new Microsoft.ApplicationInsights.Telemetry.Exception(new Error("test error")), "ExceptionTelemetryTests");
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name + "Exceptions array is initialized in constructor",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error("test error"));
Assert.ok(telemetry.exceptions, "exceptions were initialized by the constructor");
Assert.equal(telemetry.exceptions.length, 1, "incorrect number of exceptions");
}
});
this.testCase({
name: name + "Exception is initialized with undefined severityLevel",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error("test error"), "HA");
Assert.equal(undefined, telemetry.severityLevel, "Exception shouldn't have severity level by default");
}
});
this.testCase({
name: name + "User can override severityLevel",
test: () => {
var level = AI.SeverityLevel.Critical;
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error("test error"), null, null, level);
Assert.equal(level, telemetry.severityLevel, "Exception has proper severity level");
}
});
this.testCase({
name: name + "Exception stack is limited to 32kb",
test: () => {
// setup
var testError = {
name: "Error",
message: "Test - stack is too large",
stack: "Error: testMaxSize"
}
var rawStackFrame = "\nat function" + i + " (http://myScript.js:" + i + ":20)";
var maxSize = 32 * 1024;
for (var i = 0; i < maxSize; i++) {
testError.stack += rawStackFrame;
}
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Exception(testError);
var exception = telemetry.exceptions[0];
// verify unparsed stack is truncated
Assert.ok(exception.stack.length === maxSize, "max size was applied to raw stack");
// verify parsed stack is truncated
var fullStr = JSON.stringify(exception);
var postSerializedException = JSON.parse(fullStr);
var parsedStackStr = JSON.stringify(postSerializedException.parsedStack);
Assert.ok(parsedStackStr.length <= maxSize, "parsed stack was truncated");
}
});
this.testCase({
name: name + "ExceptionTelemetry captures required data from input Error object",
test: () => {
var testErrors = [
{
name: "Error",
message: "chrome formatted error",
stack: "\
Error: testmessage1\n\
at new PageViewPerformanceData (http://myScript.js:10:20)\n\
at new PageViewPerformanceTelemetry (http://myScript.js:30:40)\n\
at http://myScript.js:40:50\n\
at myFunction (http://myScript.js:60:70)\n\
at <anonymous>:80:90"
}, {
name: "Error",
message: "firefox formatted error",
stack: "\
PageViewPerformanceData@http://myScript.js:10:20\n\
PageViewPerformanceTelemetry@http://myScript.js:30:40\n\
@http://myScript.js:40:50\n\
myFunction@http://myScript.js:60:70\n\
@anonymous debugger eval code:80:90"
}, {
name: "Error",
message: "ie formatted error",
stack: "\
Error: testmessage2\n\
at PageViewPerformanceData (http://myScript.js:10:20)\n\
at PageViewPerformanceTelemetry (http://myScript.js:30:40)\n\
at http://myScript.js:40:50\n\
at myFunction (http://myScript.js:60:70)\n\
at anonymous function (http://myScript.js:80:90)"
}
];
var fuzzyStringMatch = (a, b) => {
if (typeof a === "number") {
return a === b ? 1 : 0;
} else if (a === b) {
return 1;
} else {
var map = {};
for (var i = 1; i < a.length; i++) {
map[a[i - 1] + a[i]] = true;
}
var matches = 0;
for (i = 1; i < b.length; i++) {
if (map[b[i - 1] + b[i]]) {
matches++;
}
}
var len = Math.max(a.length, b.length) || 1;
return matches / len;
}
}
var test = (first, second) => {
Assert.ok(first.hasFullStack, first.message + " has full stack");
Assert.ok(second.hasFullStack, second.message + " has full stack");
Assert.equal(first.parsedStack.length, second.parsedStack.length, first.message + " stack length matches " + second.message);
// -1 to skip the last field which contains anonymous stack frame which varies widely between browsers
for (var i = 0; i < first.parsedStack.length - 1; i++) {
var fields = ["method", "line", "fileName", "level"];
var matchLevel = [0.7, 1, 0.7, 1];
while (fields.length) {
var field = fields.pop();
var requiredMatch = matchLevel.pop();
var similarity = fuzzyStringMatch(first.parsedStack[i][field], second.parsedStack[i][field]);
Assert.ok(similarity >= requiredMatch, field + " matches between: (" + first.message + ") and (" + second.message + ") by " + Math.round(similarity * 10000) / 100 + "% --- [" + first.parsedStack[i][field] + "] vs. [" + second.parsedStack[i][field] + "]");
}
}
};
var getFrame = (testError) => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Exception(testError);
return telemetry.exceptions[0];
};
var chrome = getFrame(testErrors[0]);
var firefox = getFrame(testErrors[1]);
var ie = getFrame(testErrors[2]);
test(chrome, firefox);
test(chrome, ie);
test(firefox, chrome);
test(firefox, ie);
test(ie, chrome);
test(ie, firefox);
}
});
this.testCase({
name: "CreateSimpleException returns Exception instance with specified properties",
test: () => {
var expectedMessage = "Test Message";
var expectedTypeName = "Test Type Name";
var expectedDetails = "Test Details";
var expectedAssembly = "Test Assembly";
var expectedFileName = "Test File Name";
var expectedLineNumber = 42;
var actual = Microsoft.ApplicationInsights.Telemetry.Exception.CreateSimpleException(expectedMessage, expectedTypeName, expectedAssembly, expectedFileName, expectedDetails, expectedLineNumber);
Assert.equal(expectedMessage, actual.exceptions[0].message);
Assert.equal(expectedTypeName, actual.exceptions[0].typeName);
Assert.equal(expectedDetails, actual.exceptions[0].stack);
Assert.equal(true, actual.exceptions[0].hasFullStack);
Assert.equal(undefined, actual.exceptions[0].parsedStack);
}
});
this.testCase({
name: "Stack trace with no method serializes as <no_method>",
test: () => {
// Act
var sut = new Microsoft.ApplicationInsights.Telemetry._StackFrame(" at http://myScript.js:40:50", 1);
// Verify
Assert.equal("<no_method>", sut.method);
}
});
}
}
new ExceptionTelemetryTests().registerTests();

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

@ -1,27 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../TestFramework/ContractTestHelper.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/Metric.ts" />
var metricName = "test";
var metricValue = 42;
class MetricTelemetryTests extends ContractTestHelper {
constructor() {
super(() => new Microsoft.ApplicationInsights.Telemetry.Metric(metricName, metricValue), "MetricTelemetryTests");
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name + "MetricTelemetry captures required data from user",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Metric(metricName, metricValue);
Assert.equal(metricName, telemetry.metrics[0].name, "name is incorrect");
Assert.equal(metricValue, telemetry.metrics[0].value, "value is incorrect");
}
});
}
}
new MetricTelemetryTests().registerTests();

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

@ -1,45 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../TestFramework/ContractTestHelper.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/PageView.ts" />
class PageViewTelemetryTests extends ContractTestHelper {
constructor() {
super(() => new Microsoft.ApplicationInsights.Telemetry.PageView("name", "url", 0, null, null, "id"), "PageViewTelemetryTests");
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
var testValues = {
id: "id",
name: "name",
url: "url",
duration: 1000,
properties: {
"property1": 5,
"property2": 10
},
measurements: {
"measurement": 300
}
};
this.testCase({
name: name + "PageviewData is initialized in constructor with 6 parameters (name, url, durationMs, properties, measurements, id) and valid",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageView(testValues.name, testValues.url, testValues.duration, testValues.properties, testValues.measurements, testValues.id);
Assert.equal(testValues.id, telemetry.id);
Assert.equal(testValues.name, telemetry.name);
Assert.equal(testValues.url, telemetry.url);
Assert.equal(Microsoft.ApplicationInsights.Util.msToTimeSpan(testValues.duration), telemetry.duration);
Assert.deepEqual(testValues.properties, telemetry.properties);
Assert.deepEqual(testValues.measurements, telemetry.measurements);
this.checkSerializableObject(() => telemetry, "PageviewData");
}
});
}
}
new PageViewTelemetryTests().registerTests();

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

@ -1,292 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../TestFramework/ContractTestHelper.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/PageViewPerformance.ts" />
class PageViewPerformanceTelemetryTests extends ContractTestHelper {
constructor() {
super(() => new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0), "PageViewPerformanceTelemetryTests");
}
public testCleanup() {
// Reset verboseLogging to the default value
Microsoft.ApplicationInsights._InternalLogging.verboseLogging = () => false;
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name + "getDuration() calculates a correct duration",
test: () => {
var duration = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.getDuration(10, 20);
Assert.equal(10, duration, "20 - 10 == 10");
duration = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.getDuration(1, 1);
Assert.equal(0, duration, "1 - 1 == 0");
duration = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.getDuration(100, 99);
Assert.equal(0, duration, "99 - 100 -> 0");
}
});
this.testCase({
name: name + "getDuration() returns undefined for invalid inputs",
test: () => {
var duration = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.getDuration(10, undefined);
Assert.equal(undefined, duration);
duration = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.getDuration("ab", 123);
Assert.equal(undefined, duration);
duration = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.getDuration(undefined, null);
Assert.equal(undefined, duration);
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry correct timing data",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
var isAvailable = window.performance && window.performance.timing; // safari doesn't support this
if (isAvailable) {
Assert.equal(typeof telemetry.perfTotal, "string");
Assert.equal(typeof telemetry.networkConnect, "string");
Assert.equal(typeof telemetry.receivedResponse, "string");
Assert.equal(typeof telemetry.sentRequest, "string");
Assert.equal(typeof telemetry.domProcessing, "string");
} else {
var check = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.isPerformanceTimingSupported();
Assert.equal(false, check, "isPerformanceTimingSupported returns false when not performance timing is not supported");
}
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry has correct serialization contract",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
Assert.equal(Microsoft.ApplicationInsights.FieldType.Required, telemetry.aiDataContract.ver, "version fields is required");
// all other fields are optional
for (var field in telemetry.aiDataContract) {
if (field == "ver") {
continue;
}
var contract = telemetry.aiDataContract[field];
Assert.notEqual(true, contract.isRequired, field + " is not required");
}
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry measurements are correct",
test: () => {
var timing = {
navigationStart: 1,
connectEnd: 10,
requestStart: 11,
responseStart: 30,
responseEnd: 42,
loadEventEnd: 60,
};
var timingSpy = this.sandbox.stub(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance, "getPerformanceTiming", () => {
return timing;
});
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
Assert.equal(true, telemetry.getIsValid());
var data = telemetry;
Assert.equal(Microsoft.ApplicationInsights.Util.msToTimeSpan(59), data.perfTotal);
Assert.equal(Microsoft.ApplicationInsights.Util.msToTimeSpan(9), data.networkConnect);
Assert.equal(Microsoft.ApplicationInsights.Util.msToTimeSpan(19), data.sentRequest);
Assert.equal(Microsoft.ApplicationInsights.Util.msToTimeSpan(12), data.receivedResponse);
Assert.equal(Microsoft.ApplicationInsights.Util.msToTimeSpan(18), data.domProcessing);
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry detects when perf data is sent by the browser incorrectly and doesn't send it",
test: () => {
var timing = {
navigationStart: 1,
connectEnd: 40,
requestStart: 11,
responseStart: 30,
responseEnd: 42,
loadEventEnd: 60,
};
var timingSpy = this.sandbox.stub(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance, "getPerformanceTiming", () => {
return timing;
});
var actualLoggedMessage = null;
Microsoft.ApplicationInsights._InternalLogging.verboseLogging = () => true;
var loggingSpy = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "warnToConsole", (m) => actualLoggedMessage = m);
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
Assert.equal(false, telemetry.getIsValid());
var data = telemetry;
Assert.equal(undefined, data.perfTotal);
Assert.equal(undefined, data.networkConnect);
Assert.equal(undefined, data.sentRequest);
Assert.equal(undefined, data.receivedResponse);
Assert.equal(undefined, data.domProcessing);
Assert.equal("AI (Internal): ClientPerformanceMathError message:\"client performance math error.\" props:\"{total:59,network:39,request:19,response:12,dom:18}\"", actualLoggedMessage);
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry is not reporting duration if a request is coming from a Googlebot",
test: () => {
// mock user agent
let originalUserAgent = navigator.userAgent;
try {
this.setUserAgent("Googlebot/2.1");
} catch (ex) {
Assert.ok(true, 'cannot run this test in the current setup - try Chrome');
return;
}
var timing = {
navigationStart: 1,
connectEnd: 2,
requestStart: 3,
responseStart: 30,
responseEnd: 42,
loadEventEnd: 60,
};
var timingSpy = this.sandbox.stub(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance, "getPerformanceTiming", () => {
return timing;
});
var actualLoggedMessage: string = "";
Microsoft.ApplicationInsights._InternalLogging.verboseLogging = () => true;
var loggingSpy = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "warnToConsole", (m) => actualLoggedMessage = m);
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
Assert.equal(false, telemetry.getIsValid());
var data = telemetry;
Assert.equal(undefined, data.perfTotal);
Assert.equal(undefined, data.networkConnect);
Assert.equal(undefined, data.sentRequest);
Assert.equal(undefined, data.receivedResponse);
Assert.equal(undefined, data.domProcessing);
timingSpy.restore();
loggingSpy.restore();
// restore original user agent
this.setUserAgent(originalUserAgent);
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry checks if any duration exceeds 1h and don't send it",
test: () => {
// see comment PageViewPerformance constructor on how timing data is calculated
// here we set values, so each metric will be exactly 3600000 (1h).
let timingModifiers = [(timing) => timing.loadEventEnd = 3600001,
(timing) => timing.connectEnd = 3600001,
(timing) => timing.responseStart = 3600003,
(timing) => timing.responseEnd = 3600030,
(timing) => timing.loadEventEnd = 3600042];
for (var i = 0; i < timingModifiers.length; i++) {
var timing = {
navigationStart: 1,
connectEnd: 2,
requestStart: 3,
responseStart: 30,
responseEnd: 42,
loadEventEnd: 60,
};
// change perf timing value
timingModifiers[i](timing);
var timingSpy = this.sandbox.stub(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance, "getPerformanceTiming", () => {
return timing;
});
var actualLoggedMessage: string = "";
Microsoft.ApplicationInsights._InternalLogging.verboseLogging = () => true;
var loggingSpy = this.sandbox.stub(Microsoft.ApplicationInsights._InternalLogging, "warnToConsole", (m) => actualLoggedMessage = m);
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
Assert.equal(false, telemetry.getIsValid());
var data = telemetry;
Assert.equal(undefined, data.perfTotal);
Assert.equal(undefined, data.networkConnect);
Assert.equal(undefined, data.sentRequest);
Assert.equal(undefined, data.receivedResponse);
Assert.equal(undefined, data.domProcessing);
if (i === 0) {
// check props only for the first timingModifier
Assert.equal("AI (Internal): InvalidDurationValue message:\"Invalid page load duration value. Browser perf data won't be sent.\" props:\"{total:3600000,network:1,request:27,response:12,dom:3599959}\"", actualLoggedMessage);
} else {
Assert.ok(actualLoggedMessage.lastIndexOf("AI (Internal): InvalidDurationValue message:\"Invalid page load duration value. Browser perf data won't be sent.", 0) === 0);
}
timingSpy.restore();
loggingSpy.restore();
}
}
});
this.testCase({
name: name + "shouldCollectDuration() should detect all google bots",
test: () => {
try {
this.setUserAgent('fake user agent');
} catch (ex) {
Assert.ok(true, 'cannot run this test in the current setup - try Chrome');
return;
}
let testCases = [
// bots
{ string: 'Googlebot/2.1 (+http://www.google.com/bot.html)', shouldCollect: false },
{ string: 'Googlebot-Image/1.0', shouldCollect: false },
{ string: 'AdsBot-Google-Mobile-Apps', shouldCollect: false },
{ string: 'Mozilla/5.0 (Linux; Android 5.0; SM-G920A) AppleWebKit (KHTML, like Gecko) Chrome Mobile Safari (compatible; AdsBot-Google-Mobile; +http://www.google.com/mobile/adsbot.html)', shouldCollect: false },
{ string: 'APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)', shouldCollect: false },
// browsers
{ string: 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', shouldCollect: true },
{ string: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246', shouldCollect: true },
{ string: 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1', shouldCollect: true },
];
for (let i = 0; i < testCases.length; i++) {
this.setUserAgent(testCases[i].string);
let shouldCollect = Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.shouldCollectDuration(10);
Assert.equal(testCases[i].shouldCollect, shouldCollect);
}
}
});
}
}
new PageViewPerformanceTelemetryTests().registerTests();

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

@ -1,100 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../TestFramework/ContractTestHelper.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/SeverityLevel.ts" />
class RemoteDependencyTests extends ContractTestHelper {
private exception;
private static id = "someid";
private static method = "GET";
private static testName = "testName"
private static url = "http://myurl.com/"
private static hostName = "myurl.com";
private static totalTime = 123;
private static success = false;
private static resultCode = 404;
constructor() {
super(
() => new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData(
RemoteDependencyTests.id, RemoteDependencyTests.testName, RemoteDependencyTests.url, RemoteDependencyTests.totalTime, RemoteDependencyTests.success, RemoteDependencyTests.resultCode, RemoteDependencyTests.method),
"RemoteDependencyTelemetryTests");
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name + "Constructor parameters are set correctly",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData(
RemoteDependencyTests.id, RemoteDependencyTests.url, RemoteDependencyTests.testName, RemoteDependencyTests.totalTime, RemoteDependencyTests.success, RemoteDependencyTests.resultCode, RemoteDependencyTests.method);
Assert.equal("00:00:00.123", telemetry.duration, "value should be set correctly");
Assert.equal(RemoteDependencyTests.success, telemetry.success, "success should be set correctly");
Assert.equal(RemoteDependencyTests.resultCode, telemetry.resultCode, "resultCode should be set correctly");
Assert.equal("GET /", telemetry.name, "name gets correct value");
Assert.equal(RemoteDependencyTests.hostName, telemetry.target, "target gets correct value");
Assert.equal(RemoteDependencyTests.testName, telemetry.data, "data should be set correctly");
}
});
this.testCase({
name: name + "Data is truncated if too long",
test: () => {
var urlLength = 2049;
var longUrl = "";
for (var i = 0; i < urlLength; i++) {
longUrl += "A";
}
var telemetry = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData(
RemoteDependencyTests.id, longUrl, longUrl, RemoteDependencyTests.totalTime, RemoteDependencyTests.success, RemoteDependencyTests.resultCode, RemoteDependencyTests.method);
Assert.equal(2048, telemetry.data.length, "data should be truncated");
}
});
this.testCase({
name: name + "name is truncated if too long",
test: () => {
var urlLength = 1025;
var longUrl = "";
for (var i = 0; i < urlLength; i++) {
longUrl += "A";
}
var telemetry = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData(
RemoteDependencyTests.id, longUrl, longUrl, RemoteDependencyTests.totalTime, RemoteDependencyTests.success, RemoteDependencyTests.resultCode, RemoteDependencyTests.method);
Assert.equal(1024, telemetry.name.length, "name should be truncated");
}
});
this.testCase({
name: name + "Duration field is populated as expected",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData(
RemoteDependencyTests.id, RemoteDependencyTests.url, RemoteDependencyTests.testName, 86400000, RemoteDependencyTests.success, RemoteDependencyTests.resultCode, RemoteDependencyTests.method);
Assert.equal("1.00:00:00.000", telemetry.duration, "value should be set correctly");
telemetry = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData(
RemoteDependencyTests.id, RemoteDependencyTests.url, RemoteDependencyTests.testName, 86400026, RemoteDependencyTests.success, RemoteDependencyTests.resultCode, RemoteDependencyTests.method);
Assert.equal("1.00:00:00.026", telemetry.duration, "value should be set correctly");
}
});
this.testCase({
name: name + "default properties are set correctly",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("", "", "", 0, false, 0, null);
Assert.equal("Ajax", telemetry.type, "dependencyTypeName gets correct default value");
Assert.equal("", telemetry.name, "name gets correct default value");
}
});
}
}
new RemoteDependencyTests().registerTests();

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

@ -1,25 +0,0 @@
/// <reference path="../../TestFramework/Common.ts" />
/// <reference path="../../TestFramework/ContractTestHelper.ts" />
/// <reference path="../../../JavaScriptSDK/Telemetry/Trace.ts" />
class TraceTelemetryTests extends ContractTestHelper {
constructor() {
super(() => new Microsoft.ApplicationInsights.Telemetry.Trace("test"), "TraceTelemetryTests");
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
this.testCase({
name: name + "Trace captures required data from user",
test: () => {
var message = "test";
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Trace(message);
Assert.equal(message, telemetry.message, "message is set correctly");
}
});
}
}
new TraceTelemetryTests().registerTests();

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

@ -1,587 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/TelemetryContext.ts" />
/// <reference path="../../JavaScriptSDK/AppInsights.ts" />
/// <reference path="../../JavaScriptSDK/Telemetry/Common/Envelope.ts"/>
class TelemetryContextTests extends TestClass {
private _telemetryContext: Microsoft.ApplicationInsights.TelemetryContext;
private _config: Microsoft.ApplicationInsights.ITelemetryConfig;
/** Method called before the start of each test method */
public testInitialize() {
this._config = {
instrumentationKey: () => "testKey",
accountId: () => undefined,
sessionRenewalMs: () => 10,
sessionExpirationMs: () => 10,
endpointUrl: () => "asdf",
emitLineDelimitedJson: () => false,
maxBatchSizeInBytes: () => 1000000,
maxBatchInterval: () => 1,
disableTelemetry: () => false,
sampleRate: () => 100,
cookieDomain: undefined,
enableSessionStorageBuffer: () => false,
isRetryDisabled: () => false,
isBeaconApiDisabled: () => true,
sdkExtension: () => null,
isBrowserLinkTrackingEnabled: () => false,
appId: () => undefined,
}
this._telemetryContext = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
}
/** Method called after each test method has completed */
public testCleanup() {
(<any>this._telemetryContext).telemetryInitializers = undefined;
}
public registerTests() {
this.testCase({
name: "TelemtetryContext: constructor initializers sender and ikey",
test: () => {
var tc = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
Assert.ok(tc._sender, "sender is initialized");
Assert.ok(tc._config.instrumentationKey(), "iKey is initialized");
}
});
this.testCase({
name: "TelemtetryContext: constructor intialized with correct sdk version",
test: () => {
var tc = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
Assert.ok(tc.internal, "context.internal is initialized");
var expectedSdkVersion = "javascript:" + Microsoft.ApplicationInsights.Version;
Assert.equal(expectedSdkVersion, tc.internal.sdkVersion, "sdkVersion is initialized");
}
});
this.testCase({
name: "TelemtetryContext: constructor intialized with correct sdk version and sdk extension name",
test: () => {
this._config.sdkExtension = () => "abc";
var tc = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
Assert.ok(tc.internal, "context.internal is initialized");
var expectedSdkVersion = "abc_javascript:" + Microsoft.ApplicationInsights.Version;
Assert.equal(expectedSdkVersion, tc.internal.sdkVersion, "sdkVersion is initialized");
// clean up
this._config.sdkExtension = () => null;
}
});
this.testCase({
name: "TelemtetryContext: constructor intialized correctly when snippet version is missing",
test: () => {
var tc = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
Assert.ok(tc.internal, "context.internal is initialized");
var expectedSnippet = undefined;
Assert.equal(expectedSnippet, tc.internal.agentVersion, "agentVersion is NOT initialized with the snippet version is missing");
}
});
this.testCase({
name: "TelemtetryContext: calling track with null or undefined fails",
test: () => {
var tc = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
var logSpy = this.sandbox.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternal");
tc.track(undefined);
Assert.ok(logSpy.calledOnce, "sender throws with undefined");
tc.track(null);
Assert.ok(logSpy.calledTwice, "sender throws with null");
}
});
this.testCase({
name: "TelemtetryContext: does not overwrite user sessioncontext with defaults",
test: () => {
this._telemetryContext.session.id = "101";
this._telemetryContext.session.isFirst = true;
var env = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(null, "");
this._telemetryContext.track(env);
var contextKeys = new AI.ContextTagKeys();
Assert.equal("101", env.tags[contextKeys.sessionId], "session.id");
Assert.equal(true, env.tags[contextKeys.sessionIsFirst], "session.isFirst");
}
});
function getEnvelope<T>(item, dataType: string, envelopeType: string) {
var data = new Microsoft.ApplicationInsights.Telemetry.Common.Data<T>(dataType, item);
return new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, envelopeType);
}
this.testCase({
name: "TelemetryContext: page views get sampled",
test: () => {
var stub = this.getStub(Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType, this._telemetryContext);
var envelope = getEnvelope<Microsoft.ApplicationInsights.Telemetry.PageView>(
new Microsoft.ApplicationInsights.Telemetry.PageView("asdf", "asdf", 10, null, null, "asdf"),
Microsoft.ApplicationInsights.Telemetry.PageView.dataType,
Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType);
// act
this._telemetryContext.track(envelope);
// assert
Assert.equal(1, stub.isSampledInCallsCount);
// tear down
}
});
this.testCase({
name: "TelemetryContext: events get sampled",
test: () => {
var stub = this.getStub(Microsoft.ApplicationInsights.Telemetry.Event.envelopeType, this._telemetryContext);
var envelope = getEnvelope<Microsoft.ApplicationInsights.Telemetry.Event>(
new Microsoft.ApplicationInsights.Telemetry.Event("asdf"),
Microsoft.ApplicationInsights.Telemetry.Event.dataType,
Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
// act
this._telemetryContext.track(envelope);
// assert
Assert.equal(1, stub.isSampledInCallsCount);
// tear down
}
});
this.testCase({
name: "TelemetryContext: exceptions get sampled",
test: () => {
var stub = this.getStub(Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType, this._telemetryContext);
var exception;
try {
throw new Error("asdf");
} catch (e) {
exception = e;
}
var envelope = getEnvelope<Microsoft.ApplicationInsights.Telemetry.Exception>(
new Microsoft.ApplicationInsights.Telemetry.Exception(exception),
Microsoft.ApplicationInsights.Telemetry.Exception.dataType,
Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType);
// act
this._telemetryContext.track(envelope);
// assert
Assert.equal(1, stub.isSampledInCallsCount);
// tear down
}
});
this.testCase({
name: "TelemetryContext: metrics do NOT get sampled",
test: () => {
var stub = this.getStub(Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType, this._telemetryContext);
var envelope = getEnvelope<Microsoft.ApplicationInsights.Telemetry.Metric>(
new Microsoft.ApplicationInsights.Telemetry.Metric("asdf", 1234),
Microsoft.ApplicationInsights.Telemetry.Metric.dataType,
Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType);
// act
this._telemetryContext.track(envelope);
// assert
Assert.equal(0, stub.isSampledInCallsCount);
// tear down
}
});
this.testCase({
name: "TelemetryContext: pageViewPerformance gets sampled",
test: () => {
var stub = this.getStub(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType, this._telemetryContext);
var envelope = getEnvelope<Microsoft.ApplicationInsights.Telemetry.PageViewPerformance>(
new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("adsf", "asdf", 10),
Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.dataType,
Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType);
// act
this._telemetryContext.track(envelope);
// assert
Assert.equal(1, stub.isSampledInCallsCount);
// tear down
}
});
this.testCase({
name: "TelemetryContext: traces get sampled",
test: () => {
var stub = this.getStub(Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType, this._telemetryContext);
var envelope = getEnvelope<Microsoft.ApplicationInsights.Telemetry.Trace>(
new Microsoft.ApplicationInsights.Telemetry.Trace("afd"),
Microsoft.ApplicationInsights.Telemetry.Trace.dataType,
Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
// act
this._telemetryContext.track(envelope);
// assert
Assert.equal(1, stub.isSampledInCallsCount);
// tear down
}
});
this.testCase({
name: "TelemetryContext: onBeforeSendTelemetry is called within track() and gets the envelope as an argument",
test: () => {
var eventEnvelope = this.getTestEventEnvelope();
var telemetryInitializer = {
initializer: (envelope) => { }
}
var spy = this.sandbox.spy(telemetryInitializer, "initializer");
this._telemetryContext.addTelemetryInitializer(<any>telemetryInitializer.initializer);
// act
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(spy.calledOnce, "telemetryInitializer was called");
Assert.ok(eventEnvelope === spy.args[0][0]);
// teardown
}
});
this.testCase({
name: "TelemetryContext: onBeforeSendTelemetry changes the envelope props and sender gets them",
test: () => {
var nameOverride = "my unique name";
var eventEnvelope = this.getTestEventEnvelope();
Assert.notEqual(eventEnvelope.name, nameOverride);
var telemetryInitializer = {
initializer: (envelope: Microsoft.ApplicationInsights.Telemetry.Common.Envelope) => {
envelope.name = nameOverride;
return true;
}
}
this._telemetryContext.addTelemetryInitializer(<any>telemetryInitializer.initializer);
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.calledOnce, "sender was called");
Assert.ok(eventEnvelope === stub.args[0][0]);
Assert.equal(nameOverride,
(<Microsoft.ApplicationInsights.Telemetry.Common.Envelope>stub.args[0][0]).name);
// teardown
}
});
this.testCase({
name: "TelemetryContext: telemetryInitializers array is empty means envelope goes straight to the sender",
test: () => {
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
var defaultInitsStub = this.sandbox.stub(this._telemetryContext, "_addDefaultTelemetryInitializers");
// act
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.calledOnce, "sender was called");
Assert.ok(eventEnvelope === stub.args[0][0]);
}
});
this.testCase({
name: "TelemetryContext: telemetryInitializers array is populated with the default initializers",
test: () => {
var eventEnvelope = this.getTestEventEnvelope();
// has one initializer to remove browserLinks
Assert.equal((<any>this._telemetryContext).telemetryInitializers.length, 1);
}
});
this.testCase({
name: "TelemetryContext: default initializers will reject BrowserLink Ajax requests",
test: () => {
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
let getRequestEnvelope = (url: string, name: string) => {
let browserLinkRequest = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData('id_1', url, name, 1, true, 200);
let requestData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData>(Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, browserLinkRequest);
let requestEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(requestData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType);
return requestEnvelope;
}
let request1 = getRequestEnvelope('http://localhost/__browserLink/test/test?testarg=1', 'GET /__browserLink/test/test');
let request2 = getRequestEnvelope('http://localhost/browserLinkSignalR/test/test?testarg=1', 'GET /browserLinkSignalR/test/test');
(<any>this._telemetryContext)._track(request1);
(<any>this._telemetryContext)._track(request2);
Assert.ok(stub.notCalled);
let request3 = getRequestEnvelope('http://localhost/__browser', 'GET /__browser');
(<any>this._telemetryContext)._track(request3);
Assert.ok(stub.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: can enable the BrowserLink tracking",
test: () => {
this._config.isBrowserLinkTrackingEnabled = () => true;
this._telemetryContext = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
let getRequestEnvelope = (url: string, name: string) => {
let browserLinkRequest = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData('id_1', url, name, 1, true, 200);
let requestData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData>(Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, browserLinkRequest);
let requestEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(requestData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType);
return requestEnvelope;
}
let request1 = getRequestEnvelope('http://localhost/__browserLink/test/test?testarg=1', 'GET /__browserLink/test/test');
let request2 = getRequestEnvelope('http://localhost/browserLinkSignalR/test/test?testarg=1', 'GET /browserLinkSignalR/test/test');
(<any>this._telemetryContext)._track(request1);
(<any>this._telemetryContext)._track(request2);
Assert.equal(2, stub.callCount);
// reset
this._config.isBrowserLinkTrackingEnabled = () => false;
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer can modify the contents of an envelope",
test: () => {
var eventEnvelope = this.getTestEventEnvelope();
var telemetryInitializer = {
// This illustrates how to use telemetry initializer (onBeforeSendTelemetry)
// to access/ modify the contents of an envelope.
init: (envelope: Microsoft.ApplicationInsights.Telemetry.Common.Envelope) => {
if (envelope.name ==
Microsoft.ApplicationInsights.Telemetry.Event.envelopeType) {
var telemetryItem = (<any>envelope.data).baseData;
telemetryItem.name = "my name";
telemetryItem.properties = telemetryItem.properties || {};
telemetryItem.properties["prop1"] = "val1";
}
}
}
this._telemetryContext.addTelemetryInitializer(<any>telemetryInitializer.init);
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.calledOnce, "sender should be called");
Assert.equal("my name", (<any>stub.args[0][0]).data.baseData.name);
Assert.equal("val1", (<any>stub.args[0][0]).data.baseData.properties["prop1"]);
}
});
this.testCase({
name: "TelemetryContext: all added telemetry initializers get invoked",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var initializer1 = { init: () => { } };
var initializer2 = { init: () => { } };
var spy1 = this.sandbox.spy(initializer1, "init");
var spy2 = this.sandbox.spy(initializer2, "init");
// act
this._telemetryContext.addTelemetryInitializer(<any>initializer1.init);
this._telemetryContext.addTelemetryInitializer(<any>initializer2.init);
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(spy1.calledOnce);
Assert.ok(spy2.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning false means don't send an item",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
this._telemetryContext.addTelemetryInitializer(<any>(() => { return false; }));
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.notCalled);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning void means do send an item (back compact with older telemetry initializers)",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
this._telemetryContext.addTelemetryInitializer(<any>(() => { return; }));
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning true means do send an item",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
this._telemetryContext.addTelemetryInitializer(<any>(() => { return true; }));
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - if one of initializers returns false than item is not sent",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
this._telemetryContext.addTelemetryInitializer(<any>(() => { return true; }));
this._telemetryContext.addTelemetryInitializer(<any>(() => { return false; }));
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.notCalled);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - if one of initializers returns false (any order) than item is not sent",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
this._telemetryContext.addTelemetryInitializer(<any>(() => { return false; }));
this._telemetryContext.addTelemetryInitializer(<any>(() => { return true; }));
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.notCalled);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - returning not boolean/undefined/null means do send an item (back compat with older telemetry initializers)",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
this._telemetryContext.addTelemetryInitializer(<any>(() => { return "asdf"; }));
this._telemetryContext.addTelemetryInitializer(<any>(() => { return null; }));
this._telemetryContext.addTelemetryInitializer(<any>(() => { return undefined; }));
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.calledOnce);
}
});
this.testCase({
name: "TelemetryContext: telemetry initializer - if one initializer fails then telemetry is not sent",
test: () => {
// prepare
var eventEnvelope = this.getTestEventEnvelope();
var stub = this.sandbox.stub(this._telemetryContext._sender, "send");
// act
this._telemetryContext.addTelemetryInitializer(<any>(() => { throw new Error(); }));
this._telemetryContext.addTelemetryInitializer(<any>(() => { }));
(<any>this._telemetryContext)._track(eventEnvelope);
// verify
Assert.ok(stub.notCalled);
}
});
}
/**
* Gets the sinon stub for telemetryContext.sample.isSampledIn function. Result is wrapped to an object
* which has a counter of how many times the stub was accessed with expected envelope type.
*/
private getStub(envelopeType: string, telemetryContext: Microsoft.ApplicationInsights.TelemetryContext) {
var stub = {
sinonStub: null,
isSampledInCallsCount: 0
};
var isSampledInStub = this.sandbox.stub(telemetryContext.sample, "isSampledIn",
(envelope: Microsoft.ApplicationInsights.Telemetry.Common.Envelope) => {
if (envelope.name === envelopeType) {
++stub.isSampledInCallsCount;
}
});
stub.sinonStub = isSampledInStub;
return stub;
}
private getTestEventEnvelope(properties?: Object, measurements?: Object) {
var event = new Microsoft.ApplicationInsights.Telemetry.Event('Test Event', properties, measurements);
var eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Event>(Microsoft.ApplicationInsights.Telemetry.Event.dataType, event);
var eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
return eventEnvelope;
}
}
new TelemetryContextTests().registerTests();

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

@ -1,626 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/Util.ts" />
class UtilTests extends TestClass {
public testCleanup() {
// reset storage cache
(<any>Microsoft.ApplicationInsights.Util)._canUseLocalStorage = undefined;
(<any>Microsoft.ApplicationInsights.Util)._canUseSessionStorage = undefined;
}
public registerTests() {
var Util = Microsoft.ApplicationInsights.Util;
var UrlHelper = Microsoft.ApplicationInsights.UrlHelper;
this.testCase({
name: "UtilTests: getStorage with available storage",
test: () => {
var storage = this.getMockStorage();
var getStorageObjectStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "_getLocalStorageObject", () => storage);
storage["test"] = "A";
Assert.equal("A", Util.getStorage("test"), "getStorage should return value of getItem for known keys");
Assert.equal(undefined, Util.getStorage("another"), "getStorage should return value of getItem for unknown keys");
}
});
this.testCase({
name: "UtilTests: getStorage with no storage support",
test: () => {
var storage = undefined;
var getStorageObjectStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "_getLocalStorageObject", () => storage);
Assert.equal(null, Util.getStorage("test"), "getStorage should return null when storage is unavailable");
}
});
this.testCase({
name: "UtilTests: can disable local and session storage",
test: () => {
// can use local and session storage by default
Assert.ok(Util.canUseLocalStorage(), "can use local storage by default");
Assert.ok(Util.canUseSessionStorage(), "can use session storage by default");
Util.setStorage("key1", "value1");
Util.setSessionStorage("key2", "value2");
Assert.equal("value1", Util.getStorage("key1"), "can rad from local storage with it is enabled");
Assert.equal("value2", Util.getSessionStorage("key2"), "can rad from session storage with it is enabled");
// disable storages
Util.disableStorage();
// can't read
Assert.ok(!Util.canUseLocalStorage(), "can use local storage after it was disabled");
Assert.ok(!Util.canUseSessionStorage(), "can use session storage after it was disabled");
Assert.equal(null, Util.getStorage("key1"), "can't read from local storage when disabled");
Assert.equal(null, Util.getSessionStorage("key2"), "can't read from session storage when disabled");
}
});
this.testCase({
name: "UtilTests: setStorage with available storage",
test: () => {
var storage = this.getMockStorage();
var getStorageObjectStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "_getLocalStorageObject", () => storage);
Assert.ok(Util.setStorage("test", "A"), "setStorage should return true if storage is available for writes");
}
});
this.testCase({
name: "UtilTests: setStorage with no storage support",
test: () => {
var storage = undefined;
var getStorageObjectStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "_getLocalStorageObject", () => storage);
Assert.ok(!Util.setStorage("test", "A"), "setStorage should return false if storage is unavailable for writes");
}
});
this.testCase({
name: "UtilTests: removeStorage with available storage",
test: () => {
var storage = this.getMockStorage();
var getStorageObjectStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "_getLocalStorageObject", () => storage);
storage["test"] = "A";
Assert.ok(Util.removeStorage("test"), "removeStorage should return true if storage is available for writes");
Assert.deepEqual(undefined, storage["test"], "removeStorage should remove items from storage");
}
});
this.testCase({
name: "UtilTests: removeStorage with no storage support",
test: () => {
var storage = undefined;
var getStorageObjectStub = this.sandbox.stub(Microsoft.ApplicationInsights.Util, "_getLocalStorageObject", () => storage);
Assert.ok(!Util.removeStorage("test"), "removeStorage should return false if storage is unavailable for writes");
}
});
this.testCase({
name: "UtilTests: isArray",
test: () => {
var isArray = Util["isArray"];
Assert.ok(isArray([]));
Assert.ok(!isArray("sdf"));
Assert.ok(isArray([0, 1]));
Assert.ok(!isArray({ length: "" }));
Assert.ok(!isArray({ length: 10 }));
// arr instanceof Array; // false for this case
var iframe = document.createElement('iframe');
iframe.style.cssText = 'display:none;';
document.body.appendChild(iframe);
var iframeArray = window.frames[window.frames.length - 1]["Array"];
if (typeof iframeArray === "function") {
var arr = new iframeArray(1, 2, 3); // [1,2,3]
Assert.ok(!(arr instanceof Array), "instanceof doesn't work here");
Assert.ok(isArray(arr));
}
}
});
this.testCase({
name: "UtilTests: cookies",
test: () => {
// mock cookies
((document) => {
var cookies = {};
(<any>document).__defineGetter__('cookie', () => {
var output = [];
for (var cookieName in cookies) {
output.push(cookieName + "=" + cookies[cookieName]);
}
return output.join(";");
});
(<any>document).__defineSetter__('cookie', (s) => {
var indexOfSeparator = s.indexOf("=");
var key = s.substr(0, indexOfSeparator);
var value = s.substring(indexOfSeparator + 1);
cookies[key] = value;
return key + "=" + value;
});
(<any>document).clearCookies = () => {
cookies = {};
};
})(document);
var expectedValue = "testValue";
Util.setCookie("test", expectedValue);
var ua = navigator.userAgent.toLowerCase();
var isSafari = ua.indexOf('safari') > -1 && ua.indexOf('chrome') < 0;
if (isSafari) {
Assert.ok("Safari doesn't allow mocking cookies");
} else {
var actualValue = Util.getCookie("test");
Assert.equal(expectedValue, actualValue, "cookie content was set and retrieved");
actualValue = Util.getCookie("");
Assert.equal("", actualValue, "cookie content was set and retrieved");
}
}
});
this.testCase({
name: "UtilTests: can disable cookies",
test: () => {
Assert.ok(Util.canUseCookies(), "can use cookies by default");
Util.disableCookies();
Assert.ok(!Util.canUseCookies(), "cannot use cookies after they were disabled");
// reset
(<any>Util)._canUseCookies = undefined;
}
});
this.testCase({
name: "UtilTests: parse cookie",
test: () => {
try {
var test = (cookie, query, expected) => {
Util["document"] = <any>{
cookie: cookie
};
var actual = Util.getCookie(query);
Assert.deepEqual(expected, actual, "cookie is parsed correctly");
}
test("testCookie=id|acq|renewal", "testCookie", "id|acq|renewal");
test("other=something; testCookie=id|acq|renewal", "testCookie", "id|acq|renewal");
test("another=bar; ;a=testCookie=; testCookie=id|acq|renewal; other=something|3|testCookie=", "testCookie", "id|acq|renewal");
test("xtestCookiex=id|acq|renewal", "testCookie", "");
test("", "testCookie", "");
} finally {
Util["document"] = document;
}
}
});
this.testCase({
name: "UtilTests: canUseCookies returns false if document.cookie is not available",
test: () => {
var oldDocument = Util["document"];
(<any>Util)._canUseCookies = undefined;
Util["document"] = <any>{
cookie: undefined
};
Assert.equal(false, Util.canUseCookies(), "cookie are not available");
// restore document object
Util["document"] = oldDocument;
(<any>Util)._canUseCookies = undefined;
}
});
this.testCase({
name: "UtilTests: cannot set/get/delete cookies if document.cookie is not available",
test: () => {
var oldDocument = Util["document"];
(<any>Util)._canUseCookies = undefined;
Util["document"] = <any>{
cookie: undefined
};
var name = "test";
Util.setCookie(name, "value");
Assert.equal(undefined, Util.getCookie(name), "cookies are not supported");
Util.deleteCookie(name);
Assert.equal(undefined, Util.getCookie(name), "cookies are not supported");
// restore document object
Util["document"] = oldDocument;
(<any>Util)._canUseCookies = undefined;
}
});
this.testCase({
name: "UtilTests: new GUID",
test: () => {
var results = [];
for (var i = 0; i < 100; i++) {
var newId = Util.newId();
for (var j = 0; j < results.length; j++) {
Assert.notEqual(newId, results[j]);
}
results.push(newId);
}
}
});
this.testCase({
name: "UtilTests: toISO string for IE8",
test: () => {
var test = () => {
var date = new Date();
var output = Util.toISOStringForIE8(date);
var regex = new RegExp("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{3}Z");
Assert.ok(regex.test(output), "expected format was emitted");
try {
var expected = new Date().toISOString();
Assert.equal(expected, output, "format matches default in non-IE8");
} catch (e) {
Assert.ok(true, "IE8");
}
};
test();
var toISOString = Date.prototype.toISOString;
Date.prototype.toISOString = undefined;
test();
Date.prototype.toISOString = toISOString;
}
});
this.testCase({
name: "UtilTests: msToTimeSpan",
test: () => {
var test = (input, expected, message) => {
var actual = Util.msToTimeSpan(input);
Assert.equal(expected, actual, message);
}
test(0, "00:00:00.000", "zero");
test(1, "00:00:00.001", "milliseconds digit 1");
test(8.7, "00:00:00.009", "milliseconds digit 1 with high precision");
test(10, "00:00:00.010", "milliseconds digit 2");
test(99.99, "00:00:00.100", "milliseconds digit 2 with high precision");
test(100, "00:00:00.100", "milliseconds digit 3");
test(456.123, "00:00:00.456", "milliseconds digit 3 with high precision");
test(999.6789, "00:00:01.000", "milliseconds digit 3 with high precision, rounded to full a second");
test(1 * 1000, "00:00:01.000", "seconds digit 1");
test(10 * 1000, "00:00:10.000", "seconds digit 2");
test(1 * 60 * 1000, "00:01:00.000", "minutes digit 1");
test(10 * 60 * 1000, "00:10:00.000", "minutes digit 2");
test(1 * 60 * 60 * 1000, "01:00:00.000", "hours digit 1");
test(10 * 60 * 60 * 1000, "10:00:00.000", "hours digit 2");
test(24 * 60 * 60 * 1000, "1.00:00:00.000", "a full day")
test(10 * 24 * 60 * 60 * 1000 + 123.444, "10.00:00:00.123", "ten days and 123ms")
test(11 * 3600000 + 11 * 60000 + 11111, "11:11:11.111", "all digits");
test(11 * 3600000 + 11 * 60000 + 11111 + 0.33333, "11:11:11.111", "all digits with high precision");
test(7 * 3600000 + 59 * 60000 + 59999 + 0.999, "08:00:00.000", "all digits with high precision, rounded to a full hour");
test(23 * 3600000 + 59 * 60000 + 59999 + 0.556, "1.00:00:00.000", "all digits with high precision, rounded to a full day");
test("", "00:00:00.000", "invalid input");
test("'", "00:00:00.000", "invalid input");
test(NaN, "00:00:00.000", "invalid input");
test({}, "00:00:00.000", "invalid input");
test([], "00:00:00.000", "invalid input");
test(-1, "00:00:00.000", "invalid input");
}
});
this.testCase({
name: "Tests stringToBoolOrDefault() returns true only for 'true' string (ignoring case)",
test: () => {
Assert.ok(Util.stringToBoolOrDefault(undefined) === false);
Assert.ok(Util.stringToBoolOrDefault(null) === false);
Assert.ok(Util.stringToBoolOrDefault("") === false);
Assert.ok(Util.stringToBoolOrDefault("asdf") === false);
Assert.ok(Util.stringToBoolOrDefault(0) === false);
Assert.ok(Util.stringToBoolOrDefault({ asfd: "sdf" }) === false);
Assert.ok(Util.stringToBoolOrDefault(new Object()) === false);
Assert.ok(Util.stringToBoolOrDefault("true") === true);
Assert.ok(Util.stringToBoolOrDefault("TrUe") === true);
}
});
this.testCase({
name: "UtilTests: isCrossOriginError",
test: () => {
Assert.ok(Util.isCrossOriginError("Script error.", "", 0, 0, null) === true);
Assert.ok(Util.isCrossOriginError("Script error.", "http://microsoft.com", 0, 0, null)
=== true);
}
});
this.testCase({
name: "Util.dump returns string that includes information about object type",
test: () => {
var object: any = new Error();
var result: string = Util.dump(object);
var toStringRepresentation = Object.prototype.toString.call(object);
Assert.notEqual(-1, result.indexOf(toStringRepresentation));
}
});
this.testCase({
name: "Util.dump returns string that includes information about object property values",
test: () => {
var object: any = { "property": "value" };
var result: string = Util.dump(object);
var jsonRepresentation: string = JSON.stringify(object);
Assert.notEqual(-1, result.indexOf(jsonRepresentation));
}
});
this.testCase({
name: "Util.addEventHandler should attach the callback for the given event name",
test: () => {
// Assemble
var eventName = 'goat';
var customEvent = document.createEvent('Event');
customEvent.initEvent(eventName, true, true);
var isCallbackExecuted = false;
var callback = function (e) {
isCallbackExecuted = true;
};
// Act
var returnValue = Util.addEventHandler(eventName, callback);
document.dispatchEvent(customEvent);
// Assert
Assert.ok(returnValue, 'Event handler was not attached.');
Assert.ok(isCallbackExecuted, 'Callback was not executed');
}
});
this.testCase({
name: "Util.addEventHandler should handle illegal event name",
test: () => {
// Assemble
var eventName = undefined;
var customEvent = document.createEvent('Event');
customEvent.initEvent(eventName, true, true);
var isCallbackExecuted = false;
var callback = function (e) {
isCallbackExecuted = true;
};
// Act
var returnValue = Util.addEventHandler(eventName, callback);
document.dispatchEvent(customEvent);
// Assert
Assert.equal(false, returnValue, 'Event handler was attached for illegal event name');
Assert.equal(false, isCallbackExecuted, 'Callback was executed when it was not supposed to.');
}
});
this.testCase({
name: "Util.addEventHandler should handle illegal callback",
test: () => {
// Assemble
var eventName = 'goat';
var customEvent = document.createEvent('Event');
customEvent.initEvent(eventName, true, true);
var isCallbackExecuted = false;
var callback = undefined;
// Act
var returnValue = Util.addEventHandler(eventName, callback);
document.dispatchEvent(customEvent);
// Assert
Assert.equal(false, returnValue, 'Event handler was attached for illegal callback');
}
});
this.testCase({
name: "getIE function should return null for non-IE user agent string and IE version for IE",
test: () => {
// Assert
Assert.equal(null, Util.getIEVersion("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36"), "Should return null for non-IE");
Assert.equal(8, Util.getIEVersion("Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 10.0; Win64; x64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729"), "Should return IE version for IE browser");
}
});
this.testCase({
name: "isInternalApplicationInsightsEndpoint function handles endpoints correctly",
test: () => {
// Assert
Assert.equal(true, Util.isInternalApplicationInsightsEndpoint("https://dc.services.visualstudio.com/v2/track"));
Assert.equal(true, Util.isInternalApplicationInsightsEndpoint("https://DC.services.VisualStudio.com/v2/track"));
Assert.equal(true, Util.isInternalApplicationInsightsEndpoint("https://breeze.aimon.applicationinsights.io/v2/track"));
Assert.equal(true, Util.isInternalApplicationInsightsEndpoint("https://dc-int.services.visualstudio.com/v2/track"));
Assert.equal(false, Util.isInternalApplicationInsightsEndpoint("https://somethingelse.com/v2/track"));
}
});
this.testCase({
name: "UrlHelper: parseUrl should contain host field even if document.createElement is not defined",
test: () => {
var origCreateElement = document.createElement;
document.createElement = null;
let passed;
let match;
try {
const host = UrlHelper.parseUrl("https://portal.azure.com/some/endpoint").host.toLowerCase();
passed = true;
match = host === "portal.azure.com";
} catch (e) {
passed = false;
}
// Need to reset createElement before doing any assertions, else qunit crashes
document.createElement = origCreateElement;
Assert.ok(passed);
Assert.ok(match, "host should be portal.azure.com");
}
});
this.testCase({
name: "UrlHelper: parseHost should return correct host name",
test: () => {
Assert.equal("portal.azure.com", UrlHelper.parseHost("https://portal.azure.com/some/endpoint"));
Assert.equal("bing.com", UrlHelper.parseHost("http://www.bing.com"));
Assert.equal("bing.com", UrlHelper.parseHost("https://www2.bing.com/"));
Assert.equal("p.r.e.f.i.x.bing.com", UrlHelper.parseHost("http://wwW2.p.r.e.f.i.x.bing.com/"));
}
});
this.testCase({
name: "Check disableSameSiteCookie status",
test: () => {
let excludeValues = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; WebView/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.2 Safari/605.1.15",
"Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Mobile Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (iPad; CPU OS 12_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One; MSAppHost/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393",
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/71.0.3578.89 Mobile/15E148 Safari/605.1",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.1 Safari/605.1.15",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; WebView/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) GSA/65.0.225212226 Mobile/15E148 Safari/605.1",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; WebView/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C101",
"Mozilla/5.0 (iPad; CPU OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.1.00.31860 Chrome/61.0.3163.100 Electron/2.0.10 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G950F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; Xbox; Xbox One; WebView/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G930F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (iPad; CPU OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/71.0.3578.89 Mobile/15E148 Safari/605.1",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/605.1.15 (KHTML, like Gecko)",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Windows NT 10.0; WebView/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G935F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
"Mozilla/5.0 (iPad; CPU OS 12_0_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; WebView/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6821.400 QQBrowser/10.3.3040.400",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Yammer/2.1.0 Chrome/66.0.3359.181 Electron/3.0.6 Safari/537.36",
"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G965F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-A520F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G955F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36 LBBROWSER",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G950U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G960U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.1.00.31860 Chrome/61.0.3163.100 Electron/2.0.10 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15",
"Mozilla/5.0 (iPad; CPU OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) GSA/65.0.225212226 Mobile/15E148 Safari/605.1",
"Mozilla/5.0 (iPad; CPU OS 12_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16C50",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-N950U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (iPad; CPU OS 12_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G965U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 6.0.1; SM-G532M Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.91 Mobile Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36",
"Mozilla/5.0 (Linux; Android 7.0; SAMSUNG SM-G920F Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-G955U Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6821.400 QQBrowser/10.3.3040.400",
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 EdgiOS/42.8.6 Mobile/16C101 Safari/605.1.15",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.0.0; SAMSUNG SM-N950F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36",
"Mozilla/5.0 (Linux; Android 8.1.0; SAMSUNG SM-J530F Build/M1AJQ) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/8.2 Chrome/63.0.3239.111 Mobile Safari/537.36"
];
let acceptValues = [
"",
null,
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko",
"Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko/20100101 Firefox/12.0",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/11.1.2 Safari/605.1.15"
];
for (let lp = 0; lp < excludeValues.length; lp++) {
Assert.equal(true, Util.disallowsSameSiteNone(excludeValues[lp]), excludeValues[lp]);
}
for (let lp = 0; lp < acceptValues.length; lp++) {
Assert.equal(false, Util.disallowsSameSiteNone(acceptValues[lp]), acceptValues[lp]);
}
}
});
}
private getMockStorage() {
var storage = <any>{};
storage.getItem = (name) => storage[name];
storage.setItem = (name, value) => (storage[name] = value);
storage.removeItem = (name, value) => (storage[name] = undefined);
return storage;
}
}
new UtilTests().registerTests();

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

@ -1,307 +0,0 @@
/// <reference path="../TestFramework/Common.ts" />
/// <reference path="../../JavaScriptSDK/ajax/ajax.ts" />
/// <reference path="../../JavaScriptSDK/Util.ts"/>
/// <reference path="../../JavaScriptSDK/Telemetry/RemoteDependencyData.ts"/>
class AjaxTests extends TestClass {
private appInsightsMock = {
trackDependency: (id: string, method: string, absoluteUrl: string, isAsync: boolean, totalTime: number, success: boolean) => { },
trackDependencyData: (dependency: Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData) => { },
context: {
operation: {
id: "asdf"
},
appId: () => "someid"
},
config: {
disableCorrelationHeaders: false,
enableCorsCorrelation: false
}
}
private trackDependencySpy;
private callbackSpy;
private requests;
public testInitialize() {
this.trackDependencySpy = this.sandbox.spy(this.appInsightsMock, "trackDependencyData");
this.callbackSpy = this.sandbox.spy();
this.trackDependencySpy.reset();
var xhr = sinon.useFakeXMLHttpRequest();
}
public testCleanup() {
}
public registerTests() {
this.testCase({
name: "Ajax: xhr.open gets instrumented",
test: () => {
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
// act
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://microsoft.com");
// assert
var ajaxData = (<any>xhr).ajaxData;
Assert.equal("http://microsoft.com", ajaxData.requestUrl, "RequestUrl is collected correctly");
}
});
this.testCase({
name: "Ajax: successful request, ajax monitor doesn't change payload",
test: () => {
var callback = this.sandbox.spy();
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
// Act
var xhr = new XMLHttpRequest();
xhr.onload = callback;
xhr.open("GET", "/bla");
xhr.send();
Assert.ok(!this.trackDependencySpy.called, "TrackAjax should not be called yet");
// Emulate response
(<any>xhr).respond(200, { "Content-Type": "application/json" }, "bla");
Assert.ok(this.trackDependencySpy.called, "TrackAjax is called");
// Assert
var result = callback.args[0][0].target;
Assert.ok(callback.called, "Ajax callback is called");
Assert.equal("bla", result.responseText, "Expected result mismatch");
Assert.equal(200, result.status, "Expected 200 response code");
Assert.equal(4, xhr.readyState, "Expected readyState is 4 after request is finished");
}
});
this.testCase({
name: "Ajax: custom onreadystatechange gets called",
test: () => {
var onreadystatechangeSpy = this.sandbox.spy();
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
// Act
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = onreadystatechangeSpy;
xhr.open("GET", "/bla");
xhr.send();
Assert.ok(!this.trackDependencySpy.called, "TrackAjax should not be called yet");
// Emulate response
(<any>xhr).respond();
// Assert
Assert.ok(this.trackDependencySpy.called, "TrackAjax is called");
Assert.ok(onreadystatechangeSpy.called, "custom onreadystatechange should be called");
}
});
this.testCase({
name: "Ajax: 200 means success",
test: () => {
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
// Act
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bla");
xhr.send();
// Emulate response
(<any>xhr).respond(200, {}, "");
// Assert
Assert.equal(true, this.trackDependencySpy.args[0][0].success, "TrackAjax should receive true as a 'success' argument");
}
});
this.testCase({
name: "Ajax: non 200 means failure",
test: () => {
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
// Act
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bla");
xhr.send();
// Emulate response
(<any>xhr).respond(404, {}, "");
// Assert
Assert.equal(false, this.trackDependencySpy.args[0][0].success, "TrackAjax should receive false as a 'success' argument");
}
});
[200, 201, 202, 203, 204, 301, 302, 303, 304].forEach((responseCode) => {
this.testCase({
name: "Ajax: test success http response code: " + responseCode,
test: () => {
this.testAjaxSuccess(responseCode, true);
}
})
});
[400, 401, 402, 403, 404, 500, 501].forEach((responseCode) => {
this.testCase({
name: "Ajax: test failure http response code: " + responseCode,
test: () => {
this.testAjaxSuccess(responseCode, false);
}
})
});
this.testCase({
name: "Ajax: overriding ready state change handlers in all possible ways",
test: () => {
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
var cb1 = this.sandbox.spy();
var cb2 = this.sandbox.spy();
var cb3 = this.sandbox.spy();
var cb4 = this.sandbox.spy();
var cb5 = this.sandbox.spy();
var cb6 = this.sandbox.spy();
var cb7 = this.sandbox.spy();
// Act
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", cb1);
xhr.addEventListener("readystatechange", cb2);
xhr.open("GET", "/bla");
xhr.onreadystatechange = cb3;
xhr.addEventListener("readystatechange", cb4);
xhr.addEventListener("readystatechange", cb5);
xhr.send();
xhr.addEventListener("readystatechange", cb6);
xhr.addEventListener("readystatechange", cb7);
Assert.ok(!this.trackDependencySpy.called, "TrackAjax should not be called yet");
// Emulate response
(<any>xhr).respond(404, {}, "");
// Assert
Assert.ok(this.trackDependencySpy.calledOnce, "TrackAjax should be called");
Assert.ok(cb1.called, "callback 1 should be called");
Assert.ok(cb2.called, "callback 2 should be called");
Assert.ok(cb3.called, "callback 3 should be called");
Assert.ok(cb4.called, "callback 4 should be called");
Assert.ok(cb5.called, "callback 5 should be called");
Assert.ok(cb6.called, "callback 6 should be called");
Assert.ok(cb7.called, "callback 7 should be called");
}
});
this.testCase({
name: "Ajax: test ajax duration is calculated correctly",
test: () => {
var initialPerformance = window.performance;
try {
// Mocking window performance (sinon doesn't have it).
// tick() is similar to sinon's clock.tick()
(<any>window).performance = <any>{
current: 0,
now: function () {
return this.current;
},
tick: function (ms: number) {
this.current += ms;
},
timing: initialPerformance.timing
};
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
// tick to set the initial time be non zero
(<any>window.performance).tick(23);
// Act
var xhr = new XMLHttpRequest();
var clock = this.clock;
var expectedResponseDuration = 50;
xhr.onreadystatechange = () => {
if (xhr.readyState == 3) {
(<any>window.performance).tick(expectedResponseDuration);
}
}
xhr.open("GET", "/bla");
xhr.send();
// Emulate response
(<any>xhr).respond(404, {}, "");
// Assert
Assert.ok(this.trackDependencySpy.calledOnce, "TrackAjax should be called");
Assert.equal("00:00:00.050", this.trackDependencySpy.args[0][0].duration, "Ajax duration should match expected duration");
} finally {
(<any>window.performance).performance = initialPerformance;
}
}
});
this.testCase({
name: "Ajax: 2nd invokation of xhr.send doesn't cause send wrapper to execute 2nd time",
test: () => {
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
var spy = this.sandbox.spy(ajax, "sendHandler");
// Act
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bla");
xhr.send();
try {
xhr.send();
} catch (e) { }
// Assert
Assert.ok(spy.calledOnce, "sendPrefixInstrumentor should be called only once");
}
});
this.testCase({
name: "Ajax: 2 invokation of xhr.open() doesn't cause send wrapper to execute 2nd time",
test: () => {
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
var spy = this.sandbox.spy(ajax, "openHandler");
// Act
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bla");
try {
xhr.open("GET", "/bla");
} catch (e) { }
// Assert
Assert.ok(spy.calledOnce, "sendPrefixInstrumentor should be called only once");
}
});
}
private testAjaxSuccess(responseCode: number, success: boolean) {
var ajax = new Microsoft.ApplicationInsights.AjaxMonitor(<any>this.appInsightsMock);
// Act
var xhr = new XMLHttpRequest();
xhr.open("GET", "/bla");
xhr.send();
// Emulate response
(<any>xhr).respond(responseCode, {}, "");
// Assert
Assert.equal(success, this.trackDependencySpy.args[0][0].success, "TrackAjax should receive " + success + " as a 'success' argument");
}
}
new AjaxTests().registerTests();

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

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

@ -1,60 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property AvailabilityData.ver was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.ver !== null, "AvailabilityData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with AvailabilityData.ver");
});
QUnit.test("Test property AvailabilityData.id was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.id !== null, "AvailabilityData.id == null");
});
QUnit.test("Test property AvailabilityData.name was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.name !== null, "AvailabilityData.name == null");
});
QUnit.test("Test property AvailabilityData.duration was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.duration !== null, "AvailabilityData.duration == null");
});
QUnit.test("Test property AvailabilityData.success was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.success !== null, "AvailabilityData.success == null");
});
QUnit.test("Test property AvailabilityData.runLocation was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.runLocation !== null, "AvailabilityData.runLocation == null");
});
QUnit.test("Test property AvailabilityData.message was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.message !== null, "AvailabilityData.message == null");
});
QUnit.test("Test property AvailabilityData.properties was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.properties !== null, "AvailabilityData.properties == null");
});
QUnit.test("Test property AvailabilityData.measurements was created and default is set", function () {
var temp = new AI.AvailabilityData();
QUnit.ok(temp.measurements !== null, "AvailabilityData.measurements == null");
});

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

@ -1,11 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Domain.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Base.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Data.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Envelope.ts" />
QUnit.test("Test property Base.baseType was created and default is set", function () {
var temp = new Microsoft.Telemetry.Base();
QUnit.ok(temp.baseType !== null, "Base.baseType == null");
});

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

@ -1,159 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ContextTagKeys.ts" />
QUnit.test("Test property ContextTagKeys.ApplicationVersion was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.applicationVersion !== null, "ContextTagKeys.applicationVersion == null");
QUnit.ok(temp.applicationVersion === "ai.application.ver", "Issue with ContextTagKeys.applicationVersion");
});
QUnit.test("Test property ContextTagKeys.DeviceId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceId !== null, "ContextTagKeys.deviceId == null");
QUnit.ok(temp.deviceId === "ai.device.id", "Issue with ContextTagKeys.deviceId");
});
QUnit.test("Test property ContextTagKeys.DeviceLocale was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceLocale !== null, "ContextTagKeys.deviceLocale == null");
QUnit.ok(temp.deviceLocale === "ai.device.locale", "Issue with ContextTagKeys.deviceLocale");
});
QUnit.test("Test property ContextTagKeys.DeviceModel was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceModel !== null, "ContextTagKeys.deviceModel == null");
QUnit.ok(temp.deviceModel === "ai.device.model", "Issue with ContextTagKeys.deviceModel");
});
QUnit.test("Test property ContextTagKeys.DeviceOEMName was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceOEMName !== null, "ContextTagKeys.deviceOEMName == null");
QUnit.ok(temp.deviceOEMName === "ai.device.oemName", "Issue with ContextTagKeys.deviceOEMName");
});
QUnit.test("Test property ContextTagKeys.DeviceOSVersion was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceOSVersion !== null, "ContextTagKeys.deviceOSVersion == null");
QUnit.ok(temp.deviceOSVersion === "ai.device.osVersion", "Issue with ContextTagKeys.deviceOSVersion");
});
QUnit.test("Test property ContextTagKeys.DeviceType was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceType !== null, "ContextTagKeys.deviceType == null");
QUnit.ok(temp.deviceType === "ai.device.type", "Issue with ContextTagKeys.deviceType");
});
QUnit.test("Test property ContextTagKeys.LocationIp was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.locationIp !== null, "ContextTagKeys.locationIp == null");
QUnit.ok(temp.locationIp === "ai.location.ip", "Issue with ContextTagKeys.locationIp");
});
QUnit.test("Test property ContextTagKeys.LocationCountry was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.locationCountry !== null, "ContextTagKeys.locationCountry == null");
QUnit.ok(temp.locationCountry === "ai.location.country", "Issue with ContextTagKeys.locationCountry");
});
QUnit.test("Test property ContextTagKeys.LocationProvince was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.locationProvince !== null, "ContextTagKeys.locationProvince == null");
QUnit.ok(temp.locationProvince === "ai.location.province", "Issue with ContextTagKeys.locationProvince");
});
QUnit.test("Test property ContextTagKeys.LocationCity was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.locationCity !== null, "ContextTagKeys.locationCity == null");
QUnit.ok(temp.locationCity === "ai.location.city", "Issue with ContextTagKeys.locationCity");
});
QUnit.test("Test property ContextTagKeys.OperationId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.operationId !== null, "ContextTagKeys.operationId == null");
QUnit.ok(temp.operationId === "ai.operation.id", "Issue with ContextTagKeys.operationId");
});
QUnit.test("Test property ContextTagKeys.OperationName was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.operationName !== null, "ContextTagKeys.operationName == null");
QUnit.ok(temp.operationName === "ai.operation.name", "Issue with ContextTagKeys.operationName");
});
QUnit.test("Test property ContextTagKeys.OperationParentId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.operationParentId !== null, "ContextTagKeys.operationParentId == null");
QUnit.ok(temp.operationParentId === "ai.operation.parentId", "Issue with ContextTagKeys.operationParentId");
});
QUnit.test("Test property ContextTagKeys.OperationSyntheticSource was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.operationSyntheticSource !== null, "ContextTagKeys.operationSyntheticSource == null");
QUnit.ok(temp.operationSyntheticSource === "ai.operation.syntheticSource", "Issue with ContextTagKeys.operationSyntheticSource");
});
QUnit.test("Test property ContextTagKeys.OperationCorrelationVector was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.operationCorrelationVector !== null, "ContextTagKeys.operationCorrelationVector == null");
QUnit.ok(temp.operationCorrelationVector === "ai.operation.correlationVector", "Issue with ContextTagKeys.operationCorrelationVector");
});
QUnit.test("Test property ContextTagKeys.SessionId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.sessionId !== null, "ContextTagKeys.sessionId == null");
QUnit.ok(temp.sessionId === "ai.session.id", "Issue with ContextTagKeys.sessionId");
});
QUnit.test("Test property ContextTagKeys.SessionIsFirst was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.sessionIsFirst !== null, "ContextTagKeys.sessionIsFirst == null");
QUnit.ok(temp.sessionIsFirst === "ai.session.isFirst", "Issue with ContextTagKeys.sessionIsFirst");
});
QUnit.test("Test property ContextTagKeys.UserAccountId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.userAccountId !== null, "ContextTagKeys.userAccountId == null");
QUnit.ok(temp.userAccountId === "ai.user.accountId", "Issue with ContextTagKeys.userAccountId");
});
QUnit.test("Test property ContextTagKeys.UserId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.userId !== null, "ContextTagKeys.userId == null");
QUnit.ok(temp.userId === "ai.user.id", "Issue with ContextTagKeys.userId");
});
QUnit.test("Test property ContextTagKeys.UserAuthUserId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.userAuthUserId !== null, "ContextTagKeys.userAuthUserId == null");
QUnit.ok(temp.userAuthUserId === "ai.user.authUserId", "Issue with ContextTagKeys.userAuthUserId");
});
QUnit.test("Test property ContextTagKeys.CloudRole was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.cloudRole !== null, "ContextTagKeys.cloudRole == null");
QUnit.ok(temp.cloudRole === "ai.cloud.role", "Issue with ContextTagKeys.cloudRole");
});
QUnit.test("Test property ContextTagKeys.CloudRoleInstance was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.cloudRoleInstance !== null, "ContextTagKeys.cloudRoleInstance == null");
QUnit.ok(temp.cloudRoleInstance === "ai.cloud.roleInstance", "Issue with ContextTagKeys.cloudRoleInstance");
});
QUnit.test("Test property ContextTagKeys.InternalSdkVersion was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.internalSdkVersion !== null, "ContextTagKeys.internalSdkVersion == null");
QUnit.ok(temp.internalSdkVersion === "ai.internal.sdkVersion", "Issue with ContextTagKeys.internalSdkVersion");
});
QUnit.test("Test property ContextTagKeys.InternalAgentVersion was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.internalAgentVersion !== null, "ContextTagKeys.internalAgentVersion == null");
QUnit.ok(temp.internalAgentVersion === "ai.internal.agentVersion", "Issue with ContextTagKeys.internalAgentVersion");
});
QUnit.test("Test property ContextTagKeys.InternalNodeName was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.internalNodeName !== null, "ContextTagKeys.internalNodeName == null");
QUnit.ok(temp.internalNodeName === "ai.internal.nodeName", "Issue with ContextTagKeys.internalNodeName");
});

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

@ -1,16 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Domain.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Base.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Data.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Envelope.ts" />
QUnit.test("Test property Data.baseType was created and default is set", function () {
var temp = new Microsoft.Telemetry.Data<number>();
QUnit.ok(temp.baseType !== null, "Data.baseType == null");
});
QUnit.test("Test property Data.baseData was created and default is set", function () {
var temp = new Microsoft.Telemetry.Data<number>();
QUnit.ok(temp.baseData !== null, "Data.baseData == null");
});

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

@ -1,50 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property DataPoint.name was created and default is set", function () {
var temp = new AI.DataPoint();
QUnit.ok(temp.name !== null, "DataPoint.name == null");
});
QUnit.test("Test property DataPoint.kind was created and default is set", function () {
var temp = new AI.DataPoint();
QUnit.ok(temp.kind !== null, "DataPoint.kind == null");
QUnit.ok(temp.kind === AI.DataPointType.Measurement, "Issue with DataPoint.kind");
});
QUnit.test("Test property DataPoint.value was created and default is set", function () {
var temp = new AI.DataPoint();
QUnit.ok(temp.value !== null, "DataPoint.value == null");
});
QUnit.test("Test property DataPoint.count was created and default is set", function () {
var temp = new AI.DataPoint();
QUnit.ok(temp.count !== null, "DataPoint.count == null");
});
QUnit.test("Test property DataPoint.min was created and default is set", function () {
var temp = new AI.DataPoint();
QUnit.ok(temp.min !== null, "DataPoint.min == null");
});
QUnit.test("Test property DataPoint.max was created and default is set", function () {
var temp = new AI.DataPoint();
QUnit.ok(temp.max !== null, "DataPoint.max == null");
});
QUnit.test("Test property DataPoint.stdDev was created and default is set", function () {
var temp = new AI.DataPoint();
QUnit.ok(temp.stdDev !== null, "DataPoint.stdDev == null");
});

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

@ -1,48 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Domain.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Base.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Data.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/Envelope.ts" />
QUnit.test("Test property Envelope.ver was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.ver !== null, "Envelope.ver == null");
QUnit.ok(temp.ver === 1, "Issue with Envelope.ver");
});
QUnit.test("Test property Envelope.name was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.name !== null, "Envelope.name == null");
});
QUnit.test("Test property Envelope.time was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.time !== null, "Envelope.time == null");
});
QUnit.test("Test property Envelope.sampleRate was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.sampleRate !== null, "Envelope.sampleRate == null");
QUnit.ok(temp.sampleRate === 100.0, "Issue with Envelope.sampleRate");
});
QUnit.test("Test property Envelope.seq was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.seq !== null, "Envelope.seq == null");
});
QUnit.test("Test property Envelope.iKey was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.iKey !== null, "Envelope.iKey == null");
});
QUnit.test("Test property Envelope.tags was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.tags !== null, "Envelope.tags == null");
});
QUnit.test("Test property Envelope.data was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.data !== null, "Envelope.data == null");
});

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

@ -1,35 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property EventData.ver was created and default is set", function () {
var temp = new AI.EventData();
QUnit.ok(temp.ver !== null, "EventData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with EventData.ver");
});
QUnit.test("Test property EventData.name was created and default is set", function () {
var temp = new AI.EventData();
QUnit.ok(temp.name !== null, "EventData.name == null");
});
QUnit.test("Test property EventData.properties was created and default is set", function () {
var temp = new AI.EventData();
QUnit.ok(temp.properties !== null, "EventData.properties == null");
});
QUnit.test("Test property EventData.measurements was created and default is set", function () {
var temp = new AI.EventData();
QUnit.ok(temp.measurements !== null, "EventData.measurements == null");
});

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

@ -1,40 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property ExceptionData.ver was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.ver !== null, "ExceptionData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with ExceptionData.ver");
});
QUnit.test("Test property ExceptionData.exceptions was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.exceptions !== null, "ExceptionData.exceptions == null");
});
QUnit.test("Test property ExceptionData.severityLevel was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.severityLevel !== null, "ExceptionData.severityLevel == null");
});
QUnit.test("Test property ExceptionData.properties was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.properties !== null, "ExceptionData.properties == null");
});
QUnit.test("Test property ExceptionData.measurements was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.measurements !== null, "ExceptionData.measurements == null");
});

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

@ -1,50 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property ExceptionDetails.id was created and default is set", function () {
var temp = new AI.ExceptionDetails();
QUnit.ok(temp.id !== null, "ExceptionDetails.id == null");
});
QUnit.test("Test property ExceptionDetails.outerId was created and default is set", function () {
var temp = new AI.ExceptionDetails();
QUnit.ok(temp.outerId !== null, "ExceptionDetails.outerId == null");
});
QUnit.test("Test property ExceptionDetails.typeName was created and default is set", function () {
var temp = new AI.ExceptionDetails();
QUnit.ok(temp.typeName !== null, "ExceptionDetails.typeName == null");
});
QUnit.test("Test property ExceptionDetails.message was created and default is set", function () {
var temp = new AI.ExceptionDetails();
QUnit.ok(temp.message !== null, "ExceptionDetails.message == null");
});
QUnit.test("Test property ExceptionDetails.hasFullStack was created and default is set", function () {
var temp = new AI.ExceptionDetails();
QUnit.ok(temp.hasFullStack !== null, "ExceptionDetails.hasFullStack == null");
QUnit.ok(temp.hasFullStack === true, "Issue with ExceptionDetails.hasFullStack");
});
QUnit.test("Test property ExceptionDetails.stack was created and default is set", function () {
var temp = new AI.ExceptionDetails();
QUnit.ok(temp.stack !== null, "ExceptionDetails.stack == null");
});
QUnit.test("Test property ExceptionDetails.parsedStack was created and default is set", function () {
var temp = new AI.ExceptionDetails();
QUnit.ok(temp.parsedStack !== null, "ExceptionDetails.parsedStack == null");
});

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

@ -1,35 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property MessageData.ver was created and default is set", function () {
var temp = new AI.MessageData();
QUnit.ok(temp.ver !== null, "MessageData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with MessageData.ver");
});
QUnit.test("Test property MessageData.message was created and default is set", function () {
var temp = new AI.MessageData();
QUnit.ok(temp.message !== null, "MessageData.message == null");
});
QUnit.test("Test property MessageData.severityLevel was created and default is set", function () {
var temp = new AI.MessageData();
QUnit.ok(temp.severityLevel !== null, "MessageData.severityLevel == null");
});
QUnit.test("Test property MessageData.properties was created and default is set", function () {
var temp = new AI.MessageData();
QUnit.ok(temp.properties !== null, "MessageData.properties == null");
});

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

@ -1,30 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property MetricData.ver was created and default is set", function () {
var temp = new AI.MetricData();
QUnit.ok(temp.ver !== null, "MetricData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with MetricData.ver");
});
QUnit.test("Test property MetricData.metrics was created and default is set", function () {
var temp = new AI.MetricData();
QUnit.ok(temp.metrics !== null, "MetricData.metrics == null");
});
QUnit.test("Test property MetricData.properties was created and default is set", function () {
var temp = new AI.MetricData();
QUnit.ok(temp.properties !== null, "MetricData.properties == null");
});

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

@ -1,50 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property PageViewData.ver was created and default is set", function () {
var temp = new AI.PageViewData();
QUnit.ok(temp.ver !== null, "PageViewData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with PageViewData.ver");
});
QUnit.test("Test property PageViewData.url was created and default is set", function () {
var temp = new AI.PageViewData();
QUnit.ok(temp.url !== null, "PageViewData.url == null");
});
QUnit.test("Test property PageViewData.name was created and default is set", function () {
var temp = new AI.PageViewData();
QUnit.ok(temp.name !== null, "PageViewData.name == null");
});
QUnit.test("Test property PageViewData.duration was created and default is set", function () {
var temp = new AI.PageViewData();
QUnit.ok(temp.duration !== null, "PageViewData.duration == null");
});
QUnit.test("Test property PageViewData.id was created and default is set", function () {
var temp = new AI.PageViewData();
QUnit.ok(temp.id !== null, "PageViewData.id == null");
});
QUnit.test("Test property PageViewData.properties was created and default is set", function () {
var temp = new AI.PageViewData();
QUnit.ok(temp.properties !== null, "PageViewData.properties == null");
});
QUnit.test("Test property PageViewData.measurements was created and default is set", function () {
var temp = new AI.PageViewData();
QUnit.ok(temp.measurements !== null, "PageViewData.measurements == null");
});

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

@ -1,70 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property PageViewPerfData.ver was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.ver !== null, "PageViewPerfData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with PageViewPerfData.ver");
});
QUnit.test("Test property PageViewPerfData.url was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.url !== null, "PageViewPerfData.url == null");
});
QUnit.test("Test property PageViewPerfData.perfTotal was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.perfTotal !== null, "PageViewPerfData.perfTotal == null");
});
QUnit.test("Test property PageViewPerfData.name was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.name !== null, "PageViewPerfData.name == null");
});
QUnit.test("Test property PageViewPerfData.duration was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.duration !== null, "PageViewPerfData.duration == null");
});
QUnit.test("Test property PageViewPerfData.networkConnect was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.networkConnect !== null, "PageViewPerfData.networkConnect == null");
});
QUnit.test("Test property PageViewPerfData.sentRequest was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.sentRequest !== null, "PageViewPerfData.sentRequest == null");
});
QUnit.test("Test property PageViewPerfData.receivedResponse was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.receivedResponse !== null, "PageViewPerfData.receivedResponse == null");
});
QUnit.test("Test property PageViewPerfData.domProcessing was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.domProcessing !== null, "PageViewPerfData.domProcessing == null");
});
QUnit.test("Test property PageViewPerfData.properties was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.properties !== null, "PageViewPerfData.properties == null");
});
QUnit.test("Test property PageViewPerfData.measurements was created and default is set", function () {
var temp = new AI.PageViewPerfData();
QUnit.ok(temp.measurements !== null, "PageViewPerfData.measurements == null");
});

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

@ -1,71 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property RemoteDependencyData.ver was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.ver !== null, "RemoteDependencyData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with RemoteDependencyData.ver");
});
QUnit.test("Test property RemoteDependencyData.name was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.name !== null, "RemoteDependencyData.name == null");
});
QUnit.test("Test property RemoteDependencyData.id was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.id !== null, "RemoteDependencyData.id == null");
});
QUnit.test("Test property RemoteDependencyData.resultCode was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.resultCode !== null, "RemoteDependencyData.resultCode == null");
});
QUnit.test("Test property RemoteDependencyData.duration was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.duration !== null, "RemoteDependencyData.duration == null");
});
QUnit.test("Test property RemoteDependencyData.success was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.success !== null, "RemoteDependencyData.success == null");
QUnit.ok(temp.success === true, "Issue with RemoteDependencyData.success");
});
QUnit.test("Test property RemoteDependencyData.data was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.data !== null, "RemoteDependencyData.data == null");
});
QUnit.test("Test property RemoteDependencyData.target was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.target !== null, "RemoteDependencyData.target == null");
});
QUnit.test("Test property RemoteDependencyData.type was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.type !== null, "RemoteDependencyData.type == null");
});
QUnit.test("Test property RemoteDependencyData.properties was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.properties !== null, "RemoteDependencyData.properties == null");
});
QUnit.test("Test property RemoteDependencyData.measurements was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.measurements !== null, "RemoteDependencyData.measurements == null");
});

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

@ -1,55 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property RequestData.ver was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.ver !== null, "RequestData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with RequestData.ver");
});
QUnit.test("Test property RequestData.id was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.id !== null, "RequestData.id == null");
});
QUnit.test("Test property RequestData.source was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.source !== null, "RequestData.source == null");
});
QUnit.test("Test property RequestData.name was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.name !== null, "RequestData.name == null");
});
QUnit.test("Test property RequestData.success was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.success !== null, "RequestData.success == null");
});
QUnit.test("Test property RequestData.url was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.url !== null, "RequestData.url == null");
});
QUnit.test("Test property RequestData.properties was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.properties !== null, "RequestData.properties == null");
});
QUnit.test("Test property RequestData.measurements was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.measurements !== null, "RequestData.measurements == null");
});

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

@ -1,39 +0,0 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK.Interfaces/Contracts/Generated/AvailabilityData.ts" />
QUnit.test("Test property StackFrame.level was created and default is set", function () {
var temp = new AI.StackFrame();
QUnit.ok(temp.level !== null, "StackFrame.level == null");
});
QUnit.test("Test property StackFrame.method was created and default is set", function () {
var temp = new AI.StackFrame();
QUnit.ok(temp.method !== null, "StackFrame.method == null");
});
QUnit.test("Test property StackFrame.assembly was created and default is set", function () {
var temp = new AI.StackFrame();
QUnit.ok(temp.assembly !== null, "StackFrame.assembly == null");
});
QUnit.test("Test property StackFrame.fileName was created and default is set", function () {
var temp = new AI.StackFrame();
QUnit.ok(temp.fileName !== null, "StackFrame.fileName == null");
});
QUnit.test("Test property StackFrame.line was created and default is set", function () {
var temp = new AI.StackFrame();
QUnit.ok(temp.line !== null, "StackFrame.line == null");
});

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

@ -1,27 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="Cache-control" content="no-Cache" />
<title>Tests for Application Insights JavaScript API</title>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.18.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.18.0.js"></script>
<script src="http://sinonjs.org/releases/sinon-1.17.2.js"></script>
<script type="text/javascript">
window.AIResults = [];
QUnit.testDone(function (result) {
window.AIResults.push(result);
});
</script>
<script src="../../../bundle/test/ai.schema.tests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<div id="error-message"></div>
</body>
</html>

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

@ -1,187 +0,0 @@
/// <reference path="../../JavaScriptSDK/AppInsights.ts" />
/// <reference path="../../JavaScriptSDK/UtilHelpers.ts" />
// This file was copied from https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/master/types/applicationinsights-js/applicationinsights-js-tests.ts
// and is used to validate ApplicationInsights-JS definition types.
// If you have to change this file, plese update the DefinitelyTyped repo too - https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/applicationinsights-js
const config: Microsoft.ApplicationInsights.IConfig = {
instrumentationKey: "<your iKey>",
endpointUrl: "endpointUrl",
emitLineDelimitedJson: false,
accountId: "accountId",
sessionRenewalMs: 30,
sessionExpirationMs: 24 * 60 * 60 * 1000,
maxBatchSizeInBytes: 100 * 1024,
maxBatchInterval: 15,
enableDebug: false,
disableTelemetry: false,
verboseLogging: false,
diagnosticLogInterval: 10,
samplingPercentage: 100,
autoTrackPageVisitTime: true,
disableExceptionTracking: false,
disableAjaxTracking: false,
overridePageViewDuration: false,
maxAjaxCallsPerView: -1,
disableDataLossAnalysis: true,
disableCorrelationHeaders: true,
disableFlushOnBeforeUnload: false,
enableSessionStorageBuffer: false,
cookieDomain: "",
isCookieUseDisabled: true,
isRetryDisabled: true,
isStorageUseDisabled: true,
enableCorsCorrelation: false
};
var appInsights: Microsoft.ApplicationInsights.IAppInsights = {
config,
context: null,
queue: null,
startTrackPage(name?: string) { return null; },
stopTrackPage(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; },
trackPageView(name?: string, url?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, duration?: number) { return null; },
startTrackEvent(name: string) { return null; },
stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; },
trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; },
trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; },
trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; },
trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; },
trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: AI.SeverityLevel) { return null; },
flush() { return null; },
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string) { return null; },
clearAuthenticatedUserContext() { return null; },
_onerror(message: string, url: string, lineNumber: number, columnNumber: number, error: Error) { return null; }
};
// trackPageView
appInsights.trackPageView("page1");
appInsights.trackPageView("page2", "http://example.com", null, null, 1000);
// startTrackPage
appInsights.startTrackPage("page");
// stopTrackPage
appInsights.stopTrackPage("page");
appInsights.stopTrackPage("page", "http://example.com", null, null);
// trackEvent
appInsights.trackEvent("page1");
appInsights.trackEvent("page1", null, null);
// trackMetric
appInsights.trackMetric("page1", 999);
appInsights.trackMetric("page1", 999, 1, 1, 2, null);
// trackException
appInsights.trackException(new Error("sample error"));
appInsights.trackException(new Error("sample error"), "handledAt", null, null);
// trackTrace
appInsights.trackTrace("message");
appInsights.trackTrace("message", null);
appInsights.trackTrace("message", { a: '1', b: '2' }, AI.SeverityLevel.Error);
// trackDependency
appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null);
// flush
appInsights.flush();
// setAuthenticatedUserContext
appInsights.setAuthenticatedUserContext("userId");
appInsights.setAuthenticatedUserContext("userId", "accountId");
// set config dynamically
appInsights.config.instrumentationKey = "<new key>";
// UtilHelpers
var Util: typeof Microsoft.ApplicationInsights.UtilHelpers;
Util.newId();
// TelementryContext
const context: Microsoft.ApplicationInsights.ITelemetryContext = appInsights.context;
context.application.ver = "v0.0.0";
context.application.build = "1.1.1";
context.device.type = "sampleDevice";
context.device.locale = "en-US";
context.user.id = "userId";
context.user.authenticatedId = "authId";
context.session.id = "sessionId";
context.session.isFirst = true;
context.location.ip = "127.0.0.1";
context.operation.id = "1";
context.operation.syntheticSource = "testAgent";
// track
const data = new Microsoft.Telemetry.Base();
const envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, "name");
context.track(envelope);
context.addTelemetryInitializer(envelope => false);
context.addTelemetryInitializer(envelope => { });
// a sample from: https://github.com/microsoft/ApplicationInsights-JS/blob/master/API-reference.md#example
context.addTelemetryInitializer(envelope => {
let telemetryItem = envelope.data.baseData;
if (envelope.name === Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType) {
telemetryItem.url = "URL CENSORED";
}
telemetryItem.properties = telemetryItem.properties || {};
telemetryItem.properties["globalProperty"] = "boo";
});
// track event
const eventObj = new Microsoft.ApplicationInsights.Telemetry.Event("test", null, null);
const eventData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Event>(Microsoft.ApplicationInsights.Telemetry.Event.dataType, eventObj);
const eventEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(eventData, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
context.track(eventEnvelope);
// track exception
const exceptionObj = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error(), null, null, AI.SeverityLevel.Critical);
const exceptionData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Exception>(
Microsoft.ApplicationInsights.Telemetry.Exception.dataType, exceptionObj);
const exceptionEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(exceptionData, Microsoft.ApplicationInsights.Telemetry.Exception.envelopeType);
context.track(exceptionEnvelope);
// track metric
const metricObj = new Microsoft.ApplicationInsights.Telemetry.Metric("name", 1234, 1, 0, 100, null);
const metricData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Metric>(Microsoft.ApplicationInsights.Telemetry.Metric.dataType, metricObj);
const metricEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(metricData, Microsoft.ApplicationInsights.Telemetry.Metric.envelopeType);
context.track(metricEnvelope);
// track page view
const pageViewObj = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", "url", 999, null, null, "id");
const pageViewData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageView>(Microsoft.ApplicationInsights.Telemetry.PageView.dataType, pageViewObj);
const pageViewEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewData, Microsoft.ApplicationInsights.Telemetry.PageView.envelopeType);
context.track(pageViewEnvelope);
// track page view performance
const pageViewPerfObj = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", "url", 999, null, null);
const pageViewPerfData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.PageViewPerformance>(
Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.dataType, pageViewPerfObj);
const pageViewPerfEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(pageViewPerfData, Microsoft.ApplicationInsights.Telemetry.PageViewPerformance.envelopeType);
context.track(pageViewPerfEnvelope);
// track remote dependency
const remoteDepObj = new Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData("id", "url", "command", 1, true, 1234, "GET");
const remoteDepData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData>(
Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.dataType, remoteDepObj);
const remoteDepEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(remoteDepData, Microsoft.ApplicationInsights.Telemetry.RemoteDependencyData.envelopeType);
context.track(pageViewPerfEnvelope);
// track trace
const traceObj = new Microsoft.ApplicationInsights.Telemetry.Trace("message", null);
const traceData = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Trace>(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, traceObj);
const traceEnvelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(traceData, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
context.track(traceEnvelope);

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше