adding tests and test build targets

This commit is contained in:
Max Shekhovtsov 2015-04-10 12:11:26 -07:00
Родитель 02b6fa479c
Коммит feb360dbbf
104 изменённых файлов: 28595 добавлений и 3 удалений

63
.gitattributes поставляемый Normal file
Просмотреть файл

@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

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

@ -0,0 +1,160 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Rr]elease/
[Bb]in/
[Oo]bj/
[Oo]bj//Core/Javascript/ai*.[tj]s*
# Telemetry output
*.onesipkg
# Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets
!packages/*/build/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
*_i.c
*_p.c
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.log
*.scc
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
*.ncrunch*
.*crunch*.local.xml
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.Publish.xml
# NuGet binaries downloaded automatically
packages/
# Windows Azure Build Output
csx
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.[Pp]ublish.xml
*.publishsettings
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file to a newer
# Visual Studio version. Backup files are not needed, because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
App_Data/*.mdf
App_Data/*.ldf
#LightSwitch generated files
GeneratedArtifacts/
_Pvt_Extensions/
ModelManifest.xml
# =========================
# Windows detritus
# =========================
# Windows image file caches
Thumbs.db
ehthumbs.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Mac desktop service store files
.DS_Store
# Build log files
*.err
*.prf
*.wrn

4
Common.props Normal file
Просмотреть файл

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), 'Global.props'))\Global.props" />
</Project>

0
EnlistmentRoot.marker Normal file
Просмотреть файл

143
Global.props Normal file
Просмотреть файл

@ -0,0 +1,143 @@
<?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>0</SemanticVersionMajor>
<SemanticVersionMinor>15</SemanticVersionMinor>
<SemanticVersionPatch>0</SemanticVersionPatch>
<!--
Date when Semantic Version was changed.
Update for every public release.
-->
<SemanticVersionDate>2015-3-17</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>

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

@ -0,0 +1,30 @@
# 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/ai.js
/*/E2ETests/sprint*Snippet.js
/*/E2ETests/testSnippet.js
/*/E2ETests/*.html
/*/Selenium/testPageWithAppInsights.html

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

@ -0,0 +1,355 @@
/// <reference path="../../../JavaScriptSDK/context/session.ts" />
/// <reference path="../../testframework/common.ts" />
/// <reference path="../Util.tests.ts"/>
class SessionContextTests 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() {
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 newGuidStub = sinon.stub(Microsoft.ApplicationInsights.Util, "newGuid", () => "newGuid");
var getCookieStub = sinon.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => "");
var setCookieStub = sinon.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("newGuid", cookieValueParts[0].split('|')[0], "First part of cookie value should be new user id guid");
Assert.equal(new Date().toString(), (new Date(cookieValueParts[0].split('|')[1])).toString(), "Second part of cookie should be parsable as date");
Assert.equal(new Date().toString(), (new Date(cookieValueParts[0].split('|')[2])).toString(), "Third part of cookie should be parsable as date");
// Having expiration 1 year allows to set sesion.IsFirst only when we generated cookie for the first time for a given browser
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(365, expirationDate.getTime() / 1000 / 60 / 60 / 24, "cookie expiration should be in the 1 year");
// cleanup
getCookieStub.restore();
setCookieStub.restore();
newGuidStub.restore();
}
});
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.Util.toISOStringForIE8(new Date());
var renewalDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date());
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.restoreFakeCookie();
}
});
this.testCase({
name: "SessionContext: session start is generated without cookies",
test: () => {
// no cookie, isNew should be true
Microsoft.ApplicationInsights.Util["document"] = <any>{
cookie: ""
};
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null, (t) => { this.results.push(t); });
sessionManager.update();
Assert.equal(AI.SessionState.Start, this.results[0], "session start generated");
}
});
this.testCase({
name: "SessionContext: session start and end are generated after timeout 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 = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date(cookieTime));
var renewalDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date(cookieTime));
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null, (t) => { this.results.push(t); });
sessionManager.update();
// verify
Assert.equal(2, this.results.length);
Assert.equal(AI.SessionState.End, this.results[0], "session end generated");
Assert.equal(AI.SessionState.Start, this.results[1], "session start generated");
this.restoreFakeCookie();
}
});
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 = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date(cookieTime));
var renewalDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date());
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null, (t) => { this.results.push(t); });
sessionManager.update();
// verify
Assert.equal(2, this.results.length);
Assert.equal(AI.SessionState.End, this.results[0], "session end generated");
Assert.equal(AI.SessionState.Start, this.results[1], "session start generated");
this.restoreFakeCookie();
}
});
this.testCase({
name: "SessionContext: session manager honors session from the cookie",
test: () => {
// setup
var testGuid = "00000000-0000-0000-0000-000000000000";
var acquisitionDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date());
var renewalDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date());
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.restoreFakeCookie();
}
});
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 = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date(cookieTime));
var renewalDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date(cookieTime));
this.setFakeCookie(testGuid, acquisitionDate, renewalDate);
// act
var sessionManager = new Microsoft.ApplicationInsights.Context._SessionManager(null, (t) => { this.results.push(t); });
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");
Assert.equal(2, this.results.length);
Assert.equal(AI.SessionState.End, this.results[0], "session end generated");
Assert.equal(AI.SessionState.Start, this.results[1], "session start generated");
this.restoreFakeCookie();
}
});
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 = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date(cookieTime));
var renewalDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date());
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.restoreFakeCookie();
}
});
this.testCase({
name: "SessionContext: session manager updates renewal date when updated",
test: () => {
// setup
var testGuid = "00000000-0000-0000-0000-000000000000";
var acquisitionDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date());
var renewalDate = Microsoft.ApplicationInsights.Util.toISOStringForIE8(new Date());
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.restoreFakeCookie();
}
});
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
};
// 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=foo; ai_session=" + [id, acqDate, renewalDate].join("|")
};
}
private restoreFakeCookie() {
Microsoft.ApplicationInsights.Util["document"] = this.originalDocument;
}
}
new SessionContextTests().registerTests();

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

@ -0,0 +1,110 @@
/// <reference path="../../../JavaScriptSDK/context/user.ts" />
/// <reference path="../../testframework/common.ts" />
/// <reference path="../Util.tests.ts"/>
class UserContextTests extends TestClass {
/** 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 = sinon.stub(Microsoft.ApplicationInsights.Util, "getCookie", () => id + "||||");
// act
var user = new Microsoft.ApplicationInsights.Context.User(undefined);
// verify
Assert.equal(id, user.id, "user id was set from cookie");
cookieStub.restore();
}
});
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 newGuidStub = sinon.stub(Microsoft.ApplicationInsights.Util, "newGuid",() => "newGuid");
var getCookieStub = sinon.stub(Microsoft.ApplicationInsights.Util, "getCookie",() => "");
var setCookieStub = sinon.stub(Microsoft.ApplicationInsights.Util, "setCookie",(cookieName, cookieValue) => {
actualCookieName = cookieName;
actualCookieValue = cookieValue;
});
// act
var user = new Microsoft.ApplicationInsights.Context.User(undefined);
// 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("newGuid", 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");
// cleanup
getCookieStub.restore();
setCookieStub.restore();
newGuidStub.restore();
}
});
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 newGuidStub = sinon.stub(Microsoft.ApplicationInsights.Util, "newGuid",() => "newGuid");
var getCookieStub = sinon.stub(Microsoft.ApplicationInsights.Util, "getCookie",() => "");
var setCookieStub = sinon.stub(Microsoft.ApplicationInsights.Util, "setCookie",(cookieName, cookieValue) => {
actualCookieName = cookieName;
actualCookieValue = cookieValue;
});
// act
var user = new Microsoft.ApplicationInsights.Context.User(undefined);
// 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("newGuid", 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");
// cleanup
getCookieStub.restore();
setCookieStub.restore();
newGuidStub.restore();
}
});
}
}
new UserContextTests().registerTests();

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

@ -0,0 +1,154 @@

/// <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: "//dc-int.services.visualstudio.com/v2/track",
accountId: undefined,
appUserId: undefined,
sessionRenewalMs: 10,
sessionExpirationMs: 10,
maxBatchSizeInBytes: 1000000,
maxBatchInterval: 1,
enableDebug: true,
autoCollectErrors: false,
disableTelemetry: false,
verboseLogging: true,
diagnosticLogInterval: 1
};
// 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,
appUserId: undefined,
sessionRenewalMs: undefined,
sessionExpirationMs: undefined,
maxBatchSizeInBytes: undefined,
maxBatchInterval: undefined,
enableDebug: undefined,
autoCollectErrors: undefined,
disableTelemetry: undefined,
verboseLogging: undefined,
diagnosticLogInterval: undefined
};
var snippet = <Microsoft.ApplicationInsights.Snippet> {
config: emptyConfig,
queue: []
}
var init = new Microsoft.ApplicationInsights.Initialization(snippet);
Assert.equal("//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(1000000, init.config.maxBatchSizeInBytes);
Assert.equal(15000, init.config.maxBatchInterval);
Assert.ok(!init.config.enableDebug);
Assert.ok(init.config.autoCollectErrors);
Assert.equal(15000, init.config.maxBatchInterval);
Assert.ok(!init.config.verboseLogging);
Assert.equal(10000, init.config.diagnosticLogInterval);
}
});
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.autoCollectErrors);
Assert.equal(1, init.config.maxBatchInterval);
Assert.ok(init.config.verboseLogging);
Assert.equal(1, init.config.diagnosticLogInterval);
}
});
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 = sinon.spy(appInsightsLocal, "trackTrace");
var queue: Array<string> = Microsoft.ApplicationInsights._InternalLogging["queue"];
var length = queue.length;
for (var i = 0; i < length; i++) {
queue.shift();
}
queue.push("Hello1");
queue.push("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);
trackTraceSpy.restore();
}
});
}
}
new InitializationTests().registerTests();

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

@ -0,0 +1,207 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../JavaScriptSDK/logging.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
class LoggingTests extends TestClass {
public testCleanup() {
// Clear the queue
var length = Microsoft.ApplicationInsights._InternalLogging.queue.length;
for (var i = 0; i < length; i++) {
Microsoft.ApplicationInsights._InternalLogging.queue.shift();
}
}
public registerTests() {
this.testCase({
name: "LoggingTests: enableDebugExceptions enables exceptions",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = sinon.spy(console, "warn");
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies \n" + e.toString());
}
// verify
Assert.ok(!Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions(), "enableDebugExceptions is false by default");
// act
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, "error!");
// verify
Assert.ok(!throwSpy || throwSpy.calledOnce, "console.warn was called instead of throwing while enableDebugExceptions is false");
// act
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => true;
// verify
Assert.throws(() =>
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, "error!"),
"error is thrown when enableDebugExceptions is true");
Assert.ok(!throwSpy || throwSpy.calledOnce, "console.warn was not called when the error was thrown");
// cleanup
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
!throwSpy || throwSpy.restore(); // IE8
}
});
this.testCase({
name: "LoggingTests: verboseLogging collects all logs",
test: () => {
// setup
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
Microsoft.ApplicationInsights._InternalLogging.verboseLogging = () => true;
// act
var message = "error!";
Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, message);
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, message);
Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, message);
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, message);
//verify
Assert.equal(4, Microsoft.ApplicationInsights._InternalLogging.queue.length);
Assert.equal("AI (Internal): " + message, Microsoft.ApplicationInsights._InternalLogging.queue[0]);
Assert.equal("AI: " + message, Microsoft.ApplicationInsights._InternalLogging.queue[1]);
Assert.equal("AI (Internal): " + message, Microsoft.ApplicationInsights._InternalLogging.queue[2]);
Assert.equal("AI: " + message, Microsoft.ApplicationInsights._InternalLogging.queue[3]);
// cleanup
Microsoft.ApplicationInsights._InternalLogging.verboseLogging = () => false;
}
});
this.testCase({
name: "LoggingTests: Logging only collects CRITICAL logs by default",
test: () => {
// setup
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
// act
var message = "error!";
Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, message);
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.WARNING, message);
Assert.equal(0, Microsoft.ApplicationInsights._InternalLogging.queue.length);
Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, message);
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, message);
//verify
Assert.equal(2, Microsoft.ApplicationInsights._InternalLogging.queue.length);
Assert.equal("AI (Internal): " + message, Microsoft.ApplicationInsights._InternalLogging.queue[0]);
Assert.equal("AI: " + message, Microsoft.ApplicationInsights._InternalLogging.queue[1]);
}
});
this.testCase({
name: "LoggingTests: throwInternalUserActionable adds to the queue and calls console.warn",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = sinon.spy(console, "warn");
// act
var message = "error!";
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, message);
// verify
Assert.ok(throwSpy.calledOnce, "console.warn was not called while debug mode was false");
Assert.equal(1, Microsoft.ApplicationInsights._InternalLogging.queue.length);
Assert.equal("AI: " + message, Microsoft.ApplicationInsights._InternalLogging.queue[0]);
// cleanup
throwSpy.restore();
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: throwInternalNonUserActionable adds to the queue and calls console.warn",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = sinon.spy(console, "warn");
// act
var message = "error!";
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
Microsoft.ApplicationInsights._InternalLogging.throwInternalNonUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, message);
// verify
Assert.ok(throwSpy.calledOnce, "console.warn was not called while debug mode was false");
Assert.equal(1, Microsoft.ApplicationInsights._InternalLogging.queue.length);
Assert.equal("AI (Internal): " + message, Microsoft.ApplicationInsights._InternalLogging.queue[0]);
// cleanup
throwSpy.restore();
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
}
}
});
this.testCase({
name: "LoggingTests: warn does not add to the queue ",
test: () => {
// setup
var throwSpy = null;
try {
throwSpy = sinon.spy(console, "warn");
// act
var message = "error!";
Microsoft.ApplicationInsights._InternalLogging.warn(message);
// verify
Assert.ok(throwSpy.calledOnce, "console.warn was called once");
Assert.equal(0, Microsoft.ApplicationInsights._InternalLogging.queue.length);
// cleanup
throwSpy.restore();
} 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 = sinon.spy(console, "log");
// act
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
Microsoft.ApplicationInsights._InternalLogging.throwInternalUserActionable(Microsoft.ApplicationInsights.LoggingSeverity.CRITICAL, "error!");
// verify
Assert.ok(throwSpy.calledOnce, "console.log was called when console.warn was not present");
// cleanup
throwSpy.restore();
} catch (e) {
Assert.ok(true, "IE8 breaks sinon spies on window objects\n" + e.toString());
} finally {
console.warn = warn;
}
}
});
}
}
new LoggingTests().registerTests();

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

@ -0,0 +1,413 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../JavaScriptSDK/sender.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
class SenderTests extends TestClass {
private xhr;
private xdr;
private fakeServer;
private getSender;
private errorSpy;
private successSpy;
private loggingSpy;
private testTelemetry;
private endpointUrl: string;
private maxBatchSizeInBytes: number;
private maxBatchInterval: number;
private disableTelemetry: boolean;
public testInitialize() {
this.xhr = window["XMLHttpRequest"];
this.xdr = window["XDomainRequest"];
this.fakeServer = sinon.fakeServer.create();
this.endpointUrl = "testUrl";
this.maxBatchSizeInBytes = 1000000;
this.maxBatchInterval = 1;
this.disableTelemetry = false;
var config: Microsoft.ApplicationInsights.ISenderConfig = {
endpointUrl: () => this.endpointUrl,
maxBatchSizeInBytes: () => this.maxBatchSizeInBytes,
maxBatchInterval: () => this.maxBatchInterval,
disableTelemetry: () => this.disableTelemetry
};
this.getSender = () => new Microsoft.ApplicationInsights.Sender(config);
this.errorSpy = sinon.spy(Microsoft.ApplicationInsights.Sender, "_onError");
this.successSpy = sinon.stub(Microsoft.ApplicationInsights.Sender, "_onSuccess");
this.loggingSpy = sinon.stub(Microsoft.ApplicationInsights._InternalLogging, "warn");
this.testTelemetry = { aiDataContract: true };
}
public testCleanup() {
if (this.xhr === undefined) {
delete window["XMLHttpRequest"];
} else {
window["XMLHttpRequest"] = this.xhr;
}
if (this.xdr === undefined) {
delete window["XDomainRequest"];
} else {
window["XDomainRequest"] = this.xdr;
}
this.errorSpy.restore();
this.successSpy.restore();
this.loggingSpy.restore();
}
public registerTests() {
var requestAsserts = () => {
Assert.ok(this.fakeServer.requests.length > 0, "request was sent");
var method = this.fakeServer.getHTTPMethod(this.fakeServer.requests[0]);
Assert.equal("POST", method, "requets method is 'POST'");
}
var logAsserts = (expectedCount) => {
var isValidCallCount = this.loggingSpy.callCount === expectedCount;
Assert.ok(isValidCallCount, "logging spy was called " + expectedCount + " time(s)");
if (!isValidCallCount) {
for (var i = 0; i < this.loggingSpy.args.length; i++) {
Assert.ok(false, "[warning thrown]: " + this.loggingSpy.args[i]);
}
}
}
var successAsserts = () => {
Assert.ok(this.successSpy.called, "success was invoked");
Assert.ok(this.errorSpy.notCalled, "no error");
}
var errorAsserts = () => {
Assert.ok(this.errorSpy.called, "error was invoked");
Assert.ok(this.successSpy.notCalled, "success was not invoked");
}
this.testCase({
name: "SenderTests: uninitialized sender throws a warning when invoked",
test: () => {
// act
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
sender.send(this.testTelemetry);
// verify
Assert.ok(this.successSpy.notCalled, "success handler was not invoked");
Assert.ok(this.errorSpy.notCalled, "error handler was not invoked");
logAsserts(1);
}
});
this.testCase({
name: "SenderTests: sender throws when no arg is passed",
test: () => {
// setup
XMLHttpRequest = <any>(() => {
var xhr = new this.xhr;
xhr.withCredentials = false;
return xhr;
});
// act
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
sender.send(undefined);
// verify
Assert.ok(this.successSpy.notCalled, "success handler was not invoked");
Assert.ok(this.errorSpy.notCalled, "error handler was not invoked");
logAsserts(1);
}
});
this.testCase({
name: "SenderTests: XMLHttpRequest sender can be invoked and handles errors",
test: () => {
// setup
XMLHttpRequest = <any>(() => {
var xhr = new this.xhr;
xhr.withCredentials = false;
return xhr;
});
// act
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
// verify
Assert.ok(sender, "sender was constructed");
// act
this.fakeServer.requests.pop();
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
// verify
requestAsserts();
this.fakeServer.requests.pop().respond(200, { "Content-Type": "application/json" }, '{"test":"success"}"');
successAsserts();
logAsserts(0);
this.successSpy.reset();
this.errorSpy.reset();
// act
this.fakeServer.requests.pop();
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
// verify
requestAsserts();
this.fakeServer.requests.pop().respond(404, { "Content-Type": "application/json" }, '{"test":"not found"}"');
errorAsserts();
logAsserts(1);
this.successSpy.reset();
this.errorSpy.reset();
}
});
this.testCase({
name: "SenderTests: XDomain sender can be invoked and handles errors",
test: () => {
// setup
XDomainRequest = <any>(() => {
var xdr = new this.xhr;
xdr.onload = xdr.onreadystatechange;
xdr.responseText = 200;
return xdr;
});
// act
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
// verify
Assert.ok(sender, "sender was constructed");
// act
this.fakeServer.requests.pop();
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
// verify
requestAsserts();
this.fakeServer.requests[0].respond(200, { "Content-Type": "application/json" }, '200');
successAsserts();
logAsserts(0);
this.successSpy.reset();
this.errorSpy.reset();
// act
this.fakeServer.requests.pop();
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
// verify
requestAsserts();
this.fakeServer.requests[0].respond(404, { "Content-Type": "application/json" }, '400');
errorAsserts();
logAsserts(2);
this.successSpy.reset();
this.errorSpy.reset();
}
});
this.testCase({
name: "SenderTests: XMLHttpRequest and XDomainRequest native error handlers are logged",
test: () => {
// setup
var xhr = new this.xhr;
XMLHttpRequest = <any>(() => {
xhr.withCredentials = false;
return xhr;
});
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
this.clock.tick(sender._config.maxBatchInterval() + 1);
sender.send(this.testTelemetry);
sender.triggerSend();
xhr.onerror();
// verify
errorAsserts();
this.errorSpy.reset();
// setup
var xdr = new this.xhr;
XMLHttpRequest = <any>(() => {});
XDomainRequest = <any>(() => {
xdr.onload = xdr.onreadystatechange;
xdr.responseText = 200;
return xdr;
});
sender = this.getSender();
this.clock.tick(sender._config.maxBatchInterval() + 1);
sender.send(this.testTelemetry);
sender.triggerSend();
xdr.onerror();
// verify
errorAsserts();
this.errorSpy.reset();
}
});
this.testCase({
name: "SenderTests: sender invokes early when the buffer is full",
test: () => {
// setup
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
sender._sender = () => null;
var senderSpy = sinon.spy(sender, "_sender");
this.maxBatchSizeInBytes = Microsoft.ApplicationInsights.Serializer.serialize(this.testTelemetry).length
this.maxBatchInterval = 1;
this.clock.now = 1;
// act (this will fill the buffer and then overflow to send immediately)
sender.send(this.testTelemetry);
sender.send(this.testTelemetry);
// verify
Assert.ok(senderSpy.calledOnce, "sender was invoked");
// act (make sure second message is sent after max interval is reached)
senderSpy.reset();
this.clock.tick(sender._config.maxBatchInterval());
// verify
Assert.ok(senderSpy.calledOnce, "sender was invoked a second time after maxInterval elapsed");
logAsserts(0);
// act (make sure nothing more is sent when max interval is reached)
senderSpy.reset();
this.clock.tick(sender._config.maxBatchInterval());
// verify
Assert.ok(senderSpy.notCalled, "sender was not invoked a third time after maxInterval elapsed");
logAsserts(0);
senderSpy.restore();
}
});
this.testCase({
name: "SenderTests: sender timeout is reset after each successful send",
test: () => {
// setup
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
sender._sender = () => null;
var senderSpy = sinon.spy(sender, "_sender");
this.maxBatchSizeInBytes = Microsoft.ApplicationInsights.Serializer.serialize(this.testTelemetry).length;
this.maxBatchInterval = 1;
this.clock.now = 1;
// act (this will fill the buffer once, trigger a send, then refill and overflow)
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => true;
sender.send(this.testTelemetry);
sender.send(this.testTelemetry);
// sender.send(this.testTelemetry); todo: send again here once throttling is re-enabled
// verify
Assert.ok(senderSpy.calledOnce, "sender was invoked");
logAsserts(0);
senderSpy.restore();
Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions = () => false;
}
});
this.testCase({
name: "SenderTests: sender throttles requests when buffer is filled twice before minInterval has ellapsed",
test: () => {
// setup
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
sender._sender = () => null;
var senderSpy = sinon.spy(sender, "_sender");
this.maxBatchSizeInBytes = Microsoft.ApplicationInsights.Serializer.serialize(this.testTelemetry).length * 2;
this.maxBatchInterval = 2;
// act
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
// verify
Assert.ok(senderSpy.calledTwice, "sender was invoked twice");
logAsserts(0);
// act (fill buffer, trigger send, refill buffer, wait)
this.clock.tick(1);
senderSpy.reset();
sender.send(this.testTelemetry);
sender.send(this.testTelemetry);
sender.send(this.testTelemetry);
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
// verify
Assert.ok(senderSpy.calledTwice, "sender was invoked twice");
logAsserts(0);
senderSpy.restore();
}
});
this.testCase({
name: "SenderTests: Verify default value of enableTracking is false",
test: () => {
// setup
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
// verify
Assert.ok(!sender._config.disableTelemetry(), "default value for disable tracking is false");
logAsserts(0);
}
});
this.testCase({
name: "SenderTests: enableTracking swtich is set to false. Sender should not send/save data",
test: () => {
// setup
this.disableTelemetry = true;
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
sender._sender = () => null;
var senderSpy = sinon.spy(sender, "_sender");
// act
sender.send(this.testTelemetry);
this.clock.tick(sender._config.maxBatchInterval());
// verify
Assert.ok(senderSpy.notCalled, "sender was not called");
logAsserts(0);
senderSpy.restore();
}
});
this.testCase({
name: "SenderTests: enableTracking swtich is set to false. Trigger send should not send data",
test: () => {
// setup
this.disableTelemetry = true;
var sender: Microsoft.ApplicationInsights.Sender = this.getSender();
sender._sender = () => null;
var senderSpy = sinon.spy(sender, "_sender");
this.maxBatchInterval = 100;
// act
sender.send(this.testTelemetry);
sender.triggerSend();
// verify
Assert.ok(senderSpy.notCalled, "sender was not called");
logAsserts(0);
senderSpy.restore();
}
});
}
}
new SenderTests().registerTests();

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

@ -0,0 +1,294 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../JavaScriptSDK/serializer.ts" />
class SerializerTests extends TestClass {
private throwInternalNonUserActionableSpy;
private throwInternalUserActionableSpy;
/** Method called before the start of each test method */
public testInitialize() {
this.throwInternalNonUserActionableSpy = sinon.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternalNonUserActionable");
this.throwInternalUserActionableSpy = sinon.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternalUserActionable");
}
/** Method called after each test method has completed */
public testCleanup() {
this.throwInternalNonUserActionableSpy.restore();
this.throwInternalUserActionableSpy.restore();
}
public registerTests() {
this.testCase({
name: "SerializerTests: empty input",
test: () => {
// act
Microsoft.ApplicationInsights.Serializer.serialize(null);
// verify
Assert.ok(this.throwInternalUserActionableSpy.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: true,
noContract: true
}
};
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.throwInternalUserActionableSpy.calledOnce, "warning when contract is omitted");
}
});
this.testCase({
name: "SerializerTests: required objects that are not present throw",
test: () => {
// act
var obj = {
aiDataContract: {
str: true
}
};
var expected = "{}";
var actual = Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.equal(expected, actual, "Object is serialized correctly");
Assert.ok(this.throwInternalUserActionableSpy.calledOnce, "broken contracts throw");
}
});
this.testCase({
name: "SerializerTests: serialize an item with an array",
test: () => {
// act
var noCycle = { value: "value", aiDataContract: { value: true } };
var obj = {
arr: [
noCycle,
noCycle,
noCycle
],
aiDataContract: { arr: [] }
};
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.throwInternalNonUserActionableSpy.notCalled, "no non user actionable errors");
Assert.ok(this.throwInternalUserActionableSpy.notCalled, "no user actionable 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.Serializer.serialize(obj);
// verify
Assert.ok(this.throwInternalNonUserActionableSpy.notCalled, "no non user actionable errors");
Assert.ok(this.throwInternalUserActionableSpy.calledOnce, "got user actionable errors");
}
});
this.testCase({
name: "SerializerTests: cycles without contracts are handled",
test: () => {
// act
var cyclePt1 = { value: undefined, aiDataContract: { value: true } };
var cyclePt2 = { value: cyclePt1, aiDataContract: { value: true } };
cyclePt1.value = cyclePt2;
var obj = {
noContractWithCycle: {
notSerializable: cyclePt1
},
aiDataContract: {
noContractWithCycle: true,
}
};
Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.ok(this.throwInternalUserActionableSpy.calledTwice, "user actionable error is thrown");
var error = this.throwInternalUserActionableSpy.args[0][1].toLowerCase();
Assert.equal("attempting to serialize an object which does not implement iserializable: nocontractwithcycle", error);
}
});
this.testCase({
name: "SerializerTests: cycles with contracts are handled",
test: () => {
// act
var cyclePt1 = { value: undefined, aiDataContract: { value: true } };
var cyclePt2 = { value: cyclePt1, aiDataContract: { value: true } };
cyclePt1.value = cyclePt2;
var obj = {
aCycleWithContract: cyclePt1,
aiDataContract: {
aCycleWithContract: true,
}
};
Microsoft.ApplicationInsights.Serializer.serialize(obj);
// verify
Assert.ok(this.throwInternalUserActionableSpy.calledOnce, "error is thrown");
var error = this.throwInternalUserActionableSpy.args[0][1].toLowerCase();
Assert.ok(error.indexOf("circular") >= 0 || error.indexOf("cyclic") >= 0, "error message");
}
});
this.testCase({
name: "SerializerTests: object not present in the contract are not serialized",
test: () => {
// act
var obj = {
str: "str",
notInContract: "foo",
aiDataContract: {
str: true,
}
};
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: true
}
};
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.throwInternalNonUserActionableSpy.notCalled, "no non user actionable errors");
Assert.ok(this.throwInternalUserActionableSpy.notCalled, "no user actionable 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: false,
measurements: false
}
};
this.throwInternalUserActionableSpy.reset();
var result = Microsoft.ApplicationInsights.Serializer.serialize(obj);
Assert.ok(result.indexOf("invalid field") < 0, message);
Assert.ok(this.throwInternalUserActionableSpy.notCalled, "no user actionable 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: false,
measurements: false
}
};
this.throwInternalUserActionableSpy.reset();
var result = Microsoft.ApplicationInsights.Serializer.serialize(obj);
Assert.equal(expectedOutput, result);
Assert.ok(this.throwInternalUserActionableSpy.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();

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

@ -0,0 +1,138 @@
/// <reference path="../../testframework/common.ts" />
/// <reference path="../../../JavaScriptSDK/telemetry/Common/DataSanitizer.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 with illegal chars is sanitized",
test: () => {
var expectedName = "_________Hello()World/\ -0123456789_______";
var name = "~`@#$%^&*Hello()World/\ -0123456789_{}[]|=";
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 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 = {
"he000": 1,
"he001": 2,
"he002": 3,
"he003": 4,
"he004": 5
}
var validatedMap = Microsoft.ApplicationInsights.Telemetry.Common.DataSanitizer.sanitizeMeasurements(map);
Assert.deepEqual(expectedMap, validatedMap);
}
});
}
}
new DataSanitizerTests().registerTests();

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

@ -0,0 +1,45 @@
/// <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();

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

@ -0,0 +1,161 @@
/// <reference path="../../testframework/common.ts" />
/// <reference path="../../testframework/contracttesthelper.ts" />
/// <reference path="../../../JavaScriptSDK/telemetry/exception.ts" />
/// <reference path="../../../JavaScriptSDK/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 + "HandledAt is initialized in constructor",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Exception(new Error("test error"), "HA");
Assert.equal(telemetry.handledAt, "HA");
}
});
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);
}
});
}
}
new ExceptionTelemetryTests().registerTests();

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

@ -0,0 +1,27 @@
/// <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();

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

@ -0,0 +1,43 @@
/// <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), "PageViewTelemetryTests");
}
public registerTests() {
super.registerTests();
var name = this.name + ": ";
var testValues = {
name: "name",
url: "url",
duration: 1000,
properties: {
"property1": 5,
"property2": 10
},
measurements: {
"measurement": 300
}
};
this.testCase({
name: name + "PageviewData is initialized in constructor with 5 parameters (name, url, durationMs, properties, measurements) and valid",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageView(testValues.name, testValues.url, testValues.duration, testValues.properties, testValues.measurements);
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();

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

@ -0,0 +1,119 @@
/// <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 registerTests() {
super.registerTests();
var name = this.name + ": ";
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.checkPageLoad();
Assert.equal(undefined, check, "checkPageLoad returns undefined when not available");
}
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry has correct serialization contract",
test: () => {
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
Assert.equal("boolean", typeof telemetry.aiDataContract.perfTotal, "perfTotal is set in data contract");
Assert.equal("boolean", typeof telemetry.aiDataContract.networkConnect, "networkConnect is set in data contract");
Assert.equal("boolean", typeof telemetry.aiDataContract.receivedResponse, "receivedResponse is set in data contract");
Assert.equal("boolean", typeof telemetry.aiDataContract.sentRequest, "sentRequest is set in data contract");
Assert.equal("boolean", typeof telemetry.aiDataContract.domProcessing, "domProcessing is set in data contract");
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry measurements are correct",
test: () => {
var timing = <PerformanceTiming>{};
timing.navigationStart = 1;
timing.connectEnd = 10;
timing.requestStart = 11;
timing.responseStart = 30;
timing.responseEnd = 42;
timing.domLoading = 52;
timing.loadEventEnd = 60;
var timingSpy = sinon.stub(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance, "getPerformanceTiming",() => {
return timing;
});
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
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(8), data.domProcessing);
timingSpy.restore();
}
});
this.testCase({
name: name + "PageViewPerformanceTelemetry detects when perf data is sent by the browser incorrectly and doesn't send it",
test: () => {
var timing = <PerformanceTiming>{};
timing.navigationStart = 1;
timing.connectEnd = 40;
timing.requestStart = 11;
timing.responseStart = 30;
timing.responseEnd = 42;
timing.domLoading = 52;
timing.loadEventEnd = 60;
var timingSpy = sinon.stub(Microsoft.ApplicationInsights.Telemetry.PageViewPerformance, "getPerformanceTiming",() => {
return timing;
});
var actualLoggedMessage = null;
var loggingSpy = sinon.stub(Microsoft.ApplicationInsights._InternalLogging, "warn",(m) => actualLoggedMessage = m);
var telemetry = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("name", "url", 0);
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("client performance math error:59 < 39 + 19 + 12 + 8", actualLoggedMessage);
timingSpy.restore();
loggingSpy.restore();
}
});
}
}
new PageViewPerformanceTelemetryTests().registerTests();

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

@ -0,0 +1,25 @@
/// <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();

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

@ -0,0 +1,72 @@
/// <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 1of each test method */
public testInitialize() {
this._config = {
instrumentationKey: () => "testKey",
accountId: () => undefined,
appUserId: () => undefined,
sessionRenewalMs: () => 10,
sessionExpirationMs: () => 10,
endpointUrl: () => "asdf",
maxBatchSizeInBytes: () => 1000000,
maxBatchInterval: () => 1,
disableTelemetry: () => false
}
this._telemetryContext = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
}
/** Method called after each test method has completed */
public testCleanup() {
}
public registerTests() {
this.testCase({
name: "TelemtetryContect: 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: "TelemtetryContect: calling track with null or undefined fails",
test: () => {
var tc = new Microsoft.ApplicationInsights.TelemetryContext(this._config);
var logSpy = sinon.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternalUserActionable");
tc.track(undefined);
Assert.ok(logSpy.calledOnce, "sender throws with undefined");
tc.track(null);
Assert.ok(logSpy.calledTwice, "sender throws with null");
logSpy.restore();
}
});
this.testCase({
name: "TelemtetryContect: 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");
}
});
}
}
new TelemetryContextTests().registerTests();

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

@ -0,0 +1,160 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../JavaScriptSDK/util.ts" />
class UtilTests extends TestClass {
public registerTests() {
this.testCase({
name: "UtilTests: isArray",
test: () => {
var isArray = Microsoft.ApplicationInsights.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 = {};
document.__defineGetter__('cookie', () => {
var output = [];
for (var cookieName in cookies) {
output.push(cookieName + "=" + cookies[cookieName]);
}
return output.join(";");
});
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;
});
document.clearCookies = () => {
cookies = {};
};
})(document);
var expectedValue = "testValue";
Microsoft.ApplicationInsights.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 = Microsoft.ApplicationInsights.Util.getCookie("test");
Assert.equal(expectedValue, actualValue, "cookie content was set and retrieved");
actualValue = Microsoft.ApplicationInsights.Util.getCookie("");
Assert.equal("", actualValue, "cookie content was set and retrieved");
}
}
});
this.testCase({
name: "UtilTests: parse cookie",
test: () => {
var test = (cookie, query, expected) => {
Microsoft.ApplicationInsights.Util["document"] = <any>{
cookie: cookie
};
var actual = Microsoft.ApplicationInsights.Util.getCookie(query);
Assert.deepEqual(expected, actual, "cookie is parsed correctly");
}
test("testCookie=id|acq|renewal", "testCookie", "id|acq|renewal");
test("other=foo; testCookie=id|acq|renewal", "testCookie", "id|acq|renewal");
test("another=bar; ;a=testCookie=; testCookie=id|acq|renewal; other=foo|3|testCookie=", "testCookie", "id|acq|renewal");
test("xtestCookiex=id|acq|renewal", "testCookie", "");
test("", "testCookie", "");
}
});
this.testCase({
name: "UtilTests: new GUID",
test: () => {
sinon.stub(Math, "random", () => 0);
var expected = "00000000-0000-4000-8000-000000000000";
var actual = Microsoft.ApplicationInsights.Util.newGuid();
Assert.equal(expected, actual, "expected guid was generated");
}
});
this.testCase({
name: "UtilTests: toISO string for IE8",
test: () => {
var test = () => {
var date = new Date();
var output = Microsoft.ApplicationInsights.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 = Microsoft.ApplicationInsights.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(10, "00:00:00.010", "milliseconds digit 2");
test(100, "00:00:00.100", "milliseconds digit 3");
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, "00:00:00.000", "hours overflow");
test(11 * 3600000 + 11 * 60000 + 11111, "11:11:11.111", "all digits");
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");
}
});
}
}
new UtilTests().registerTests();

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

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

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

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

@ -0,0 +1,11 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Domain.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Base.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Data.ts" />
/// <reference path="../../../JavaScriptSDK/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");
});

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

@ -0,0 +1,207 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/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.ApplicationBuild was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.applicationBuild !== null, "ContextTagKeys.applicationBuild == null");
QUnit.ok(temp.applicationBuild === "ai.application.build", "Issue with ContextTagKeys.applicationBuild");
});
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.DeviceIp was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceIp !== null, "ContextTagKeys.deviceIp == null");
QUnit.ok(temp.deviceIp === "ai.device.ip", "Issue with ContextTagKeys.deviceIp");
});
QUnit.test("Test property ContextTagKeys.DeviceLanguage was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceLanguage !== null, "ContextTagKeys.deviceLanguage == null");
QUnit.ok(temp.deviceLanguage === "ai.device.language", "Issue with ContextTagKeys.deviceLanguage");
});
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.DeviceNetwork was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceNetwork !== null, "ContextTagKeys.deviceNetwork == null");
QUnit.ok(temp.deviceNetwork === "ai.device.network", "Issue with ContextTagKeys.deviceNetwork");
});
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.DeviceOS was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceOS !== null, "ContextTagKeys.deviceOS == null");
QUnit.ok(temp.deviceOS === "ai.device.os", "Issue with ContextTagKeys.deviceOS");
});
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.DeviceRoleInstance was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceRoleInstance !== null, "ContextTagKeys.deviceRoleInstance == null");
QUnit.ok(temp.deviceRoleInstance === "ai.device.roleInstance", "Issue with ContextTagKeys.deviceRoleInstance");
});
QUnit.test("Test property ContextTagKeys.DeviceRoleName was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceRoleName !== null, "ContextTagKeys.deviceRoleName == null");
QUnit.ok(temp.deviceRoleName === "ai.device.roleName", "Issue with ContextTagKeys.deviceRoleName");
});
QUnit.test("Test property ContextTagKeys.DeviceScreenResolution was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceScreenResolution !== null, "ContextTagKeys.deviceScreenResolution == null");
QUnit.ok(temp.deviceScreenResolution === "ai.device.screenResolution", "Issue with ContextTagKeys.deviceScreenResolution");
});
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.DeviceMachineName was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.deviceMachineName !== null, "ContextTagKeys.deviceMachineName == null");
QUnit.ok(temp.deviceMachineName === "ai.device.machineName", "Issue with ContextTagKeys.deviceMachineName");
});
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.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.OperationRootId was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.operationRootId !== null, "ContextTagKeys.operationRootId == null");
QUnit.ok(temp.operationRootId === "ai.operation.rootId", "Issue with ContextTagKeys.operationRootId");
});
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.OperationIsSynthetic was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.operationIsSynthetic !== null, "ContextTagKeys.operationIsSynthetic == null");
QUnit.ok(temp.operationIsSynthetic === "ai.operation.isSynthetic", "Issue with ContextTagKeys.operationIsSynthetic");
});
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.SessionIsNew was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.sessionIsNew !== null, "ContextTagKeys.sessionIsNew == null");
QUnit.ok(temp.sessionIsNew === "ai.session.isNew", "Issue with ContextTagKeys.sessionIsNew");
});
QUnit.test("Test property ContextTagKeys.UserAccountAcquisitionDate was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.userAccountAcquisitionDate !== null, "ContextTagKeys.userAccountAcquisitionDate == null");
QUnit.ok(temp.userAccountAcquisitionDate === "ai.user.accountAcquisitionDate", "Issue with ContextTagKeys.userAccountAcquisitionDate");
});
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.UserAgent was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.userAgent !== null, "ContextTagKeys.userAgent == null");
QUnit.ok(temp.userAgent === "ai.user.userAgent", "Issue with ContextTagKeys.userAgent");
});
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.UserStoreRegion was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.userStoreRegion !== null, "ContextTagKeys.userStoreRegion == null");
QUnit.ok(temp.userStoreRegion === "ai.user.storeRegion", "Issue with ContextTagKeys.userStoreRegion");
});
QUnit.test("Test property ContextTagKeys.SampleRate was created and default is set", function () {
var temp = new AI.ContextTagKeys();
QUnit.ok(temp.sampleRate !== null, "ContextTagKeys.sampleRate == null");
QUnit.ok(temp.sampleRate === "ai.sample.sampleRate", "Issue with ContextTagKeys.sampleRate");
});
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");
});

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

@ -0,0 +1,16 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Domain.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Base.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Data.ts" />
/// <reference path="../../../JavaScriptSDK/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");
});

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

@ -0,0 +1,50 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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");
});

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

@ -0,0 +1,83 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Domain.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Base.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/Data.ts" />
/// <reference path="../../../JavaScriptSDK/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.flags was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.flags !== null, "Envelope.flags == null");
});
QUnit.test("Test property Envelope.deviceId was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.deviceId !== null, "Envelope.deviceId == null");
});
QUnit.test("Test property Envelope.os was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.os !== null, "Envelope.os == null");
});
QUnit.test("Test property Envelope.osVer was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.osVer !== null, "Envelope.osVer == null");
});
QUnit.test("Test property Envelope.appId was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.appId !== null, "Envelope.appId == null");
});
QUnit.test("Test property Envelope.appVer was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.appVer !== null, "Envelope.appVer == null");
});
QUnit.test("Test property Envelope.userId was created and default is set", function () {
var temp = new Microsoft.Telemetry.Envelope();
QUnit.ok(temp.userId !== null, "Envelope.userId == 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");
});

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

@ -0,0 +1,35 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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");
});

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

@ -0,0 +1,55 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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.handledAt was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.handledAt !== null, "ExceptionData.handledAt == null");
});
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.problemId was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.problemId !== null, "ExceptionData.problemId == null");
});
QUnit.test("Test property ExceptionData.crashThreadId was created and default is set", function () {
var temp = new AI.ExceptionData();
QUnit.ok(temp.crashThreadId !== null, "ExceptionData.crashThreadId == 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");
});

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

@ -0,0 +1,50 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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");
});

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

@ -0,0 +1,35 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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");
});

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

@ -0,0 +1,30 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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");
});

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

@ -0,0 +1,45 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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.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");
});

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

@ -0,0 +1,70 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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");
});

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

@ -0,0 +1,94 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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.kind was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.kind !== null, "RemoteDependencyData.kind == null");
QUnit.ok(temp.kind === AI.DataPointType.Measurement, "Issue with RemoteDependencyData.kind");
});
QUnit.test("Test property RemoteDependencyData.value was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.value !== null, "RemoteDependencyData.value == null");
});
QUnit.test("Test property RemoteDependencyData.count was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.count !== null, "RemoteDependencyData.count == null");
});
QUnit.test("Test property RemoteDependencyData.min was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.min !== null, "RemoteDependencyData.min == null");
});
QUnit.test("Test property RemoteDependencyData.max was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.max !== null, "RemoteDependencyData.max == null");
});
QUnit.test("Test property RemoteDependencyData.stdDev was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.stdDev !== null, "RemoteDependencyData.stdDev == null");
});
QUnit.test("Test property RemoteDependencyData.dependencyKind was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.dependencyKind !== null, "RemoteDependencyData.dependencyKind == null");
QUnit.ok(temp.dependencyKind === AI.DependencyKind.Other, "Issue with RemoteDependencyData.dependencyKind");
});
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.async was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.async !== null, "RemoteDependencyData.async == null");
});
QUnit.test("Test property RemoteDependencyData.dependencySource was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.dependencySource !== null, "RemoteDependencyData.dependencySource == null");
QUnit.ok(temp.dependencySource === AI.DependencySourceType.Undefined, "Issue with RemoteDependencyData.dependencySource");
});
QUnit.test("Test property RemoteDependencyData.commandName was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.commandName !== null, "RemoteDependencyData.commandName == null");
});
QUnit.test("Test property RemoteDependencyData.dependencyTypeName was created and default is set", function () {
var temp = new AI.RemoteDependencyData();
QUnit.ok(temp.dependencyTypeName !== null, "RemoteDependencyData.dependencyTypeName == 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");
});

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

@ -0,0 +1,70 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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.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.startTime was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.startTime !== null, "RequestData.startTime == null");
});
QUnit.test("Test property RequestData.duration was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.duration !== null, "RequestData.duration == null");
});
QUnit.test("Test property RequestData.responseCode was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.responseCode !== null, "RequestData.responseCode == 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.httpMethod was created and default is set", function () {
var temp = new AI.RequestData();
QUnit.ok(temp.httpMethod !== null, "RequestData.httpMethod == 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");
});

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

@ -0,0 +1,15 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/SessionStateData.ts" />
QUnit.test("Test property SessionStateData.ver was created and default is set", function () {
var temp = new AI.SessionStateData();
QUnit.ok(temp.ver !== null, "SessionStateData.ver == null");
QUnit.ok(temp.ver === 2, "Issue with SessionStateData.ver");
});
QUnit.test("Test property SessionStateData.state was created and default is set", function () {
var temp = new AI.SessionStateData();
QUnit.ok(temp.state !== null, "SessionStateData.state == null");
QUnit.ok(temp.state === AI.SessionState.Start, "Issue with SessionStateData.state");
});

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

@ -0,0 +1,39 @@
// THIS FILE WAS AUTOGENERATED
/// <reference path="../../External/qunit.d.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/DataPoint.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MetricData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RemoteDependencyData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/RequestData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/StackFrame.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionDetails.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/ExceptionData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/MessageData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/EventData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/PageViewPerfData.ts" />
/// <reference path="../../../JavaScriptSDK/Contracts/Generated/AjaxCallData.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");
});

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

@ -0,0 +1,167 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
class DisableTelemetryTests extends TestClass {
private errorSpy;
private successSpy;
private loggingSpy;
/** Method called before the start of each test method */
public testInitialize() {
this.useFakeServer = false;
sinon.fakeServer["restore"]();
this.useFakeTimers = false;
this.clock.restore();
this.errorSpy = sinon.spy(Microsoft.ApplicationInsights.Sender, "_onError");
this.successSpy = sinon.stub(Microsoft.ApplicationInsights.Sender, "_onSuccess");
this.loggingSpy = sinon.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternalUserActionable");
}
/** Method called after each test method has completed */
public testCleanup() {
this.useFakeServer = true;
this.useFakeTimers = true;
this.errorSpy.restore();
this.successSpy.restore();
this.loggingSpy.restore();
}
public registerTests() {
var snippet = window["appInsights"];
/*
// uncomment this to target prod instead of int
snippet.endpointUrl = "http://dc.services.visualstudio.com/v2/track";
snippet.instrumentationKey = "89330895-7c53-4315-a242-85d136ad9c16";
*/
var delay = snippet.config.maxBatchInterval + 10;
var boilerPlateAsserts = () => {
Assert.ok(this.successSpy.called, "success");
Assert.ok(!this.errorSpy.called, "no error sending");
var isValidCallCount = this.loggingSpy.callCount === 0;
Assert.ok(isValidCallCount, "logging spy was called 0 time(s)");
if (!isValidCallCount) {
while (this.loggingSpy.args.length) {
Assert.ok(false, "[warning thrown]: " + this.loggingSpy.args.pop());
}
}
}
var asserts = [];
var pollingCount = 100;
for (var i = 0; i < pollingCount; i++) {
asserts.push(() => {
var message = "polling: " + new Date().toISOString();
Assert.ok(true, message);
console.log(message);
// calling start() causes sinon to resume and ends the async test
if (this.successSpy.called) {
boilerPlateAsserts();
this.testCleanup();
start();
} else if (this.errorSpy.called || this.loggingSpy.called) {
boilerPlateAsserts();
start();
}
});
}
asserts.push(() => Assert.ok(this.successSpy.called, "success"));
var assertNoMessages = [];
var pollingCountForNoMessages = 50; // I don't think we need polling for this
for (var j = 0; j < pollingCountForNoMessages; j++) {
assertNoMessages.push(() => {
var message = "polling for no messages: " + new Date().toISOString();
Assert.ok(true, message);
console.log(message);
// calling start() causes sinon to resume and ends the async test
if (this.successSpy.called) {
Assert.ok(false, "should not have received a success");
this.testCleanup();
start();
} else if (this.errorSpy.called || this.loggingSpy.called) {
Assert.ok(false, "should not have received an error or logging");
}
});
}
this.testCaseAsync({
name: "TelemetryContext: master switch disables tracking",
stepDelay: delay,
steps: [
() => {
var testAiNoMessages = new Microsoft.ApplicationInsights.AppInsights(snippet.config);
testAiNoMessages.config.disableTelemetry = true;
var exception = null;
try {
window["a"]["b"]();
} catch (e) {
exception = e;
}
Assert.ok(exception);
testAiNoMessages.trackEvent("test");
testAiNoMessages.trackException(exception);
testAiNoMessages.trackMetric("test", Math.round(100 * Math.random()));
testAiNoMessages.trackTrace("test");
testAiNoMessages.trackPageView();
}
].concat(assertNoMessages)
});
this.testCaseAsync({
name: "TelemetryContext: master switch disables and enables tracking",
stepDelay: delay,
steps: [
() => {
var testAiNoMessages = new Microsoft.ApplicationInsights.AppInsights(snippet.config);
testAiNoMessages.config.disableTelemetry = true;
var exception = null;
try {
window["a"]["b"]();
} catch (e) {
exception = e;
}
Assert.ok(exception);
testAiNoMessages.trackEvent("test");
testAiNoMessages.trackException(exception);
testAiNoMessages.trackMetric("test", Math.round(100 * Math.random()));
testAiNoMessages.trackTrace("test");
testAiNoMessages.trackPageView();
}
].concat(assertNoMessages).concat([
() => {
var testAi = new Microsoft.ApplicationInsights.AppInsights(snippet.config);
testAi.config.disableTelemetry = false;
var exception = null;
try {
window["a"]["b"]();
} catch (e) {
exception = e;
}
Assert.ok(exception);
testAi.trackEvent("test");
testAi.trackException(exception);
testAi.trackMetric("test", Math.round(100 * Math.random()));
testAi.trackTrace("test");
testAi.trackPageView();
}
]).concat(asserts)
});
}
}
new DisableTelemetryTests().registerTests();

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

@ -0,0 +1,95 @@
# Copy snippet files and replace // with http:// otherwise the tests will not be able to load the file://
Param(
[ValidateNotNullOrEmpty()]
[parameter(Mandatory=$true, HelpMessage="The project directory.")]
[string]$projectDir,
[ValidateNotNullOrEmpty()]
[parameter(Mandatory=$false, HelpMessage="The instrumentation key.")]
[string]$iKey = "0011cf0f-6d64-4a0e-a19f-4eb82a36f134", #"1b9aa9ee-cf04-42de-8060-9e2fa87803e5",
[ValidateNotNullOrEmpty()]
[parameter(Mandatory=$false, HelpMessage="The endpoinoint URL. (dev: datacollection-devred.cloudapp.net, int: dc-int.services.visualstudio.com, prod: dc.services.visualstudio.com")]
[string]$endpointUrl = "http://dc-int.services.visualstudio.com/v2/track",
[ValidateNotNullOrEmpty()]
[parameter(Mandatory=$false, HelpMessage="CDN URL -- NOTE this is only used to as a replacement index")]
[string]$cdnUrl = "//az639152.vo.msecnd.net/sdk/a/ai.0.10.js"
)
# copy ai full
$path = "$($projectDir)\..\JavaScriptSDK\min\ai.js"
if(-not (test-path $path)) {
$path = "$($projectDir)\..\JavaScriptSDK\min\ai_tests.js"
}
$content = gc $path
$content | out-file "$($projectDir)\E2ETests\ai.js"
# build ai path in file:// format
$aiPath = "file:///" + ($projectDir -replace "\\", "/") + "/E2ETests/ai.js"
# test the queue
$queueTest = "var i = 100; while(i--){appInsights.queue.push(function() {window.queueTest('from the queue')})};"
# copy snippet and convert protocol to file://
$edgePrefix = gc "$($projectDir)\..\JavaScriptSDK\snippet.js"
$edgePrefix = $edgePrefix -replace $cdnUrl, $aiPath
$edgePrefix = $edgePrefix -replace "instrumentationKey: ""INSTRUMENTATION_KEY""", "instrumentationKey: ""$($iKey)"", endpointUrl: ""$($endpointUrl)"", maxBatchInterval: 1"
$edgePrefix = $edgePrefix -replace 'CDN_PATH',$aiPath
$edgePrefix += $queueTest
$edgePrefix | out-file "$($projectDir)\E2ETests\sprint70Snippet.js"
# copy snippet and convert protocol to file://
$sprint69Snippet = gc "$($projectDir)\E2ETests\standalone\legacySnippetSprint69.js"
$sprint69Snippet = $sprint69Snippet -replace $cdnUrl, $aiPath
$sprint69Snippet = $sprint69Snippet -replace "iKey: ""INSTRUMENTATION_KEY""", "iKey: ""$($iKey)"", endpointUrl: ""$($endpointUrl)"", maxBatchInterval: 1"
$sprint69Snippet = $sprint69Snippet -replace 'CDN_PATH',$aiPath
$sprint69Snippet += $queueTest
$sprint69Snippet | out-file "$($projectDir)\E2ETests\sprint69Snippet.js"
# copy legacy snippet and convert protocol to file://
$sprint66Snippet = gc "$($projectDir)\E2ETests\standalone\legacySnippet.js"
$sprint66Snippet = $sprint66Snippet -replace $cdnUrl, $aiPath
$sprint66Snippet = $sprint66Snippet -replace "appInsights.start\(\);", "appInsights.start(""$($iKey)"");"
$sprint66Snippet += "appInsights.endpointUrl = ""$($endpointUrl)""; appInsights.maxBatchInterval = 1"
$sprint66Snippet += $queueTest
$sprint66Snippet | out-file "$($projectDir)\E2ETests\sprint66Snippet.js"
$testSnippet = gc "$($projectDir)\E2ETests\standalone\testSnippet.js"
$testSnippet = $testSnippet -replace "ENDPOINT_URL", $endpointUrl
$testSnippet = $testSnippet -replace "INSTRUMENTATION_KEY", $iKey
$testSnippet = $testSnippet -replace "CDN_URL",$aiPath
$testSnippet += $queueTest
$testSnippet | out-file "$($projectDir)\E2ETests\testSnippet.js"
# add snippet to error test files
$instrumentation = gc "$($projectDir)\E2ETests\autoCollectionTemplates\instrumentation.js"
$files = @("errorDom.html", "errorScriptGlobal.html", "errorScriptNested.html", "errorScriptSyntax.html")
foreach ($file in $files) {
$content = gc "$($projectDir)\E2ETests\autoCollectionTemplates\$($file)"
$strSnippet = ""
foreach ($line in $edgePrefix) {
$strSnippet += $line + "`r`n "
}
$strInstrumentation = ""
foreach ($line in $instrumentation) {
$strInstrumentation += $line + "`r`n "
}
$content = $content -replace 'PREFIX_PLACEHOLDER', $strSnippet
$content = $content -replace 'INSTRUMENTATION_PLACEHOLDER', $strInstrumentation
$content | out-file "$($projectDir)\E2ETests\$($file)"
}
# add snippet to performance test file
$content = gc "$($projectDir)\Selenium\testPageNoAppInsights.html"
$strSnippet = ""
foreach ($line in $edgePrefix) {
$strSnippet += $line + "`r`n "
}
$content = $content -replace '//PREFIX_PLACEHOLDER', $strSnippet
$content | out-file "$($projectDir)\Selenium\testPageWithAppInsights.html"

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

@ -0,0 +1,174 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
class PublicApiTests extends TestClass {
private errorSpy;
private successSpy;
private loggingSpy;
/** Method called before the start of each test method */
public testInitialize() {
this.useFakeServer = false;
sinon.fakeServer["restore"]();
this.useFakeTimers = false;
this.clock.restore();
this.errorSpy = sinon.spy(Microsoft.ApplicationInsights.Sender, "_onError");
this.successSpy = sinon.stub(Microsoft.ApplicationInsights.Sender, "_onSuccess");
this.loggingSpy = sinon.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternalUserActionable");
}
/** Method called after each test method has completed */
public testCleanup() {
this.useFakeServer = true;
this.useFakeTimers = true;
this.errorSpy.restore();
this.successSpy.restore();
this.loggingSpy.restore();
}
public registerTests() {
var snippet = window["appInsights"];
/*
// uncomment this to target prod instead of int
snippet.endpointUrl = "http://dc.services.visualstudio.com/v2/track";
snippet.instrumentationKey = "89330895-7c53-4315-a242-85d136ad9c16";
*/
var delay = snippet.config.maxBatchInterval + 100;
var testAi = new Microsoft.ApplicationInsights.AppInsights(snippet.config);
// disable session state event:
testAi.context._sessionManager._sessionHandler = null;
var boilerPlateAsserts = () => {
Assert.ok(this.successSpy.called, "success");
Assert.ok(!this.errorSpy.called, "no error sending");
var isValidCallCount = this.loggingSpy.callCount === 0;
Assert.ok(isValidCallCount, "logging spy was called 0 time(s)");
if (!isValidCallCount) {
while (this.loggingSpy.args.length) {
Assert.ok(false, "[warning thrown]: " + this.loggingSpy.args.pop());
}
}
}
var asserts = [];
var pollingCount = 100;
for (var i = 0; i < pollingCount; i++) {
asserts.push(() => {
var message = "polling: " + new Date().toISOString();
Assert.ok(true, message);
console.log(message);
// calling start() causes sinon to resume and ends the async test
if (this.successSpy.called) {
boilerPlateAsserts();
this.testCleanup();
start();
} else if (this.errorSpy.called || this.loggingSpy.called) {
boilerPlateAsserts();
start();
}
});
}
asserts.push(() => Assert.ok(this.successSpy.called, "success"));
this.testCaseAsync({
name: "TelemetryContext: track event",
stepDelay: delay,
steps: [
() => {
testAi.trackEvent("test");
}
].concat(asserts)
});
this.testCaseAsync({
name: "TelemetryContext: track exception",
stepDelay: delay,
steps: [
() => {
var exception = null;
try {
window["a"]["b"]();
} catch (e) {
exception = e;
testAi.trackException(e);
}
Assert.ok(exception);
}
].concat(asserts)
});
this.testCaseAsync({
name: "TelemetryContext: track metric",
stepDelay: delay,
steps: [
() => {
for (var i = 0; i < 100; i++) {
testAi.trackMetric("test" + i, Math.round(100 * Math.random()));
}
}
].concat(asserts)
});
this.testCaseAsync({
name: "TelemetryContext: track trace",
stepDelay: delay,
steps: [
() => {
testAi.trackTrace("test");
}
].concat(asserts)
});
this.testCaseAsync({
name: "TelemetryContext: track page view",
stepDelay: delay,
steps: [
() => {
testAi.trackPageView();
}
].concat(asserts)
});
this.testCaseAsync({
name: "TelemetryContext: track all types in batch",
stepDelay: delay,
steps: [
() => {
var exception = null;
try {
window["a"]["b"]();
} catch (e) {
exception = e;
}
Assert.ok(exception);
testAi.trackEvent("test");
testAi.trackException(exception);
testAi.trackMetric("test", Math.round(100 * Math.random()));
testAi.trackTrace("test");
testAi.trackPageView();
}
].concat(asserts)
});
this.testCaseAsync({
name: "TelemetryContext: track all types in a large batch",
stepDelay: delay,
steps: [
() => {
for (var i = 0; i < 100; i++) {
testAi.trackMetric("test", Math.round(100 * Math.random()));
}
}
].concat(asserts)
});
}
}
new PublicApiTests().registerTests();

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

@ -0,0 +1,165 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
class Sanitizer2ETests extends TestClass {
private errorSpy;
private successSpy;
private loggingSpy;
/** Method called before the start of each test method */
public testInitialize() {
this.useFakeServer = false;
sinon.fakeServer["restore"]();
this.useFakeTimers = false;
this.clock.restore();
this.errorSpy = sinon.spy(Microsoft.ApplicationInsights.Sender, "_onError");
this.successSpy = sinon.stub(Microsoft.ApplicationInsights.Sender, "_onSuccess");
this.loggingSpy = sinon.stub(Microsoft.ApplicationInsights._InternalLogging, "throwInternalUserActionable");
}
/** Method called after each test method has completed */
public testCleanup() {
this.useFakeServer = true;
this.useFakeTimers = true;
this.errorSpy.restore();
this.successSpy.restore();
this.loggingSpy.restore();
}
public registerTests() {
var snippet = window["appInsights"];
/*
// uncomment this to target prod instead of int
snippet.endpointUrl = "http://dc.services.visualstudio.com/v2/track";
snippet.instrumentationKey = "89330895-7c53-4315-a242-85d136ad9c16";
*/
var delay = snippet.config.maxBatchInterval + 100;
var testAi = new Microsoft.ApplicationInsights.AppInsights(snippet.config);
var boilerPlateAsserts = () => {
Assert.ok(this.successSpy.called, "success");
Assert.ok(!this.errorSpy.called, "no error sending");
}
var asserts = [];
var pollingCount = 100;
for (var i = 0; i < pollingCount; i++) {
asserts.push(() => {
var message = "polling: " + new Date().toISOString();
Assert.ok(true, message);
console.log(message);
// calling start() causes sinon to resume and ends the async test
if (this.successSpy.called) {
boilerPlateAsserts();
this.testCleanup();
start();
} else if (this.errorSpy.called || this.loggingSpy.called) {
boilerPlateAsserts();
start();
}
});
}
asserts.push(() => Assert.ok(this.successSpy.called, "success"));
this.testCaseAsync({
name: "Sanitizer2ETests: Data platform accepts sanitized names",
stepDelay: delay,
steps: [
() => {
var properties = {
"property1%^~`": "hello",
"property2*&#+": "world"
};
var measurements = {
"measurement@|": 300
};
testAi.trackMetric("test", 5);
}
].concat(asserts)
});
this.testCaseAsync({
name: "Sanitizer2ETests: Data platform accepts legal charater set names",
stepDelay: delay,
steps: [
() => {
var properties = {
"abcdefghijklmnopqrstuvwxyz": "hello",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ": "world"
};
var measurements = {
"(1234567890/ \_-.)": 300
};
testAi.trackMetric("test", 5);
}
].concat(asserts)
});
this.testCaseAsync({
name: "Sanitizer2ETests: Data platform accepts up to 150 charaters for names",
stepDelay: delay,
steps: [
() => {
var len = 150;
var name = new Array(len + 1).join('a');
testAi.trackMetric(name, 5);
}
].concat(asserts)
});
this.testCaseAsync({
name: "Sanitizer2ETests: Data platform accepts up to 1024 charaters for values",
stepDelay: delay,
steps: [
() => {
var len = 1024;
var value = new Array(len + 1).join('a');
var properties = {
"testProp": value
};
testAi.trackMetric("test", 5);
}
].concat(asserts)
});
this.testCaseAsync({
name: "Sanitizer2ETests: Data platform accepts up to 2048 charaters for url",
stepDelay: delay,
steps: [
() => {
var len = 2048;
var url = "http://hello.com/";
url = url + new Array(len - url.length + 1).join('a');
testAi.trackPageView("test", url);
}
].concat(asserts)
});
this.testCaseAsync({
name: "Sanitizer2ETests: Data platform accepts up to 32768 charaters for messages",
stepDelay: delay,
steps: [
() => {
var len = 32768;
var message = new Array(len + 1).join('a');
testAi.trackTrace(message, 5);
}
].concat(asserts)
});
}
}
new Sanitizer2ETests().registerTests();

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

@ -0,0 +1,244 @@
/// <reference path="../../javascriptsdk/telemetry/exception.ts" />
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
class AutoCollectionTests extends TestClass {
/** Turns on/off sinon's syncronous implementation of setTimeout. On by default. */
public errorSpy: SinonSpy;
/** Method called before the start of each test method */
public testInitialize() {
this.useFakeTimers = false;
this.clock.restore();
this.errorSpy = this.getListener("ErrorSpy");
}
/** Method called after each test method has completed */
public testCleanup() {
this.useFakeTimers = true;
this.errorSpy.reset();
}
public registerTests() {
var delay = 100;
//var errorDomSpy = this.getListener("errorDom");
this.testCaseAsync({
name: "AutoCollection: errorDom",
stepDelay: delay,
steps: [
() => {
this.loadErrorTest("errorDom");
}
].concat(this.poll(() => {
return this.verifyErrorMessages(this.errorSpy, [
//General Error message
"NotFoundError",
// Safari specific error message
"An attempt was made to reference a Node in a context where it does not exist"
], 1);
}))
});
//var errorScriptGlobalSpy = this.getListener("errorScriptGlobal");
this.testCaseAsync({
name: "AutoCollection: errorScriptGlobal",
stepDelay: delay,
steps: [
() => {
this.loadErrorTest("errorScriptGlobal");
}
].concat(this.poll(() => {
return this.verifyErrorMessages(this.errorSpy, [
// General errors
"undefinedObject is not defined",
// IE specific error messages
"Object doesn't support property or method 'unsupportedMethod'",
"The use of a keyword for an identifier is invalid",
"Array length must be a finite positive integer",
"Cannot assign to a function result",
"'undefinedObject' is undefined",
"Boolean.prototype.toString: 'this' is not a Boolean object",
"Function expected",
// Chrome specific error messages
"Invalid array length",
"Invalid left-hand side in assignment",
"Boolean.prototype.toString is not generic",
"object is not a function",
"undefined is not a function",
// Firefox specific error messages
"obj.unsupportedMethod is not a function",
"invalid array length",
"invalid assignment left-hand side",
"toString method called on incompatible Object",
"o is not a function",
// Safari specific error messages
"'undefined' is not a function",
"Array size is not a small enough positive integer",
"Left side of assignment is not a reference",
"Can't find variable: undefinedObject",
"Type error",
"'[object Object]' is not a function (evaluating 'o()')"
], 7);
}))
});
//var errorScriptNestedSpy = this.getListener("errorScriptNested");
this.testCaseAsync({
name: "AutoCollection: errorScriptNested",
stepDelay: delay,
steps: [
() => {
this.loadErrorTest("errorScriptNested");
}
].concat(this.poll(() => {
return this.verifyErrorMessages(this.errorSpy, [
//General Error message
"first is not defined",
"afterFullAiLoads",
// IE specific error messages
"'first' is undefined",
"Unable to get property 'exist' of undefined or null reference",
// Chrome specific error messages
"Cannot read property 'exist' of undefined",
// Firefox specific error messages
"no element found",
"window.doesNot is undefined",
// Safari specific error messages
"Can't find variable: first",
"'undefined' is not an object"
], 3);
}))
});
//var errorScriptSyntaxSpy = this.getListener("errorScriptSyntax");
this.testCaseAsync({
name: "AutoCollection: errorScriptSyntax",
stepDelay: delay,
steps: [
() => {
this.loadErrorTest("errorScriptSyntax");
}
].concat(this.poll(() => {
return this.verifyErrorMessages(this.errorSpy, [
// IE specific error messages
"Object doesn't support property or method 'unsupportedMethod'",
"Expected '}'",
"Unterminated string constant",
// Chrome specific error messages
"undefined is not a function",
"Unexpected end of input",
"Unexpected token ILLEGAL",
// Firefox specific error messages
"obj.unsupportedMethod is not a function",
"missing } in compound statement",
"unterminated string literal",
"missing } after function body",
// Safari specific error messages
"Expected token '}'",
"Unexpected EOF"
], 5);
}))
});
}
private getListener(address): SinonSpy {
var listener = { onMessage: () => null };
var spy = sinon.spy(listener, "onMessage");
if (window.addEventListener) {
addEventListener("message", listener.onMessage, false);
} else {
attachEvent("onmessage", listener.onMessage);
}
return spy;
}
private loadErrorTest(path) {
window["appInsights"] = undefined;
var href = window.location.href.toLowerCase();
var fullPath = href.split("e2etests")[0] + "e2etests/" + path + ".html";
var iframe = document.createElement("iframe");
iframe.src = fullPath;
iframe.id = path;
document.getElementsByTagName("body")[0].parentNode.appendChild(iframe);
return iframe;
}
private poll(func: () => boolean, count: number = 25) {
var polling = [];
for (var i = 0; i < count; i++) {
polling.push(() => {
if (func()) {
Assert.ok(true, "validated, stopping poll cycle");
start();
this.testCleanup();
}
});
}
polling.push(() => {
Assert.ok(false, "timeout reached");
start();
this.testCleanup();
});
return polling;
}
private getExceptionsFromMessage(args) {
var exceptions = [];
for (var i = 0; i < args.length; i++) {
var payload = args[i][0];
var data = JSON.parse(payload.data);
for (var j = 0; j < data.length; j++) {
var d = data[j].data;
if (d && d.baseType === Microsoft.ApplicationInsights.Telemetry.Exception.dataType) {
exceptions.push(d.baseData);
}
}
}
return exceptions;
}
private verifyErrorMessages(spy: SinonSpy, expectedMessages, numberOfTests) {
var done = false;
if (spy.called) {
var args = spy.args;
var exceptions = this.getExceptionsFromMessage(args);
var count = 0;
for (var i = 0; i < exceptions.length; i++) {
var exception = exceptions[i];
var message = exception.exceptions[0].message;
for (var j = 0; j < expectedMessages.length; j++) {
if (message.indexOf(expectedMessages[j]) >= 0) {
Assert.ok(true, "Message '" + expectedMessages[j] + "' is contained in: " + message);
count++;
break;
}
}
}
done = count >= numberOfTests;
}
return done;
}
}
new AutoCollectionTests().registerTests();

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

@ -0,0 +1,31 @@
<!DOCTYPE html>
<html>
<head>
<title>errorDom</title>
<!-- placeholder for snippet injected by PostBuild.ps1 -->
<script>
PREFIX_PLACEHOLDER
INSTRUMENTATION_PLACEHOLDER
</script>
</head>
<body>
<script>
// dom exception
setTimeout(function() {
var node = document.getElementsByTagName('h1').item(0);
var siblingNode = node.nextSibling;
var invalidNode = document.createTextNode('invalid node specification');
node.insertBefore(invalidNode, siblingNode);
}, 500);
// file not found exception (this is not caught, leaving in case there is a way to catch this type of erro)
setTimeout(function () {
var scriptElement = document.createElement("script");
scriptElement.src = "../doesNotExist.js";
document.getElementsByTagName("script")[0].parentNode.appendChild(scriptElement);
}, 500);
</script>
<h1>DOM error test page</h1>
</body>
</html>

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

@ -0,0 +1,54 @@
<!DOCTYPE html>
<html>
<head>
<title>errorGlobal</title>
<!-- placeholder for snippet injected by PostBuild.ps1 -->
<script>
PREFIX_PLACEHOLDER
INSTRUMENTATION_PLACEHOLDER
</script>
</head>
<body>
<h1>Global script error test page</h1>
<script type="text/javascript">
var breakStuff = function(action) {
setTimeout(action, 100);
};
// runtime errors: http://msdn.microsoft.com/en-us/library/ie/1dk3k160(v=vs.94).aspx
breakStuff(function() {
var obj = {};
obj.unsupportedMethod(); // 438 unsupported method/property
});
breakStuff(function() {
new Array(3.14159);; // 5029 array length must be positive integer
});
breakStuff(function() {
new Array(NaN);; // 5030 array length must be positive integer
});
breakStuff(function() {
"".split() = 42; // Attempting to assign the value 42 to the result of the function call.
});
breakStuff(function() {
undefinedObject.split(); // object is undefined
});
breakStuff(function() {
var o = new Object; // 5010 Boolean expected
o.f = Boolean.prototype.toString;
o.f();
});
breakStuff(function () {
var o = new Object; // 5002 Function expected
o();
});
</script>
</html>

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

@ -0,0 +1,54 @@
<!DOCTYPE html>
<html>
<head>
<title>errorNested</title>
<!-- placeholder for snippet injected by PostBuild.ps1 -->
<script>
PREFIX_PLACEHOLDER
INSTRUMENTATION_PLACEHOLDER
</script>
</head>
<body>
<h1>Nested script error test page</h1>
<script type="text/javascript">
function fisrt() {
throw "error";
}
function second() {
first();
}
function third() {
second();
}
third();
</script>
<script type="text/javascript">
function async1() {
window.doesNot.exist();
}
function async2() {
setTimeout(async1, 200);
}
function async() {
setTimeout(async2, 200);
}
async();
</script>
<script type="text/javascript">
function afterFullAiLoads() {
throw "afterFullAiLoads"
}
setTimeout(afterFullAiLoads, 1000);
</script>
</body>
</html>

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

@ -0,0 +1,40 @@
<!DOCTYPE html>
<html>
<head>
<title>errorSyntax</title>
<!-- placeholder for snippet injected by PostBuild.ps1 -->
<script>
PREFIX_PLACEHOLDER
INSTRUMENTATION_PLACEHOLDER
</script>
</head>
<body>
<h1>Syntax script error test page</h1>
<script type="text/javascript">
function badSyntax() {
var str = "asdfas;'
if (true) {
}
}
badSyntax();
</script>
<script type="text/javascript">
function badSyntax() {
var str = "asdfas;";
if (true) {
console.log(str);
}
worseSyntax();
</script>
<script>{</script>
<script>"unclosed string</script>
<script>setTimeout("{", 10);</script>
</body>
</body>
</html>

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

@ -0,0 +1,12 @@
// make sure we send things immediately for tests, we don't want batching
appInsights.maxBatchInterval = 0;
// hook the send method of XHLHttpRequest so that we can validate that errors are logged
var originalSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function (data) { // don't use typescript lambda
top.postMessage(data, "*");
return originalSend.apply(this, arguments);
};
// don't break snippet tests
window['queueTest'] = function () { };

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

@ -0,0 +1,10 @@
rem Copy target files
pushd %~dp0
xcopy ..\..\..\JavaScriptSDK\min targets /y
xcopy ..\..\..\JavaScriptSDK\*.* targets /y
xcopy ..\..\..\Node\*.* targets /y
xcopy ..\..\..\Node\Context\*.* targets /y
rem Run Policheck
"%programfiles(x86)%\MS\PoliCheck\MS.BGIT.Policheck.exe" /task:task.xml
popd

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

@ -0,0 +1,141 @@
<?xml version="1.0"?>
<Task>
<TaskName>Check JS and Node SDKs</TaskName>
<Target>.\Targets</Target>
<ResultFile>.\results.xml</ResultFile>
<LocalName>JavaScriptSDK</LocalName>
<CustomRulesDBPath />
<TermTables>
<TermTable Type="0" Name="Finnish" LCID="1035" />
<TermTable Type="0" Name="Lithuanian" LCID="1063" />
<TermTable Type="0" Name="Telugu" LCID="1098" />
<TermTable Type="0" Name="Norwegian (Nynorsk)" LCID="2068" />
<TermTable Type="0" Name="Bangla – India" LCID="1093" />
<TermTable Type="0" Name="Georgian" LCID="1079" />
<TermTable Type="0" Name="Serbian (Cyrillic)" LCID="3098" />
<TermTable Type="0" Name="Kinyarwanda" LCID="135" />
<TermTable Type="0" Name="Ukrainian" LCID="1058" />
<TermTable Type="0" Name="isiXhosa" LCID="1076" />
<TermTable Type="0" Name="Punjabi" LCID="1094" />
<TermTable Type="0" Name="Quechua (Peru)" LCID="3179" />
<TermTable Type="0" Name="Gujarati" LCID="1095" />
<TermTable Type="0" Name="Central Kurdish" LCID="146" />
<TermTable Type="0" Name="Tatar" LCID="1092" />
<TermTable Type="0" Name="Chinese (Traditional) - Hong Kong SAR" LCID="3076" />
<TermTable Type="0" Name="German" LCID="1031" />
<TermTable Type="0" Name="Urdu" LCID="1056" />
<TermTable Type="0" Name="Konkani" LCID="1111" />
<TermTable Type="0" Name="Chinese (Simplified)" LCID="2052" />
<TermTable Type="0" Name="Vietnamese" LCID="1066" />
<TermTable Type="0" Name="Uyghur" LCID="128" />
<TermTable Type="0" Name="Mongolian" LCID="1104" />
<TermTable Type="0" Name="Russian" LCID="1049" />
<TermTable Type="0" Name="Sesotho sa Leboa" LCID="1132" />
<TermTable Type="0" Name="Setswana" LCID="1074" />
<TermTable Type="0" Name="Tigrinya" LCID="115" />
<TermTable Type="0" Name="Chinese (Traditional) - Taiwan" LCID="1028" />
<TermTable Type="0" Name="Pashto" LCID="1123" />
<TermTable Type="0" Name="Lao" LCID="1108" />
<TermTable Type="0" Name="Dari" LCID="1164" />
<TermTable Type="0" Name="Indonesian" LCID="1057" />
<TermTable Type="0" Name="Cherokee" LCID="1169" />
<TermTable Type="0" Name="Yoruba" LCID="1130" />
<TermTable Type="0" Name="Turkmen" LCID="1090" />
<TermTable Type="0" Name="Hausa" LCID="1128" />
<TermTable Type="0" Name="Latvian" LCID="1062" />
<TermTable Type="0" Name="Portuguese - Brazil" LCID="1046" />
<TermTable Type="0" Name="Kazakh" LCID="1087" />
<TermTable Type="0" Name="Irish" LCID="2108" />
<TermTable Type="0" Name="Azerbaijani" LCID="1068" />
<TermTable Type="0" Name="Albanian" LCID="1052" />
<TermTable Type="0" Name="Japanese" LCID="1041" />
<TermTable Type="0" Name="Bosnian - Latin" LCID="5146" />
<TermTable Type="0" Name="Nepali" LCID="1121" />
<TermTable Type="0" Name="Amharic" LCID="1118" />
<TermTable Type="0" Name="Hindi" LCID="1081" />
<TermTable Type="0" Name="Dutch" LCID="1043" />
<TermTable Type="0" Name="Malayalam" LCID="1100" />
<TermTable Type="0" Name="Swedish" LCID="1053" />
<TermTable Type="0" Name="Kyrgyz" LCID="1088" />
<TermTable Type="0" Name="Malay" LCID="1086" />
<TermTable Type="0" Name="French" LCID="1036" />
<TermTable Type="0" Name="Maltese" LCID="1082" />
<TermTable Type="0" Name="Tamil" LCID="1097" />
<TermTable Type="0" Name="Kannada" LCID="1099" />
<TermTable Type="0" Name="Filipino" LCID="1124" />
<TermTable Type="0" Name="Afrikaans" LCID="1078" />
<TermTable Type="0" Name="Valencian" LCID="2051" />
<TermTable Type="0" Name="Odia" LCID="1096" />
<TermTable Type="0" Name="Igbo" LCID="1136" />
<TermTable Type="0" Name="Wolof" LCID="136" />
<TermTable Type="0" Name="Inuktitut" LCID="1117" />
<TermTable Type="0" Name="isiZulu" LCID="1077" />
<TermTable Type="0" Name="Thai" LCID="1054" />
<TermTable Type="0" Name="Spanish" LCID="1034" />
<TermTable Type="0" Name="Danish" LCID="1030" />
<TermTable Type="0" Name="Croatian" LCID="1050" />
<TermTable Type="0" Name="Turkish" LCID="1055" />
<TermTable Type="0" Name="K'iche'" LCID="134" />
<TermTable Type="0" Name="Belarusian" LCID="35" />
<TermTable Type="0" Name="Punjabi (Pakistan)" LCID="2118" />
<TermTable Type="0" Name="Tajik" LCID="40" />
<TermTable Type="0" Name="Scottish Gaelic" LCID="145" />
<TermTable Type="0" Name="Romanian" LCID="1048" />
<TermTable Type="0" Name="Basque" LCID="1069" />
<TermTable Type="0" Name="Hungarian" LCID="1038" />
<TermTable Type="0" Name="Sindhi" LCID="2137" />
<TermTable Type="0" Name="Welsh" LCID="1106" />
<TermTable Type="0" Name="Pulaar" LCID="1171" />
<TermTable Type="0" Name="Persian" LCID="1065" />
<TermTable Type="0" Name="Maori" LCID="1153" />
<TermTable Type="0" Name="Khmer" LCID="1107" />
<TermTable Type="0" Name="Slovenian" LCID="1060" />
<TermTable Type="0" Name="English" LCID="9" />
<TermTable Type="0" Name="Polish" LCID="1045" />
<TermTable Type="0" Name="Arabic" LCID="14337" />
<TermTable Type="0" Name="Serbian (Latin)" LCID="2074" />
<TermTable Type="0" Name="Luxembourgish" LCID="1134" />
<TermTable Type="0" Name="Assamese" LCID="1101" />
<TermTable Type="0" Name="Portuguese - Portugal" LCID="2070" />
<TermTable Type="0" Name="Czech" LCID="1029" />
<TermTable Type="0" Name="Greek" LCID="1032" />
<TermTable Type="0" Name="Sesotho" LCID="1072" />
<TermTable Type="0" Name="Armenian" LCID="1067" />
<TermTable Type="0" Name="Bosnian - Cyrillic" LCID="8218" />
<TermTable Type="0" Name="Estonian" LCID="1061" />
<TermTable Type="0" Name="Catalan" LCID="1027" />
<TermTable Type="0" Name="Uzbek" LCID="1091" />
<TermTable Type="0" Name="Hebrew" LCID="1037" />
<TermTable Type="0" Name="Icelandic" LCID="1039" />
<TermTable Type="0" Name="Sinhala" LCID="1115" />
<TermTable Type="0" Name="Norwegian (Bokmål)" LCID="1044" />
<TermTable Type="0" Name="Macedonian" LCID="1071" />
<TermTable Type="0" Name="Marathi" LCID="1102" />
<TermTable Type="0" Name="Slovak" LCID="1051" />
<TermTable Type="0" Name="Korean" LCID="1042" />
<TermTable Type="0" Name="Bulgarian" LCID="1026" />
<TermTable Type="0" Name="Breton" LCID="1150" />
<TermTable Type="0" Name="Italian" LCID="1040" />
<TermTable Type="0" Name="Bangla - Bangladesh" LCID="2117" />
<TermTable Type="0" Name="Serbian (Cyrillic, Bosnia and Herzegovina)" LCID="7194" />
<TermTable Type="0" Name="Global" LCID="127" />
</TermTables>
<ScanType>File</ScanType>
<SOMConfigurationEnabled>True</SOMConfigurationEnabled>
<LogEnabled>False</LogEnabled>
<TargetType>0</TargetType>
<SeverityFilters><Severity Type="1" Enabled="1"></Severity><Severity Type="2" Enabled="1"></Severity><Severity Type="3" Enabled="1"></Severity><Severity Type="4" Enabled="1"></Severity></SeverityFilters>
<TermClassifications />
<HistoryManagement Enabled="0">
<PreviousVersion>0</PreviousVersion>
<Version>0</Version>
<RootDirectory />
</HistoryManagement>
<Exclusions><GlobalExclusions><GlobalExclusion Name="Enable Exclusions" Enabled="0"></GlobalExclusion><GlobalExclusion Name="Enable Context Exception" Enabled="1"></GlobalExclusion></GlobalExclusions><PersonalExclusions><PersonalExclusion Name="Enable Exclusion" Enabled="0"></PersonalExclusion><PersonalExclusion Name="Enable File Exception" Enabled="0"></PersonalExclusion><PersonalExclusion Name="Enable Context Exception" Enabled="0"></PersonalExclusion><PersonalExclusion Name="Enable File Context Exception" Enabled="0"></PersonalExclusion></PersonalExclusions></Exclusions>
<CustomFTSetsPath />
<CodeComments Enabled="1" />
<SkipUnchangedFiles Enabled="0" />
<IncludeSubDirectories Enabled="1" />
</Task>

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

@ -0,0 +1,252 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../../javascriptsdk/sender.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
class SnippetTests extends TestClass {
private name = "appInsights";
private instrumentationKey = window["appInsights"].instrumentationKey;
private originalAppInsights;
private timingOffset = 0;
private queueSpy;
private queueCallCount = 100;
private loadSnippet(path) {
// load ai via the snippet
window["appInsights"] = undefined;
var key = "E2ETests";
var snippetPath = window.location.href.split(key)[0] + key + path;
var scriptElement = document.createElement("script");
scriptElement.src = snippetPath;
scriptElement.id = "testSnippet";
document.getElementsByTagName("script")[0].parentNode.appendChild(scriptElement);
}
/** Method called before the start of each test method */
public testInitialize() {
var timingEnabled = typeof window != "undefined" && window.performance && window.performance.timing;
this.timingOffset = timingEnabled ? 1 : 0;
this.originalAppInsights = window[this.name];
window[this.name] = undefined;
try {
delete window[this.name];
} catch (e) {
}
window['queueTest'] = () => null;
this.queueSpy = sinon.spy(window, "queueTest");
this.useFakeTimers = false;
this.clock.restore();
this.useFakeServer = false;
sinon.fakeServer["restore"]();
}
/** Method called after each test method has completed */
public testCleanup() {
this.useFakeServer = true;
this.useFakeTimers = true;
window[this.name] = this.originalAppInsights;
this.queueSpy.restore();
}
public registerTests() {
var path70 = "/sprint70Snippet.js";
var path69 = "/sprint69Snippet.js";
var path66 = "/sprint66Snippet.js";
this.testSnippet(path70);
this.testSnippet(path69);
this.testSnippet(path66);
var senderSpy71V2;
this.testCaseAsync({
name: "SnippetTests: API version 0.10 and lower can send (url,prop,meas) and the url is set correctly",
stepDelay: 250,
steps: [
() => {
this.loadSnippet(path69);
},
() => {
senderSpy71V2 = this.setAppInsights();
window["appInsights"].trackPageView("test", { property: "p1" }, { measurement: 5 });
},
() => {
Assert.equal(this.queueCallCount, this.queueSpy.callCount, "queue is emptied");
Assert.equal(2, senderSpy71V2.sender.callCount, "v2 send called " + 2 + " times");
this.boilerPlateAsserts(senderSpy71V2);
// check url and properties
var pv = <Microsoft.ApplicationInsights.Telemetry.PageView>senderSpy71V2.sender.args[0][0].data.baseData;
Assert.deepEqual("test", pv.url, "url was set correctly");
Assert.deepEqual({ property: "p1" }, pv.properties, "properties were set correctly");
Assert.deepEqual({ measurement: 5 }, pv.measurements, "measurements were set correctly");
senderSpy71V2.restore();
}
]
});
var senderSpy66V2V1;
this.testCaseAsync({
name: "SnippetTests: sprint 66 snippet sends to v2 endpoint with v1 API",
stepDelay: 250,
steps: [
() => {
this.loadSnippet(path66);
},
() => {
senderSpy66V2V1 = this.setAppInsights();
window["appInsights"].logEvent("test");
window["appInsights"].logPageView();
},
() => {
Assert.equal(this.queueCallCount, this.queueSpy.callCount, "queue is emptied");
var count = 2 + this.timingOffset;
Assert.equal(count, senderSpy66V2V1.sender.callCount, "v2 send called " + count + " times");
this.boilerPlateAsserts(senderSpy66V2V1);
senderSpy66V2V1.restore();
}
]
});
}
private testSnippet(snippetPath) {
var delay = 250;
this.testCaseAsync({
name: "SnippetTests: sprint " + snippetPath + " is loaded",
stepDelay: 50,
steps: [
() => {
this.loadSnippet(snippetPath);
},
() => {
Assert.ok(window[this.name], this.name + " is loaded");
}
]
});
this.testCaseAsync({
name: "SnippetTests: sprint " + snippetPath + " drains the queue",
stepDelay: 250,
steps: [
() => {
this.loadSnippet(snippetPath);
},
() => {
Assert.equal(this.queueCallCount, this.queueSpy.callCount, "queue is emptied");
}
]
});
this.testCaseAsync({
name: "SnippetTests: sprint " + snippetPath + " configuration is read dynamically",
stepDelay: delay,
steps: [
() => {
this.loadSnippet(snippetPath);
},
this.checkConfig
]
});
var sender;
this.testCaseAsync({
name: "SnippetTests: sprint " + snippetPath + " can send to v2 endpoint with V2 API",
stepDelay: delay,
steps: [
() => {
this.loadSnippet(snippetPath);
},
() => {
sender = this.setAppInsights();
window[this.name].trackEvent("test");
window[this.name].trackException(new Error("oh no!"));
window[this.name].trackMetric("test", Math.round(100 * Math.random()));
window[this.name].trackTrace("test");
window[this.name].trackPageView();
},
() => {
Assert.equal(this.queueCallCount, this.queueSpy.callCount, "queue is emptied");
var count = 5 + this.timingOffset;
Assert.equal(count, sender.sender.callCount, "send called " + count + " times");
this.boilerPlateAsserts(sender);
sender.restore();
}
]
});
}
private checkConfig() {
var initial = window[this.name];
var test = (expected, memberName, readFunction) => {
var appIn = <Microsoft.ApplicationInsights.AppInsights>window[this.name];
appIn.config[memberName] = expected;
var actual = readFunction();
Assert.equal(expected, actual, memberName + ": value is read dynamically");
};
var testSenderValues = (expected, memberName) => {
var appIn = <Microsoft.ApplicationInsights.AppInsights>window[this.name];
test(expected, memberName, appIn.context._sender._config[memberName]);
};
var testContextValues = (expected, memberName) => {
var appIn = <Microsoft.ApplicationInsights.AppInsights>window[this.name];
test(expected, memberName, appIn.context._config[memberName]);
};
// sender values
testSenderValues(10, "maxBatchInterval");
testSenderValues(10, "maxBatchSizeInBytes");
testSenderValues(10, "endpointUrl");
testSenderValues(false, "disableTelemetry");
// context values
testContextValues("instrumentationKey", "instrumentationKey");
testContextValues("accountId", "accountId");
testContextValues("appUserId", "appUserId");
// logging
test(true, "enableDebug", Microsoft.ApplicationInsights._InternalLogging.enableDebugExceptions);
}
private setAppInsights() {
window["appInsights"].endpointUrl = "http://dc-int.services.visualstudio.com/v2/track";
window["appInsights"].maxBatchInterval = 1;
var appIn = <Microsoft.ApplicationInsights.AppInsights>window[this.name];
var sender = sinon.spy(appIn.context._sender, "send");
var errorSpy = sinon.spy(Microsoft.ApplicationInsights.Sender, "_onError");
var successSpy = sinon.spy(Microsoft.ApplicationInsights.Sender, "_onSuccess");
var loggingSpy = sinon.spy(Microsoft.ApplicationInsights._InternalLogging, "throwInternalUserActionable");
return {
sender: sender,
errorSpy: errorSpy,
successSpy: successSpy,
loggingSpy: loggingSpy,
restore: () => {
sender.restore();
errorSpy.restore();
successSpy.restore();
loggingSpy.restore();
}
};
}
private boilerPlateAsserts(spies) {
Assert.ok(spies.successSpy.called, "success handler was called");
Assert.ok(!spies.errorSpy.called, "no error sending");
var isValidCallCount = spies.loggingSpy.callCount === 0;
Assert.ok(isValidCallCount, "logging spy was called 0 time(s)");
if (!isValidCallCount) {
while (spies.loggingSpy.args.length) {
Assert.ok(false, "[warning thrown]: " + spies.loggingSpy.args.pop());
}
}
}
}
new SnippetTests().registerTests();

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

@ -0,0 +1,63 @@
window.appInsights = {
queue: [],
applicationInsightsId: null,
accountId: null,
appUserId: null,
configUrl: null,
start: function (appId) {
// Assigning these to local variables allows them to be minified to save space:
var localDocument = document;
var localAppInsights = this;
localAppInsights.applicationInsightsId = appId;
function createLazyMethod(methodName) {
// Define a temporary method that queues-up a the real method call
localAppInsights[methodName] = function () {
// Capture the original arguments passed to the method
var originalArguments = arguments;
// Queue-up a call to the real method
localAppInsights.queue.push(function () {
// Invoke the real method with the captured original arguments
localAppInsights[methodName].apply(localAppInsights, originalArguments);
});
}
}
// Note: you can replace this with ["logEvent", "logPageView"].forEach(createLazyMethod) once this list gets larger
// You can also make createLazyMethod anonymous to save more space ([...].forEach(function(methodName) { ... })
createLazyMethod("logEvent");
createLazyMethod("logPageView");
var scriptText = "script";
function createScriptElement(url, loadFunc) {
if (!url) {
loadFunc();
} else {
var scriptElement = localDocument.createElement(scriptText);
scriptElement.type = "text/javascript";
scriptElement.src = url;
scriptElement.async = true;
scriptElement.onload = loadFunc;
localDocument.getElementsByTagName(scriptText)[0].parentNode.appendChild(scriptElement);
}
}
// Here's how this works: this code will first try and load the config file asynchronously.
// If configUrl is null / undefined, it will just invoke the anonymous function instantly. Otherwise
// it will set it as the event handler for onload and onerror. If configUrl is defined, then this
// function will be called after the config file is loaded. The handler just adds the ai.js file
// to the page so that it's loaded asynchronously. Note that there is no need to pass in a loadFunc
// because the url is set. This is a bit of a hack, but it saves some space in minification.
createScriptElement(localAppInsights.configUrl, function () {
createScriptElement("//az639152.vo.msecnd.net/sdk/a/ai.0.10.js");
});
// Don't load a second time:
localAppInsights.start = function () { }
}
};
appInsights.start();
appInsights.logPageView();

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

@ -0,0 +1,38 @@
window.appInsights = window.appInsights || (function (aiConfig) {
// Assigning these to local variables allows them to be minified to save space:
var localDocument = document;
var localWindow = window;
var scriptText = "script";
var scriptElement = localDocument.createElement(scriptText);
scriptElement.src = aiConfig.url || "CDN_PATH";
localDocument.getElementsByTagName(scriptText)[0].parentNode.appendChild(scriptElement);
// capture initial cookie
aiConfig.cookie = localDocument.cookie;
aiConfig.queue = [];
function createLazyMethod(name) {
// Define a temporary method that queues-up a the real method call
aiConfig[name] = function () {
// Capture the original arguments passed to the method
var originalArguments = arguments;
// Queue-up a call to the real method
aiConfig.queue.push(function () {
// Invoke the real method with the captured original arguments
aiConfig[name].apply(aiConfig, originalArguments);
});
}
};
var method = ["Event", "Exception", "Metric", "PageView", "Trace"];
while (method.length) {
createLazyMethod("track" + method.pop());
}
return aiConfig;
})({
iKey: "INSTRUMENTATION_KEY"
});
appInsights.trackPageView();

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

@ -0,0 +1,3 @@
This test can be run for E2E validation of our SDK on CDN along with each version of the snippet. In order to check back-compat with older browsers it is necessary to host the directory in IIS.
To toggle between targetting prod/int/dev update the variables in PostBuild.ps1

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

@ -0,0 +1,25 @@
<html>
<head>
<style type="text/css">
.success {
background: #00cc00;
word-wrap: break-word;
}
.failure {
background: #cc0000;
word-wrap: break-word;
}
li:hover {
cursor: pointer;
opacity: 0.9;
}
</style>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<script type="text/javascript" src="../../External/jquery-1.11.1.js"></script>
<script type="text/javascript" src="sprint66Snippet.js"></script>
</head>
<body>
<h3>Tests for sprint 66 snippet</h3>
<script type="text/javascript" src="tests.js"></script>
</body>
</html>

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

@ -0,0 +1,25 @@
<html>
<head>
<style type="text/css">
.success {
background: #00cc00;
word-wrap: break-word;
}
.failure {
background: #cc0000;
word-wrap: break-word;
}
li:hover {
cursor: pointer;
opacity: 0.9;
}
</style>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<script type="text/javascript" src="../../External/jquery-1.11.1.js"></script>
<script type="text/javascript" src="sprint69Snippet.js"></script>
</head>
<body>
<h3>Tests for sprint 69 snippet</h3>
<script type="text/javascript" src="tests.js"></script>
</body>
</html>

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

@ -0,0 +1,25 @@
<html>
<head>
<style type="text/css">
.success {
background: #00cc00;
word-wrap: break-word;
}
.failure {
background: #cc0000;
word-wrap: break-word;
}
li:hover {
cursor: pointer;
opacity: 0.9;
}
</style>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<script type="text/javascript" src="../../External/jquery-1.11.1.js"></script>
<script type="text/javascript" src="sprint70Snippet.js"></script>
</head>
<body>
<h3>Tests for sprint 70 snippet</h3>
<script type="text/javascript" src="tests.js"></script>
</body>
</html>

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

@ -0,0 +1,39 @@
<html>
<head>
<style type="text/css">
.frames {
position: absolute;
top: 60px;
bottom: 0;
left: 0;
right: 0;
}
.frame {
position: relative;
width: 50%;
height: 100%;
display: block;
float: left;
}
iframe {
width: 100%;
height: 100%;
margin: -4px;
}
</style>
</head>
<body>
<h1>Test Application Insights Javascript SDK</h1>
<div class="frames">
<div class="frame">
<iframe id="sprint70" src='sprint70.html'></iframe>
</div>
<div class="frame">
<iframe id="sprint69" src='sprint69.html'></iframe>
</div>
<div class="frame">
<iframe id="sprint66" src='sprint66.html'></iframe>
</div>
</div>
</body>
</html>

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

@ -0,0 +1,31 @@
window.appInsights = {
config: {
instrumentationKey: "INSTRUMENTATION_KEY",
url: "CDN_URL",
endpointUrl: "ENDPOINT_URL",
maxBatchInterval: 0,
},
queue: [
function () {
console.log('from the queue');
},
function () {
console.log('from the queue');
},
function () {
console.log('from the queue');
},
function () {
console.log('from the queue');
},
function () {
console.log('from the queue');
},
function () {
console.log('from the queue');
},
function () {
console.log('from the queue');
}
]
}

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

@ -0,0 +1,80 @@
var time = new Date().getTime().toString();
var url = document.location.href;
var tests = [
{
name: "appInsights is loaded",
test: function() {
return !!appInsights;
}
}, {
name: "appInsights queue is emptied",
test: function() {
return !appInsights.queue;
}
}, {
name: "V1 API log event",
test: function() {
appInsights.bufferMinInterval = 0;
appInsights.bufferMaxInterval = 1;
appInsights.bufferSize = 10;
return !appInsights.logEvent(url + " test app " + time);
}
}, {
name: "V1 API log page",
test: function() {
return !appInsights.logPageView(url + " test app " + time);
}
}, {
name: "V2 API trackEvent",
test: function() {
return appInsights.trackEvent(url + " test app " + time);
}
}, {
name: "V2 API trackException",
test: function() {
return appInsights.trackException(new Error(url + " test app " + time));
}
}, {
name: "V2 API trackMetric",
test: function() {
return appInsights.trackMetric(url + " test app " + time, Math.round(100 * Math.random()));
}
}, {
name: "V2 API trackTrace",
test: function() {
return appInsights.trackTrace(url + " test app " + time);
}
}, {
name: "V2 API trackPageView",
test: function() {
return appInsights.trackPageView();
}
}
];
// execute test cases and display results
$('body').append('<ol id="results">');
setTimeout(function() {
for (var i = 0; i < tests.length; i++) {
var test = function(input, div) {
var result = true;
try {
input.test();
} catch (e) {
console.error(e.toString());
result = false;
}
div.toggleClass("success", !!result);
div.toggleClass("failure", !result);
}
var input = tests[i];
var li = $('<li class="success">' + input.name + '</li>');
var proxy = $.proxy(test, this, input, li);
proxy();
li.click(proxy);
$('#results').append(li);
}
}, 500);

10308
JavaScript/JavaScriptSDK.Tests/External/jquery-1.11.1.js поставляемый Normal file

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

3926
JavaScript/JavaScriptSDK.Tests/External/jquery.d.ts поставляемый Normal file

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

723
JavaScript/JavaScriptSDK.Tests/External/qunit.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,723 @@
// Type definitions for QUnit 1.10
// Project: http://qunitjs.com/
// Definitions by: Diullei Gomes <https://github.com/diullei>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
interface DoneCallbackObject {
/**
* The number of failed assertions
*/
failed: number;
/**
* The number of passed assertions
*/
passed: number;
/**
* The total number of assertions
*/
total: number;
/**
* The time in milliseconds it took tests to run from start to finish.
*/
runtime: number;
}
interface LogCallbackObject {
/**
* The boolean result of an assertion, true means passed, false means failed.
*/
result: boolean;
/**
* One side of a comparision assertion. Can be undefined when ok() is used.
*/
actual: Object;
/**
* One side of a comparision assertion. Can be undefined when ok() is used.
*/
expected: Object;
/**
* A string description provided by the assertion.
*/
message: string;
/**
* The associated stacktrace, either from an exception or pointing to the source
* of the assertion. Depends on browser support for providing stacktraces, so can be
* undefined.
*/
source: string;
}
interface ModuleStartCallbackObject {
/**
* Name of the next module to run
*/
name: string;
}
interface ModuleDoneCallbackObject {
/**
* Name of this module
*/
name: string;
/**
* The number of failed assertions
*/
failed: number;
/**
* The number of passed assertions
*/
passed: number;
/**
* The total number of assertions
*/
total: number;
}
interface TestDoneCallbackObject {
/**
* TName of the next test to run
*/
name: string;
/**
* Name of the current module
*/
module: string;
/**
* The number of failed assertions
*/
failed: number;
/**
* The number of passed assertions
*/
passed: number;
/**
* The total number of assertions
*/
total: number;
/**
* The total runtime, including setup and teardown
*/
duration: number;
}
interface TestStartCallbackObject {
/**
* Name of the next test to run
*/
name: string;
/**
* Name of the current module
*/
module: string;
}
interface Config {
altertitle: boolean;
autostart: boolean;
current: Object;
reorder: boolean;
requireExpects: boolean;
testTimeout: number;
urlConfig: Array<URLConfigItem>;
done: any;
}
interface URLConfigItem {
id: string;
label: string;
tooltip: string;
}
interface LifecycleObject {
/**
* Runs before each test
*/
setup?: () => any;
/**
* Runs after each test
*/
teardown?: () => any;
}
interface QUnitAssert {
/* ASSERT */
assert: any;
current_testEnvironment: any;
jsDump: any;
/**
* A deep recursive comparison assertion, working on primitive types, arrays, objects,
* regular expressions, dates and functions.
*
* The deepEqual() assertion can be used just like equal() when comparing the value of
* objects, such that { key: value } is equal to { key: value }. For non-scalar values,
* identity will be disregarded by deepEqual.
*
* @param actual Object or Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
deepEqual(actual: any, expected: any, message?: string): any;
/**
* A non-strict comparison assertion, roughly equivalent to JUnit assertEquals.
*
* The equal assertion uses the simple comparison operator (==) to compare the actual
* and expected arguments. When they are equal, the assertion passes: any; otherwise, it fails.
* When it fails, both actual and expected values are displayed in the test result,
* in addition to a given message.
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
equal(actual: any, expected: any, message?: string): any;
/**
* An inverted deep recursive comparison assertion, working on primitive types,
* arrays, objects, regular expressions, dates and functions.
*
* The notDeepEqual() assertion can be used just like equal() when comparing the
* value of objects, such that { key: value } is equal to { key: value }. For non-scalar
* values, identity will be disregarded by notDeepEqual.
*
* @param actual Object or Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
notDeepEqual(actual: any, expected: any, message?: string): any;
/**
* A non-strict comparison assertion, checking for inequality.
*
* The notEqual assertion uses the simple inverted comparison operator (!=) to compare
* the actual and expected arguments. When they aren't equal, the assertion passes: any;
* otherwise, it fails. When it fails, both actual and expected values are displayed
* in the test result, in addition to a given message.
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
notEqual(actual: any, expected: any, message?: string): any;
notPropEqual(actual: any, expected: any, message?: string): any;
propEqual(actual: any, expected: any, message?: string): any;
/**
* A non-strict comparison assertion, checking for inequality.
*
* The notStrictEqual assertion uses the strict inverted comparison operator (!==)
* to compare the actual and expected arguments. When they aren't equal, the assertion
* passes: any; otherwise, it fails. When it fails, both actual and expected values are
* displayed in the test result, in addition to a given message.
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
notStrictEqual(actual: any, expected: any, message?: string): any;
/**
* A boolean assertion, equivalent to CommonJSs assert.ok() and JUnits assertTrue().
* Passes if the first argument is truthy.
*
* The most basic assertion in QUnit, ok() requires just one argument. If the argument
* evaluates to true, the assertion passes; otherwise, it fails. If a second message
* argument is provided, it will be displayed in place of the result.
*
* @param state Expression being tested
* @param message A short description of the assertion
*/
ok(state: any, message?: string): any;
/**
* A strict type and value comparison assertion.
*
* The strictEqual() assertion provides the most rigid comparison of type and value with
* the strict equality operator (===)
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
strictEqual(actual: any, expected: any, message?: string): any;
/**
* Assertion to test if a callback throws an exception when run.
*
* When testing code that is expected to throw an exception based on a specific set of
* circumstances, use throws() to catch the error object for testing and comparison.
*
* @param block Function to execute
* @param expected Error Object to compare
* @param message A short description of the assertion
*/
throws(block: () => any, expected: any, message?: string): any;
/**
* @param block Function to execute
* @param message A short description of the assertion
*/
throws(block: () => any, message?: string): any;
}
interface QUnitStatic extends QUnitAssert{
/* ASYNC CONTROL */
/**
* Start running tests again after the testrunner was stopped. See stop().
*
* When your async test has multiple exit points, call start() for the corresponding number of stop() increments.
*
* @param decrement Optional argument to merge multiple start() calls into one. Use with multiple corrsponding stop() calls.
*/
start(decrement?: number): any;
/**
* Stop the testrunner to wait for async tests to run. Call start() to continue.
*
* When your async test has multiple exit points, call stop() with the increment argument, corresponding to the number of start() calls you need.
*
* On Blackberry 5.0, window.stop is a native read-only function. If you deal with that browser, use QUnit.stop() instead, which will work anywhere.
*
* @param decrement Optional argument to merge multiple stop() calls into one. Use with multiple corrsponding start() calls.
*/
stop(increment? : number): any;
/* CALLBACKS */
/**
* Register a callback to fire whenever the test suite begins.
*
* QUnit.begin() is called once before running any tests. (a better would've been QUnit.start,
* but thats already in use elsewhere and can't be changed.)
*
* @param callback Callback to execute
*/
begin(callback: () => any): any;
/**
* Register a callback to fire whenever the test suite ends.
*
* @param callback Callback to execute.
*/
done(callback: (details: DoneCallbackObject) => any): any;
/**
* Register a callback to fire whenever an assertion completes.
*
* This is one of several callbacks QUnit provides. Its intended for integration scenarios like
* PhantomJS or Jenkins. The properties of the details argument are listed below as options.
*
* @param callback Callback to execute.
*/
log(callback: (details: LogCallbackObject) => any): any;
/**
* Register a callback to fire whenever a module ends.
*
* @param callback Callback to execute.
*/
moduleDone(callback: (details: ModuleDoneCallbackObject) => any): any;
/**
* Register a callback to fire whenever a module begins.
*
* @param callback Callback to execute.
*/
moduleStart(callback: (details: ModuleStartCallbackObject) => any): any;
/**
* Register a callback to fire whenever a test ends.
*
* @param callback Callback to execute.
*/
testDone(callback: (details: TestDoneCallbackObject) => any): any;
/**
* Register a callback to fire whenever a test begins.
*
* @param callback Callback to execute.
*/
testStart(callback: (details: TestStartCallbackObject) => any): any;
/* CONFIGURATION */
/**
* QUnit has a bunch of internal configuration defaults, some of which are
* useful to override. Check the description for each option for details.
*/
config: Config;
/* TEST */
/**
* Add an asynchronous test to run. The test must include a call to start().
*
* For testing asynchronous code, asyncTest will automatically stop the test runner
* and wait for your code to call start() to continue.
*
* @param name Title of unit being tested
* @param expected Number of assertions in this test
* @param test Function to close over assertions
*/
asyncTest(name: string, expected: number, test: () => any): any;
/**
* Add an asynchronous test to run. The test must include a call to start().
*
* For testing asynchronous code, asyncTest will automatically stop the test runner
* and wait for your code to call start() to continue.
*
* @param name Title of unit being tested
* @param test Function to close over assertions
*/
asyncTest(name: string, test: () => any): any;
/**
* Specify how many assertions are expected to run within a test.
*
* To ensure that an explicit number of assertions are run within any test, use
* expect( number ) to register an expected count. If the number of assertions
* run does not match the expected count, the test will fail.
*
* @param amount Number of assertions in this test.
*/
expect(amount: number): any;
/**
* Group related tests under a single label.
*
* All tests that occur after a call to module() will be grouped into that module.
* The test names will all be preceded by the module name in the test results.
* You can then use that module name to select tests to run.
*
* @param name Label for this group of tests
* @param lifecycle Callbacks to run before and after each test
*/
module(name: string, lifecycle?: LifecycleObject): any;
/**
* Add a test to run.
*
* When testing the most common, synchronous code, use test().
* The assert argument to the callback contains all of QUnit's assertion methods.
* If you are avoiding using any of QUnit's globals, you can use the assert
* argument instead.
*
* @param title Title of unit being tested
* @param expected Number of assertions in this test
* @param test Function to close over assertions
*/
test(title: string, expected: number, test: (assert: QUnitAssert) => any): any;
/**
* @param title Title of unit being tested
* @param test Function to close over assertions
*/
test(title: string, test: (assert: QUnitAssert) => any): any;
/**
* https://github.com/jquery/qunit/blob/master/qunit/qunit.js#L1568
*/
equiv(a: any, b: any): any;
// https://github.com/jquery/qunit/blob/master/qunit/qunit.js#L661
raises: any;
/**
* https://github.com/jquery/qunit/blob/master/qunit/qunit.js#L897
*/
push(result: any, actual: any, expected: any, message: string): any;
/**
* https://github.com/jquery/qunit/blob/master/qunit/qunit.js#L839
*/
reset(): any;
}
/* ASSERT */
/**
* A deep recursive comparison assertion, working on primitive types, arrays, objects,
* regular expressions, dates and functions.
*
* The deepEqual() assertion can be used just like equal() when comparing the value of
* objects, such that { key: value } is equal to { key: value }. For non-scalar values,
* identity will be disregarded by deepEqual.
*
* @param actual Object or Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
declare function deepEqual(actual: any, expected: any, message?: string): any;
/**
* A non-strict comparison assertion, roughly equivalent to JUnit assertEquals.
*
* The equal assertion uses the simple comparison operator (==) to compare the actual
* and expected arguments. When they are equal, the assertion passes: any; otherwise, it fails.
* When it fails, both actual and expected values are displayed in the test result,
* in addition to a given message.
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
declare function equal(actual: any, expected: any, message?: string): any;
/**
* An inverted deep recursive comparison assertion, working on primitive types,
* arrays, objects, regular expressions, dates and functions.
*
* The notDeepEqual() assertion can be used just like equal() when comparing the
* value of objects, such that { key: value } is equal to { key: value }. For non-scalar
* values, identity will be disregarded by notDeepEqual.
*
* @param actual Object or Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
declare function notDeepEqual(actual: any, expected: any, message?: string): any;
/**
* A non-strict comparison assertion, checking for inequality.
*
* The notEqual assertion uses the simple inverted comparison operator (!=) to compare
* the actual and expected arguments. When they aren't equal, the assertion passes;
* otherwise, it fails. When it fails, both actual and expected values are displayed
* in the test result, in addition to a given message.
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
declare function notEqual(actual: any, expected: any, message?: string): any;
/**
* A non-strict comparison assertion, checking for inequality.
*
* The notStrictEqual assertion uses the strict inverted comparison operator (!==)
* to compare the actual and expected arguments. When they aren't equal, the assertion
* passes; otherwise, it fails. When it fails, both actual and expected values are
* displayed in the test result, in addition to a given message.
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
declare function notStrictEqual(actual: any, expected: any, message?: string): any;
/**
* A boolean assertion, equivalent to CommonJSs assert.ok() and JUnits assertTrue().
* Passes if the first argument is truthy.
*
* The most basic assertion in QUnit, ok() requires just one argument. If the argument
* evaluates to true, the assertion passes; otherwise, it fails. If a second message
* argument is provided, it will be displayed in place of the result.
*
* @param state Expression being tested
* @param message A short description of the assertion
*/
declare function ok(state: any, message?: string): any;
/**
* A strict type and value comparison assertion.
*
* The strictEqual() assertion provides the most rigid comparison of type and value with
* the strict equality operator (===)
*
* @param actual Expression being tested
* @param expected Known comparison value
* @param message A short description of the assertion
*/
declare function strictEqual(actual: any, expected: any, message?: string): any;
/**
* Assertion to test if a callback throws an exception when run.
*
* When testing code that is expected to throw an exception based on a specific set of
* circumstances, use throws() to catch the error object for testing and comparison.
*
* @param block Function to execute
* @param expected Error Object to compare
* @param message A short description of the assertion
*/
declare function throws(block: () => any, expected: any, message?: string): any;
/**
* @param block Function to execute
* @param message A short description of the assertion
*/
declare function throws(block: () => any, message?: string): any;
/* ASYNC CONTROL */
/**
* Start running tests again after the testrunner was stopped. See stop().
*
* When your async test has multiple exit points, call start() for the corresponding number of stop() increments.
*
* @param decrement Optional argument to merge multiple start() calls into one. Use with multiple corrsponding stop() calls.
*/
declare function start(decrement?: number): any;
/**
* Stop the testrunner to wait for async tests to run. Call start() to continue.
*
* When your async test has multiple exit points, call stop() with the increment argument, corresponding to the number of start() calls you need.
*
* On Blackberry 5.0, window.stop is a native read-only function. If you deal with that browser, use QUnit.stop() instead, which will work anywhere.
*
* @param decrement Optional argument to merge multiple stop() calls into one. Use with multiple corrsponding start() calls.
*/
declare function stop(increment? : number): any;
/* CALLBACKS */
/**
* Register a callback to fire whenever the test suite begins.
*
* QUnit.begin() is called once before running any tests. (a better would've been QUnit.start,
* but thats already in use elsewhere and can't be changed.)
*
* @param callback Callback to execute
*/
declare function begin(callback: () => any): any;
/**
* Register a callback to fire whenever the test suite ends.
*
* @param callback Callback to execute.
*/
declare function done(callback: (details: DoneCallbackObject) => any): any;
/**
* Register a callback to fire whenever an assertion completes.
*
* This is one of several callbacks QUnit provides. Its intended for integration scenarios like
* PhantomJS or Jenkins. The properties of the details argument are listed below as options.
*
* @param callback Callback to execute.
*/
declare function log(callback: (details: LogCallbackObject) => any): any;
/**
* Register a callback to fire whenever a module ends.
*
* @param callback Callback to execute.
*/
declare function moduleDone(callback: (details: ModuleDoneCallbackObject) => any): any;
/**
* Register a callback to fire whenever a module begins.
*
* @param callback Callback to execute.
*/
declare function moduleStart(callback: (name: string) => any): any;
/**
* Register a callback to fire whenever a test ends.
*
* @param callback Callback to execute.
*/
declare function testDone(callback: (details: TestDoneCallbackObject) => any): any;
/**
* Register a callback to fire whenever a test begins.
*
* @param callback Callback to execute.
*/
declare function testStart(callback: (details: TestStartCallbackObject) => any): any;
/* TEST */
/**
* Add an asynchronous test to run. The test must include a call to start().
*
* For testing asynchronous code, asyncTest will automatically stop the test runner
* and wait for your code to call start() to continue.
*
* @param name Title of unit being tested
* @param expected Number of assertions in this test
* @param test Function to close over assertions
*/
declare function asyncTest(name: string, expected?: any, test?: () => any): any;
/**
* Add an asynchronous test to run. The test must include a call to start().
*
* For testing asynchronous code, asyncTest will automatically stop the test runner
* and wait for your code to call start() to continue.
*
* @param name Title of unit being tested
* @param test Function to close over assertions
*/
declare function asyncTest(name: string, test: () => any): any;
/**
* Specify how many assertions are expected to run within a test.
*
* To ensure that an explicit number of assertions are run within any test, use
* expect( number ) to register an expected count. If the number of assertions
* run does not match the expected count, the test will fail.
*
* @param amount Number of assertions in this test.
*/
declare function expect(amount: number): any;
// ** conflict with TypeScript module keyword. Must be used on QUnit namespace
//declare var module: (name: string, lifecycle?: LifecycleObject) => any;
/**
* Add a test to run.
*
* When testing the most common, synchronous code, use test().
* The assert argument to the callback contains all of QUnit's assertion methods.
* If you are avoiding using any of QUnit's globals, you can use the assert
* argument instead.
*
* @param title Title of unit being tested
* @param expected Number of assertions in this test
* @param test Function to close over assertions
*/
declare function test(title: string, expected: number, test: (assert?: QUnitAssert) => any): any;
/**
* @param title Title of unit being tested
* @param test Function to close over assertions
*/
declare function test(title: string, test: (assert?: QUnitAssert) => any): any;
declare function notPropEqual(actual: any, expected: any, message?: string): any;
declare function propEqual(actual: any, expected: any, message?: string): any;
// https://github.com/jquery/qunit/blob/master/qunit/qunit.js#L1568
declare function equiv(a: any, b: any): any;
// https://github.com/jquery/qunit/blob/master/qunit/qunit.js#L661
declare var raises: any;
/* QUNIT */
declare var QUnit: QUnitStatic;

4291
JavaScript/JavaScriptSDK.Tests/External/sinon-1.7.3.js поставляемый Normal file

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

394
JavaScript/JavaScriptSDK.Tests/External/sinon.d.ts поставляемый Normal file
Просмотреть файл

@ -0,0 +1,394 @@
// Type definitions for Sinon 1.5
// Project: http://sinonjs.org/
// Definitions by: William Sears <https://github.com/mrbigdog2u>
// DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped
interface SinonSpyCallApi {
// Properties
thisValue: any;
args: any[];
exception: any;
returnValue: any;
// Methods
calledOn(obj: any): boolean;
calledWith(...args: any[]): boolean;
calledWithExactly(...args: any[]): boolean;
calledWithMatch(...args: SinonMatcher[]): boolean;
notCalledWith(...args: any[]): boolean;
notCalledWithMatch(...args: SinonMatcher[]): boolean;
returned(value: any): boolean;
threw(): boolean;
threw(type: string): boolean;
threw(obj: any): boolean;
callArg(pos: number): void;
callArgOn(pos: number, obj: any, ...args: any[]): void;
callArgWith(pos: number, ...args: any[]): void;
callArgOnWith(pos: number, obj: any, ...args: any[]): void;
yield(...args: any[]): void;
yieldOn(obj: any, ...args: any[]): void;
yieldTo(property: string, ...args: any[]): void;
yieldToOn(property: string, obj: any, ...args: any[]): void;
}
interface SinonSpyCall extends SinonSpyCallApi {
calledBefore(call: SinonSpyCall): boolean;
calledAfter(call: SinonSpyCall): boolean;
calledWithNew(call: SinonSpyCall): boolean;
}
interface SinonSpy extends SinonSpyCallApi {
// Properties
callCount: number;
called: boolean;
notCalled: boolean;
calledOnce: boolean;
calledTwice: boolean;
calledThrice: boolean;
firstCall: SinonSpyCall;
secondCall: SinonSpyCall;
thirdCall: SinonSpyCall;
lastCall: SinonSpyCall;
thisValues: any[];
args: any[][];
exceptions: any[];
returnValues: any[];
// Methods
(...args: any[]): any;
calledBefore(anotherSpy: SinonSpy): boolean;
calledAfter(anotherSpy: SinonSpy): boolean;
calledWithNew(spy: SinonSpy): boolean;
withArgs(...args: any[]): void;
alwaysCalledOn(obj: any);
alwaysCalledWith(...args: any[]);
alwaysCalledWithExactly(...args: any[]);
alwaysCalledWithMatch(...args: SinonMatcher[]);
neverCalledWith(...args: any[]);
neverCalledWithMatch(...args: SinonMatcher[]);
alwaysThrew(): boolean;
alwaysThrew(type: string);
alwaysThrew(obj: any);
alwaysReturned(): boolean;
invokeCallback(...args: any[]): void;
getCall(n: number): SinonSpyCall;
reset(): void;
printf(format: string, ...args: any[]);
restore(): void;
}
interface SinonSpyStatic {
(): SinonSpy;
(func: any): SinonSpy;
(obj: any, method: string): SinonSpy;
}
interface SinonStatic {
spy: SinonSpyStatic;
}
interface SinonStub extends SinonSpy {
resetBehavior(): void;
returns(obj: any): SinonStub;
returnsArg(index: number): SinonStub;
throws(type?: string): SinonStub;
throws(obj: any): SinonStub;
callsArg(index: number): SinonStub;
callsArgOn(index: number, context: any): SinonStub;
callsArgWith(index: number, ...args: any[]): SinonStub;
callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub;
callsArgAsync(index: number): SinonStub;
callsArgOnAsync(index: number, context: any): SinonStub;
callsArgWithAsync(index: number, ...args: any[]): SinonStub;
callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub;
yields(...args: any[]): SinonStub;
yieldsOn(context: any, ...args: any[]): SinonStub;
yieldsTo(property: string, ...args: any[]): SinonStub;
yieldsToOn(property: string, context: any, ...args: any[]): SinonStub;
yieldsAsync(...args: any[]): SinonStub;
yieldsOnAsync(context: any, ...args: any[]): SinonStub;
yieldsToAsync(property: string, ...args: any[]): SinonStub;
yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub;
}
interface SinonStubStatic {
(): SinonStub;
(obj: any): SinonStub;
(obj: any, method: string): SinonStub;
(obj: any, method: string, func: any): SinonStub;
}
interface SinonStatic {
stub: SinonStubStatic;
}
interface SinonExpectation {
atLeast(n: number): SinonExpectation;
atMost(n: number): SinonExpectation;
never(): SinonExpectation;
once(): SinonExpectation;
twice(): SinonExpectation;
thrice(): SinonExpectation;
exactly(n: number): SinonExpectation;
withArgs(...args: any[]): SinonExpectation;
withExactArgs(...args: any[]): SinonExpectation;
on(obj: any): SinonExpectation;
verify(): SinonExpectation;
restore(): void;
}
interface SinonExpectationStatic {
create(methodName?: string): SinonExpectation;
}
interface SinonMock {
expects(method: string): SinonExpectation;
restore(): void;
verify(): void;
}
interface SinonMockStatic {
(): SinonExpectation;
(obj: any): SinonMock;
}
interface SinonStatic {
expectation: SinonExpectationStatic;
mock: SinonMockStatic;
}
interface SinonFakeTimers {
now: number;
create(now: number): SinonFakeTimers;
setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number;
clearTimeout(id: number): void;
setInterval(callback: (...args: any[]) => void, timeout: number, ...args: any[]): number;
clearInterval(id: number): void;
tick(ms: number): number;
reset(): void;
Date(): Date;
Date(year: number): Date;
Date(year: number, month: number): Date;
Date(year: number, month: number, day: number): Date;
Date(year: number, month: number, day: number, hour: number): Date;
Date(year: number, month: number, day: number, hour: number, minute: number): Date;
Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date;
Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date;
restore(): void;
}
interface SinonFakeTimersStatic {
(): SinonFakeTimers;
(...timers: string[]): SinonFakeTimers;
(now: number, ...timers: string[]): SinonFakeTimers;
}
interface SinonStatic {
useFakeTimers: SinonFakeTimersStatic;
clock: SinonFakeTimers;
}
interface SinonFakeXMLHttpRequest {
// Properties
onCreate: (xhr: SinonFakeXMLHttpRequest) => void;
url: string;
method: string;
requestHeaders: any;
requestBody: string;
status: number;
statusText: string;
async: boolean;
username: string;
password: string;
responseXML: Document;
getResponseHeader(header: string): string;
getAllResponseHeaders(): any;
// Methods
restore(): void;
useFilters: boolean;
addFilter(filter: (method, url, async, username, password) => boolean): void;
setResponseHeaders(headers: any): void;
setResponseBody(body: string): void;
respond(status: number, headers: any, body: string): void;
autoRespond(ms: number): void;
}
interface SinonFakeXMLHttpRequestStatic {
(): SinonFakeXMLHttpRequest;
}
interface SinonStatic {
useFakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic;
FakeXMLHttpRequest: SinonFakeXMLHttpRequest;
}
interface SinonFakeServer {
// Properties
autoRespond: boolean;
autoRespondAfter: number;
fakeHTTPMethods: boolean;
getHTTPMethod: (request: SinonFakeXMLHttpRequest) => string;
requests: SinonFakeXMLHttpRequest[];
// Methods
respondWith(body: string): void;
respondWith(response: any[]): void;
respondWith(fn: (SinonFakeXMLHttpRequest) => void): void;
respondWith(url: string, body: string): void;
respondWith(url: string, response: any[]): void;
respondWith(url: string, fn: (SinonFakeXMLHttpRequest) => void): void;
respondWith(method: string, url: string, body: string): void;
respondWith(method: string, url: string, response: any[]): void;
respondWith(method: string, url: string, fn: (SinonFakeXMLHttpRequest) => void): void;
respondWith(url: RegExp, body: string): void;
respondWith(url: RegExp, response: any[]): void;
respondWith(url: RegExp, fn: (SinonFakeXMLHttpRequest) => void): void;
respondWith(method: string, url: RegExp, body: string): void;
respondWith(method: string, url: RegExp, response: any[]): void;
respondWith(method: string, url: RegExp, fn: (SinonFakeXMLHttpRequest) => void): void;
respond(): void;
restore(): void;
}
interface SinonFakeServerStatic {
create(): SinonFakeServer;
}
interface SinonStatic {
fakeServer: SinonFakeServerStatic;
fakeServerWithClock: SinonFakeServerStatic;
}
interface SinonExposeOptions {
snippet?: string;
includeFail?: boolean;
}
interface SinonAssert {
// Properties
failException: string;
fail: (message?: string) => void; // Overridable
pass: (assertion: any) => void; // Overridable
// Methods
notCalled(spy: SinonSpy): void;
called(spy: SinonSpy): void;
calledOnce(spy: SinonSpy): void;
calledTwice(spy: SinonSpy): void;
calledThrice(spy: SinonSpy): void;
callCount(spy: SinonSpy, count: number): void;
callOrder(...spies: SinonSpy[]): void;
calledOn(spy: SinonSpy, obj: any): void;
alwaysCalledOn(spy: SinonSpy, obj: any): void;
calledWith(spy: SinonSpy, ...args: any[]): void;
alwaysCalledWith(spy: SinonSpy, ...args: any[]): void;
neverCalledWith(spy: SinonSpy, ...args: any[]): void;
calledWithExactly(spy: SinonSpy, ...args: any[]): void;
alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void;
calledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void;
alwaysCalledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void;
neverCalledWithMatch(spy: SinonSpy, ...args: SinonMatcher[]): void;
threw(spy: SinonSpy): void;
threw(spy: SinonSpy, exception: string): void;
threw(spy: SinonSpy, exception: any): void;
alwaysThrew(spy: SinonSpy): void;
alwaysThrew(spy: SinonSpy, exception: string): void;
alwaysThrew(spy: SinonSpy, exception: any): void;
expose(obj: any, options?: SinonExposeOptions): void;
}
interface SinonStatic {
assert: SinonAssert;
}
interface SinonMatcher {
and(expr: SinonMatcher): SinonMatcher;
or(expr: SinonMatcher): SinonMatcher;
}
interface SinonMatch {
(value: number): SinonMatcher;
(value: string): SinonMatcher;
(expr: RegExp): SinonMatcher;
(obj: any): SinonMatcher;
(callback: (value: any) => boolean): SinonMatcher;
any: SinonMatcher;
defined: SinonMatcher;
truthy: SinonMatcher;
falsy: SinonMatcher;
boolean: SinonMatcher;
number: SinonMatcher;
string: SinonMatcher;
object: SinonMatcher;
func: SinonMatcher;
array: SinonMatcher;
regexp: SinonMatcher;
date: SinonMatcher;
same(obj: any): SinonMatcher;
typeOf(type: string): SinonMatcher;
instanceOf(type: any): SinonMatcher;
has(property: string, expect?: any): SinonMatcher;
hasOwn(property: string, expect?: any): SinonMatcher;
}
interface SinonStatic {
match: SinonMatch;
}
interface SinonSandboxConfig {
injectInto?: any;
properties?: string[];
useFakeTimers?: any;
useFakeServer?: any;
}
interface SinonSandbox {
args: any[];
clock: SinonFakeTimers;
requests: SinonFakeXMLHttpRequest;
server: SinonFakeServer;
spy(): SinonSpy;
stub(): SinonStub;
mock(): SinonMock;
useFakeTimers: SinonFakeTimers;
useFakeXMLHttpRequest: SinonFakeXMLHttpRequest;
restore(): void;
verifyAndRestore(): void;
}
interface SinonSandboxStatic {
create(): SinonSandbox;
create(config: SinonSandboxConfig): SinonSandbox;
}
interface SinonStatic {
sandbox: SinonSandboxStatic;
}
interface SinonTestConfig {
injectIntoThis?: boolean;
injectInto?: any;
properties?: string[];
useFakeTimers?: boolean;
useFakeServer?: boolean;
}
interface SinonTestWrapper extends SinonSandbox {
(...args: any[]): any;
}
interface SinonStatic {
config: SinonTestConfig;
test(fn: Function): SinonTestWrapper;
testCase(tests: any): any;
}
// Utility overridables
interface SinonStatic {
createStubInstance(constructorFunction: any): any;
format: (obj: any) => string;
log: (message: string) => void;
}
declare var sinon: SinonStatic;

Двоичные данные
JavaScript/JavaScriptSDK.Tests/IEDriverServer.exe Normal file

Двоичный файл не отображается.

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

@ -0,0 +1,223 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), 'Global.props'))\Global.props" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C6CA61F8-4855-4C77-B199-A56BAD047ADB}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ApplicationInsights.Javascript.Tests</RootNamespace>
<AssemblyName>ApplicationInsights.Javascript.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
<ReferencePath>$(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages</ReferencePath>
<IsCodedUITest>False</IsCodedUITest>
<TestProjectType>UnitTest</TestProjectType>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
<SccProjectName>SAK</SccProjectName>
<SccLocalPath>SAK</SccLocalPath>
<SccAuxPath>SAK</SccAuxPath>
<SccProvider>SAK</SccProvider>
<TypeScriptSourceMap>true</TypeScriptSourceMap>
<TypeScriptModuleKind>CommonJS</TypeScriptModuleKind>
<EnableTypeScript>true</EnableTypeScript>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System" />
<Reference Include="System.Drawing" />
<Reference Include="System.ServiceProcess" />
<Reference Include="WebDriver, Version=2.43.1.0, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\packages\Selenium.WebDriver.2.43.1\lib\net40\WebDriver.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Selenium\IISExpress.cs" />
<Compile Include="Selenium\Tests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="E2ETests\policheck\run.cmd" />
<None Include="chutzpah.json" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<None Include="E2ETests\PostBuild.ps1" />
<Content Include="E2ETests\autoCollectionTemplates\instrumentation.js" />
<Content Include="E2ETests\standalone\legacySnippet.js" />
<Content Include="E2ETests\ai.js">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\sprint66Snippet.js">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\sprint69Snippet.js">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\sprint70Snippet.js">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\standalone\legacySnippetSprint69.js" />
<Content Include="E2ETests\standalone\sprint70.html" />
<Content Include="E2ETests\standalone\testSnippet.js" />
<Content Include="E2ETests\testSnippet.js">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\errorDom.html">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\errorScriptGlobal.html">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\errorScriptNested.html">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
<Content Include="E2ETests\errorScriptSyntax.html">
<DependentUpon>PostBuild.ps1</DependentUpon>
</Content>
</ItemGroup>
<ItemGroup>
<Content Include="E2ETests\autoCollectionTemplates\errorDom.html" />
<Content Include="E2ETests\autoCollectionTemplates\errorScriptGlobal.html" />
<Content Include="E2ETests\autoCollectionTemplates\errorScriptNested.html" />
<Content Include="E2ETests\autoCollectionTemplates\errorScriptSyntax.html" />
<Content Include="E2ETests\policheck\task.xml" />
<Content Include="External\jquery-1.11.1.js" />
<Content Include="E2ETests\standalone\readme.txt" />
<Content Include="E2ETests\standalone\sprint66.html" />
<Content Include="E2ETests\standalone\sprint69.html" />
<Content Include="E2ETests\standalone\test.html" />
<Content Include="E2ETests\standalone\tests.js" />
<Content Include="Performance\readme.txt" />
<Content Include="Selenium\testPageNoAppInsights.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Selenium\testPageWithAppInsights.html">
<DependentUpon>testPageNoAppInsights.html</DependentUpon>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Selenium\JSLitmus.js">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="External\sinon-1.7.3.js" />
<Content Include="chromedriver.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="IEDriverServer.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="README.txt" />
<Content Include="Selenium\PerfTests.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="Selenium\Tests.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JavaScriptSDK\JavaScriptSDK.csproj">
<Project>{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}</Project>
<Name>JavaScriptSDK</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="External\qunit.d.ts" />
<Content Include="External\sinon.d.ts" />
<Content Include="TestFramework\Assert.ts" />
<Content Include="TestFramework\Common.ts" />
<Content Include="TestFramework\TestCase.ts" />
<Content Include="TestFramework\TestClass.ts" />
<TypeScriptCompile Include="CheckinTests\appInsights.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Initialization.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Telemetry\DataSanitizer.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Telemetry\PageViewPerformance.tests.ts" />
<TypeScriptCompile Include="Contracts\Generated\Base.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\ContextTagKeys.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\Data.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\DataPoint.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\Envelope.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\EventData.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\ExceptionData.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\ExceptionDetails.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\MessageData.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\MetricData.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\PageViewData.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\PageViewPerfData.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\SessionStateData.unittests.ts" />
<TypeScriptCompile Include="Contracts\Generated\StackFrame.unittests.ts" />
<TypeScriptCompile Include="E2ETests\autoCollection.tests.ts" />
<TypeScriptCompile Include="E2ETests\DisableTelemetryTests.ts" />
<TypeScriptCompile Include="E2ETests\SanitizerE2E.tests.ts" />
<TypeScriptCompile Include="E2ETests\snippet.tests.ts" />
<TypeScriptCompile Include="External\jquery.d.ts" />
<TypeScriptCompile Include="Performance\api.perftests.ts" />
<TypeScriptCompile Include="Performance\pageLoad.perftests.ts" />
<TypeScriptCompile Include="Performance\serializer.perftests.ts" />
<TypeScriptCompile Include="TestFramework\ContractTestHelper.ts" />
<TypeScriptCompile Include="E2ETests\PublicApiTests.ts" />
<TypeScriptCompile Include="CheckinTests\Logging.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Sender.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Serializer.tests.ts" />
<TypeScriptCompile Include="CheckinTests\TelemetryContext.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Context\Session.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Context\User.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Telemetry\Event.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Telemetry\Exception.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Telemetry\Metric.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Telemetry\PageView.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Telemetry\Trace.tests.ts" />
<TypeScriptCompile Include="CheckinTests\Util.tests.ts" />
<TypeScriptCompile Include="TestFramework\PerformanceTestHelper.ts" />
</ItemGroup>
<ItemGroup>
<SeleniumCheckinTests Include="Selenium\checkinTests.ts" />
<SeleniumPerformance Include="Selenium\performanceTests.ts" />
<Content Include="Selenium\checkinTests.js">
<DependentUpon>checkinTests.ts</DependentUpon>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="Selenium\performanceTests.js">
<DependentUpon>performanceTests.ts</DependentUpon>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="E2ETests\policheck\targets\" />
</ItemGroup>
<Import Project="$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets" Condition="Exists('$(VSToolsPath)\TeamTest\Microsoft.TestTools.targets')" />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="BeforeBuild">
<Message Text="Compiling TypeScript files" />
<Exec Command="tsc --module CommonJS @(SeleniumCheckinTests ->'&quot;%(fullpath)&quot;', ' ') --out Selenium\checkinTests.js" />
<Exec Command="tsc --module CommonJS @(SeleniumPerformance ->'&quot;%(fullpath)&quot;', ' ') --out Selenium\performanceTests.js" />
<Exec Command="Powershell.exe -ExecutionPolicy ByPass -File &quot;$(ProjectDir)E2ETests\PostBuild.ps1&quot; -projectDir $(ProjectDir)" />
</Target>
<PropertyGroup>
<PreBuildEvent>
</PreBuildEvent>
</PropertyGroup>
</Project>

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

@ -0,0 +1,34 @@
/// <reference path="../testframework/performancetesthelper.ts" />
class ApiPerfTests extends PerformanceTestHelper {
public registerTests() {
this.testCaseAsync({
name: "perf: Test API methods",
stepDelay: 30 * 1000,
steps: [
() => {
var error = new Error("test error");
// appInsights
this.enqueueTest("appInsights.trackEvent", () => this.appInsights.trackEvent("ev", this.testProperties, this.testMeasurements));
this.enqueueTest("appInsights.trackException", () => this.appInsights.trackException(error, null, this.testProperties, this.testMeasurements));
this.enqueueTest("appInsights.trackMetric", () => this.appInsights.trackMetric("m", 1, this.testProperties, this.testMeasurements));
this.enqueueTest("appInsights.trackPageView", () => this.appInsights.trackPageView("name", "url", this.testProperties, this.testMeasurements));
this.enqueueTest("appInsights.trackTrace", () => this.appInsights.trackTrace("t", this.testProperties, this.testMeasurements));
// context
var telemetry = new Microsoft.ApplicationInsights.Telemetry.Trace("trace");
var data = new Microsoft.ApplicationInsights.Telemetry.Common.Data(Microsoft.ApplicationInsights.Telemetry.Trace.dataType, telemetry);
var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, Microsoft.ApplicationInsights.Telemetry.Trace.envelopeType);
this.enqueueTest("appInsights.context.track", () => this.appInsights.context.track(envelope));
this.runTests();
},
() => this.onTimeout()
]
});
}
}
new ApiPerfTests().registerTests();

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

@ -0,0 +1,179 @@
/// <reference path="../testframework/performancetesthelper.ts" />
class PageLoadPerfTests extends PerformanceTestHelper {
/** Turns on/off sinon's syncronous implementation of setTimeout. On by default. */
public errorSpy: SinonSpy;
/** Method called before the start of each test method */
public testInitialize() {
this.useFakeTimers = false;
this.clock.restore();
this.errorSpy = this.getListener();
}
public registerTests() {
var detect = this.detectPlatformAndOs();
var platform = detect.platform;
var os = detect.os;
var results = [];
var firstDone = false;
var secondDone = false;
var delay = 100;
this.testCaseAsync({
name: "perf: testPageNoAppInsights",
stepDelay: delay,
steps: [
() => {
// load once to avoid network delays
this.loadPageToIFrame("testPageNoAppInsights");
},
() => {
this.errorSpy.reset();
this.loadPageToIFrame("testPageNoAppInsights");
}
].concat(this.poll(() => {
if (this.errorSpy.called) {
var timing = JSON.parse(this.errorSpy.args[0][0].data);
results.push({
name: "pageLoad.noAppInsights",
time: timing.loadEventEnd - timing.navigationStart,
count: 1,
period: 1,
date: +new Date,
platform: platform,
os: os
});
this.errorSpy.reset();
Assert.ok(true, "collected page load time");
firstDone = true;
if (firstDone && secondDone) {
JSLitmus._tests = results;
this.onTestsComplete();
} else {
return true;
}
} else {
return false
}
}))
});
this.testCaseAsync({
name: "perf: testPageWithAppInsights",
stepDelay: delay,
steps: [
() => {
// load once to avoid network delays
this.loadPageToIFrame("testPageNoAppInsights");
},
() => {
this.errorSpy.reset();
this.loadPageToIFrame("testPageWithAppInsights");
}
].concat(this.poll(() => {
if (this.errorSpy.called) {
var timing = JSON.parse(this.errorSpy.args[0][0].data);
results.push({
name: "pageLoad.withAppInsights",
time: timing.loadEventEnd - timing.navigationStart,
count: 1,
period: 1,
date: +new Date,
platform: platform,
os: os
});
this.errorSpy.reset();
Assert.ok(true, "collected page load time");
secondDone = true;
if (firstDone && secondDone) {
JSLitmus._tests = results;
this.onTestsComplete();
} else {
return true;
}
} else {
return false
}
}))
});
}
private poll(func: () => boolean, count: number = 50) {
var polling = [];
if (typeof window != "undefined" && window.performance && window.performance.timing) {
for (var i = 0; i < count; i++) {
polling.push(() => {
if (func()) {
Assert.ok(true, "validated, stopping poll cycle");
start();
}
});
}
polling.push(() => {
Assert.ok(false, "timeout reached");
this.onTestsComplete();
});
} else {
polling.push(() => {
Assert.ok(true, "this browser does not support page timing (window.performance.timing)");
});
}
return polling;
}
private detectPlatformAndOs() {
// Get platform info but don't go crazy trying to recognize everything
// that's out there. This is just for the major platforms and OSes.
var platform = 'unknown platform', ua = navigator.userAgent;
// Detect OS
var oses = ['Windows', 'iPhone OS', '(Intel |PPC )?Mac OS X', 'Linux'].join('|');
var pOS = new RegExp('((' + oses + ') [^ \);]*)').test(ua) ? RegExp.$1 : null;
if (!pOS) pOS = new RegExp('((' + oses + ')[^ \);]*)').test(ua) ? RegExp.$1 : null;
// Detect browser
var pName = /(Chrome|MSIE|Safari|Opera|Firefox)/.test(ua) ? RegExp.$1 : null;
// Detect version
var vre = new RegExp('(Version|' + pName + ')[ \/]([^ ;]*)');
var pVersion = (pName && vre.test(ua)) ? RegExp.$2 : null;
var platform = (pOS && pName && pVersion) ? pName + ' ' + pVersion + ' on ' + pOS : 'unknown platform';
return { platform: platform, os: pOS };
}
private getListener(): SinonSpy {
var listener = { onMessage: (data) => null };
var spy = sinon.spy(listener, "onMessage");
if (window.addEventListener) {
addEventListener("message", listener.onMessage, false);
} else {
attachEvent("onmessage", listener.onMessage);
}
return spy;
}
private loadPageToIFrame(path) {
window["appInsights"] = undefined;
var href = window.location.href.toLowerCase();
var replace = href.indexOf("performance") >= 0 ? "performance" : "selenium";
var fullPath = href.split(replace)[0] + "selenium/" + path + ".html";
var iframe = document.createElement("iframe");
iframe.src = fullPath;
iframe.width = "100%";
iframe.height = "250px";
iframe.id = path;
document.getElementsByTagName("body")[0].parentNode.appendChild(iframe);
return iframe;
}
}
new PageLoadPerfTests().registerTests();

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

@ -0,0 +1 @@


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

@ -0,0 +1,45 @@
/// <reference path="../testframework/performancetesthelper.ts" />
/// <reference path="../../JavaScriptSDK/Serializer.ts" />
class SerializerPerfTests extends PerformanceTestHelper {
public registerTests() {
this.testCaseAsync({
name: "perf: Serializer methods",
stepDelay: 160 * 1000,
steps: [
() => {
var error = new Error("test error");
var pageView = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", undefined);
var pageViewPerformance = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", undefined, 42);
var metric = new Microsoft.ApplicationInsights.Telemetry.Metric("metric name", 42);
var exception = new Microsoft.ApplicationInsights.Telemetry.Exception(error, "unhandled");
var event = new Microsoft.ApplicationInsights.Telemetry.Event("event name");
var trace = new Microsoft.ApplicationInsights.Telemetry.Trace("this is a trace");
var pageViewPropsMeas = new Microsoft.ApplicationInsights.Telemetry.PageView("page name", undefined, this.testProperties, this.testMeasurements);
var pageViewPerformancePropsMeas = new Microsoft.ApplicationInsights.Telemetry.PageViewPerformance("page name", undefined, 42, this.testProperties, this.testMeasurements);
var exceptionPropsMeas = new Microsoft.ApplicationInsights.Telemetry.Exception(error, "unhandled", this.testProperties, this.testMeasurements);
var eventPropsMeas = new Microsoft.ApplicationInsights.Telemetry.Event("event name", this.testProperties, this.testMeasurements);
var tracePropsMeas = new Microsoft.ApplicationInsights.Telemetry.Trace("this is a trace", this.testProperties);
this._enqueueTest("serializer.serialize(pageView)", pageView);
this._enqueueTest("serializer.serialize(pageViewPerformance)", pageViewPerformance);
this._enqueueTest("serializer.serialize(metric)", metric);
this._enqueueTest("serializer.serialize(exception)", exception);
this._enqueueTest("serializer.serialize(event)", event);
this._enqueueTest("serializer.serialize(trace)", trace);
this.runTests();
},
() => this.onTimeout()
]
});
}
private _enqueueTest(name, telemetry: Microsoft.ApplicationInsights.ISerializable) {
//telemetry.iKey = "fakeIKey";
this.enqueueTest(name, () => Microsoft.ApplicationInsights.Serializer.serialize(telemetry));
}
}
new SerializerPerfTests().registerTests();

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

@ -0,0 +1,23 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ApplicationInsights.Javascript.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft Corp.")]
[assembly: AssemblyProduct("ApplicationInsights.Javascript.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft Corp. 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3eb898a8-3258-4ce2-9c50-2a8c046b2a59")]

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

@ -0,0 +1,6 @@
Checked-in EXEs are required in order to run tests for the Chrome and Internet Explorer browsers
through Selenium's WebDriver. These must be copied to the output directory (or otherwise be located
somewhere in the global PATH) in order for WebDriver to find them.
The latest IEDriverServer.exe is published at http://code.google.com/p/selenium/downloads/list
The latest ChromeDriver.exe is published at http://chromedriver.storage.googleapis.com/index.html

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

@ -0,0 +1,167 @@
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace ApplicationInsights.Javascript.Tests
{
/// <summary>
/// Wrapper for starting up IIS Express to host test files.
/// </summary>
internal class IISExpress
{
private Process process;
private readonly string path;
private readonly int port;
/// <summary>
/// Constructor that specifies the path to the project and the port number to listen on.
/// </summary>
/// <param name="path">Path to root of local server</param>
/// <param name="port">Port to listen for HTTP requests</param>
internal IISExpress(string path, int port)
{
this.path = path;
this.port = port;
}
/// <summary>
/// Starts IIS express
/// </summary>
/// <returns></returns>
internal bool Start()
{
Debug.Assert(this.process == null, "IIS Express was already started");
string iisExpress = FindIISExpress();
if (string.IsNullOrEmpty(iisExpress))
{
return false;
}
this.process = Process.Start(new ProcessStartInfo()
{
FileName = iisExpress,
Arguments = string.Format("/path:\"{0}\" /port:{1}", this.path, this.port),
RedirectStandardInput = true,
RedirectStandardOutput = true,
CreateNoWindow = false,
UseShellExecute = false,
});
StringBuilder data = new StringBuilder();
char[] buffer = new char[1024];
while (!IsRunning(data.ToString()) && !FailedToRun(data.ToString()))
{
int r = this.process.StandardOutput.Read(buffer, 0, 1024);
data.Append(buffer, 0, r);
}
if (!IsRunning(data.ToString()))
{
Stop();
return false;
}
this.process.StandardOutput.Close();
return true;
}
internal void Stop()
{
if (this.process != null)
{
this.process.StandardInput.Write("Q\r\n");
this.process.StandardInput.Flush();
this.process.StandardInput.Close();
this.process.WaitForExit(4000);
if (!this.process.HasExited)
{
this.process.Kill();
}
using (this.process)
{
this.process = null;
}
}
}
private static bool IsRunning(string consoleOutput)
{
// Add more strings here if they change in different versions of iisexpress
return consoleOutput.Contains("IIS Express is running") || consoleOutput.ToUpperInvariant().Contains("SUCCESSFULLY REGISTERED URL");
}
private static bool FailedToRun(string consoleOutput)
{
// Add more strings here if they change in different versions of iisexpress
return consoleOutput.Contains("Unable to start iisexpress") || consoleOutput.ToUpperInvariant().Contains("CANNOT CREATE A FILE WHEN THAT FILE ALREADY EXISTS");
}
#region iisexpress.exe Search
private static string FindIISExpress()
{
RegistryKey rk = GetIISExpressKeys(RegistryView.Registry32)
.Concat(GetIISExpressKeys(RegistryView.Registry64))
.FirstOrDefault(IISExists);
if (rk != null)
{
return GetIISExe(rk);
}
else
{
return null;
}
}
private static IEnumerable<RegistryKey> GetIISExpressKeys(RegistryView view)
{
RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, view);
if (hklm != null)
{
using (hklm)
{
RegistryKey iisRoot = hklm.OpenSubKey(@"SOFTWARE\Microsoft\IISExpress");
if (iisRoot != null)
{
using (iisRoot)
{
List<string> subkeys = iisRoot.GetSubKeyNames().ToList();
// Latest version first
subkeys.Sort((a, b) => Version.Parse(b).CompareTo(Version.Parse(a)));
foreach (string subkey in subkeys)
{
yield return iisRoot.OpenSubKey(subkey);
}
}
}
}
}
}
private static string GetIISExe(RegistryKey rk)
{
string path = rk.GetValue("InstallPath", null) as string;
if (path != null)
{
return System.IO.Path.Combine(path, "iisexpress.exe");
}
return null;
}
private static bool IISExists(RegistryKey rk)
{
string iisexe = GetIISExe(rk);
return !string.IsNullOrEmpty(iisexe) && System.IO.File.Exists(iisexe);
}
#endregion
}
}

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

@ -0,0 +1,25 @@
<!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="//cdnjs.cloudflare.com/ajax/libs/qunit/1.14.0/qunit.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/qunit/1.14.0/qunit.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/sinon.js/1.7.3/sinon.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<script src="jslitmus.js"></script>
<script type="text/javascript">
window.AIResults = [];
QUnit.testDone(function(result) {
window.AIResults.push(result);
});
</script>
<script src="performanceTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<div id="error-message"></div>
</body>
</html>

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

@ -0,0 +1,224 @@
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Remote;
namespace ApplicationInsights.Javascript.Tests
{
/// <summary>
/// Runs QUnit Javascript tests in each browser through Selenium WebDriver and reports
/// results to standard output (and passes/fails the overall test)
/// </summary>
[TestClass]
public class Tests
{
#region IIS express stuff
private const int PORT = 55555;
private static IISExpress iisExpress;
private const string PATH_TO_TESTS = "/Selenium/Tests.html";
private const string PATH_TO_PERF_TESTS = "/Selenium/PerfTests.html";
private const string PERF_RESULTS_PATH = @"\\smfiles\Privates\scsouthw\perfResults.txt";
[ClassInitialize]
public static void Setup(TestContext context)
{
string localPath = System.IO.Path.GetDirectoryName(typeof(Tests).Assembly.Location);
iisExpress = new IISExpress(localPath, PORT);
Assert.IsTrue(iisExpress.Start(), "IIS Express failed to start");
}
[ClassCleanup]
public static void Cleanup()
{
iisExpress.Stop();
iisExpress = null;
}
#endregion
[TestMethod]
public void Firefox()
{
RunTest(new OpenQA.Selenium.Firefox.FirefoxDriver());
}
/**
* Removing IE tests until they fix this bug which prevents selenium from working:
* https://code.google.com/p/selenium/issues/detail?id=8302
* https://connect.microsoft.com/IE/feedback/details/1062093/installation-of-kb3025390-breaks-out-of-process-javascript-execution-in-ie11
*/
//[TestMethod]
//public void InternetExplorer()
//{
// RunTest(new OpenQA.Selenium.IE.InternetExplorerDriver());
//}
//[TestMethod]
//public void InternetExplorerPerf()
//{
// RunPerfTest(new OpenQA.Selenium.IE.InternetExplorerDriver());
//}
[TestMethod]
public void Safari()
{
RunTest(new OpenQA.Selenium.Safari.SafariDriver());
}
[TestMethod]
public void Chrome()
{
RunTest(new OpenQA.Selenium.Chrome.ChromeDriver());
}
[TestMethod]
public void FirefoxPerf()
{
RunPerfTest(new OpenQA.Selenium.Firefox.FirefoxDriver());
}
[TestMethod]
public void SafariPerf()
{
RunPerfTest(new OpenQA.Selenium.Safari.SafariDriver());
}
[TestMethod]
public void ChromePerf()
{
RunPerfTest(new OpenQA.Selenium.Chrome.ChromeDriver());
}
/// <summary>
/// Navigates the specified browser driver to the tests page and pulls results with
/// the help of TestLogger.js (in the Javascript project).
/// </summary>
/// <param name="driver"></param>
private void RunTest(RemoteWebDriver driver)
{
using (driver)
{
var navigator = driver.Navigate();
driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 100, 0));
navigator.GoToUrl(string.Format("http://localhost:{0}{1}", PORT, PATH_TO_TESTS));
navigator.Refresh();
// log test results
var testStart = DateTime.Now;
ReadOnlyCollection<object> response = (ReadOnlyCollection<object>)driver.ExecuteScript("return window.AIResults");
var lastTestsCount = -1;
int currentTestsCount = response.Count;
while (lastTestsCount != currentTestsCount)
{
Thread.Sleep(5000);
response = (ReadOnlyCollection<object>)driver.ExecuteScript("return window.AIResults");
lastTestsCount = currentTestsCount;
currentTestsCount = response.Count;
if ((DateTime.Now - testStart).Minutes > 5)
throw new Exception("Test failed. Timeout.");
}
Console.WriteLine("{0} tests executed", response.Count);
Assert.IsTrue(response.Count > 0, "no tests executed");
foreach (dynamic testResult in response)
{
string name = testResult["name"];
long passed = testResult["passed"];
long total = testResult["total"];
Console.WriteLine("{0}. passed {1}/{2}", name, passed, total);
Assert.IsTrue(passed == total, name);
}
}
}
/// <summary>
/// Navigates the specified browser driver to the tests page and pulls results with
/// the help of TestLogger.js (in the Javascript project).
/// </summary>
/// <param name="driver"></param>
private void RunPerfTest(RemoteWebDriver driver)
{
using (driver)
{
try
{
var navigator = driver.Navigate();
driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0, 100, 0));
navigator.GoToUrl(string.Format("http://localhost:{0}{1}", PORT, PATH_TO_PERF_TESTS));
navigator.Refresh();
// log test results
ReadOnlyCollection<object> response =
(ReadOnlyCollection<object>) driver.ExecuteScript("return window.AIResults");
while (response.Count < 4)
{
Thread.Sleep(1000);
response = (ReadOnlyCollection<object>) driver.ExecuteScript("return window.AIResults");
}
Console.WriteLine("{0} tests executed", response.Count);
Assert.IsTrue(response.Count > 0, "no tests executed");
foreach (dynamic testResult in response)
{
string name = testResult["name"];
long passed = testResult["passed"];
long total = testResult["total"];
Console.WriteLine("{0}. passed {1}/{2}", name, passed, total);
Assert.IsTrue(passed == total, name, passed.ToString() + " tests passed out of " + total.ToString());
}
// save perf results
dynamic perfResults = driver.ExecuteScript("return window.perfResults");
dynamic perfResultsCsv = driver.ExecuteScript("return window.perfResultsCsv");
dynamic perfResultsCsvHeaders = driver.ExecuteScript("return window.perfResultsCsvHeaders");
Assert.IsNotNull(perfResults, "perf results are not null");
Assert.IsNotNull(perfResultsCsv, "perf csv results are not null");
Assert.IsNotNull(perfResultsCsvHeaders, "perf csv results are not null");
this.writeHelper(PERF_RESULTS_PATH, perfResults, "");
this.writeHelper(PERF_RESULTS_PATH + ".csv", perfResultsCsv, perfResultsCsvHeaders);
}
catch (Exception exception)
{
var machineName = System.Environment.MachineName;
var exceptionPath = PERF_RESULTS_PATH + "_error.txt";
var content = DateTime.Now.ToString() + "\t" + machineName + "\r\n" + exception.ToString();
this.writeHelper(exceptionPath, content, "");
throw exception;
}
}
}
private void writeHelper(string path, string content, string header)
{
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
if (header.Length > 0)
{
sw.WriteLine(header);
}
sw.WriteLine(content);
}
}
else
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(content);
}
}
}
}
}

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

@ -0,0 +1,23 @@
<!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="//cdnjs.cloudflare.com/ajax/libs/qunit/1.14.0/qunit.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/qunit/1.14.0/qunit.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/sinon.js/1.7.3/sinon.js"></script>
<script type="text/javascript">
window.AIResults = [];
QUnit.testDone(function(result) {
window.AIResults.push(result);
});
</script>
<script src="checkinTests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
<div id="error-message"></div>
</body>
</html>

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

@ -0,0 +1,18 @@
/// <reference path="../checkintests/context/user.tests.ts" />
/// <reference path="../checkintests/context/session.tests.ts" />
/// <reference path="../checkintests/telemetry/event.tests.ts" />
/// <reference path="../checkintests/telemetry/exception.tests.ts" />
/// <reference path="../checkintests/telemetry/metric.tests.ts" />
/// <reference path="../checkintests/telemetry/pageviewperformance.tests.ts" />
/// <reference path="../checkintests/telemetry/pageview.tests.ts" />
/// <reference path="../checkintests/telemetry/trace.tests.ts" />
/// <reference path="../checkintests/telemetry/DataSanitizer.tests.ts" />
/// <reference path="../checkintests/appinsights.tests.ts" />
/// <reference path="../checkintests/logging.tests.ts" />
/// <reference path="../checkintests/sender.tests.ts" />
/// <reference path="../checkintests/serializer.tests.ts" />
/// <reference path="../checkintests/telemetrycontext.tests.ts" />
/// <reference path="../checkintests/util.tests.ts" />
/// <reference path="../checkintests/initialization.tests.ts" />

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

@ -0,0 +1,4 @@
/// <reference path="../performance/api.perftests.ts" />
/// <reference path="../performance/serializer.perftests.ts" />
/// <reference path="../performance/pageload.perftests.ts" />

Различия файлов скрыты, потому что одна или несколько строк слишком длинны

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

@ -0,0 +1,146 @@
/// <reference path="..\External\qunit.d.ts" />
/** Wrapper around QUnit asserts. This class has two purposes:
* - Make Assertion methods easy to discover.
* - Make them consistent with XUnit assertions in the order of the actual and expected parameter values.
*/
class Assert {
/**
* A deep recursive comparison assertion, working on primitive types, arrays, objects,
* regular expressions, dates and functions.
*
* The deepEqual() assertion can be used just like equal() when comparing the value of
* objects, such that { key: value } is equal to { key: value }. For non-scalar values,
* identity will be disregarded by deepEqual.
*
* @param expected Known comparison value
* @param actual Object or Expression being tested
* @param message A short description of the assertion
*/
public static deepEqual(expected: any, actual: any, message?: string): any {
return deepEqual(actual, expected, message);
}
/**
* A non-strict comparison assertion, roughly equivalent to JUnit assertEquals.
*
* The equal assertion uses the simple comparison operator (==) to compare the actual
* and expected arguments. When they are equal, the assertion passes: any; otherwise, it fails.
* When it fails, both actual and expected values are displayed in the test result,
* in addition to a given message.
*
* @param expected Known comparison value
* @param actual Expression being tested
* @param message A short description of the assertion
*/
public static equal(expected: any, actual: any, message?: string): any {
return equal(actual, expected, message);
}
/**
* An inverted deep recursive comparison assertion, working on primitive types,
* arrays, objects, regular expressions, dates and functions.
*
* The notDeepEqual() assertion can be used just like equal() when comparing the
* value of objects, such that { key: value } is equal to { key: value }. For non-scalar
* values, identity will be disregarded by notDeepEqual.
*
* @param expected Known comparison value
* @param actual Object or Expression being tested
* @param message A short description of the assertion
*/
public static notDeepEqual(expected: any, actual: any, message?: string): any {
return notDeepEqual(actual, expected, message);
}
/**
* A non-strict comparison assertion, checking for inequality.
*
* The notEqual assertion uses the simple inverted comparison operator (!=) to compare
* the actual and expected arguments. When they aren't equal, the assertion passes: any;
* otherwise, it fails. When it fails, both actual and expected values are displayed
* in the test result, in addition to a given message.
*
* @param expected Known comparison value
* @param actual Expression being tested
* @param message A short description of the assertion
*/
public static notEqual(expected: any, actual: any, message?: string): any {
return notEqual(actual, expected, message);
}
public static notPropEqual(expected: any, actual: any, message?: string): any {
return notPropEqual(actual, expected, message);
}
public static propEqual(expected: any, actual: any, message?: string): any {
return propEqual(actual, expected, message);
}
/**
* A non-strict comparison assertion, checking for inequality.
*
* The notStrictEqual assertion uses the strict inverted comparison operator (!==)
* to compare the actual and expected arguments. When they aren't equal, the assertion
* passes: any; otherwise, it fails. When it fails, both actual and expected values are
* displayed in the test result, in addition to a given message.
*
* @param expected Known comparison value
* @param actual Expression being tested
* @param message A short description of the assertion
*/
public static notStrictEqual(expected: any, actual: any, message?: string): any {
return notStrictEqual(actual, expected, message);
}
/**
* A boolean assertion, equivalent to CommonJS's assert.ok() and JUnit's assertTrue().
* Passes if the first argument is truthy.
*
* The most basic assertion in QUnit, ok() requires just one argument. If the argument
* evaluates to true, the assertion passes; otherwise, it fails. If a second message
* argument is provided, it will be displayed in place of the result.
*
* @param state Expression being tested
* @param message A short description of the assertion
*/
public static ok(state: any, message?: string): any {
return ok(state, message);
}
/**
* A strict type and value comparison assertion.
*
* The strictEqual() assertion provides the most rigid comparison of type and value with
* the strict equality operator (===)
*
* @param expected Known comparison value
* @param actual Expression being tested
* @param message A short description of the assertion
*/
public static strictEqual(expected: any, actual: any, message?: string): any {
return strictEqual(actual, expected, message);
}
/**
* Assertion to test if a callback throws an exception when run.
*
* When testing code that is expected to throw an exception based on a specific set of
* circumstances, use throws() to catch the error object for testing and comparison.
*
* @param block Function to execute
* @param expected Error Object to compare
* @param message A short description of the assertion
*/
public static throws(block: () => any, expected: any, message?: string): any;
/**
* @param block Function to execute
* @param message A short description of the assertion
*/
public static throws(block: () => any, message?: string): any;
public static throws(block: () => any, expected?: any, message?: string): any {
return throws(block, expected, message);
}
}

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

@ -0,0 +1,5 @@
/// <reference path="..\External\sinon.d.ts" />
/// <reference path="..\External\qunit.d.ts" />
/// <reference path="Assert.ts" />
/// <reference path="TestClass.ts" />
/// <reference path="TestCase.ts" />

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

@ -0,0 +1,146 @@
/// <reference path="../../JavaScriptSDK/serializer.ts" />
/// <reference path="./TestClass.ts"/>
class ContractTestHelper extends TestClass {
public name: string;
private initializer: () => Microsoft.ApplicationInsights.ISerializable;
constructor(initializer: () => Microsoft.ApplicationInsights.ISerializable, name: string) {
super();
this.name = name;
this.initializer = initializer;
}
/** Method called before the start of each test method */
public testInitialize() {
}
/** Method called after each test method has completed */
public testCleanup() {
}
public registerTests() {
var name = this.name + ": ";
this.testCase({
name: name + "constructor does not throw errors",
test: () => {
this.getSubject(this.initializer, this.name);
}
});
this.testCase({
name: name + "serialization does not throw errors",
test: () => {
var subject = this.getSubject(this.initializer, this.name);
this.serialize(subject, this.name);
}
});
this.testCase({
name: name + "all required fields are constructed",
test: () => {
this.allRequiredFieldsAreConstructed(this.initializer, this.name);
}
});
this.testCase({
name: name + "extra fields are removed upon serialization",
test: () => {
this.extraFieldsAreRemovedBySerializer(this.initializer, this.name);
}
});
this.testCase({
name: this.name + "optional fields are not required by the back end",
test: () => {
this.optionalFieldsAreNotRequired(this.initializer, this.name);
}
});
this.testCase({
name: this.name + "all fields are serialized if included",
test: () => {
this.allFieldsAreIncludedIfSpecified(this.initializer, this.name);
}
});
}
public checkSerializableObject(initializer: () => any, name: string) {
this.allRequiredFieldsAreConstructed(initializer, name);
this.extraFieldsAreRemovedBySerializer(initializer, name);
this.allFieldsAreIncludedIfSpecified(initializer, name);
}
private allRequiredFieldsAreConstructed(initializer: () => any, name: string) {
var subject = this.getSubject(initializer, name);
for (var field in subject.aiDataContract) {
if (subject.aiDataContract[field]) {
Assert.ok(subject[field] != null, "The required field '" + field + "' is constructed for: '" + name + "'");
}
}
}
private extraFieldsAreRemovedBySerializer(initializer: () => any, name: string) {
var subject = this.getSubject(initializer, name);
var extra = "extra";
subject[extra + 0] = extra;
subject[extra + 1] = extra;
subject[extra + 3] = extra;
var serializedSubject = this.serialize(subject, name);
for (var field in serializedSubject) {
Assert.ok(subject.aiDataContract[field] != null, "The field '" + field + "' exists in the contract for '" + name + "' and was serialized");
}
}
private optionalFieldsAreNotRequired(initializer: () => any, name: string) {
var subject = this.getSubject(this.initializer, this.name);
for (var field in subject.aiDataContract) {
if (!subject.aiDataContract[field]) {
delete subject[field];
}
}
}
private allFieldsAreIncludedIfSpecified(initializer: () => any, name: string) {
var subject = this.getSubject(this.initializer, this.name);
for (var field in subject.aiDataContract) {
subject[field] = field;
}
var serializedSubject = this.serialize(subject, this.name);
for (field in subject.aiDataContract) {
Assert.ok(serializedSubject[field] === field, "Field '" + field + "' was not serialized" + this.name);
}
for (field in serializedSubject) {
Assert.ok(subject.aiDataContract[field] !== undefined, "Field '" + field + "' was included but is not specified in the contract " + this.name);
}
}
private serialize(subject: Microsoft.ApplicationInsights.ISerializable, name: string) {
var serialized = "";
try {
serialized = Microsoft.ApplicationInsights.Serializer.serialize(subject);
} catch (e) {
Assert.ok(false, "Failed to serialize '" + name + "'\r\n" + e);
}
return JSON.parse(serialized);
}
private getSubject(construction: () => Microsoft.ApplicationInsights.ISerializable, name: string): any {
var subject = construction();
Assert.ok(!!subject, "can construct " + name);
return subject;
}
}

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

@ -0,0 +1,227 @@
/// <reference path="..\TestFramework\Common.ts" />
/// <reference path="../external/jquery.d.ts" />
/// <reference path="../../javascriptsdk/appinsights.ts" />
/// <reference path="../../JavaScriptSDK/Telemetry/Common/Data.ts" />
interface IJSLitmus {
test: (name: string, f: Function) => void;
stop: () => void;
runAll: (e?: Event) => JQueryDeferred<void>;
_tests: any[];
}
interface IPerfResult {
operationCount: number;
timeInMs: number;
name: string;
opsPerSec: number;
period: number;
date: number;
platform: string;
os: string;
oneHrDate: number;
friendlyDate: string;
group: string;
millisecondsPerOp: number;
microsecondsPerOp: number;
secondsPerOp: number;
}
declare var JSLitmus: IJSLitmus;
class PerformanceTestHelper extends TestClass {
public testCount;
public appInsights;
public testProperties;
public testMeasurements;
public results: IPerfResult[];
private isDone;
constructor(timeout?: number) {
super();
this.testCount = 0;
this.synchronouslyLoadJquery();
this.results = [];
}
/** Method called before the start of each test method */
public testInitialize() {
this.useFakeServer = false;
sinon.fakeServer["restore"]();
this.useFakeTimers = false;
this.clock.restore();
this.appInsights = new Microsoft.ApplicationInsights.AppInsights(<any>{
instrumentationKey: "0011cf0f-6d64-4a0e-a19f-4eb82a36f134",
url: "file:///C:/src/sdk/src/JavaScript/JavaScriptSDK.Tests//E2ETests/ai.js",
endpointUrl: "http://dc-int.services.visualstudio.com/v2/track",
maxBatchInterval: 0
});
this.appInsights.context._sender._sender = () => null;
this.testProperties = { p1: "val", p2: "val", p3: "val", p4: "val", p5: "val", p6: "val", p7: "val" };
this.testMeasurements = { m1: 1, m2: 1, m3: 1, m4: 1, m5: 1, m6: 1, m7: 1, m8: 1, m9: 1 };
}
/** Method called after each test method has completed */
public testCleanup() {
this.useFakeServer = true;
this.useFakeTimers = true;
var serializedPerfResults: string = window["perfResults"] || "[]";
var perfResults: IPerfResult[] = <any>(JSON.parse(serializedPerfResults));
perfResults = perfResults.concat(this.results);
window["perfResults"] = JSON.stringify(perfResults);
window["perfResultsCsv"] = this.toCsv(perfResults).csv;
window["perfResultsCsvHeaders"] = this.toCsv(perfResults).headers;
}
private toCsv(array: any[]) {
var headers = "";
if (array.length > 0) {
var names = [];
for (var name in array[0]) {
names.push(name);
}
headers = names.join(",");
}
var csv = [];
for (var i = 0; i < array.length; i++) {
var datum = array[i];
var values = [];
for (var j = 0; j < names.length; j++) {
values.push(datum[names[j]]);
}
csv.push(values.join(","));
}
return { headers: headers, csv: csv.join("\r\n") };
}
public enqueueTest(name: string, action: () => void) {
JSLitmus.test(name, (count) => {
while (count--) {
action();
}
});
}
public runTests() {
JSLitmus.runAll().done(() => this.onTestsComplete());
}
public onTestsComplete() {
var perfLogging = new Microsoft.ApplicationInsights.AppInsights(<any>{
instrumentationKey: "1a6933ad-f260-447f-a2b0-e2233f6658eb",
url: "file:///C:/src/sdk/src/JavaScript/JavaScriptSDK.Tests//E2ETests/ai.js",
endpointUrl: "http://prodintdataforker.azurewebsites.net/dcservices?intKey=4d93aad0-cf1d-45b7-afc9-14f55504f6d5",
sessionRenewalMs: 30 * 60 * 1000,
sessionExpirationMs: 24 * 60 * 60 * 1000,
maxBatchSizeInBytes: 1000000,
maxBatchInterval: 0
});
perfLogging.context._sender._sender = (payload) => {
var xhr = new sinon["xhr"].workingXHR();
xhr.open("POST", perfLogging.config.endpointUrl, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(payload);
}
JSLitmus.stop();
for (var i = 0; i < JSLitmus._tests.length; i++) {
var test = JSLitmus._tests[i];
var opsPerSec = test.count / test.time;
Assert.ok(true, test.name + " operations per sec:" + opsPerSec);
var timeInMs = <number>test.time;
var date = +new Date;
var oneHr = 60 * 60 * 1000;
var oneHrDate = Math.floor(date / oneHr) * oneHr;
var friendlyDate = new Date(oneHrDate).toISOString();
var platform = <string>test.platform;
var browser = "internetExplorer";
var name = <string>test.name;
var group = name.split(".")[0];
if (platform.toLowerCase().indexOf("chrome") >= 0) {
browser = "chrome";
} else if (platform.toLowerCase().indexOf("firefox") >= 0) {
browser = "firefox";
} else if (platform.toLowerCase().indexOf("safari") >= 0) {
browser = "safari";
}
var result: IPerfResult = {
name: name,
timeInMs: timeInMs,
operationCount: 1,
opsPerSec: 1 / (timeInMs / 1000),
period: 1,
date: date,
oneHrDate: oneHrDate,
friendlyDate: friendlyDate,
group: group,
platform: platform,
browser: browser,
os: <string>test.os,
millisecondsPerOp: (timeInMs / 1),
microsecondsPerOp: (timeInMs / 1) * 1000,
secondsPerOp: (timeInMs / 1) / 1000
};
perfLogging.trackMetric(result.name, opsPerSec);
var event = new Microsoft.ApplicationInsights.Telemetry.Event(result.name, opsPerSec, result);
var data = new Microsoft.ApplicationInsights.Telemetry.Common.Data<Microsoft.ApplicationInsights.Telemetry.Event>(
Microsoft.ApplicationInsights.Telemetry.Event.dataType, event);
var envelope = new Microsoft.ApplicationInsights.Telemetry.Common.Envelope(data, Microsoft.ApplicationInsights.Telemetry.Event.envelopeType);
perfLogging.context.track(envelope);
this.results.push(result);
}
JSLitmus._tests.length = 0;
this.isDone = true;
this.testCleanup();
start();
}
public onTimeout() {
if (!this.isDone) {
Assert.ok(false, "timeout reached");
this.onTestsComplete();
}
}
/**
* Synchronously loads jquery
* we could regress the test suite and develop sublte jquery dependencies in the product code
* if jquery were added to all tests as it hides a lot of cross browser weirdness. However,
* for these tests it is useful to manipulate the dom to display performance results.
*/
private synchronouslyLoadJquery() {
if (!window["$"]) {
// get some kind of XMLHttpRequest
var xhrObj = <any>false;
if (window["ActiveXObject"]) {
xhrObj = <any>new ActiveXObject("Microsoft.XMLHTTP");
} else if (window["XMLHttpRequest"]) {
xhrObj = <any>new XMLHttpRequest();
} else {
alert("Please upgrade your browser! Your browser does not support AJAX!");
}
// open and send a synchronous request
xhrObj.open('GET', "http://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js", false);
xhrObj.send('');
// add the returned content to a newly created script tag
var script = document.createElement('script');
script.type = "text/javascript";
script.text = xhrObj.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
}
}
}

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

@ -0,0 +1,22 @@

/** Defines a test case */
class TestCase {
/** Name to use for the test case */
public name: string;
/** Test case method */
public test: () => void;
}
/** Defines a test case */
interface TestCaseAsync {
/** Name to use for the test case */
name: string;
/** time to wait after pre before invoking post and calling start() */
stepDelay: number;
/** async steps */
steps: Array<() => void>;
}

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

@ -0,0 +1,217 @@
/// <reference path="..\External\sinon.d.ts" />
/// <reference path="..\External\qunit.d.ts" />
/// <reference path="Assert.ts" />
/// <reference path="./TestCase.ts"/>
class TestClass {
/** The instance of the currently running suite. */
public static currentTestClass: TestClass;
/** Turns on/off sinon's syncronous implementation of setTimeout. On by default. */
public useFakeTimers: boolean = true;
/** Turns on/off sinon's fake implementation of XMLHttpRequest. On by default. */
public useFakeServer: boolean = true;
/** Method called before the start of each test method */
public testInitialize() {
}
/** Method called after each test method has completed */
public testCleanup() {
}
/** Method in which test class intances should call this.testCase(...) to register each of this suite's tests. */
public registerTests() {
}
/** Register an async Javascript unit testcase. */
public testCaseAsync(testInfo: TestCaseAsync) {
if (!testInfo.name) {
throw new Error("Must specify name in testInfo context in registerTestcase call");
}
if (isNaN(testInfo.stepDelay)) {
throw new Error("Must specify 'stepDelay' period between pre and post");
}
if (!testInfo.steps) {
throw new Error("Must specify 'steps' to take asynchronously");
}
// Create a wrapper around the test method so we can do test initilization and cleanup.
var testMethod = () => {
// Save off the instance of the currently running suite.
TestClass.currentTestClass = this;
// Run the test.
try {
this._testStarting();
var steps = testInfo.steps;
var trigger = () => {
if (steps.length) {
var step = steps.shift();
try {
step.call(this);
} catch (e) {
start();
this._testCompleted();
Assert.ok(false, e.toString());
return;
}
setTimeout(() => {
if (QUnit.config["semaphore"] > 0) {
trigger();
}
}, testInfo.stepDelay);
} else {
start();
this._testCompleted();
}
};
trigger();
//this._testCompleted();
} catch (ex) {
Assert.ok(false, "Unexpected Exception: " + ex);
this._testCompleted(true);
}
};
// Register the test with QUnit
QUnit.asyncTest(testInfo.name, testMethod);
}
/** Register a Javascript unit testcase. */
public testCase(testInfo: TestCase) {
if (!testInfo.name) {
throw new Error("Must specify name in testInfo context in registerTestcase call");
}
if (!testInfo.test) {
throw new Error("Must specify 'test' method in testInfo context in registerTestcase call");
}
// Create a wrapper around the test method so we can do test initilization and cleanup.
var testMethod = () => {
// Save off the instance of the currently running suite.
TestClass.currentTestClass = this;
// Run the test.
try {
this._testStarting();
testInfo.test.call(this);
this._testCompleted();
}
catch (ex) {
Assert.ok(false, "Unexpected Exception: " + ex);
this._testCompleted(true);
}
};
// Register the test with QUnit
test(testInfo.name, testMethod);
}
/** Called when the test is starting. */
private _testStarting() {
// Initialize the sandbox similar to what is done in sinon.js "test()" override. See note on class.
var config = (<any>sinon).getConfig(sinon.config);
config.useFakeTimers = this.useFakeTimers;
config.useFakeServer = this.useFakeServer;
config.injectInto = config.injectIntoThis && this || config.injectInto;
this.sandbox = sinon.sandbox.create(config);
this.server = this.sandbox.server;
// Allow the derived class to perform test initialization.
this.testInitialize();
}
/** Called when the test is completed. */
private _testCompleted(failed?: boolean) {
if (failed) {
// Just cleanup the sandbox since the test has already failed.
this.sandbox.restore();
}
else {
// Verify the sandbox and restore.
(<any>this.sandbox).verifyAndRestore();
}
this.testCleanup();
// Clear the instance of the currently running suite.
TestClass.currentTestClass = null;
}
/**** Sinon methods and properties ***/
// These methods and properties are injected by Sinon and will override the implementation here.
// These are here purely to make typescript happy.
public clock: SinonFakeTimers;
public server: SinonFakeServer;
public sandbox: SinonSandbox;
/** Creates an anonymous function that records arguments, this value, exceptions and return values for all calls. */
public spy(): SinonSpy;
/** Spies on the provided function */
public spy(funcToWrap: Function): SinonSpy;
/** Creates a spy for object.methodName and replaces the original method with the spy. The spy acts exactly like the original method in all cases. The original method can be restored by calling object.methodName.restore(). The returned spy is the function object which replaced the original method. spy === object.method. */
public spy(object: any, methodName: string, func?: Function): SinonSpy;
public spy(...args: any[]): SinonSpy { return null; }
/** Creates an anonymous stub function. */
public stub(): SinonStub;
/** Stubs all the object's methods. */
public stub(object: any): SinonStub;
/** Replaces object.methodName with a func, wrapped in a spy. As usual, object.methodName.restore(); can be used to restore the original method. */
public stub(object: any, methodName: string, func?: Function): SinonStub;
public stub(...args: any[]): SinonStub { return null; }
/** Creates a mock for the provided object.Does not change the object, but returns a mock object to set expectations on the object's methods. */
public mock(object: any): SinonMock { return null; }
/**** end: Sinon methods and properties ***/
/** Sends a JSON response to the provided request.
* @param request The request to respond to.
* @param data Data to respond with.
* @param errorCode Optional error code to send with the request, default is 200
*/
public sendJsonResponse(request: SinonFakeXMLHttpRequest, data: any, errorCode?: number) {
if (errorCode === undefined) {
errorCode = 200;
}
request.respond(
errorCode,
{ "Content-Type": "application/json" },
JSON.stringify(data));
}
}
// Configure Sinon
sinon.assert.fail = function (msg?) {
Assert.ok(false, msg);
};
sinon.assert.pass = function (assertion) {
Assert.ok(assertion, "sinon assert");
};
sinon.config = {
injectIntoThis: true,
injectInto: null,
properties: ["spy", "stub", "mock", "clock", "sandbox"],
useFakeTimers: true,
useFakeServer: true
};

Двоичные данные
JavaScript/JavaScriptSDK.Tests/chromedriver.exe Normal file

Двоичный файл не отображается.

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

@ -0,0 +1,9 @@
{
"Framework": "qunit",
"References": [
{ "Path": "External/Sinon-1.7.3.js" },
{ "Path": "Selenium/JSLitmus.js" },
{ "Path": "E2ETests/testSnippet.js" }
],
"CodeCoverageExcludes": ["*Tests*"]
}

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

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Selenium.WebDriver" version="2.43.1" targetFramework="net45" />
</packages>

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

@ -31,7 +31,7 @@
</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')" />
<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}">
@ -168,8 +168,8 @@
<ItemGroup />
<Import Project="$(VSToolsPath)\TypeScript\Microsoft.TypeScript.targets" Condition="Exists('$(VSToolsPath)\TypeScript\Microsoft.TypeScript.targets')" />
<Target Name="EnsureAjaxMinBuildImported" BeforeTargets="BeforeBuild" Condition="'$(AjaxMinOutputFolder)' == ''">
<Error Condition="!Exists('..\packages\AjaxMin.5.5.5091.22839\tools\net40\AjaxMin.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." />
<Error Condition="Exists('..\packages\AjaxMin.5.5.5091.22839\tools\net40\AjaxMin.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." />
<Error Condition="!Exists('..\..\..\packages\AjaxMin.5.5.5091.22839\tools\net40\AjaxMin.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." />
<Error Condition="Exists('..\..\..\packages\AjaxMin.5.5.5091.22839\tools\net40\AjaxMin.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." />
</Target>
<Target Name="AfterBuild" DependsOnTargets="BuildAjaxMinManifests">
<Message Text="Build snippet.html" />

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

@ -3,18 +3,59 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.30723.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NuGet.JavaScript", "NuGet.JavaScript\NuGet.JavaScript.csproj", "{7C2662E9-96D3-473A-B0DD-55A80343A237}"
ProjectSection(ProjectDependencies) = postProject
{49ECFE69-8C92-4FA7-A7C3-CDB957C71654} = {49ECFE69-8C92-4FA7-A7C3-CDB957C71654}
{C6CA61F8-4855-4C77-B199-A56BAD047ADB} = {C6CA61F8-4855-4C77-B199-A56BAD047ADB}
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{59A3A3F8-A4CA-48B7-91BB-B3F1DE661EB9}"
ProjectSection(SolutionItems) = preProject
..\Global.props = ..\Global.props
..\.nuget\NuGet.targets = ..\.nuget\NuGet.targets
..\Package.targets = ..\Package.targets
PostTestScript.cmd = PostTestScript.cmd
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JavaScriptSDK", "JavaScriptSDK\JavaScriptSDK.csproj", "{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JavaScriptSDK.Tests", "JavaScriptSDK.Tests\JavaScriptSDK.Tests.csproj", "{C6CA61F8-4855-4C77-B199-A56BAD047ADB}"
ProjectSection(ProjectDependencies) = postProject
{49ECFE69-8C92-4FA7-A7C3-CDB957C71654} = {49ECFE69-8C92-4FA7-A7C3-CDB957C71654}
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{6437E05C-5120-4E44-B696-61F19B0FD73A}"
ProjectSection(SolutionItems) = preProject
.nuget\packages.config = .nuget\packages.config
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NuGet.TypeScript", "NuGet.TypeScript\NuGet.TypeScript.csproj", "{314B90F5-0E04-456A-AF38-914F520C3BF3}"
ProjectSection(ProjectDependencies) = postProject
{7C2662E9-96D3-473A-B0DD-55A80343A237} = {7C2662E9-96D3-473A-B0DD-55A80343A237}
{C6CA61F8-4855-4C77-B199-A56BAD047ADB} = {C6CA61F8-4855-4C77-B199-A56BAD047ADB}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{7C2662E9-96D3-473A-B0DD-55A80343A237}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7C2662E9-96D3-473A-B0DD-55A80343A237}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7C2662E9-96D3-473A-B0DD-55A80343A237}.Release|Any CPU.Build.0 = Release|Any CPU
{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}.Debug|Any CPU.Build.0 = Debug|Any CPU
{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}.Release|Any CPU.ActiveCfg = Release|Any CPU
{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}.Release|Any CPU.Build.0 = Release|Any CPU
{C6CA61F8-4855-4C77-B199-A56BAD047ADB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C6CA61F8-4855-4C77-B199-A56BAD047ADB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C6CA61F8-4855-4C77-B199-A56BAD047ADB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C6CA61F8-4855-4C77-B199-A56BAD047ADB}.Release|Any CPU.Build.0 = Release|Any CPU
{314B90F5-0E04-456A-AF38-914F520C3BF3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{314B90F5-0E04-456A-AF38-914F520C3BF3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{314B90F5-0E04-456A-AF38-914F520C3BF3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{314B90F5-0E04-456A-AF38-914F520C3BF3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

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

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), 'Global.props'))\Global.props" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<SchemaVersion>2.0</SchemaVersion>
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ProjectGuid>{7C2662E9-96D3-473A-B0DD-55A80343A237}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.ApplicationInsights.JavaScript.NuGet</RootNamespace>
<AssemblyName>Microsoft.ApplicationInsights.JavaScript.NuGet</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- Suppress the "CS2008: No source files specified" warning -->
<NoWarn>2008</NoWarn>
<PackageSpecFile>$(MSBuildProjectDirectory)\Package.nuspec</PackageSpecFile>
<PackageVersionFile>$(BinRoot)\$(Configuration)\JavaScript\NuGet.JavaScript\Microsoft.ApplicationInsights.JavaScript.NuGet.dll</PackageVersionFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' " />
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " />
<ItemGroup>
<None Include="Package.nuspec" />
<Content Include="..\JavaScriptSDK\min\ai.js">
<Link>ai.js</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\JavaScriptSDK\min\ai.min.js">
<Link>ai.min.js</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="..\JavaScriptSDK\min\snippet_vsix.html">
<Link>snippet.html</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JavaScriptSDK\JavaScriptSDK.csproj">
<Project>{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}</Project>
<Name>JavaScriptSDK</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\..\NuGet.targets" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), 'Package.targets'))\Package.targets" />
</Project>

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

@ -0,0 +1,23 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>Microsoft.ApplicationInsights.JavaScript</id>
<version>$version$</version>
<title>Application Insights API for JavaScript Applications</title>
<authors>Microsoft</authors>
<owners>Microsoft</owners>
<language>en-us</language>
<licenseUrl>http://go.microsoft.com/fwlink/?LinkId=323613</licenseUrl>
<projectUrl>http://go.microsoft.com/fwlink/?LinkId=323612</projectUrl>
<iconUrl>$image$</iconUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>
<description>Application Insights API enables you to get insights into user behavior and monitor usage patterns for your Web and Multi-Device Hybrid Apps. Application Insights service collects the data, analyzes it and presents the results in the forms of graphs and reports in Application Insights portal in Microsoft Azure.</description>
<tags>Analytics Insights Telemetry JavaScript MDD Multi-Device ApplicationInsights Cordova Web</tags>
<copyright>Copyright © 2013-2022, Microsoft. All rights reserved.</copyright>
</metadata>
<files>
<file src="$configuration$\Javascript\Nuget.JavaScript\snippet.html" target="tools\prefix.html" />
<file src="$configuration$\Javascript\Nuget.JavaScript\ai.js" target="content\scripts\ai.$version$.js" />
<file src="$configuration$\Javascript\Nuget.JavaScript\ai.min.js" target="content\scripts\ai.$version$.min.js" />
</files>
</package>

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

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), 'Global.props'))\Global.props" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<SchemaVersion>2.0</SchemaVersion>
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<ProjectGuid>{314b90f5-0e04-456a-af38-914f520c3bf3}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>Microsoft.ApplicationInsights.TypeScript.NuGet</RootNamespace>
<AssemblyName>Microsoft.ApplicationInsights.TypeScript.NuGet</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<!-- Suppress the "CS2008: No source files specified" warning -->
<NoWarn>2008</NoWarn>
<PackageSpecFile>$(MSBuildProjectDirectory)\Package.nuspec</PackageSpecFile>
<PackageVersionFile>$(BinRoot)\$(Configuration)\JavaScript\NuGet.TypeScript\Microsoft.ApplicationInsights.TypeScript.NuGet.dll</PackageVersionFile>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' " />
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' " />
<ItemGroup>
<None Include="Package.nuspec" />
<Content Include="..\JavaScriptSDK\min\ai.d.ts">
<Link>ai.d.ts</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JavaScriptSDK\JavaScriptSDK.csproj">
<Project>{49ECFE69-8C92-4FA7-A7C3-CDB957C71654}</Project>
<Name>JavaScriptSDK</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\..\NuGet.targets" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), 'Package.targets'))\Package.targets" />
</Project>

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

@ -0,0 +1,24 @@
<?xml version="1.0"?>
<package >
<metadata>
<id>Microsoft.ApplicationInsights.TypeScript</id>
<version>$version$</version>
<title>Application Insights API for JavaScript Applications</title>
<authors>Microsoft</authors>
<owners>Microsoft</owners>
<language>en-us</language>
<licenseUrl>http://go.microsoft.com/fwlink/?LinkId=323613</licenseUrl>
<projectUrl>http://go.microsoft.com/fwlink/?LinkId=323612</projectUrl>
<iconUrl>$image$</iconUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>
<description>Application Insights API enables you to get insights into user behavior and monitor usage patterns for your Web and Multi-Device Hybrid Apps. Application Insights service collects the data, analyzes it and presents the results in the forms of graphs and reports in Application Insights portal in Microsoft Azure.</description>
<tags>Analytics Insights Telemetry JavaScript MDD Multi-Device ApplicationInsights Cordova Web</tags>
<copyright>Copyright © 2013-2022, Microsoft. All rights reserved.</copyright>
<dependencies>
<dependency id="Microsoft.ApplicationInsights.JavaScript" version="$version$"/>
</dependencies>
</metadata>
<files>
<file src="$configuration$\Javascript\NuGet.TypeScript\ai.d.ts" target="content\scripts\ai.$version$.d.ts" />
</files>
</package>

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

@ -0,0 +1,9 @@
rem This script is called by the CI build after each test run.
rem Kill all remaining IIS Express at the end of the test run.
rem This is a workaround for it locking the build directory and breaking the subsequent build.
tasklist /FI "IMAGENAME eq iisexpress*" | find /I /N "iisexpress"
if "%ERRORLEVEL%"=="0" taskkill /im iisexpress*
rem Push the nupkg file to our private NuGet repository
call %TF_BUILD_SOURCESDIRECTORY%\PushNugetPackages.cmd

24
NuGet.config Normal file
Просмотреть файл

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!-- This file belongs into the EnlistmentRoot folder next to EnlistmentRoot.marker. -->
<!-- See the comments in Global.props for explanations. -->
<packageRestore>
<add key="enabled" value="True" />
<add key="automatic" value="True" />
</packageRestore>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
<packageSources>
<add key="nuget.org" value="https://www.nuget.org/api/v2/" />
</packageSources>
<disabledPackageSources>
<!--add key="CDM Feed" value="true" /-->
</disabledPackageSources>
<activePackageSource>
<add key="All" value="(Aggregate source)" />
</activePackageSource>
<config>
<add key="repositoryPath" value="..\packages" />
</config>
</configuration>

Двоичные данные
NuGet.exe Normal file

Двоичный файл не отображается.

136
NuGet.targets Normal file
Просмотреть файл

@ -0,0 +1,136 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>
<!-- Enable the restore command to run before builds -->
<RestorePackages Condition=" '$(RestorePackages)' == '' ">false</RestorePackages>
<!-- Property that enables building a package from a project -->
<BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>
<!-- Determines if package restore consent is required to restore packages -->
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>
<!-- Download NuGet.exe if it does not already exist -->
<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
</PropertyGroup>
<ItemGroup Condition=" '$(PackageSources)' == '' ">
<!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used -->
<!-- The official NuGet package source (https://www.nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list -->
<!--
<PackageSource Include="https://www.nuget.org/api/v2/" />
<PackageSource Include="https://my-nuget-source/nuget/" />
-->
</ItemGroup>
<PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
<!-- Windows specific commands -->
<NuGetToolsPath>$(MSBuildThisFileDirectory)</NuGetToolsPath>
<PackagesConfig>$([System.IO.Path]::Combine($(ProjectDir), "packages.config"))</PackagesConfig>
</PropertyGroup>
<PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
<!-- We need to launch nuget.exe with the mono command if we're not on windows -->
<NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
<PackagesConfig>packages.config</PackagesConfig>
</PropertyGroup>
<PropertyGroup>
<!-- NuGet command -->
<NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\NuGet.exe</NuGetExePath>
<PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>
<NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
<NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 $(NuGetExePath)</NuGetCommand>
<PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>
<RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
<NonInteractiveSwitch Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' ">-NonInteractive</NonInteractiveSwitch>
<PaddedSolutionDir Condition=" '$(OS)' == 'Windows_NT'">"$(SolutionDir) "</PaddedSolutionDir>
<PaddedSolutionDir Condition=" '$(OS)' != 'Windows_NT' ">"$(SolutionDir)"</PaddedSolutionDir>
<!-- Commands -->
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>
<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>
<!-- We need to ensure packages are restored prior to assembly resolve -->
<BuildDependsOn Condition="$(RestorePackages) == 'true'">
RestorePackages;
$(BuildDependsOn);
</BuildDependsOn>
<!-- Make the build depend on restore packages -->
<BuildDependsOn Condition="$(BuildPackage) == 'true'">
$(BuildDependsOn);
BuildPackage;
</BuildDependsOn>
</PropertyGroup>
<Target Name="CheckPrerequisites">
<!-- Raise an error if we're unable to locate nuget.exe -->
<Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
<!--
Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once.
This effectively acts as a lock that makes sure that the download operation will only happen once and all
parallel builds will have to wait for it to complete.
-->
<MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT;DownloadNuGetExe=$(DownloadNuGetExe)" />
</Target>
<Target Name="_DownloadNuGet">
<DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
</Target>
<Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(RestoreCommand)"
Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />
<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target>
<Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(BuildCommand)"
Condition=" '$(OS)' != 'Windows_NT' " />
<Exec Command="$(BuildCommand)"
LogStandardErrorAsError="true"
Condition=" '$(OS)' == 'Windows_NT' " />
</Target>
<UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<OutputFilename ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Core" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Net" />
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try {
OutputFilename = Path.GetFullPath(OutputFilename);
Log.LogMessage("Downloading latest version of NuGet.exe...");
WebClient webClient = new WebClient();
webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);
return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}
]]>
</Code>
</Task>
</UsingTask>
</Project>

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