<commit_before>var _manifest;
var _manifestError;
var _offlineView;
var _mainView;
var _zIndex = 10000;
var _enableOfflineSupport = true;
var _lastKnownLocation;
var _lastKnownLocationFailed = false;
var _whiteList = [];

// creates a webview to host content
function configureHost(url, zOrder, display) {
    var webView = document.createElement(cordova.platformId === 'windows8' ? 'iframe' : 'x-ms-webview');
    var style = webView.style;
    style.position = 'absolute';
    style.top = 0;
    style.left = 0;
    style.zIndex = zOrder;
    style.width = '100%';
    style.height = '100%';
    if (display) {
        style.display = display;
    }

    if (url) {
        webView.src = url;
    }

    webView.addEventListener("MSWebViewNavigationCompleted", navigationCompletedEvent, false);
    webView.addEventListener("MSWebViewNavigationStarting", navigationStartingEvent, false);

    document.body.appendChild(webView);

    return webView;
}

// handles webview's navigation starting event
function navigationStartingEvent(evt) {
    if (evt.uri && evt.uri !== "") {
        var isInWhitelist = false;
        for (var i = 0; i < _whiteList.length; i++) {
            var rule = _whiteList[i];
            if (rule.test(evt.uri)) {
                isInWhitelist = true;
                break;
            }
        }

        // if the url to navigate to does not match any of the rules in the whitelist, open it outside de app
        if (!isInWhitelist) {
            evt.stopImmediatePropagation();
            evt.preventDefault();
            console.log("Popping out URL: " + evt.uri);
            Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri(evt.uri));
        }
    }
}

// handles webview's navigation completed event
function navigationCompletedEvent(evt) {
    if (evt.uri && evt.uri !== "") {
        if (evt.isSuccess) {
            _lastKnownLocationFailed = false;
            if (_offlineView) {
                _offlineView.style.display = 'none';
            }
        } else {
            _lastKnownLocationFailed = true;
        }

        _lastKnownLocation = evt.uri;
    }
}

// handles network connectivity change events
function connectivityEvent(evt) {
    console.log('Received a network connectivity change notification. The device is currently ' + evt.type + '.');
    if (_enableOfflineSupport) {
        if (evt.type === 'offline') {
            _offlineView.style.display = 'block';
        } else if (evt.type === 'online') {
            if (_lastKnownLocationFailed) {
                if (_lastKnownLocation) {
                    console.log("Reload last known location: '" + _lastKnownLocation + "'");
                    _mainView.src = _lastKnownLocation;
                }
            } else {
                _offlineView.style.display = 'none';
            }
        }
    }
}

// sets up a secondary webview to host the offline page
function configureOfflineSupport(offlinePage) {
    var offlinePageUrl = '///www/' + offlinePage;
    var url = new Windows.Foundation.Uri('ms-appx:' + offlinePageUrl);
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(
        function (file) {
            _offlineView = configureHost('ms-appx-web:' + offlinePageUrl, 10001, 'none');
        },
        function (err) {
            var message = 'It looks like you are offline. Please reconnect to use this application.';
            var offlinePageTemplate = '
' + message + '
';
            _offlineView = configureHost(null, _zIndex + 1, 'none');

            if (cordova.platformId === 'windows8') {
                _offlineView.style.backgroundColor = 'white';
                _offlineView.contentDocument.write(offlinePageTemplate);
            } else {
                _offlineView.navigateToString(offlinePageTemplate);
            }
        }).done(function () {
            document.addEventListener('offline', connectivityEvent, false);
            document.addEventListener('online', connectivityEvent, false);
        });
}

// escapes regular expression reserved symbols
function escapeRegex(str) {
    return ("" + str).replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}

// converts a string pattern to a regular expression
function convertPatternToRegex(pattern, excludeLineStart, excludeLineEnd) {
    var isNot = (pattern[0] == '!');
    if (isNot) { pattern = pattern.substr(1) };

    var regexBody = escapeRegex(pattern);

    excludeLineStart = !!excludeLineStart;
    excludeLineEnd = !!excludeLineEnd;

    regexBody = regexBody.replace(/\\\?/g, ".?").replace(/\\\*/g, ".*?");
    if (isNot) { regexBody = "((?!" + regexBody + ").)*"; }
    if (!excludeLineStart) { regexBody = "^" + regexBody; }
    if (!excludeLineEnd) { regexBody += "\/?$"; }

    return new RegExp(regexBody);
}

// initializes an array of the access rules defined in the manifest
function configureWhiteList(manifest) {
    if (manifest) {
        // Add base access rule based on the start_url and the scope
        var baseUrlPattern = new Windows.Foundation.Uri(manifest.start_url);
        if (manifest.scope && manifest.scope.length) {
            baseUrlPattern = baseUrlPattern.combineUri(manifest.scope);
        }

        baseUrlPattern = baseUrlPattern.combineUri('*');
        _whiteList.push(convertPatternToRegex(baseUrlPattern.absoluteUri));

        // add additional access rules
        if (manifest.mjs_access_whitelist && manifest.mjs_access_whitelist instanceof Array) {
            manifest.mjs_access_whitelist.forEach(function (rule) {
                _whiteList.push(convertPatternToRegex(rule.url));
            });
        }
    }
}

module.exports = {
    // loads the W3C manifest file and parses it
    loadManifest: function (successCallback, errorCallback, args) {
        var manifestFileName = (args && args instanceof Array && args.length > 0) ? args[0] : 'manifest.json';
        var configFile = 'ms-appx:///www/' + manifestFileName;
        var uri = new Windows.Foundation.Uri(configFile);
        Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(
            function (file) {
                Windows.Storage.FileIO.readTextAsync(file).then(function (data) {
                    try {
                        _manifest = JSON.parse(data);
                        cordova.fireDocumentEvent("manifestLoaded", { manifest: _manifest });
                        if (successCallback) {
                            successCallback(_manifest);
                        }
                    } catch (err) {
                        _manifestError = 'Error parsing manifest file: ' + manifestFileName + ' - ' + err.message;
                        console.log(_manifestError);
                    }
                });
            },
            function (err) {
                _manifestError = 'Error reading manifest file: ' + manifestFileName + ' - ' + err;
                console.log(_manifestError);
                if (errorCallback) {
                    errorCallback(err);
                }
            });
    },

    // returns the currently loaded manifest
    getManifest: function (successCallback, errorCallback) {
        if (_manifest) {
            if (successCallback) {
                successCallback(_manifest);
            }
        } else {
            if (errorCallback) {
                errorCallback(new Error(_manifestError));
            }
        }
    },

    // enables offline page support
    enableOfflinePage: function () {
        _enableOfflineSupport = true;
    },

    // disables offline page support
    disableOfflinePage: function () {
        _enableOfflineSupport = false;
    },

    getWebView: function () {
      return _mainView;
    }
}; // exports

cordova.commandProxy.add('HostedWebApp', module.exports);

module.exports.loadManifest(
    function (manifest) {
        configureOfflineSupport('offline.html');
        configureWhiteList(manifest);
        _mainView = configureHost(manifest ? manifest.start_url : 'about:blank', _zIndex);
        cordova.fireDocumentEvent("webviewCreated", { webView: _mainView });
    });
<commit_msg>[windows] hide the extended splash screen when the content is loaded<commit_after>var _manifest;
var _manifestError;
var _offlineView;
var _mainView;
var _zIndex = 10000;
var _enableOfflineSupport = true;
var _lastKnownLocation;
var _lastKnownLocationFailed = false;
var _whiteList = [];

// creates a webview to host content
function configureHost(url, zOrder, display) {
    var webView = document.createElement(cordova.platformId === 'windows8' ? 'iframe' : 'x-ms-webview');
    var style = webView.style;
    style.position = 'absolute';
    style.top = 0;
    style.left = 0;
    style.zIndex = zOrder;
    style.width = '100%';
    style.height = '100%';
    if (display) {
        style.display = display;
    }

    if (url) {
        webView.src = url;
    }

    webView.addEventListener("MSWebViewNavigationCompleted", navigationCompletedEvent, false);
    webView.addEventListener("MSWebViewNavigationStarting", navigationStartingEvent, false);

    document.body.appendChild(webView);

    return webView;
}

// handles webview's navigation starting event
function navigationStartingEvent(evt) {
    if (evt.uri && evt.uri !== "") {
        var isInWhitelist = false;
        for (var i = 0; i < _whiteList.length; i++) {
            var rule = _whiteList[i];
            if (rule.test(evt.uri)) {
                isInWhitelist = true;
                break;
            }
        }

        // if the url to navigate to does not match any of the rules in the whitelist, open it outside de app
        if (!isInWhitelist) {
            evt.stopImmediatePropagation();
            evt.preventDefault();
            console.log("Popping out URL: " + evt.uri);
            Windows.System.Launcher.launchUriAsync(new Windows.Foundation.Uri(evt.uri));
        }
    }
}

// handles webview's navigation completed event
function navigationCompletedEvent(evt) {
    if (evt.uri && evt.uri !== "") {
        if (evt.isSuccess) {
            _lastKnownLocationFailed = false;
            if (_offlineView) {
                _offlineView.style.display = 'none';
            }
        } else {
            _lastKnownLocationFailed = true;
        }

        _lastKnownLocation = evt.uri;
    }
}

// handles network connectivity change events
function connectivityEvent(evt) {
    console.log('Received a network connectivity change notification. The device is currently ' + evt.type + '.');
    if (_enableOfflineSupport) {
        if (evt.type === 'offline') {
            _offlineView.style.display = 'block';
        } else if (evt.type === 'online') {
            if (_lastKnownLocationFailed) {
                if (_lastKnownLocation) {
                    console.log("Reload last known location: '" + _lastKnownLocation + "'");
                    _mainView.src = _lastKnownLocation;
                }
            } else {
                _offlineView.style.display = 'none';
            }
        }
    }
}

// sets up a secondary webview to host the offline page
function configureOfflineSupport(offlinePage) {
    var offlinePageUrl = '///www/' + offlinePage;
    var url = new Windows.Foundation.Uri('ms-appx:' + offlinePageUrl);
    Windows.Storage.StorageFile.getFileFromApplicationUriAsync(url).then(
        function (file) {
            _offlineView = configureHost('ms-appx-web:' + offlinePageUrl, 10001, 'none');
        },
        function (err) {
            var message = 'It looks like you are offline. Please reconnect to use this application.';
            var offlinePageTemplate = '
' + message + '
';
            _offlineView = configureHost(null, _zIndex + 1, 'none');

            if (cordova.platformId === 'windows8') {
                _offlineView.style.backgroundColor = 'white';
                _offlineView.contentDocument.write(offlinePageTemplate);
            } else {
                _offlineView.navigateToString(offlinePageTemplate);
            }
        }).done(function () {
            document.addEventListener('offline', connectivityEvent, false);
            document.addEventListener('online', connectivityEvent, false);
        });
}

// escapes regular expression reserved symbols
function escapeRegex(str) {
    return ("" + str).replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
}

// converts a string pattern to a regular expression
function convertPatternToRegex(pattern, excludeLineStart, excludeLineEnd) {
    var isNot = (pattern[0] == '!');
    if (isNot) { pattern = pattern.substr(1) };

    var regexBody = escapeRegex(pattern);

    excludeLineStart = !!excludeLineStart;
    excludeLineEnd = !!excludeLineEnd;

    regexBody = regexBody.replace(/\\\?/g, ".?").replace(/\\\*/g, ".*?");
    if (isNot) { regexBody = "((?!" + regexBody + ").)*"; }
    if (!excludeLineStart) { regexBody = "^" + regexBody; }
    if (!excludeLineEnd) { regexBody += "\/?$"; }

    return new RegExp(regexBody);
}

// initializes an array of the access rules defined in the manifest
function configureWhiteList(manifest) {
    if (manifest) {
        // Add base access rule based on the start_url and the scope
        var baseUrlPattern = new Windows.Foundation.Uri(manifest.start_url);
        if (manifest.scope && manifest.scope.length) {
            baseUrlPattern = baseUrlPattern.combineUri(manifest.scope);
        }

        baseUrlPattern = baseUrlPattern.combineUri('*');
        _whiteList.push(convertPatternToRegex(baseUrlPattern.absoluteUri));

        // add additional access rules
        if (manifest.mjs_access_whitelist && manifest.mjs_access_whitelist instanceof Array) {
            manifest.mjs_access_whitelist.forEach(function (rule) {
                _whiteList.push(convertPatternToRegex(rule.url));
            });
        }
    }
}

// hides the extended splash screen
function hideExtendedSplashScreen(e) {
    var extendedSplashScreen = document.getElementById("extendedSplashScreen");
    extendedSplashScreen.style.display = "none";
}

module.exports = {
    // loads the W3C manifest file and parses it
    loadManifest: function (successCallback, errorCallback, args) {
        var manifestFileName = (args && args instanceof Array && args.length > 0) ? args[0] : 'manifest.json';
        var configFile = 'ms-appx:///www/' + manifestFileName;
        var uri = new Windows.Foundation.Uri(configFile);
        Windows.Storage.StorageFile.getFileFromApplicationUriAsync(uri).then(
            function (file) {
                Windows.Storage.FileIO.readTextAsync(file).then(function (data) {
                    try {
                        _manifest = JSON.parse(data);
                        cordova.fireDocumentEvent("manifestLoaded", { manifest: _manifest });
                        if (successCallback) {
                            successCallback(_manifest);
                        }
                    } catch (err) {
                        _manifestError = 'Error parsing manifest file: ' + manifestFileName + ' - ' + err.message;
                        console.log(_manifestError);
                    }
                });
            },
            function (err) {
                _manifestError = 'Error reading manifest file: ' + manifestFileName + ' - ' + err;
                console.log(_manifestError);
                if (errorCallback) {
                    errorCallback(err);
                }
            });
    },

    // returns the currently loaded manifest
    getManifest: function (successCallback, errorCallback) {
        if (_manifest) {
            if (successCallback) {
                successCallback(_manifest);
            }
        } else {
            if (errorCallback) {
                errorCallback(new Error(_manifestError));
            }
        }
    },

    // enables offline page support
    enableOfflinePage: function () {
        _enableOfflineSupport = true;
    },

    // disables offline page support
    disableOfflinePage: function () {
        _enableOfflineSupport = false;
    },

    getWebView: function () {
      return _mainView;
    }
}; // exports

cordova.commandProxy.add('HostedWebApp', module.exports);

module.exports.loadManifest(
    function (manifest) {
        configureOfflineSupport('offline.html');
        configureWhiteList(manifest);
        _mainView = configureHost(manifest ? manifest.start_url : 'about:blank', _zIndex);
        _mainView.addEventListener("MSWebViewDOMContentLoaded", hideExtendedSplashScreen, false);

        cordova.fireDocumentEvent("webviewCreated", { webView: _mainView });
    });
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

if (this.WScript && this.WScript.LoadScriptFile) { // Check for running in ch
    this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js");
}
var tests = [
    {
        name: "function declaration test",
        body: function ()
        {
            eval("function \n\t\r foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "function assignment test",
        body: function ()
        {
            eval("var a = function \t\n\r\t foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            a = function (i) { i++; }
            assert.areEqual("function (i) { i++; }", a.toString(), "toString should add a space if one does not exist");
        }
    },
    {
        name: "generator function declaration test",
        body: function ()
        {
            eval("function* \t\r\n  foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("function \t\r\n*\n\r\n \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace,  new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "generator function assignment test",
        body: function ()
        {
            eval("var a = function* \t\n\r  \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("var a = function \t\n\r  *  \t\n foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "Named function expression tests",
        body: function ()
        {
            eval("var o = { foo : function \n\t bar \t () {}}");
            eval("o.e = function \t qui \t () {}");
            assert.areEqual("function bar() {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function qui() {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "function expression tests without names",
        body: function ()
        {
            eval("var o = { foo : function \n\t  \t () {}}");
            eval("o.e = function \t  \t () {}");
            assert.areEqual("function () {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function () {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "internal function test",
        body: function ()
        {
            eval("function foo() { return foo.toString(); }");
            var a = foo;
            assert.areEqual("function foo() { return foo.toString(); }", a(), "confirm that even if we call toString internally it has no effect on the name")
        }
    },
    {
        name: "class method test",
        body: function ()
        {
            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            assert.areEqual("func(){}", qux.func.toString(), "the name should be func")
            assert.areEqual("method(){}", quxObj.method.toString(), "the name should be method")

            var oGet = Object.getOwnPropertyDescriptor(qux.prototype, "getter");
            var oSet = Object.getOwnPropertyDescriptor(qux.prototype, "setter");
            assert.areEqual("getter(){}", oGet.get.toString(), "the name should be getter");
            assert.areEqual("setter(v){}", oSet.set.toString(), "the name should be setter");
        }
    },
    /* TODO fix and re-enable this test case (Microsoft/ChakraCore#3008)
    {
        name: "class constructor test",
        body: function ()
        {
            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            // FIXME Test threw exception: assert.areEqual failed: expected: constructor(){} actual: class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}
            assert.areEqual("constructor(){}", quxObj.constructor.toString(), "The constructor should have the toString  with name constructor");

            var qux = class { };
            var quxObj = new qux();
            // I left a space between closing ellipse ) and the opening bracket { because that's how all browsers do toString on runtime functions
            // Should this not be how other browsers do default constructor go to RuntimeCommon.h and change JS_DEFAULT_CTOR_DISPLAY_STRING
            // FIXME Test threw exception: assert.areEqual failed: expected: constructor() {} actual: class { }
            assert.areEqual("constructor() {}", quxObj.constructor.toString(), "The constructor should have the toString with name constructor")
        }
    },
    */
    {
        name: "shorthand method function test",
        body: function ()
        {
            // TODO update this test after fixing output (see Microsoft/ChakraCore#2914: Incorrect Function toString for methods declared with string in brackets)
            var o = { ['f']() { }, g() { } };
            assert.areEqual("f() { }", o.f.toString());
        }
    },
    {
        name: "arrow function Test",
        body: function ()
        {
            var arrowDecl = () => { };
            assert.areEqual("() => { }", arrowDecl.toString(), "Make sure arrow functions remain unaffected by ie12 formatting");
        }
    }
];

testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
<commit_msg>[1.7>master] [1.6>1.7] [MERGE #3361 @suwc] Fix issue#3008: [Disabled Test] Fix and re-enable test case<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

if (this.WScript && this.WScript.LoadScriptFile) { // Check for running in ch
    this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js");
}
var tests = [
    {
        name: "function declaration test",
        body: function ()
        {
            eval("function \n\t\r foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "function assignment test",
        body: function ()
        {
            eval("var a = function \t\n\r\t foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            a = function (i) { i++; }
            assert.areEqual("function (i) { i++; }", a.toString(), "toString should add a space if one does not exist");
        }
    },
    {
        name: "generator function declaration test",
        body: function ()
        {
            eval("function* \t\r\n  foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("function \t\r\n*\n\r\n \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace,  new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "generator function assignment test",
        body: function ()
        {
            eval("var a = function* \t\n\r  \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("var a = function \t\n\r  *  \t\n foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "Named function expression tests",
        body: function ()
        {
            eval("var o = { foo : function \n\t bar \t () {}}");
            eval("o.e = function \t qui \t () {}");
            assert.areEqual("function bar() {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function qui() {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "function expression tests without names",
        body: function ()
        {
            eval("var o = { foo : function \n\t  \t () {}}");
            eval("o.e = function \t  \t () {}");
            assert.areEqual("function () {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function () {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "internal function test",
        body: function ()
        {
            eval("function foo() { return foo.toString(); }");
            var a = foo;
            assert.areEqual("function foo() { return foo.toString(); }", a(), "confirm that even if we call toString internally it has no effect on the name")
        }
    },
    {
        name: "class method test",
        body: function ()
        {
            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            assert.areEqual("func(){}", qux.func.toString(), "the name should be func")
            assert.areEqual("method(){}", quxObj.method.toString(), "the name should be method")

            var oGet = Object.getOwnPropertyDescriptor(qux.prototype, "getter");
            var oSet = Object.getOwnPropertyDescriptor(qux.prototype, "setter");
            assert.areEqual("getter(){}", oGet.get.toString(), "the name should be getter");
            assert.areEqual("setter(v){}", oSet.set.toString(), "the name should be setter");
        }
    },
    {
        name: "class constructor test",
        body: function ()
        {
            // [19.2.3.5] Function.prototype.toString()
            // The string representation must have the syntax of a FunctionDeclaration, FunctionExpression, GeneratorDeclaration,
            //     GeneratorExpression, AsyncFunctionDeclaration, AsyncFunctionExpression, ClassDeclaration, ClassExpression, ArrowFunction,
            //     AsyncArrowFunction, or MethodDefinition depending upon the actual characteristics of the object.

            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            assert.areEqual("class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}",
                quxObj.constructor.toString(), "The string representation must have the syntax of a ClassExpression");

            var qux = class { };
            var quxObj = new qux();
            assert.areEqual("class { }", quxObj.constructor.toString(), "The string representation must have the syntax of a ClassDeclaration")
        }
    },
    {
        name: "shorthand method function test",
        body: function ()
        {
            // TODO update this test after fixing output (see Microsoft/ChakraCore#2914: Incorrect Function toString for methods declared with string in brackets)
            var o = { ['f']() { }, g() { } };
            assert.areEqual("f() { }", o.f.toString());
        }
    },
    {
        name: "arrow function Test",
        body: function ()
        {
            var arrowDecl = () => { };
            assert.areEqual("() => { }", arrowDecl.toString(), "Make sure arrow functions remain unaffected by ie12 formatting");
        }
    }
];

testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

if (this.WScript && this.WScript.LoadScriptFile) { // Check for running in ch
    this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js");
}
var tests = [
    {
        name: "function declaration test",
        body: function ()
        {
            eval("function \n\t\r foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "function assignment test",
        body: function ()
        {
            eval("var a = function \t\n\r\t foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            a = function (i) { i++; }
            assert.areEqual("function (i) { i++; }", a.toString(), "toString should add a space if one does not exist");
        }
    },
    {
        name: "generator function declaration test",
        body: function ()
        {
            eval("function* \t\r\n  foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("function \t\r\n*\n\r\n \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace,  new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "generator function assignment test",
        body: function ()
        {
            eval("var a = function* \t\n\r  \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("var a = function \t\n\r  *  \t\n foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "Named function expression tests",
        body: function ()
        {
            eval("var o = { foo : function \n\t bar \t () {}}");
            eval("o.e = function \t qui \t () {}");
            assert.areEqual("function bar() {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function qui() {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "function expression tests without names",
        body: function ()
        {
            eval("var o = { foo : function \n\t  \t () {}}");
            eval("o.e = function \t  \t () {}");
            assert.areEqual("function () {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function () {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "internal function test",
        body: function ()
        {
            eval("function foo() { return foo.toString(); }");
            var a = foo;
            assert.areEqual("function foo() { return foo.toString(); }", a(), "confirm that even if we call toString internally it has no effect on the name")
        }
    },
    {
        name: "class method test",
        body: function ()
        {
            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            assert.areEqual("func(){}", qux.func.toString(), "the name should be func")
            assert.areEqual("method(){}", quxObj.method.toString(), "the name should be method")

            var oGet = Object.getOwnPropertyDescriptor(qux.prototype, "getter");
            var oSet = Object.getOwnPropertyDescriptor(qux.prototype, "setter");
            assert.areEqual("getter(){}", oGet.get.toString(), "the name should be getter");
            assert.areEqual("setter(v){}", oSet.set.toString(), "the name should be setter");
        }
    },
    /* TODO fix and re-enable this test case (Microsoft/ChakraCore#3008)
    {
        name: "class constructor test",
        body: function ()
        {
            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            // FIXME Test threw exception: assert.areEqual failed: expected: constructor(){} actual: class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}
            assert.areEqual("constructor(){}", quxObj.constructor.toString(), "The constructor should have the toString  with name constructor");

            var qux = class { };
            var quxObj = new qux();
            // I left a space between closing ellipse ) and the opening bracket { because that's how all browsers do toString on runtime functions
            // Should this not be how other browsers do default constructor go to RuntimeCommon.h and change JS_DEFAULT_CTOR_DISPLAY_STRING
            // FIXME Test threw exception: assert.areEqual failed: expected: constructor() {} actual: class { }
            assert.areEqual("constructor() {}", quxObj.constructor.toString(), "The constructor should have the toString with name constructor")
        }
    },
    */
    {
        name: "shorthand method function test",
        body: function ()
        {
            // TODO update this test after fixing output (see Microsoft/ChakraCore#2914: Incorrect Function toString for methods declared with string in brackets)
            var o = { ['f']() { }, g() { } };
            assert.areEqual("f() { }", o.f.toString());
        }
    },
    {
        name: "arrow function Test",
        body: function ()
        {
            var arrowDecl = () => { };
            assert.areEqual("() => { }", arrowDecl.toString(), "Make sure arrow functions remain unaffected by ie12 formatting");
        }
    }
];

testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
<commit_msg>Fix issue#3008: [Disabled Test] Fix and re-enable test case<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------

if (this.WScript && this.WScript.LoadScriptFile) { // Check for running in ch
    this.WScript.LoadScriptFile("..\\UnitTestFramework\\UnitTestFramework.js");
}
var tests = [
    {
        name: "function declaration test",
        body: function ()
        {
            eval("function \n\t\r foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "function assignment test",
        body: function ()
        {
            eval("var a = function \t\n\r\t foo() {var a = 5;}");
            assert.areEqual("function foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            a = function (i) { i++; }
            assert.areEqual("function (i) { i++; }", a.toString(), "toString should add a space if one does not exist");
        }
    },
    {
        name: "generator function declaration test",
        body: function ()
        {
            eval("function* \t\r\n  foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("function \t\r\n*\n\r\n \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", foo.toString(), "toString should remove all extra whitespace,  new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "generator function assignment test",
        body: function ()
        {
            eval("var a = function* \t\n\r  \t foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
            eval("var a = function \t\n\r  *  \t\n foo() {var a = 5;}");
            assert.areEqual("function* foo() {var a = 5;}", a.toString(), "toString should remove all extra whitespace, new lines, tabs and carriage return before the open (");
        }
    },
    {
        name: "Named function expression tests",
        body: function ()
        {
            eval("var o = { foo : function \n\t bar \t () {}}");
            eval("o.e = function \t qui \t () {}");
            assert.areEqual("function bar() {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function qui() {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "function expression tests without names",
        body: function ()
        {
            eval("var o = { foo : function \n\t  \t () {}}");
            eval("o.e = function \t  \t () {}");
            assert.areEqual("function () {}", o.foo.toString(), "confirm that the foo identifier does not override the name bar ");
            assert.areEqual("function () {}", o.e.toString(), "confirm that the foo identifier does not override the name qui");
        }
    },
    {
        name: "internal function test",
        body: function ()
        {
            eval("function foo() { return foo.toString(); }");
            var a = foo;
            assert.areEqual("function foo() { return foo.toString(); }", a(), "confirm that even if we call toString internally it has no effect on the name")
        }
    },
    {
        name: "class method test",
        body: function ()
        {
            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            assert.areEqual("func(){}", qux.func.toString(), "the name should be func")
            assert.areEqual("method(){}", quxObj.method.toString(), "the name should be method")

            var oGet = Object.getOwnPropertyDescriptor(qux.prototype, "getter");
            var oSet = Object.getOwnPropertyDescriptor(qux.prototype, "setter");
            assert.areEqual("getter(){}", oGet.get.toString(), "the name should be getter");
            assert.areEqual("setter(v){}", oSet.set.toString(), "the name should be setter");
        }
    },
    {
        name: "class constructor test",
        body: function ()
        {
            // [19.2.3.5] Function.prototype.toString()
            // The string representation must have the syntax of a FunctionDeclaration, FunctionExpression, GeneratorDeclaration,
            //     GeneratorExpression, AsyncFunctionDeclaration, AsyncFunctionExpression, ClassDeclaration, ClassExpression, ArrowFunction,
            //     AsyncArrowFunction, or MethodDefinition depending upon the actual characteristics of the object.

            eval("var qux = class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}");
            var quxObj = new qux();
            assert.areEqual("class { constructor(){} static func(){} method(){} get getter(){} set setter(v){}}",
                quxObj.constructor.toString(), "The string representation must have the syntax of a ClassExpression");

            var qux = class { };
            var quxObj = new qux();
            assert.areEqual("class { }", quxObj.constructor.toString(), "The string representation must have the syntax of a ClassDeclaration")
        }
    },
    {
        name: "shorthand method function test",
        body: function ()
        {
            // TODO update this test after fixing output (see Microsoft/ChakraCore#2914: Incorrect Function toString for methods declared with string in brackets)
            var o = { ['f']() { }, g() { } };
            assert.areEqual("f() { }", o.f.toString());
        }
    },
    {
        name: "arrow function Test",
        body: function ()
        {
            var arrowDecl = () => { };
            assert.areEqual("() => { }", arrowDecl.toString(), "Make sure arrow functions remain unaffected by ie12 formatting");
        }
    }
];

testRunner.runTests(tests, { verbose: WScript.Arguments[0] != "summary" });
<|endoftext|>


<commit_before>'use strict';

var runFn = require('./run-fn');

function sequentialTests(beforeTestFns, test, afterTestFns) {
  var testResult, proms = [];
  var index = 0;
  function nextProm(result) {
    if (result.success) {
      if (index < proms.length - 1) {
        index++;
        return proms[index].then(nextProm);
      }

      return testResult;
    }

    return result;
  }

  if (beforeTestFns.length) {
    proms.push(
      runSequentialTests(beforeTestFns)
        .then(function onBefore(info) {
          if (!info.success) {
            info.name = 'beforeEach: ' + test.name;
            info.beforeTest = true;
          }
          return info;
        })
    );
  }

  proms.push(runFn(test).then(function onEnd(result) {
    testResult = result;
    return result;
  }));

  if (afterTestFns.length) {
    proms.push(runSequentialTests(afterTestFns)
        .then(function onAfter(info) {
          if (!info.success) {
            info.name = 'afterEach: ' + test.name;
            info.afterTest = true;
          }

          return info;
        })
    );
  }

  return proms[0].then(nextProm);
}

function runSequentialTests(tests, index) {
  index = index || 0;
  var prom = runFn(tests[index]);
  return prom.then(function onThen(result) {
    if (index < tests.length - 1) {
      return runSequentialTests(tests, index + 1);
    }
    return result;
  });
}

module.exports = sequentialTests;
<commit_msg>update test/assertion/lib/sequential-tests — for painless<commit_after>'use strict';

var runFn = require('./run-fn');

function sequentialTests(beforeTestFns, test, afterTestFns) {
  var testResult, fns = [];
  var index = 0;
  function nextProm(result) {
    if (result.success) {
      if (index < fns.length - 1) {
        index++;
        return fns[index]().then(nextProm);
      }

      return testResult;
    }

    return result;
  }

  if (beforeTestFns.length) {
    fns.push(function beforeEachs() {
      return runSequentialTests(beforeTestFns)
        .then(function onBefore(info) {
          if (!info.success) {
            info.name = 'beforeEach: ' + test.name;
            info.beforeTest = true;
          }
          return info;
        });
    });
  }

  fns.push(function onTest() {
    return runFn(test).then(function onEnd(result) {
      testResult = result;
      return result;
    });
  });

  if (afterTestFns.length) {
    fns.push(function afterEachs() {
      return runSequentialTests(afterTestFns)
          .then(function onAfter(info) {
            if (!info.success) {
              info.name = 'afterEach: ' + test.name;
              info.afterTest = true;
            }

            return info;
          });
    });
  }

  return fns[0]().then(nextProm);
}

function runSequentialTests(tests, index) {
  index = index || 0;
  var prom = runFn(tests[index]);
  return prom.then(function onThen(result) {
    if (index < tests.length - 1) {
      return runSequentialTests(tests, index + 1);
    }
    return result;
  });
}

module.exports = sequentialTests;
<|endoftext|>


<commit_before>'use strict';

/**
 * Test pattern inspired by: daniellmb
 *
 * 2013-11-29
 * https://github.com/daniellmb/angular-test-patterns/blob/master/patterns/directive.md#render-the-expected-output-
 */

describe('Directive: conversationControl', function () {

    var CLIENT = 'yanfen@example.com',
        SERVER = 'dan@example.com';

    /**
     * Social commitments
     */
    var REPLY_REQUEST_ACTION = {
            performative: 'reply request',
            action: 'friend',
            message: { content: 'some data' },
            creditor: CLIENT,
            debtor: SERVER,
            created: Date.now(),
            fulfilled: null,
        },
        PROPOSE_DISCHARGE_PERFORM_ACTION = {
            performative: 'propose discharge|perform',
            action: 'friend',
            message: { content: 'some data' },
            creditor: CLIENT,
            debtor: SERVER,
            created: Date.now(),
            fulfilled: null,
        },
        PERFORM_ACTION = {
            performative: 'perform',
            action: 'friend',
            message: { content: 'some data' },
            creditor: CLIENT,
            debtor: SERVER,
            created: Date.now(),
            fulfilled: null,
        },
        REPLY_PROPOSE_DISCHARGE_PERFORM_ACTION = {
            performative: 'reply propose|discharge|perform',
            action: 'friend',
            message: { content: 'some data' },
            creditor: SERVER,
            debtor: CLIENT,
            created: Date.now(),
            fulfilled: null,
        };

    var CONVERSATION_ID = CLIENT + ':' + Date.now();

    var element,
        scope,
        compile,
        templateCache,
        request;

    /**
     * This function sets scope variables and
     * compiles the directive passed to it
     *
     * The element returned is to be compared to the
     * element generated by _compileTemplate
     *
     * @param Object
     * @param string
     * @param string
     *
     * @return Object
     */
    function _createDirective(sc, email, template) {
        var elm;

        // Setup scope state
        scope.sc = sc;
        scope.email = email;
        scope.conversationId = CONVERSATION_ID;

        // Create directive
        elm = compile(template)(scope);

        // Trigger watchers
        scope.$apply();

        // Return
        return elm;
    }

    /**
     * This function compiles the template at
     * the path provided
     *
     * @param string
     *
     * @return string
     */
    function _compileTemplate(path) {
        var template = templateCache.get(path);

        if (!template) {
          return '';
        }

        template = compile(template)(scope);

        var blank = angular.element('

');
        angular.element(blank).append(template);

        return blank.html();
    }

    /**
     * The Request callback that delivers
     * the new message to the sender
     */
    var _message;
    var _callback = function(message) {
        _message = message;
      }

    beforeEach(module('gebo-client-performatives.conversationControl'));

    beforeEach(function() {

        inject(function($rootScope, $compile, $templateCache, Request) {
            scope = $rootScope.$new();
            compile = $compile;
            templateCache = $templateCache;
            request = Request;
        });

        request.setCallback(_callback);
        _message = {};
    });

    it('should have set a callback function', function() {
        request.callback({ some: 'message' });
        expect(_message.some).toEqual('message');
    });

    it('should render the expected server-reply-request output', function() {
        element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-reply-request.html'));
    });

    it('should render the expected client-reply-request output', function() {
        element = _createDirective(REPLY_REQUEST_ACTION, CLIENT,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/client-reply-request.html'));
    });

    it('should render the expected server-propose-discharge-perform output', function() {
        element = _createDirective(PROPOSE_DISCHARGE_PERFORM_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-propose-discharge-perform.html'));
    });

    it('should render the expected client-propose-discharge-perform output', function() {
        element = _createDirective(PROPOSE_DISCHARGE_PERFORM_ACTION, CLIENT,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/client-propose-discharge-perform.html'));
    });

    it('should render the expected server-perform output', function() {
        element = _createDirective(PERFORM_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-perform.html'));
    });

    it('should render the expected server-reply-propose-discharge-perform output', function() {
        element = _createDirective(REPLY_PROPOSE_DISCHARGE_PERFORM_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-reply-propose-discharge-perform.html'));
    });

    it('should render the expected client-reply-propose-discharge-perform output', function() {
        element = _createDirective(REPLY_PROPOSE_DISCHARGE_PERFORM_ACTION, CLIENT,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/client-reply-propose-discharge-perform.html'));
    });

    describe('Server', function() {

        /**
         * not-understood
         */
        describe('not-understood', function() {
            it('should execute callback with \'not-understood request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.notUnderstood();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('not-understood request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * refuse
         */
        describe('refuse', function() {
            it('should execute callback with \'refuse request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.refuse();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('refuse request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * timeout
         */
        describe('timeout', function() {
            it('should execute callback with \'timeout request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.timeout();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('timeout request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * agree
         */
        describe('agree', function() {
            it('should execute callback with \'agree request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.agree();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('agree request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * failure
         */
        describe('failure', function() {
            it('should execute callback with \'failure perform\' message parameter', function() {
                element = _createDirective(PERFORM_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.failure();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('failure perform');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

    });

    describe('Client', function() {

        /**
         * request
         */
//        describe('request', function() {
//            it('should execute callback with \'agree request|action\' message parameter', function() {
//                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
//                    '<conversation-control sc="{{sc}}" email="{{email}}"> conversation-id="{{conversationId}}">' +
//                    '</conversation-control>');
//                var isolateScope = element.scope();
//                isolateScope.agree();
//            });
//        });
    });
});

<commit_msg>Get failure functionality with tests<commit_after>'use strict';

/**
 * Test pattern inspired by: daniellmb
 *
 * 2013-11-29
 * https://github.com/daniellmb/angular-test-patterns/blob/master/patterns/directive.md#render-the-expected-output-
 */

describe('Directive: conversationControl', function () {

    var CLIENT = 'yanfen@example.com',
        SERVER = 'dan@example.com';

    /**
     * Social commitments
     */
    var REPLY_REQUEST_ACTION = {
            performative: 'reply request',
            action: 'friend',
            message: { content: 'some data' },
            creditor: CLIENT,
            debtor: SERVER,
            created: Date.now(),
            fulfilled: null,
        },
        PROPOSE_DISCHARGE_PERFORM_ACTION = {
            performative: 'propose discharge|perform',
            action: 'friend',
            message: { content: 'some data' },
            creditor: CLIENT,
            debtor: SERVER,
            created: Date.now(),
            fulfilled: null,
        },
        PERFORM_ACTION = {
            performative: 'perform',
            action: 'friend',
            message: { content: 'some data' },
            creditor: CLIENT,
            debtor: SERVER,
            created: Date.now(),
            fulfilled: null,
        },
        REPLY_PROPOSE_DISCHARGE_PERFORM_ACTION = {
            performative: 'reply propose|discharge|perform',
            action: 'friend',
            message: { content: 'some data' },
            creditor: SERVER,
            debtor: CLIENT,
            created: Date.now(),
            fulfilled: null,
        };

    var CONVERSATION_ID = CLIENT + ':' + Date.now();

    var element,
        scope,
        compile,
        templateCache,
        request;

    /**
     * This function sets scope variables and
     * compiles the directive passed to it
     *
     * The element returned is to be compared to the
     * element generated by _compileTemplate
     *
     * @param Object
     * @param string
     * @param string
     *
     * @return Object
     */
    function _createDirective(sc, email, template) {
        var elm;

        // Setup scope state
        scope.sc = sc;
        scope.email = email;
        scope.conversationId = CONVERSATION_ID;

        // Create directive
        elm = compile(template)(scope);

        // Trigger watchers
        scope.$apply();

        // Return
        return elm;
    }

    /**
     * This function compiles the template at
     * the path provided
     *
     * @param string
     *
     * @return string
     */
    function _compileTemplate(path) {
        var template = templateCache.get(path);

        if (!template) {
          return '';
        }

        template = compile(template)(scope);

        var blank = angular.element('

');
        angular.element(blank).append(template);

        return blank.html();
    }

    /**
     * The Request callback that delivers
     * the new message to the sender
     */
    var _message;
    var _callback = function(message) {
        _message = message;
      }

    beforeEach(module('gebo-client-performatives.conversationControl'));

    beforeEach(function() {

        inject(function($rootScope, $compile, $templateCache, Request) {
            scope = $rootScope.$new();
            compile = $compile;
            templateCache = $templateCache;
            request = Request;
        });

        request.setCallback(_callback);
        _message = {};
    });

    it('should have set a callback function', function() {
        request.callback({ some: 'message' });
        expect(_message.some).toEqual('message');
    });

    it('should render the expected server-reply-request output', function() {
        element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-reply-request.html'));
    });

    it('should render the expected client-reply-request output', function() {
        element = _createDirective(REPLY_REQUEST_ACTION, CLIENT,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/client-reply-request.html'));
    });

    it('should render the expected server-propose-discharge-perform output', function() {
        element = _createDirective(PROPOSE_DISCHARGE_PERFORM_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-propose-discharge-perform.html'));
    });

    it('should render the expected client-propose-discharge-perform output', function() {
        element = _createDirective(PROPOSE_DISCHARGE_PERFORM_ACTION, CLIENT,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/client-propose-discharge-perform.html'));
    });

    it('should render the expected server-perform output', function() {
        element = _createDirective(PERFORM_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-perform.html'));
    });

    it('should render the expected server-reply-propose-discharge-perform output', function() {
        element = _createDirective(REPLY_PROPOSE_DISCHARGE_PERFORM_ACTION, SERVER,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/server-reply-propose-discharge-perform.html'));
    });

    it('should render the expected client-reply-propose-discharge-perform output', function() {
        element = _createDirective(REPLY_PROPOSE_DISCHARGE_PERFORM_ACTION, CLIENT,
                '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                '</conversation-control>');
        expect(element.html()).toEqual(_compileTemplate('templates/client-reply-propose-discharge-perform.html'));
    });

    describe('Server', function() {

        /**
         * not-understood
         */
        describe('not-understood', function() {
            it('should execute callback with \'not-understood request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.notUnderstood();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('not-understood request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * refuse
         */
        describe('refuse', function() {
            it('should execute callback with \'refuse request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.refuse();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('refuse request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * timeout
         */
        describe('timeout', function() {
            it('should execute callback with \'timeout request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.timeout();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('timeout request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * agree
         */
        describe('agree', function() {
            it('should execute callback with \'agree request|action\' message parameter', function() {
                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.agree();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('agree request');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * failure
         */
        describe('failure', function() {
            it('should execute callback with \'failure perform\' message parameter', function() {
                element = _createDirective(PERFORM_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.failure();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('failure perform');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });

        /**
         * proposeDischarge
         */
        describe('proposeDischarge', function() {
            it('should execute callback with \'propose discharge|perform\' message parameter', function() {
                element = _createDirective(PROPOSE_DISCHARGE_PERFORM_ACTION, SERVER,
                    '<conversation-control sc="{{sc}}" email="{{email}}" conversation-id="{{conversationId}}">' +
                    '</conversation-control>');
                var isolateScope = element.scope();
                isolateScope.proposeDischarge();

                expect(_message.sender).toEqual(SERVER);
                expect(_message.receiver).toEqual(CLIENT);
                expect(_message.performative).toEqual('propose discharge|perform');
                expect(_message.action).toEqual('friend');
                expect(_message.conversationId).toEqual(CONVERSATION_ID);
            });
        });
    });

    describe('Client', function() {

        /**
         * request
         */
//        describe('request', function() {
//            it('should execute callback with \'agree request|action\' message parameter', function() {
//                element = _createDirective(REPLY_REQUEST_ACTION, SERVER,
//                    '<conversation-control sc="{{sc}}" email="{{email}}"> conversation-id="{{conversationId}}">' +
//                    '</conversation-control>');
//                var isolateScope = element.scope();
//                isolateScope.agree();
//            });
//        });
    });
});

<|endoftext|>


<commit_before>'use strict';

var IndexTracking = require('../../lib/model/IndexTracking');
var NetFlowStorage = require('../../lib/model/NetFlowStorage');
var GetLogger = require('../../lib/util/GetLogger');

var logger = new GetLogger('quiet');
var config = require('config');
var moment = require('moment');
var es = require('elasticsearch');
var chaiAsPromised = require('chai-as-promised');

var chai = require('chai');
var expect = chai.expect;

var sinon = require('sinon');
var sinonChai = require('sinon-chai');
var moment = require('moment');
chai.use(chaiAsPromised);
chai.use(sinonChai);

describe('Integration Tests', function () {
    describe('IndexTracking', function () {
        it('should delete indicies', function (cb) {
            var nfStore = new NetFlowStorage(es, logger, config);
            var indexTrack = new IndexTracking(es, logger, config);
            var momentObj = moment();
            var timestamps = [];
            var testList = [];

            var callbackSpy = sinon.spy();

            // Build our values to test and check
            for (var i = 0 ; i < 3 ; i++) {
                timestamps.push(moment(momentObj)
                    .subtract(config.get('Application.retention_days') * i, 'd')
                    .valueOf());

                // Build our test list from every value but the last
                // which is the one that should be deleted
                if (i !== 2) {
                    testList.push(config.get('Application.index_name') +
                        '.' + moment(timestamps[i]).format('MM-DD-YYYY'));
                }
            }

            // Store the flows and set the clock prior to each store
            timestamps.forEach(function (currentValue, index, array) {
                var clock = sinon.useFakeTimers(currentValue);
                nfStore.storeFlow(getFlow());
                clock.restore();
            });

            // pause for a bit to let the DB catch up
            setTimeout(function () {
                indexTrack.getExpiredIndices(function (indexList) {
                    indexTrack.deleteIndices(indexList, function () {
                        indexTrack.getIndexList(function (indexList) {
                            expect(indexList.sort()).to.deep.equal(testList.sort());
                            cb();
                        });
                    });
                });
            }, 500); // 500ms pause
        });
    });
});

var getFlow = function () {
    return {
        ipv4_src_addr: '1.1.1.1', // 16843009
        ipv4_dst_addr: '2.2.2.2', // 33686018
        ipv4_next_hop: '3.3.3.3', // 50529027
        input_snmp: 1,
        output_snmp: 0,
        in_pkts: 29,
        in_bytes: 5000,
        first_switched: 598956992,
        last_switched: 598958053,
        ipv4_src_port: 22,
        ipv4_dst_port: 37402,
        tcp_flags: 27,
        protocol: 6,
        src_tos: 0,
        in_as: 0,
        out_as: 0,
        src_mask: 0,
        dst_mask: 0
    };
};
<commit_msg>Anchor test times to start of day<commit_after>'use strict';

var IndexTracking = require('../../lib/model/IndexTracking');
var NetFlowStorage = require('../../lib/model/NetFlowStorage');
var GetLogger = require('../../lib/util/GetLogger');

var logger = new GetLogger('quiet');
var config = require('config');
var moment = require('moment');
var es = require('elasticsearch');
var chaiAsPromised = require('chai-as-promised');

var chai = require('chai');
var expect = chai.expect;

var sinon = require('sinon');
var sinonChai = require('sinon-chai');
var moment = require('moment');
chai.use(chaiAsPromised);
chai.use(sinonChai);

describe('Integration Tests', function () {
    describe('IndexTracking', function () {
        it('should delete indicies', function (cb) {
            var nfStore = new NetFlowStorage(es, logger, config);
            var indexTrack = new IndexTracking(es, logger, config);
            var momentObj = moment();
            var timestamps = [];
            var testList = [];

            var callbackSpy = sinon.spy();

            // Build our values to test and check
            for (var i = 0 ; i < 3 ; i++) {
                timestamps.push(moment(momentObj)
                    .startOf('day')
                    .subtract(config.get('Application.retention_days') * i, 'd')
                    .valueOf());

                // Build our test list from every value but the last
                // which is the one that should be deleted
                if (i !== 2) {
                    testList.push(config.get('Application.index_name') +
                        '.' + moment(timestamps[i]).format('MM-DD-YYYY'));
                }
            }

            // Store the flows and set the clock prior to each store
            timestamps.forEach(function (currentValue, index, array) {
                var clock = sinon.useFakeTimers(currentValue);
                nfStore.storeFlow(getFlow());
                clock.restore();
            });

            // pause for a bit to let the DB catch up
            setTimeout(function () {
                indexTrack.getExpiredIndices(function (indexList) {
                    indexTrack.deleteIndices(indexList, function () {
                        indexTrack.getIndexList(function (indexList) {
                            expect(indexList.sort()).to.deep.equal(testList.sort());
                            cb();
                        });
                    });
                });
            }, 500); // 500ms pause
        });
    });
});

var getFlow = function () {
    return {
        ipv4_src_addr: '1.1.1.1', // 16843009
        ipv4_dst_addr: '2.2.2.2', // 33686018
        ipv4_next_hop: '3.3.3.3', // 50529027
        input_snmp: 1,
        output_snmp: 0,
        in_pkts: 29,
        in_bytes: 5000,
        first_switched: 598956992,
        last_switched: 598958053,
        ipv4_src_port: 22,
        ipv4_dst_port: 37402,
        tcp_flags: 27,
        protocol: 6,
        src_tos: 0,
        in_as: 0,
        out_as: 0,
        src_mask: 0,
        dst_mask: 0
    };
};
<|endoftext|>


<commit_before>var common = require('../../common'),
  assert = require('assert'),
  should = require('should'),
  path = require('path'),
  async = require('async'),
  resolver = require('../../resolver');

describe('Integration', function() {
  describe('Navigation Service', function() {
    var applicationInstance;
    beforeEach(function(done) {
      var Application = resolver.resolve('./application');
      applicationInstance = new Application();
      applicationInstance.configure({}, function(err) {
        if (err)
          return done(err);
        applicationInstance.load({}, done);
      });
    });

    describe("Navigate to unregistered view", function() {
      it('standard success', function(done) {
        // arrange
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");

        //act
        messageService.send("navigateToMessage", {
          viewKey: "RandomViewKey"
        });
        return done();
      });
    });

    describe("Navigation Forward", function() {
      it('standard success', function(done) {
        // arrange
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");
        var pages = [{
          key: "viewA",
          view: class extends entry.View.Page {},
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.1.html")
        }, {
          key: "viewB",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.2.html")
        }];

        //act
        async.eachSeries(pages,
          function(page, pageCb) {
            applicationInstance.builder.registerView(page.key,
              page.view,
              page.viewModel,
              page.templateUri
            );

            var navigateDelegate = function() {
              messageService.unregister("navigatedMessage",
                navigateDelegate);

              navigationService.view.should.be.an.instanceOf(page.view);
              navigationService.viewModel.should.be.an.instanceOf(page.viewModel);

              return pageCb();
            };

            messageService.register("navigatedMessage",
              navigateDelegate);

            messageService.send("navigateToMessage", {
              viewKey: page.key
            });

          }, done);
      });
    });

    describe("Back Navigation", function() {
      it('standard success', function(done) {
        // arrange
        var WinJS = require('winjs');
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");
        var pages = [{
          key: "viewA",
          view: class extends entry.View.Page {},
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.1.html")
        }, {
          key: "viewB",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.2.html")
        }, {
          key: "viewC",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.3.html")
        }];

        //act
        async.waterfall([
          function(cb) {
            async.eachSeries(pages,
              function(page, pageCb) {
                applicationInstance.builder.registerView(page.key,
                  page.view,
                  page.viewModel,
                  page.templateUri
                );

                var navigateDelegate = function() {
                  messageService.unregister("navigatedMessage",
                    navigateDelegate);
                  return pageCb();
                };

                messageService.register("navigatedMessage",
                  navigateDelegate);

                messageService.send("navigateToMessage", {
                  viewKey: page.key
                });
              }, cb);
          },
          function(cb) {
            async.eachSeries([2, 1, 0],
              function(pageIdx, pageIdxCb) {
                var page = pages[pageIdx];
                if (pageIdx != 0) {
                  //var targetPage = pages[pageIdx - 1];

                  // Assert can go back
                  WinJS.Navigation.canGoBack.should.be.ok();

                  var navigateDelegate = function() {
                    messageService.unregister("navigatedMessage",
                      navigateDelegate);
                    return pageIdxCb();
                  };

                  messageService.register("navigatedMessage",
                    navigateDelegate);

                  messageService.send("navigateBackMessage");
                } else {
                  // Assert cannot go back
                  WinJS.Navigation.canGoBack.should.not.be.ok();
                  return pageIdxCb();
                }
              }, cb);
          }
        ], done);
      });
    });

    describe("Modal Navigation", function() {
      it('standard success', function(done) {
        // arrange
        var WinJS = require('winjs');
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");
        var pages = [{
          key: "view1",
          view: class extends entry.View.Page {},
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.1.html")
        }, {
          key: "view2",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {
            get isModal() {
              return true;
            }
          },
          templateUri: path.join(__dirname, "..", "harness", "template.2.html")
        }, {
          key: "view3",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {
            get isModal() {
              return true;
            }
          },
          templateUri: path.join(__dirname, "..", "harness", "template.3.html")
        }, {
          key: "view4",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.4.html")
        }];

        //act
        async.waterfall([
          function(cb) {
            async.eachSeries(pages,
              function(page, pageCb) {
                applicationInstance.builder.registerView(page.key,
                  page.view,
                  page.viewModel,
                  page.templateUri
                );

                var navigateDelegate = function() {
                  messageService.unregister("navigatedMessage",
                    navigateDelegate);
                  return pageCb();
                };

                messageService.register("navigatedMessage",
                  navigateDelegate);

                messageService.send("navigateToMessage", {
                  viewKey: page.key
                });
              }, cb);
          },
          function(cb) {
            async.eachSeries([1, 0],
              function(pageIdx, pageIdxCb) {
                var page = pages[pageIdx];
                if (pageIdx != 0) {
                  // Assert can go back
                  WinJS.Navigation.canGoBack.should.be.ok();

                  var navigateDelegate = function() {
                    messageService.unregister("navigatedMessage",
                      navigateDelegate);
                    return pageIdxCb();
                  };

                  messageService.register("navigatedMessage",
                    navigateDelegate);

                  messageService.send("navigateBackMessage");
                } else {
                  // Assert cannot go back
                  WinJS.Navigation.canGoBack.should.not.be.ok();
                  return pageIdxCb();
                }
              }, cb);
          }
        ], done);
      });
    });
  });
});
<commit_msg>Added bugfix for navigation tests<commit_after>var common = require('../../common'),
  assert = require('assert'),
  should = require('should'),
  path = require('path'),
  async = require('async'),
  resolver = require('../../resolver');

describe('Integration', function() {
  describe('Navigation Service', function() {
    var applicationInstance;
    beforeEach(function(done) {
      var Application = resolver.resolve('./application');
      applicationInstance = new Application();
      applicationInstance.configure({}, function(err) {
        if (err)
          return done(err);
        applicationInstance.load({}, done);
      });
    });

    describe("Navigate to unregistered view", function() {
      it('standard success', function(done) {
        // arrange
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");

        //act
        messageService.send("navigateToMessage", {
          viewKey: "RandomViewKey"
        });
        return done();
      });
    });

    describe("Navigation Forward", function() {
      it('standard success', function(done) {
        // arrange
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");
        var pages = [{
          key: "viewA",
          view: class extends entry.View.Page {},
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.1.html")
        }, {
          key: "viewB",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.2.html")
        }];

        //act
        async.eachSeries(pages,
          function(page, pageCb) {
            applicationInstance.builder.registerView(page.key,
              page.view,
              page.viewModel,
              page.templateUri
            );

            var navigateDelegate = function() {
              messageService.unregister("navigatedMessage",
                navigateDelegate);

              navigationService.view.should.be.an.instanceOf(page.view);
              navigationService.viewModel.should.be.an.instanceOf(page.viewModel);

              return pageCb();
            };

            messageService.register("navigatedMessage",
              navigateDelegate);

            messageService.send("navigateToMessage", {
              viewKey: page.key
            });

          }, done);
      });
    });

    describe("Back Navigation", function() {
      it('standard success', function(done) {
        // arrange
        var WinJS = require('winjs');
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");
        var pages = [{
          key: "viewA",
          view: class extends entry.View.Page {},
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.1.html")
        }, {
          key: "viewB",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.2.html")
        }, {
          key: "viewC",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.3.html")
        }];

        //act
        async.waterfall([
          function(cb) {
            async.eachSeries(pages,
              function(page, pageCb) {
                applicationInstance.builder.registerView(page.key,
                  page.view,
                  page.viewModel,
                  page.templateUri
                );

                var navigateDelegate = function() {
                  messageService.unregister("navigatedMessage",
                    navigateDelegate);
                  return pageCb();
                };

                messageService.register("navigatedMessage",
                  navigateDelegate);

                messageService.send("navigateToMessage", {
                  viewKey: page.key
                });
              }, cb);
          },
          function(cb) {
            async.eachSeries([2, 1, 0],
              function(pageIdx, pageIdxCb) {
                var page = pages[pageIdx];
                if (pageIdx != 0) {
                  //var targetPage = pages[pageIdx - 1];

                  // Assert can go back
                  WinJS.Navigation.canGoBack.should.be.ok();

                  var navigateDelegate = function() {
                    messageService.unregister("navigatedMessage",
                      navigateDelegate);
                    return pageIdxCb();
                  };

                  messageService.register("navigatedMessage",
                    navigateDelegate);

                  messageService.send("navigateBackMessage");
                } else {
                  // Assert cannot go back
                  WinJS.Navigation.canGoBack.should.not.be.ok();
                  return pageIdxCb();
                }
              }, cb);
          }
        ], done);
      });
    });

    describe("Modal Navigation", function() {
      it('standard success', function(done) {
        // arrange
        var WinJS = require('winjs');
        var entry = resolver.resolve('./entry');
        var messageService = applicationInstance.container.getService("message");
        var navigationService = applicationInstance.container.getService("navigation");
        var pages = [{
          key: "view1",
          view: class extends entry.View.Page {},
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.1.html")
        }, {
          key: "view2",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {
            get isModal() {
              return true;
            }
          },
          templateUri: path.join(__dirname, "..", "harness", "template.2.html")
        }, {
          key: "view3",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {
            get isModal() {
              return true;
            }
          },
          templateUri: path.join(__dirname, "..", "harness", "template.3.html")
        }, {
          key: "view4",
          view: class extends entry.View.Page {

          },
          viewModel: class extends entry.ViewModel.Base {},
          templateUri: path.join(__dirname, "..", "harness", "template.4.html")
        }];

        //act
        async.waterfall([
          function(cb) {
            async.eachSeries(pages,
              function(page, pageCb) {
                applicationInstance.builder.registerView(page.key,
                  page.view,
                  page.viewModel,
                  page.templateUri
                );

                var navigateDelegate = function() {
                  messageService.unregister("navigatedMessage",
                    navigateDelegate);
                  return pageCb();
                };

                messageService.register("navigatedMessage",
                  navigateDelegate);

                messageService.send("navigateToMessage", {
                  viewKey: page.key
                });
              }, cb);
          },
          function(cb) {
            async.eachSeries([1],
              function(pageIdx, pageIdxCb) {
                var page = pages[pageIdx];
                if (pageIdx != 0) {
                  // Assert can go back
                  WinJS.Navigation.canGoBack.should.be.ok();

                  var navigateDelegate = function() {
                    messageService.unregister("navigatedMessage",
                      navigateDelegate);
                    return pageIdxCb();
                  };

                  messageService.register("navigatedMessage",
                    navigateDelegate);

                  messageService.send("navigateBackMessage");
                } else {
                  // Assert cannot go back
                  WinJS.Navigation.canGoBack.should.not.be.ok();
                  return pageIdxCb();
                }
              }, cb);
          }
        ], done);
      });
    });
  });
});
<|endoftext|>