<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

exports.defineAutoTests = function() {
    describe('Camera (navigator.camera)', function () {
        it("should exist", function() {
            expect(navigator.camera).toBeDefined();
        });

        it("should contain a getPicture function", function() {
            expect(navigator.camera.getPicture).toBeDefined();
            expect(typeof navigator.camera.getPicture == 'function').toBe(true);
        });
    });

    describe('Camera Constants (window.Camera + navigator.camera)', function () {
        it("camera.spec.1 window.Camera should exist", function() {
            expect(window.Camera).toBeDefined();
        });

        it("camera.spec.2 should contain three DestinationType constants", function() {
            expect(Camera.DestinationType.DATA_URL).toBe(0);
            expect(Camera.DestinationType.FILE_URI).toBe(1);
            expect(Camera.DestinationType.NATIVE_URI).toBe(2);
            expect(navigator.camera.DestinationType.DATA_URL).toBe(0);
            expect(navigator.camera.DestinationType.FILE_URI).toBe(1);
            expect(navigator.camera.DestinationType.NATIVE_URI).toBe(2);
        });

        it("camera.spec.3 should contain two EncodingType constants", function() {
            expect(Camera.EncodingType.JPEG).toBe(0);
            expect(Camera.EncodingType.PNG).toBe(1);
            expect(navigator.camera.EncodingType.JPEG).toBe(0);
            expect(navigator.camera.EncodingType.PNG).toBe(1);
        });

        it("camera.spec.4 should contain three MediaType constants", function() {
            expect(Camera.MediaType.PICTURE).toBe(0);
            expect(Camera.MediaType.VIDEO).toBe(1);
            expect(Camera.MediaType.ALLMEDIA).toBe(2);
            expect(navigator.camera.MediaType.PICTURE).toBe(0);
            expect(navigator.camera.MediaType.VIDEO).toBe(1);
            expect(navigator.camera.MediaType.ALLMEDIA).toBe(2);
        });

        it("camera.spec.5 should contain three PictureSourceType constants", function() {
            expect(Camera.PictureSourceType.PHOTOLIBRARY).toBe(0);
            expect(Camera.PictureSourceType.CAMERA).toBe(1);
            expect(Camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2);
            expect(navigator.camera.PictureSourceType.PHOTOLIBRARY).toBe(0);
            expect(navigator.camera.PictureSourceType.CAMERA).toBe(1);
            expect(navigator.camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2);
        });
    });
};
<commit_msg>CB-6958 added manual tests<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

exports.defineAutoTests = function () {
    describe('Camera (navigator.camera)', function () {
        it("should exist", function () {
            expect(navigator.camera).toBeDefined();
        });

        it("should contain a getPicture function", function () {
            expect(navigator.camera.getPicture).toBeDefined();
            expect(typeof navigator.camera.getPicture == 'function').toBe(true);
        });
    });

    describe('Camera Constants (window.Camera + navigator.camera)', function () {
        it("camera.spec.1 window.Camera should exist", function () {
            expect(window.Camera).toBeDefined();
        });

        it("camera.spec.2 should contain three DestinationType constants", function () {
            expect(Camera.DestinationType.DATA_URL).toBe(0);
            expect(Camera.DestinationType.FILE_URI).toBe(1);
            expect(Camera.DestinationType.NATIVE_URI).toBe(2);
            expect(navigator.camera.DestinationType.DATA_URL).toBe(0);
            expect(navigator.camera.DestinationType.FILE_URI).toBe(1);
            expect(navigator.camera.DestinationType.NATIVE_URI).toBe(2);
        });

        it("camera.spec.3 should contain two EncodingType constants", function () {
            expect(Camera.EncodingType.JPEG).toBe(0);
            expect(Camera.EncodingType.PNG).toBe(1);
            expect(navigator.camera.EncodingType.JPEG).toBe(0);
            expect(navigator.camera.EncodingType.PNG).toBe(1);
        });

        it("camera.spec.4 should contain three MediaType constants", function () {
            expect(Camera.MediaType.PICTURE).toBe(0);
            expect(Camera.MediaType.VIDEO).toBe(1);
            expect(Camera.MediaType.ALLMEDIA).toBe(2);
            expect(navigator.camera.MediaType.PICTURE).toBe(0);
            expect(navigator.camera.MediaType.VIDEO).toBe(1);
            expect(navigator.camera.MediaType.ALLMEDIA).toBe(2);
        });

        it("camera.spec.5 should contain three PictureSourceType constants", function () {
            expect(Camera.PictureSourceType.PHOTOLIBRARY).toBe(0);
            expect(Camera.PictureSourceType.CAMERA).toBe(1);
            expect(Camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2);
            expect(navigator.camera.PictureSourceType.PHOTOLIBRARY).toBe(0);
            expect(navigator.camera.PictureSourceType.CAMERA).toBe(1);
            expect(navigator.camera.PictureSourceType.SAVEDPHOTOALBUM).toBe(2);
        });
    });
};

/******************************************************************************/
/******************************************************************************/
/******************************************************************************/

exports.defineManualTests = function (contentEl, createActionButton) {
    var platformId = cordova.require('cordova/platform').id;
    var pictureUrl = null;
    var fileObj = null;
    var fileEntry = null;
    var pageStartTime = +new Date();

    //default camera options
    var camQualityDefault = ['quality value', 50];
    var camDestinationTypeDefault = ['FILE_URI', 1];
    var camPictureSourceTypeDefault = ['CAMERA', 1];
    var camAllowEditDefault = ['allowEdit', false];
    var camEncodingTypeDefault = ['JPEG', 0];
    var camMediaTypeDefault = ['mediaType', 0];
    var camCorrectOrientationDefault = ['correctOrientation', false];
    var camSaveToPhotoAlbumDefault = ['saveToPhotoAlbum', true];

    var clearLog = function () {
        var log = document.getElementById('info');
        log.innerHTML = "";
    }

    function log(value) {
        console.log(value);
        document.getElementById('camera_status').textContent += (new Date() - pageStartTime) / 1000 + ': ' + value + '\n';
    }

    function clearStatus() {
        document.getElementById('camera_status').innerHTML = '';
        document.getElementById('camera_image').src = 'about:blank';
        var canvas = document.getElementById('canvas');
        canvas.width = canvas.height = 1;
        pictureUrl = null;
        fileObj = null;
        fileEntry = null;
    }

    function setPicture(url, callback) {
        try {
            window.atob(url);
            // if we got here it is a base64 string (DATA_URL)
            url = "data:image/jpeg;base64," + url;
        } catch (e) {
            // not DATA_URL
            log('URL: ' + url.slice(0, 100));
        }

        pictureUrl = url;
        var img = document.getElementById('camera_image');
        var startTime = new Date();
        img.src = url;
        img.onloadend = function () {
            log('Image tag load time: ' + (new Date() - startTime));
            callback && callback();
        };
    }

    function onGetPictureError(e) {
        log('Error getting picture: ' + e.code);
    }

    function getPictureWin(data) {
        setPicture(data);
        // TODO: Fix resolveLocalFileSystemURI to work with native-uri.
        if (pictureUrl.indexOf('file:') == 0 || pictureUrl.indexOf('content:') == 0) {
            resolveLocalFileSystemURI(data, function (e) {
                fileEntry = e;
                logCallback('resolveLocalFileSystemURI()', true)(e.toURL());
            }, logCallback('resolveLocalFileSystemURI()', false));
        } else if (pictureUrl.indexOf('data:image/jpeg;base64' == 0)) {
            // do nothing
        } else {
            var path = pictureUrl.replace(/^file:\/\/(localhost)?/, '').replace(/%20/g, ' ');
            fileEntry = new FileEntry('image_name.png', path);
        }
    }

    function getPicture() {
        clearStatus();
        var options = extractOptions();
        log('Getting picture with options: ' + JSON.stringify(options));
        var popoverHandle = navigator.camera.getPicture(getPictureWin, onGetPictureError, options);

        // Reposition the popover if the orientation changes.
        window.onorientationchange = function () {
            var newPopoverOptions = new CameraPopoverOptions(0, 0, 100, 100, 0);
            popoverHandle.setPosition(newPopoverOptions);
        }
    }

    function uploadImage() {
        var ft = new FileTransfer(),
            uploadcomplete = 0,
            progress = 0,
            options = new FileUploadOptions();
        options.fileKey = "photo";
        options.fileName = 'test.jpg';
        options.mimeType = "image/jpeg";
        ft.onprogress = function (progressEvent) {
            console.log('progress: ' + progressEvent.loaded + ' of ' + progressEvent.total);
        };
        var server = "http://cordova-filetransfer.jitsu.com";

        ft.upload(pictureUrl, server + '/upload', win, fail, options);
        function win(information_back) {
            log('upload complete');
        }
        function fail(message) {
            log('upload failed: ' + JSON.stringify(message));
        }
    }

    function logCallback(apiName, success) {
        return function () {
            log('Call to ' + apiName + (success ? ' success: ' : ' failed: ') + JSON.stringify([].slice.call(arguments)));
        };
    }

    /**
     * Select image from library using a NATIVE_URI destination type
     * This calls FileEntry.getMetadata, FileEntry.setMetadata, FileEntry.getParent, FileEntry.file, and FileReader.readAsDataURL.
     */
    function readFile() {
        function onFileReadAsDataURL(evt) {
            var img = document.getElementById('camera_image');
            img.style.visibility = "visible";
            img.style.display = "block";
            img.src = evt.target.result;
            log("FileReader.readAsDataURL success");
        };

        function onFileReceived(file) {
            log('Got file: ' + JSON.stringify(file));
            fileObj = file;

            var reader = new FileReader();
            reader.onload = function () {
                log('FileReader.readAsDataURL() - length = ' + reader.result.length);
            };
            reader.onerror = logCallback('FileReader.readAsDataURL', false);
            reader.readAsDataURL(file);
        };
        // Test out onFileReceived when the file object was set via a native <input> elements.
        if (fileObj) {
            onFileReceived(fileObj);
        } else {
            fileEntry.file(onFileReceived, logCallback('FileEntry.file', false));
        }
    }
    function getFileInfo() {
        // Test FileEntry API here.
        fileEntry.getMetadata(logCallback('FileEntry.getMetadata', true), logCallback('FileEntry.getMetadata', false));
        fileEntry.setMetadata(logCallback('FileEntry.setMetadata', true), logCallback('FileEntry.setMetadata', false), { "com.apple.MobileBackup": 1 });
        fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
        fileEntry.getParent(logCallback('FileEntry.getParent', true), logCallback('FileEntry.getParent', false));
    };

    /**
     * Copy image from library using a NATIVE_URI destination type
     * This calls FileEntry.copyTo and FileEntry.moveTo.
     */
    function copyImage() {
        var onFileSystemReceived = function (fileSystem) {
            var destDirEntry = fileSystem.root;

            // Test FileEntry API here.
            fileEntry.copyTo(destDirEntry, 'copied_file.png', logCallback('FileEntry.copyTo', true), logCallback('FileEntry.copyTo', false));
            fileEntry.moveTo(destDirEntry, 'moved_file.png', logCallback('FileEntry.moveTo', true), logCallback('FileEntry.moveTo', false));
        };

        window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, onFileSystemReceived, null);
    };

    /**
     * Write image to library using a NATIVE_URI destination type
     * This calls FileEntry.createWriter, FileWriter.write, and FileWriter.truncate.
     */
    function writeImage() {
        var onFileWriterReceived = function (fileWriter) {
            fileWriter.onwrite = logCallback('FileWriter.write', true);
            fileWriter.onerror = logCallback('FileWriter.write', false);
            fileWriter.write("some text!");
        };

        var onFileTruncateWriterReceived = function (fileWriter) {
            fileWriter.onwrite = logCallback('FileWriter.truncate', true);
            fileWriter.onerror = logCallback('FileWriter.truncate', false);
            fileWriter.truncate(10);
        };

        fileEntry.createWriter(onFileWriterReceived, logCallback('FileEntry.createWriter', false));
        fileEntry.createWriter(onFileTruncateWriterReceived, null);
    };

    function displayImageUsingCanvas() {
        var canvas = document.getElementById('canvas');
        var img = document.getElementById('camera_image');
        var w = img.width;
        var h = img.height;
        h = 100 / w * h;
        w = 100;
        canvas.width = w;
        canvas.height = h;
        var context = canvas.getContext('2d');
        context.drawImage(img, 0, 0, w, h);
    };

    /**
     * Remove image from library using a NATIVE_URI destination type
     * This calls FileEntry.remove.
     */
    function removeImage() {
        fileEntry.remove(logCallback('FileEntry.remove', true), logCallback('FileEntry.remove', false));
    };

    function testInputTag(inputEl) {
        clearStatus();
        // iOS 6 likes to dead-lock in the onchange context if you
        // do any alerts or try to remote-debug.
        window.setTimeout(function () {
            testNativeFile2(inputEl);
        }, 0);
    };

    function testNativeFile2(inputEl) {
        if (!inputEl.value) {
            alert('No file selected.');
            return;
        }
        fileObj = inputEl.files[0];
        if (!fileObj) {
            alert('Got value but no file.');
            return;
        }
        var URLApi = window.URL || window.webkitURL;
        if (URLApi) {
            var blobURL = URLApi.createObjectURL(fileObj);
            if (blobURL) {
                setPicture(blobURL, function () {
                    URLApi.revokeObjectURL(blobURL);
                });
            } else {
                log('URL.createObjectURL returned null');
            }
        } else {
            log('URL.createObjectURL() not supported.');
        }
    }

    function extractOptions() {
        var els = document.querySelectorAll('#image-options select');
        var ret = {};
        for (var i = 0, el; el = els[i]; ++i) {
            var value = el.value;
            if (value === '') continue;
            if (el.isBool) {
                ret[el.getAttribute("name")] = !!+value;
            } else {
                ret[el.getAttribute("name")] = +value;
            }
        }
        return ret;
    }

    function createOptionsEl(name, values, selectionDefault) {
        var openDiv = '
' + name + ': ';
        var select = '<select name=' + name + '>';

        var defaultOption = '';
        if (selectionDefault == undefined) {
            defaultOption = '<option value="">default</option>';
        }

        var options = '';
        if (typeof values == 'boolean') {
            values = { 'true': 1, 'false': 0 };
        }
        for (var k in values) {
            var isSelected = '';
            if (selectionDefault) {
                if (selectionDefault[0] == k) {
                    isSelected = 'selected';
                }
            }
            options += '<option value="' + values[k] + '" ' + isSelected + '>' + k + '</option>';
        }

        var closeDiv = '</select>
';

        return openDiv + select + defaultOption + options + closeDiv;
    }

    /******************************************************************************/

    var info_div = '
Camera
' +
            '
' +
            'Status:

' +
            'img: ' +
            'canvas: <canvas id="canvas" width="1" height="1"></canvas>' +
            '
',
        options_div = '
Cordova Camera API Options
' +
            '
' +
            createOptionsEl('sourceType', Camera.PictureSourceType, camPictureSourceTypeDefault) +
            createOptionsEl('destinationType', Camera.DestinationType, camDestinationTypeDefault) +
            createOptionsEl('encodingType', Camera.EncodingType, camEncodingTypeDefault) +
            createOptionsEl('mediaType', Camera.MediaType, camMediaTypeDefault) +
            createOptionsEl('quality', { '0': 0, '50': 50, '80': 80, '100': 100 }, camQualityDefault) +
            createOptionsEl('targetWidth', { '50': 50, '200': 200, '800': 800, '2048': 2048 }) +
            createOptionsEl('targetHeight', { '50': 50, '200': 200, '800': 800, '2048': 2048 }) +
            createOptionsEl('allowEdit', true, camAllowEditDefault) +
            createOptionsEl('correctOrientation', true, camCorrectOrientationDefault) +
            createOptionsEl('saveToPhotoAlbum', true, camSaveToPhotoAlbumDefault) +
            createOptionsEl('cameraDirection', Camera.Direction) +
            '
',
        getpicture_div = '

',
        inputs_div = '
Native File Inputs
' +
            '
input type=file <input type="file" class="testInputTag">
' +
            '
capture=camera <input type="file" accept="image/*;capture=camera" class="testInputTag">
' +
            '
capture=camcorder <input type="file" accept="video/*;capture=camcorder" class="testInputTag">
' +
            '
capture=microphone <input type="file" accept="audio/*;capture=microphone" class="testInputTag">
',
        actions_div = '
Actions
' +
            '

';

    contentEl.innerHTML = info_div + options_div + getpicture_div + inputs_div + actions_div;
    var elements = document.getElementsByClassName("testInputTag");
    var listener = function (e) {
        testInputTag(e.target);
    }
    for (var i = 0; i < elements.length; ++i) {
        var item = elements[i];
        item.addEventListener("change", listener, false);
    }

    createActionButton('Get picture', function () {
        getPicture();
    }, 'getpicture');

    createActionButton('Clear Status', function () {
        clearStatus();
    }, 'getpicture');

    createActionButton('Get File Metadata', function () {
        getFileInfo();
    }, 'actions');

    createActionButton('Read with FileReader', function () {
        readFile();
    }, 'actions');

    createActionButton('Copy Image', function () {
        copyImage();
    }, 'actions');

    createActionButton('Write Image', function () {
        writeImage();
    }, 'actions');

    createActionButton('Upload Image', function () {
        uploadImage();
    }, 'actions');

    createActionButton('Draw Using Canvas', function () {
        displayImageUsingCanvas();
    }, 'actions');

    createActionButton('Remove Image', function () {
        removeImage();
    }, 'actions');
};
<|endoftext|>


<commit_before>var module = QUnit.module,
    test = QUnit.test;

module("ES5");
(function() {

  var asc = function(a, b) {
        return a > b ? 1 : a  b ? -1 : a < b ? 1 : 0;
      };

  test("Array.prototype.sort", function(assert) {
    var list = [1, 2, 3],
        sorted = list.sort(desc);
    assert.strictEqual(list, sorted, "sort() should return this Array");
    assert.deepEqual(list, [3, 2, 1]);
  });

  test("Array.prototype.forEach", function(assert) {
    var letters = ["a", "b", "c"],
        context = {foo: "bar"};
    expect(12);
    letters.forEach(function(letter, i, list) {
      assert.ok(typeof letter === "string");
      assert.ok(typeof i === "number");
      assert.strictEqual(list, letters);
      assert.strictEqual(this, context);
    }, context);
  });

  /*
  test("Array.prototype.every", function(assert) {
  });

  test("Array.prototype.some", function(assert) {
  });

  test("Array.prototype.filter", function(assert) {
  });
  */

  test("Array.prototype.map", function(assert) {
    expect(4);
    var letters = ["a", "b", "c"].map(function(letter) {
      assert.ok(letter);
      return letter.toUpperCase();
    });
    assert.deepEqual(letters, ["A", "B", "C"], "not uppercased: " + JSON.stringify(letters));
  });

  test("Array.prototype.reduce", function(assert) {
    expect(5);
    assert.strictEqual([3, 0, 1, 2].reduce(function(memo, n) {
      assert.ok(typeof n === "number");
      return memo + n;
    }, 0), 6);
  });

})();

module("DOM");
(function() {

  test("textContent", function(assert) {
    var node = document.createElement("span");
    node.textContent = "foo";
    assert.equal(node.textContent, "foo");
    assert.equal(node.innerText, "foo");
    assert.equal(node.innerHTML, "foo");

    node.innerHTML = "foo";
    assert.equal(node.firstChild.textContent, "foo");
  });

  test("innerText", function(assert) {
    var node = document.createElement("span");
    node.textContent = "bar";
    assert.equal(node.innerText, "bar");
    assert.equal(node.textContent, "bar");
    assert.equal(node.innerHTML, "bar");

    node.innerHTML = "bar";
    assert.equal(node.firstChild.textContent, "bar");
  });

  /*
  test("dataset", function(assert) {
    var node = document.createElement("div");
    assert.ok(node.dataset);
    node.setAttribute("data-foo", "bar");
    assert.equal(node.dataset.foo, "bar");
    node.dataset.foo = "baz";
    assert.equal(node.dataset.foo, "baz");
  });
  */

})();

module("CSS");
(function() {

  test("style properties", function(assert) {
    var node = document.createElement("div");
    node.setAttribute("style", "color: red");
    assert.equal(node.style.color, "red");
    node.style.color = "green";
    assert.equal(node.getAttribute("style")
      .toLowerCase()
      .replace(/;$/, ""), "color: green");
  });

  test("style.getPropertyValue()", function(assert) {
    var node = document.createElement("div");
    assert.ok(node.style.getPropertyValue, "node.style.getPropertyValue() is not a function");
    node.style.color = "red";
    assert.equal(node.style.getPropertyValue("color"), "red");
  });

  test("style.setProperty()", function(assert) {
    var node = document.createElement("div");
    assert.ok(node.style.setProperty, "node.style.setProperty() is not a function");
    node.style.setProperty("background-color", "red");
    assert.equal(node.style.getPropertyValue("background-color"), "red");
  });

  test("window.getComputedStyle()", function(assert) {
    assert.ok(window.getComputedStyle, "window.getComputedStyle() is not a function");

    var node = document.createElement("div");
    document.body.appendChild(node);

    var red =   ["red",   "rgb(255, 0, 0)", "#FF0000"],
        green = ["green", "rgb(0, 128, 0)", "#008A00"],
        blue =  ["blue",  "rgb(0, 0, 255)", "#0000FF"],
        getColor = function() {
          return window.getComputedStyle(node, null)
            .getPropertyValue("color")
            .toLowerCase();
        };
    node.style.setProperty("color", "green");
    assert.notEqual(green.indexOf(getColor()), -1);
    node.style.setProperty("color", "red");
    assert.notEqual(red.indexOf(getColor()), -1);
    node.setAttribute("style", "color: blue");
    assert.notEqual(blue.indexOf(getColor()), -1);

    document.body.removeChild(node);
  });

})();
<commit_msg>flesh out classList tests, make it work with zuul<commit_after>if (typeof require === "function") {
  var aight = require("../aight");
}

var module = QUnit.module,
    test = QUnit.test;

module("ES5");
(function() {

  var asc = function(a, b) {
        return a > b ? 1 : a  b ? -1 : a < b ? 1 : 0;
      };

  test("Array.prototype.sort", function(assert) {
    var list = [1, 2, 3],
        sorted = list.sort(desc);
    assert.strictEqual(list, sorted, "sort() should return this Array");
    assert.deepEqual(list, [3, 2, 1]);
  });

  test("Array.prototype.forEach", function(assert) {
    var letters = ["a", "b", "c"],
        context = {foo: "bar"};
    expect(12);
    letters.forEach(function(letter, i, list) {
      assert.ok(typeof letter === "string");
      assert.ok(typeof i === "number");
      assert.strictEqual(list, letters);
      assert.strictEqual(this, context);
    }, context);
  });

  /*
  test("Array.prototype.every", function(assert) {
  });

  test("Array.prototype.some", function(assert) {
  });

  test("Array.prototype.filter", function(assert) {
  });
  */

  test("Array.prototype.map", function(assert) {
    expect(4);
    var letters = ["a", "b", "c"].map(function(letter) {
      assert.ok(letter);
      return letter.toUpperCase();
    });
    assert.deepEqual(letters, ["A", "B", "C"], "not uppercased: " + JSON.stringify(letters));
  });

  test("Array.prototype.reduce", function(assert) {
    expect(5);
    assert.strictEqual([3, 0, 1, 2].reduce(function(memo, n) {
      assert.ok(typeof n === "number");
      return memo + n;
    }, 0), 6);
  });

})();

module("DOM");
(function() {

  test("textContent", function(assert) {
    var node = document.createElement("span");
    node.textContent = "foo";
    assert.equal(node.textContent, "foo");
    assert.equal(node.innerText, "foo");
    assert.equal(node.innerHTML, "foo");

    node.innerHTML = "foo";
    assert.equal(node.childNodes.length, 1, "setting innerHTML should produce a single childNode")
    assert.equal(node.firstChild.textContent, "foo", "first child's textContent should be 'foo'");
  });

  test("innerText", function(assert) {
    var node = document.createElement("span");
    node.textContent = "bar";
    assert.equal(node.innerText, "bar");
    assert.equal(node.textContent, "bar");
    assert.equal(node.innerHTML, "bar");

    node.innerHTML = "bar";
    assert.equal(node.childNodes.length, 1, "setting innerHTML should produce a single childNode")
    assert.equal(node.firstChild.textContent, "bar", "first child's textContent should be 'bar'");
  });

})();

module("CSS");
(function() {

  test("style properties", function(assert) {
    var node = document.createElement("div");
    node.setAttribute("style", "color: red");
    assert.equal(node.style.color, "red");
    node.style.color = "green";
    assert.equal(node.getAttribute("style")
      .toLowerCase()
      .replace(/;$/, ""), "color: green");
  });

  test("style.getPropertyValue()", function(assert) {
    var node = document.createElement("div");
    assert.ok(node.style.getPropertyValue, "node.style.getPropertyValue() is not a function");
    node.style.color = "red";
    assert.equal(node.style.getPropertyValue("color"), "red");
  });

  test("style.setProperty()", function(assert) {
    var node = document.createElement("div");
    assert.ok(node.style.setProperty, "node.style.setProperty() is not a function");
    node.style.setProperty("background-color", "red");
    assert.equal(node.style.getPropertyValue("background-color"), "red");
  });

  test("classList", function(assert) {
    var node = document.createElement("div");
    assert.ok(node.classList, "element has classList property");
    node.classList.add("foo");
    assert.ok(node.classList.contains("foo"), "classList.add('foo') does not produce 'foo' in classList");
    assert.equal(node.className, "foo", "classList.add('foo') does not produce 'foo' in classList");
    node.className = "bar baz";
    assert.equal(node.classList.contains("foo"), false, "setting className does not update classList");
    assert.equal(node.classList.contains("bar"), true, "className = 'bar baz' -> !classList.contains('bar')");
    assert.equal(node.classList.contains("baz"), true, "className = 'bar baz' -> !classList.contains('bar')");
    node.classList.add("foo");
    assert.equal(node.classList.contains("foo"), true, "classList.append('foo') doesn't work");
  });

  test("window.getComputedStyle()", function(assert) {
    assert.ok(window.getComputedStyle, "window.getComputedStyle() is not a function");

    var node = document.createElement("div");
    document.body.appendChild(node);

    var red =   ["red",   "rgb(255, 0, 0)", "#ff0000"],
        green = ["green", "rgb(0, 128, 0)", "#008a00"],
        blue =  ["blue",  "rgb(0, 0, 255)", "#0000ff"],
        getColor = function() {
          return window.getComputedStyle(node, null)
            .getPropertyValue("color")
            .toLowerCase();
        };
    node.style.setProperty("color", "green");
    assert.notEqual(green.indexOf(getColor()), -1);
    node.style.setProperty("color", "red");
    assert.notEqual(red.indexOf(getColor()), -1);
    node.setAttribute("style", "color: blue");
    assert.notEqual(blue.indexOf(getColor()), -1);

    document.body.removeChild(node);
  });

})();
<|endoftext|>


<commit_before>/* global describe, it */

var assert = require('assert')
var types = require('../src/types')
var typeforce = require('typeforce')

describe('types', function () {
  describe('BigInt/ECPoint', function () {
    it('return true for duck types', function () {
      assert(types.BigInt(new function BigInteger () {}))
      assert(types.ECPoint(new function Point () {}))
    })

    it('return false for bad types', function () {
      assert(!types.BigInt(new function NotABigInteger () {}))
      assert(!types.ECPoint(new function NotAPoint () {}))
    })
  })

  describe('Buffer Hash160/Hash256', function () {
    var buffer20byte = new Buffer((new Array(20 + 1)).join('00'), 'hex')
    var buffer32byte = new Buffer((new Array(32 + 1)).join('00'), 'hex')

    it('return true for correct size', function () {
      assert(types.Hash160bit(buffer20byte))
      assert(types.Hash256bit(buffer32byte))
    })

    it('throws for incorrect size', function () {
      assert.throws(function () {
        types.Hash160bit(buffer32byte)
      }, /Expected 160-bit Buffer, got 256-bit Buffer/)

      assert.throws(function () {
        types.Hash256bit(buffer20byte)
      }, /Expected 256-bit Buffer, got 160-bit Buffer/)
    })

    it('return true for oneOf', function () {
      assert(typeforce(types.oneOf(types.Hash256bit, types.Hash160bit), buffer32byte), "Hash256 first")
      assert(typeforce(types.oneOf(types.Hash160bit, types.Hash256bit), buffer32byte), "Hash160 first")
    })
  })
})
<commit_msg>tests: fix standard error, reword descriptions<commit_after>/* global describe, it */

var assert = require('assert')
var types = require('../src/types')
var typeforce = require('typeforce')

describe('types', function () {
  describe('BigInt/ECPoint', function () {
    it('return true for duck types', function () {
      assert(types.BigInt(new function BigInteger () {}))
      assert(types.ECPoint(new function Point () {}))
    })

    it('return false for bad types', function () {
      assert(!types.BigInt(new function NotABigInteger () {}))
      assert(!types.ECPoint(new function NotAPoint () {}))
    })
  })

  describe('Buffer Hash160/Hash256', function () {
    var buffer20byte = new Buffer((new Array(20 + 1)).join('00'), 'hex')
    var buffer32byte = new Buffer((new Array(32 + 1)).join('00'), 'hex')

    it('return true for valid size', function () {
      assert(types.Hash160bit(buffer20byte))
      assert(types.Hash256bit(buffer32byte))
    })

    it('return true for oneOf', function () {
      assert(typeforce(types.oneOf(types.Hash160bit, types.Hash256bit), buffer32byte))
      assert(typeforce(types.oneOf(types.Hash256bit, types.Hash160bit), buffer32byte))
    })

    it('throws for invalid size', function () {
      assert.throws(function () {
        types.Hash160bit(buffer32byte)
      }, /Expected 160-bit Buffer, got 256-bit Buffer/)

      assert.throws(function () {
        types.Hash256bit(buffer20byte)
      }, /Expected 256-bit Buffer, got 160-bit Buffer/)
    })
  })
})
<|endoftext|>


<commit_before><commit_msg>CSS and JS files added to config<commit_after><|endoftext|>


<commit_before><commit_msg>refactor style<commit_after><|endoftext|>


<commit_before><commit_msg>make it better<commit_after><|endoftext|>


<commit_before>// https://github.com/axemclion/grunt-saucelabs#test-result-details-with-qunit
(function () {
	'use strict';

	var log = [];

	QUnit.done(function (test_results) {
		var tests = [];
		for (var i = 0, len = log.length; i < len; i++) {
			var details = log[i];
			tests.push({
				name: details.name,
				result: details.result,
				expected: details.expected,
				actual: details.actual,
				source: details.source
			});
		}
		test_results.tests = tests;
		// Required for exposing test results to the Sauce Labs API.
		// Can be removed when the following issue is fixed:
		// https://github.com/axemclion/grunt-saucelabs/issues/84
		window.global_test_results = test_results;
	});

	QUnit.testStart(function (testDetails) {
		QUnit.log(function (details) {
			if (!details.result) {
				details.name = testDetails.name;
				log.push(details);
			}
		});
	});

	window.lifecycle = {
		afterEach: function () {
			for (var cookie in Cookies.get()) {
				// Remove the cookies created using js-cookie default attributes
				Cookies.remove(cookie);
				// Remove the cookies created using browser default attributes
				Cookies.remove(cookie, {
					path: ''
				});
			}
		}
	};

	window.addEvent = function (element, eventName, fn) {
		var method = 'addEventListener';
		if (element.attachEvent) {
			eventName = 'on' + eventName;
			method = 'attachEvent';
		}
		element[ method ](eventName, fn);
	};

	window.using = function (assert) {
		function getQuery(key) {
			var queries = location.href.split('?')[1];
			if (!queries) {
				return;
			}
			var pairs = queries.split(/&|=/);
			var indexBaseURL = pairs.indexOf(key);
			var result = pairs[indexBaseURL + 1];
			if (result) {
				return decodeURIComponent(result);
			}
		}
		function setCookie(name, value) {
			return {
				then: function (callback) {
					var iframe = document.getElementById('request_target');
					var serverURL = getQuery('integration_baseurl');
					Cookies.set(name, value);
					if (!serverURL) {
						callback(Cookies.get(name), document.cookie);
					} else {
						var requestURL = [
							serverURL,
							'encoding?',
							'name=' + encodeURIComponent(name),
							'&value=' + encodeURIComponent(value)
						].join('');
						var done = assert.async();
						addEvent(iframe, 'load', function () {
							var iframeDocument = iframe.contentWindow.document;
							var root = iframeDocument.documentElement;
							var content = root.textContent;
							if (!content) {
								ok(false, [
									'"' + requestURL + '"',
									'content should not be empty'
								].join(' '));
								done();
								return;
							}
							try {
								var result = JSON.parse(content);
								callback(result.value, iframeDocument.cookie);
							} finally {
								done();
							}
						});
						iframe.src = requestURL;
					}
				}
			};
		}
		return {
			setCookie: setCookie
		};
	};

	window.loadFileSync = function (path) {
		var xhr = new XMLHttpRequest();
		xhr.open('GET', path, false);
		xhr.send(null);
		return xhr.status === 200 ? xhr.responseText : null;
	};

	window.quoted = function (input) {
		return '"' + input + '"';
	};

}());
<commit_msg>Revert "Fix running test suite in old IEs"<commit_after>// https://github.com/axemclion/grunt-saucelabs#test-result-details-with-qunit
(function () {
	'use strict';

	var log = [];

	QUnit.done(function (test_results) {
		var tests = [];
		for (var i = 0, len = log.length; i < len; i++) {
			var details = log[i];
			tests.push({
				name: details.name,
				result: details.result,
				expected: details.expected,
				actual: details.actual,
				source: details.source
			});
		}
		test_results.tests = tests;
		// Required for exposing test results to the Sauce Labs API.
		// Can be removed when the following issue is fixed:
		// https://github.com/axemclion/grunt-saucelabs/issues/84
		window.global_test_results = test_results;
	});

	QUnit.testStart(function (testDetails) {
		QUnit.log(function (details) {
			if (!details.result) {
				details.name = testDetails.name;
				log.push(details);
			}
		});
	});

	window.lifecycle = {
		afterEach: function () {
			// Remove the cookies created using js-cookie default attributes
			Object.keys(Cookies.get()).forEach(Cookies.remove);
			// Remove the cookies created using browser default attributes
			Object.keys(Cookies.get()).forEach(function (cookie) {
				Cookies.remove(cookie, {
					path: ''
				});
			});
		}
	};

	window.addEvent = function (element, eventName, fn) {
		var method = 'addEventListener';
		if (element.attachEvent) {
			eventName = 'on' + eventName;
			method = 'attachEvent';
		}
		element[ method ](eventName, fn);
	};

	window.using = function (assert) {
		function getQuery(key) {
			var queries = location.href.split('?')[1];
			if (!queries) {
				return;
			}
			var pairs = queries.split(/&|=/);
			var indexBaseURL = pairs.indexOf(key);
			var result = pairs[indexBaseURL + 1];
			if (result) {
				return decodeURIComponent(result);
			}
		}
		function setCookie(name, value) {
			return {
				then: function (callback) {
					var iframe = document.getElementById('request_target');
					var serverURL = getQuery('integration_baseurl');
					Cookies.set(name, value);
					if (!serverURL) {
						callback(Cookies.get(name), document.cookie);
					} else {
						var requestURL = [
							serverURL,
							'encoding?',
							'name=' + encodeURIComponent(name),
							'&value=' + encodeURIComponent(value)
						].join('');
						var done = assert.async();
						addEvent(iframe, 'load', function () {
							var iframeDocument = iframe.contentWindow.document;
							var root = iframeDocument.documentElement;
							var content = root.textContent;
							if (!content) {
								ok(false, [
									'"' + requestURL + '"',
									'content should not be empty'
								].join(' '));
								done();
								return;
							}
							try {
								var result = JSON.parse(content);
								callback(result.value, iframeDocument.cookie);
							} finally {
								done();
							}
						});
						iframe.src = requestURL;
					}
				}
			};
		}
		return {
			setCookie: setCookie
		};
	};

	window.loadFileSync = function (path) {
		var xhr = new XMLHttpRequest();
		xhr.open('GET', path, false);
		xhr.send(null);
		return xhr.status === 200 ? xhr.responseText : null;
	};

	window.quoted = function (input) {
		return '"' + input + '"';
	};

}());
<|endoftext|>


<commit_before>var youtube = require('../lib/youtube'),
  assert = require('chai').assert,
  merge = require('merge'),
  nock = require('nock');

describe('Video', function () {

  describe('constructor', function () {

    it('should set the default parameters to the resulting object', function () {
      var video = youtube.video('v3');

      assert.equal(video.id, null, 'Should set the id property to null when no parameters are given');
      assert.deepEqual(video.options, {}, 'Should set the options property to {} when no parameters are given');

      video = youtube.video({ version: 'v3' });

      assert.equal(video.id, null, 'Should set the id property to null when no parameters are given');
      assert.deepEqual(video.options, {}, 'Should set the options property to {} when no parameters are given');
    });

    it('should set the parameters to the resulting object', function () {
      var parameters = { version: 'v3', id: 'id' },
        video = youtube.video(parameters);

      assert.equal(video.id, parameters.id, 'Should set the id property');
      assert.equal(video.options, parameters, 'Should set the options property');
    });

  });

  describe('comments.listAll', function () {
    var topComment = {
      "kind": "youtube#comment",
      "id": "TopCommentId"
    },
      replies = [
        [
          {
            "kind": "youtube#comment",
            "id": "ReplyId"
          }
        ]
      ];

    nock('https://www.googleapis.com')
      .get('/youtube/v3/commentThreads')
      .query(true)
      .reply(200, {
        "kind": "youtube#commentThreadListResponse",
        "pageInfo": {
          "totalResults": 1,
          "resultsPerPage": 1
        },
        "items": [
          {
            "kind": "youtube#commentThread",
            "id": "ThreadId",
            "snippet": {
              "channelId": "ChannelId",
              "videoId": "VideoId",
              "topLevelComment": topComment,
              "totalReplyCount": 1,
            }
          }
        ]
      });

    nock('https://www.googleapis.com')
      .get('/youtube/v3/comments')
      .query(true)
      .reply(200, {
        "kind": "youtube#commentListResponse",
        "pageInfo": {
          "totalResults": 1,
          "resultsPerPage": 1
        },
        "items": replies
      });

    it('should return an array of comments', function () {
      var parameters = { version: 'v3', id: 'videoId' },
        video = youtube.video(parameters),
        queryParams = {
          key: 'key',
          part: 'part'
        };

      return video.comments.listAll(queryParams, queryParams).then(function (response) {
        assert.isArray(response, 'response should be an array');
        assert.equal(2, response.length, 'response length should be 3');
        assert.deepEqual(response[0], topComment, 'top comment should be in array');
        assert.deepEqual(response[1], replies[0], 'replies should be in array');
      });
    });
  });

});<commit_msg>TMGDEV-417 #time 5m test fixed<commit_after>var youtube = require('../lib/youtube'),
  assert = require('chai').assert,
  merge = require('merge'),
  nock = require('nock');

describe('Video', function () {

  describe('constructor', function () {

    it('should set the default parameters to the resulting object', function () {
      var video = youtube.video('v3');

      assert.equal(video.id, null, 'Should set the id property to null when no parameters are given');
      assert.deepEqual(video.options, {}, 'Should set the options property to {} when no parameters are given');

      video = youtube.video({ version: 'v3' });

      assert.equal(video.id, null, 'Should set the id property to null when no parameters are given');
      assert.deepEqual(video.options, {}, 'Should set the options property to {} when no parameters are given');
    });

    it('should set the parameters to the resulting object', function () {
      var parameters = { version: 'v3', id: 'id' },
        video = youtube.video(parameters);

      assert.equal(video.id, parameters.id, 'Should set the id property');
      assert.equal(video.options, parameters, 'Should set the options property');
    });

  });

  describe('comments.listAll', function () {
    var topComment = {
      "kind": "youtube#comment",
      "id": "TopCommentId"
    },
      replies = [
          {
            "kind": "youtube#comment",
            "id": "ReplyId1"
          },

          {
            "kind": "youtube#comment",
            "id": "ReplyId2"
          }
      ];

    nock('https://www.googleapis.com')
      .get('/youtube/v3/commentThreads')
      .query(true)
      .reply(200, {
        "kind": "youtube#commentThreadListResponse",
        "pageInfo": {
          "totalResults": 1,
          "resultsPerPage": 1
        },
        "items": [
          {
            "kind": "youtube#commentThread",
            "id": "ThreadId",
            "snippet": {
              "channelId": "ChannelId",
              "videoId": "VideoId",
              "topLevelComment": topComment,
              "totalReplyCount": 1,
            }
          }
        ]
      });

    nock('https://www.googleapis.com')
      .get('/youtube/v3/comments')
      .query(true)
      .reply(200, {
        "kind": "youtube#commentListResponse",
        "pageInfo": {
          "totalResults": 1,
          "resultsPerPage": 1
        },
        "items": replies
      });

    it('should return an array of comments', function () {
      var parameters = { version: 'v3', id: 'videoId' },
        video = youtube.video(parameters),
        queryParams = {
          key: 'key',
          part: 'part'
        };

      return video.comments.listAll(queryParams, queryParams).then(function (response) {
        assert.isArray(response, 'response should be an array');
        assert.equal(3, response.length, 'response length should be 3');
        assert.deepEqual(response[0], topComment, 'top comment should be in array');
        assert.deepEqual(response[1], replies[0], 'replies should be in array');
        assert.deepEqual(response[2], replies[1], 'replies should be in array');
      });
    });
  });

});<|endoftext|>


<commit_before>var test = require("tape"),
    w = require("../");

test("where", function(t){
    var arr = [
        { result: false, number: 1 },
        { result: false, number: 2 }
    ];
    t.deepEqual(w.where(arr, { result: true }), []);
    t.deepEqual(w.where(arr, { result: false }), [
        { result: false, number: 1 },
        { result: false, number: 2 }
    ]);
    t.deepEqual(w.where(arr, { result: false, number: 3 }), []);
    t.deepEqual(w.where(arr, { result: false, number: 2 }), [
        { result: false, number: 2 }
    ]);
    t.end();
});
<commit_msg>more tests<commit_after>var test = require("tape"),
    a = require("../");

test("where", function(t){
    var arr = [
        { result: false, number: 1 },
        { result: false, number: 2 }
    ];
    t.deepEqual(a.where(arr, { result: true }), []);
    t.deepEqual(a.where(arr, { result: false }), [
        { result: false, number: 1 },
        { result: false, number: 2 }
    ]);
    t.deepEqual(a.where(arr, { result: false, number: 3 }), []);
    t.deepEqual(a.where(arr, { result: false, number: 2 }), [
        { result: false, number: 2 }
    ]);
    t.end();
});

test("where, regex", function(t){
    var arr = [
        { flag: false, something: "aa" },
        { something: "bb" }
    ];
    var result = [
        { something: "bb" }
    ];
    t.deepEqual(a.where(arr, { flag: undefined, something: /.+/ }), result);
    t.end();
});

test("where, regex 2", function(t){
    var arr = [
        { flag: false },
        { something: "bb" }
    ];
    var result = [
        { something: "bb" }
    ];
    t.deepEqual(a.where(arr, { something: /.+/ }), result);
    t.end();
});
<|endoftext|>


<commit_before>module.exports = {
  root: true,
  parserOptions: {
    parser: 'babel-eslint'
  },
  env: {
    browser: true,
    'jest/globals': true
  },
  globals: {
    'createLocalVue': false,
    'shallowMount': false,
    'mount': false,
    'RouterLinkStub': false,
  },
  extends: [
    '../.eslintrc.js',
    'plugin:vue/recommended',
  ],
  // required to lint *.vue files
  plugins: [
    'vue',
    'jest'
  ],
  // add your custom rules here
  rules: {
    // allow optionalDependencies
    'import/no-extraneous-dependencies': ['error', {
      'optionalDependencies': ['test/unit/index.js']
    }],

    /* Jest rules */
    'jest/no-disabled-tests': 'warn',
    'jest/no-focused-tests': 'error',
    // 'jest/no-identical-title': 'error',
    'jest/prefer-to-have-length': 'warn',
    // 'jest/valid-expect': 'error',

    /* VueX rules */
    // disallow reassignment of function parameters
    // disallow parameter object manipulation except for specific exclusions
    'no-param-reassign': ['error', {
      props: true,
      ignorePropertyModificationsFor: [
        'state', // for vuex state
        'acc', // for reduce accumulators
        'e' // for e.returnvalue
      ]
    }],
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',

    /* YPAM custom rules */
    'import/prefer-default-export': null,

    // PERSO
    'no-extra-parens': 'error',
    'arrow-parens': ['error', 'as-needed'],

    /* WARNING TO REMOVE */
    'jest/valid-expect': 'warn', // uncomment above
    'jest/no-identical-title': 'warn', // uncomment above
    'vue/require-prop-types': 'warn',
    'import/first': 'warn',

    'no-undef': 'warn',
    'import/extensions': 'warn',
    'import/no-unresolved': 'warn',
    'no-unused-vars': 'warn'
  }
};
<commit_msg>chore(REC-244): adjust eslint config<commit_after>module.exports = {
  root: true,
  parserOptions: {
    parser: 'babel-eslint'
  },
  env: {
    browser: true,
    'jest/globals': true
  },
  globals: {
    'createLocalVue': false,
    'shallowMount': false,
    'mount': false,
    'RouterLinkStub': false,
  },
  extends: [
    '../.eslintrc.js',
    'plugin:vue/recommended',
  ],
  plugins: [
    'vue',
    'jest'
  ],
  rules: {
    'import/no-extraneous-dependencies': ['error', {
      'optionalDependencies': ['test/unit/index.js']
    }],

    'jest/no-disabled-tests': 'warn',
    'jest/no-focused-tests': 'error',
    'jest/no-identical-title': 'error',
    'jest/prefer-to-have-length': 'warn',
    'jest/valid-expect': 'error',

    /* VueX rules */
    'no-param-reassign': ['error', {
      props: true,
      ignorePropertyModificationsFor: [
        'state',
        'acc',
        'e'
      ]
    }],
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',

    /* YPAM custom rules */
    'import/prefer-default-export': null,

    // PERSO
    'arrow-parens': ['error', 'as-needed'],
    'import/extensions': 'error',
    'import/first': 'error',
    'import/no-unresolved': 'error',
    'no-extra-parens': 'error',
    'no-undef': 'error',
    'no-unused-vars': 'error',
    'vue/require-prop-types': 'error'
  }
};
<|endoftext|>


<commit_before>/*
 * Dice rolls and fun JS injections
 */

let main = require('./main'),
	{$, common, state, oneeSama} = main;

// Render dice rolls and other hash commands
oneeSama.hook('imouto', function (imouto) {
	imouto.dice = true;
	imouto.queueRoll = function(bit) {
		var n = this.allRolls.sent++;
		var info = this.allRolls[n];
		if (!info)
			info = this.allRolls[n] = {};
		info.bit = bit;
		info.$tag = $(this.callback(common.safe('')));
		this.strong = true;
		this.callback(info.dice ? common.readable_dice(bit, info.dice) : bit);
		this.strong = false;
		this.callback(common.safe(''));
	};
	imouto.allRolls = {
		sent: 0,
		seen: 0
	};
});

// Handle dice in the postForm
oneeSama.hook('insertOwnPost', function (extra) {
	let postForm = main.request('postForm');
	if (!postForm || !postForm.imouto || !extra || !extra.dice)
		return;
	let rolls = postForm.imouto.allRolls;
	for (let i = 0, lim = extra.dice.length; i < lim; i++) {
		const n = rolls.seen++;
		let info = rolls[n];
		if (!info)
			info = rolls[n] = {};
		info.dice = extra.dice[i];
		if (info.$tag) {
			const r = common.readable_dice(info.bit, info.dice);
			info.$tag.html(r.safe ? r.safe : r);
		}
	}
});

// Execute server-sent JS in fun threads
main.dispatcher[common.EXECUTE_JS] = function (msg, op) {
	if (state.page.get('thread') != op)
		return;
	try {
		eval(msg[0]);
	}
	catch (e) {
		console.error(e);
	}
};
<commit_msg>Execute JS injections globally<commit_after>/*
 * Dice rolls and fun JS injections
 */

let main = require('./main'),
	{$, common, state, oneeSama} = main;

// Render dice rolls and other hash commands
oneeSama.hook('imouto', function (imouto) {
	imouto.dice = true;
	imouto.queueRoll = function(bit) {
		var n = this.allRolls.sent++;
		var info = this.allRolls[n];
		if (!info)
			info = this.allRolls[n] = {};
		info.bit = bit;
		info.$tag = $(this.callback(common.safe('')));
		this.strong = true;
		this.callback(info.dice ? common.readable_dice(bit, info.dice) : bit);
		this.strong = false;
		this.callback(common.safe(''));
	};
	imouto.allRolls = {
		sent: 0,
		seen: 0
	};
});

// Handle dice in the postForm
oneeSama.hook('insertOwnPost', function (extra) {
	let postForm = main.request('postForm');
	if (!postForm || !postForm.imouto || !extra || !extra.dice)
		return;
	let rolls = postForm.imouto.allRolls;
	for (let i = 0, lim = extra.dice.length; i < lim; i++) {
		const n = rolls.seen++;
		let info = rolls[n];
		if (!info)
			info = rolls[n] = {};
		info.dice = extra.dice[i];
		if (info.$tag) {
			const r = common.readable_dice(info.bit, info.dice);
			info.$tag.html(r.safe ? r.safe : r);
		}
	}
});

// Execute server-sent JS in fun threads
main.dispatcher[common.EXECUTE_JS] = ([js]) => {
	try {
		eval(js);
	}
	catch (e) {
		console.error(e);
	}
};
<|endoftext|>


<commit_before>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';

Template.dashboard.onCreated(function(){
  const instance = this;

  Meteor.call('getAggr', (err, res) => {
    if (err) console.error(err);

    console.log(res);
  });
});
<commit_msg>Generate dataset<commit_after>import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import _ from 'lodash';
import config from '/config';

Template.dashboard.onCreated(function(){

  const instance = this;

  instance.cols = new ReactiveVar();
  instance.rows = new ReactiveVar();

  instance.getAnalyticsDrilldown = async function () {

    return await new Promise((resolve, reject) => {
      Meteor.call('getAnalyticsDrilldown', (err, res) => {
        if (err) reject(err);
        resolve(res);
      });
    });
  }

  instance.getAnalyticsDrilldown()
    .then((data) => {

      let cols = [];
      _.forEach(data.hits_over_time.cols, (col) => {
        cols.push(col.label);
      });
      let rows = [];
      _.forEach(data.hits_over_time.rows, (row) => {
        let cc = [];
        _.forEach(row.c, (c) => {
          cc.push(c.f);
        });
        rows.push(cc);
      });
      console.log(cols, rows);
      instance.cols.set(cols);
      instance.rows.set(rows);
    })
    .catch((err) => {
      console.error(err);
    })
});

Template.dashboard.helpers({
  cols () {
    const instance = Template.instance();
    return instance.cols.get();
  },
  rows () {
    const instance = Template.instance();
    return instance.rows.get();
  }
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Client side syncronization module
 * @author Sebastien.Robaszkiewicz@ircam.fr, Norbert.Schnell@ircam.fr
 */
'use strict';

function getMinOfArray(numArray) {
  return Math.min.apply(null, numArray);
}

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

class SyncProcess {
  constructor(getLocalTimeFunction, emitFunction, listenFunction, iterations, period, callback) {
    this.id = Math.floor(Math.random() * 1000000);

    this.getLocalTimeFunction = getLocalTimeFunction;

    this.iterations = iterations;
    this.period = period;
    this.count = 0;

    this.timeOffset = 0;

    this.timeOffsets = [];
    this.travelTimes = [];
    this.avgTimeOffset = 0;
    this.avgTravelTime = 0;
    this.minTravelTime = 0;
    this.maxTravelTime = 0;

    // Send first ping
    this.__sendPing();

    this.callback = callback;

    // When the client receives a 'pong' from the
    // server, calculate the travel time and the
    // time offset.
    // Repeat as many times as needed (__iterations).
    listenFunction('sync_pong', (id, clientPingTime, serverPongTime) => {
      if (id === this.id) {
        var now = this.getLocalTimeFunction();
        var travelTime = now - clientPingTime;
        const timeOffset = serverPongTime - (now - travelTime / 2);

        this.travelTimes.push(travelTime);
        this.timeOffsets.push(timeOffset);

        if (this.count < this.iterations) {
          setTimeout(() => {
            this.__sendPing();
          }, 1000 * this.period);
        } else {
          this.avgTravelTime = this.travelTimes.reduce((p, q) => p + q) / this.travelTimes.length;
          this.avgTimeOffset = this.timeOffsets.reduce((p, q) => p + q) / this.timeOffsets.length;
          this.minTravelTime = getMinOfArray(this.travelTimes);
          this.maxTravelTime = getMaxOfArray(this.travelTimes);

            timeOffset - this.avgTimeOffset);
          this.timeOffset = this.avgTimeOffset;

          this.callback(this.timeOffset);
          // this.socket.emit('sync_stats', stats);
        }
      }
    });
  }

  __sendPing() {
    this.count++;
    this.emitFunction('sync_ping', this.id, this.getLocalTimeFunction());
  }
}

class SyncClient {
  constructor(getLocalTimeFunction, emitFunction, listenFunction, options = {}) {
    this.iterations = options.iterations || 5; // number of ping-pongs per iteration
    this.period = options.period || 0.500; // period of pings
    this.minInterval = this.minInterval || 10; // interval of ping-pongs minimum
    this.maxInterval = this.maxInterval || 20; // interval of ping-pongs maximum

    if (this.minInterval > this.maxInterval) {
      this.minInterval = this.maxInterval;
    }

    this.getLocalTimeFunction = getLocalTimeFunction;
    this.emitFunction = emitFunction;
    this.listenFunction = listenFunction;

    this.timeOffset = 0;
  }

  start() {
    this.__syncLoop();
  }

  __syncLoop() {
    var interval = this.minInterval + Math.random() * (this.maxInterval - this.minInterval);

    var sync = new SyncProcess(this.getLocalTimeFunction, this.emitFunction, this.listenFunction, this.iterations, this.period, (offset) => {
      this.timeOffset = offset;
    });

    setTimeout(() => {
      this.__syncLoop();
    }, 1000 * interval);
  }

  getLocalTime(syncTime) {
    if (typeof syncTime !== 'undefined') {
      // conversion
      return syncTime - this.timeOffset;
    } else {
      // Read local clock
      return this.getLocalTimeFunction();
    }
  }

  getSyncTime(localTime = this.getLocalTimeFunction()) {
    // always convert
    return localTime + this.timeOffset;
  }
}

module.exports = SyncClient;<commit_msg>fixed last commit<commit_after>/**
 * @fileoverview Client side syncronization module
 * @author Sebastien.Robaszkiewicz@ircam.fr, Norbert.Schnell@ircam.fr
 */
'use strict';

function getMinOfArray(numArray) {
  return Math.min.apply(null, numArray);
}

function getMaxOfArray(numArray) {
  return Math.max.apply(null, numArray);
}

class SyncProcess {
  constructor(getLocalTimeFunction, emitFunction, listenFunction, iterations, period, callback) {
    this.id = Math.floor(Math.random() * 1000000);

    this.getLocalTimeFunction = getLocalTimeFunction;

    this.iterations = iterations;
    this.period = period;
    this.count = 0;

    this.timeOffset = 0;

    this.timeOffsets = [];
    this.travelTimes = [];
    this.avgTimeOffset = 0;
    this.avgTravelTime = 0;
    this.minTravelTime = 0;
    this.maxTravelTime = 0;

    // Send first ping
    this.__sendPing();

    this.callback = callback;

    // When the client receives a 'pong' from the
    // server, calculate the travel time and the
    // time offset.
    // Repeat as many times as needed (__iterations).
    listenFunction('sync_pong', (id, clientPingTime, serverPongTime) => {
      if (id === this.id) {
        var now = this.getLocalTimeFunction();
        var travelTime = now - clientPingTime;
        const timeOffset = serverPongTime - (now - travelTime / 2);

        this.travelTimes.push(travelTime);
        this.timeOffsets.push(timeOffset);

        if (this.count < this.iterations) {
          setTimeout(() => {
            this.__sendPing();
          }, 1000 * this.period);
        } else {
          this.avgTravelTime = this.travelTimes.reduce((p, q) => p + q) / this.travelTimes.length;
          this.avgTimeOffset = this.timeOffsets.reduce((p, q) => p + q) / this.timeOffsets.length;
          this.minTravelTime = getMinOfArray(this.travelTimes);
          this.maxTravelTime = getMaxOfArray(this.travelTimes);

          this.timeOffset = this.avgTimeOffset;

          this.callback(this.timeOffset);
          // this.socket.emit('sync_stats', stats);
        }
      }
    });
  }

  __sendPing() {
    this.count++;
    this.emitFunction('sync_ping', this.id, this.getLocalTimeFunction());
  }
}

class SyncClient {
  constructor(getLocalTimeFunction, emitFunction, listenFunction, options = {}) {
    this.iterations = options.iterations || 5; // number of ping-pongs per iteration
    this.period = options.period || 0.500; // period of pings
    this.minInterval = this.minInterval || 10; // interval of ping-pongs minimum
    this.maxInterval = this.maxInterval || 20; // interval of ping-pongs maximum

    if (this.minInterval > this.maxInterval) {
      this.minInterval = this.maxInterval;
    }

    this.getLocalTimeFunction = getLocalTimeFunction;
    this.emitFunction = emitFunction;
    this.listenFunction = listenFunction;

    this.timeOffset = 0;
  }

  start() {
    this.__syncLoop();
  }

  __syncLoop() {
    var interval = this.minInterval + Math.random() * (this.maxInterval - this.minInterval);

    var sync = new SyncProcess(this.getLocalTimeFunction, this.emitFunction, this.listenFunction, this.iterations, this.period, (offset) => {
      this.timeOffset = offset;
    });

    setTimeout(() => {
      this.__syncLoop();
    }, 1000 * interval);
  }

  getLocalTime(syncTime) {
    if (typeof syncTime !== 'undefined') {
      // conversion
      return syncTime - this.timeOffset;
    } else {
      // Read local clock
      return this.getLocalTimeFunction();
    }
  }

  getSyncTime(localTime = this.getLocalTimeFunction()) {
    // always convert
    return localTime + this.timeOffset;
  }
}

module.exports = SyncClient;<|endoftext|>


<commit_before>var canvas = document.getElementById('gameCanvas'); // gets html canvas
var ctx = canvas.getContext('2d'); // gets 2d element of canvas

function draw() {
	ctx.save();

	ctx.clearRect(0, 0, canvas.width, canvas.height); // clear screen

	//draw gradient
	var grd = ctx.createRadialGradient(canvas.width / 2, canvas.height / 2, 5, canvas.width / 2, canvas.height / 2, canvas.width);
	grd.addColorStop(0, "#27363B");
	grd.addColorStop(1, "#27363B");
	ctx.fillStyle = grd;
	ctx.fillRect(0, 0, canvas.width, canvas.height);

	if (playing) {
		//draw players
		drawPlayer(ctx, localPlayer.color, localPlayer.x, localPlayer.y);
		for (i = 0; i < otherPlayers.length; i++) {
			drawPlayer(ctx, otherPlayers[i].color, otherPlayers[i].x, otherPlayers[i].y);
		}

		//draw player list
		ctx.fillStyle = "#fff";
		ctx.font = "32pt Panama-Light";
		ctx.textAlign = "right";
		ctx.fillText("Players", canvas.width, 33);
		ctx.fillStyle = localPlayer.color;
		ctx.fillText(localPlayer.name, canvas.width, 73);
		for (i = 0; i < otherPlayers.length; i++) {
			ctx.fillStyle = otherPlayers[i].color;
			ctx.fillText(otherPlayers[i].name, canvas.width, 113 + (i * 40));
		}
	}

	ctx.restore();
}

function drawPlayer(ctx, color, x, y) {
	ctx.beginPath();
	ctx.fillStyle = color;
	ctx.rect(x, y, 40, 40);
	ctx.fill();
}

function resize() {
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
}

window.addEventListener('load', resize, false);
window.addEventListener('resize', resize, false);
<commit_msg>Added a camera, localplayer drawing is very buggy now<commit_after>var canvas = document.getElementById('gameCanvas'); // gets html canvas
var ctx = canvas.getContext('2d'); // gets 2d element of canvas

var cameraX = 0;
var cameraY = 0;

function draw() {
	ctx.save();

	ctx.translate(cameraX, cameraY);

	ctx.clearRect(-cameraX, -cameraY, canvas.width, canvas.height); // clear screen

	//draw gradient
	var grd = ctx.createRadialGradient(canvas.width / 2, canvas.height / 2, 5, canvas.width / 2, canvas.height / 2, canvas.width);
	grd.addColorStop(0, "#27363B");
	grd.addColorStop(1, "#27363B");
	ctx.fillStyle = grd;
	ctx.fillRect(-cameraX, -cameraY, canvas.width, canvas.height);

	if (playing) {
		cameraX = -localPlayer.x + canvas.width / 2;
		cameraY = -localPlayer.y + canvas.height / 2;
		drawMap();
		//draw players
		drawPlayer(localPlayer.color, localPlayer.x, localPlayer.y);
		for (i = 0; i < otherPlayers.length; i++) {
			drawPlayer(otherPlayers[i].color, otherPlayers[i].x, otherPlayers[i].y);
		}
	}
	ctx.restore();

	if (playing)
		drawUI();
}

function drawUI() {
	//draw player list
	ctx.fillStyle = "#fff";
	ctx.font = "32pt Panama-Light";
	ctx.textAlign = "right";
	ctx.fillText("Players", canvas.width, 33);
	ctx.fillStyle = localPlayer.color;
	ctx.fillText(localPlayer.name, canvas.width, 73);
	for (i = 0; i < otherPlayers.length; i++) {
		ctx.fillStyle = otherPlayers[i].color;
		ctx.fillText(otherPlayers[i].name, canvas.width, 113 + (i * 40));
	}
}

function drawMap() {
	for (i = 0; i < 10; i++) {
		for (j = 0; j < 10; j++) {
			ctx.fillStyle = "#aaa";
			ctx.fillRect(40 * i, 40 * j, 30, 30);
		}
	}
}

function drawPlayer(color, x, y) {
	ctx.fillStyle = color;
	ctx.fillRect(x, y, 40, 40);
}

function resize() {
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
}

window.addEventListener('load', resize, false);
window.addEventListener('resize', resize, false);
<|endoftext|>


<commit_before><commit_msg>added copy-userhome-content.js<commit_after><|endoftext|>


<commit_before>(function($angular) {

    describe('ngRangeSlider', function() {

        beforeEach(module('ngRangeSlider'));

        /**
         * @method compileDirective
         * @return {Object}
         */
        var compileDirective = function compileDirective() {

            var scope, html = '

';

            inject(function inject($rootScope, $compile) {

                scope       = $rootScope.$new();
                scope.range = { from: 0, to: 10 };
                $compile(html)($angular.extend(scope));
                $rootScope.$apply();

            });

            return scope.$$childHead;

        };

        it('Should be able to define a default min/max;', function() {

            var scope = compileDirective();
            expect(scope._min).toEqual(0);
            expect(scope._max).toEqual(100);

        });

    });

})(window.angular);<commit_msg>Commented out tests<commit_after>(function($angular) {

    describe('ngRangeSlider', function() {

        beforeEach(module('ngRangeSlider'));

        /**
         * @method compileDirective
         * @return {Object}
         */
        var compileDirective = function compileDirective() {

            var scope, html = '

';

            inject(function inject($rootScope, $compile) {

                scope       = $rootScope.$new();
                scope.range = { from: 0, to: 10 };
                $compile(html)($angular.extend(scope));
                $rootScope.$apply();

            });

            return scope.$$childHead;

        };

        it('Should be able to define a default min/max;', function() {

//            var scope = compileDirective();
//            expect(scope._min).toEqual(0);
//            expect(scope._max).toEqual(100);

        });

    });

})(window.angular);<|endoftext|>


<commit_before>var between = require('../').between;

module.exports = function(op, a) {
    return f.between(op(a), -Math.PI / 2, Math.PI / 2);
};

<commit_msg>Fix test<commit_after>var between = require('../').between;

module.exports = function(op, a) {
    return between(op(a), -Math.PI / 2, Math.PI / 2);
};

<|endoftext|>


<commit_before>/*
 * enum.js
 */

const path = require('path')
const gi = require('../lib/')
const GLib = gi.require('GLib')
const Gdk = gi.require('Gdk')
const Gtk = gi.require('Gtk')
const common = require('./__common__.js')

Gtk.init()

common.describe('enum', () => {
  common.it('are defined', () => {
    common.assert(Gtk.Align !== undefined,      'Gtk.Align is undefined')
    common.assert(Gtk.Align.FILL !== undefined, 'Gtk.Align.FILL is undefined')
  })

  common.it('are passed as arguments', () => {
    const btn = new Gtk.Button()
    btn.setHalign(Gtk.Align.CENTER)
    common.expect(btn.halign, Gtk.Align.CENTER)
  })

  common.it('are returned', () => {
    const btn = new Gtk.Button()
    btn.setHalign(Gtk.Align.CENTER)
    const align = btn.getHalign()
    common.expect(align, Gtk.Align.CENTER)
    console.log({ align })
  })
})
<commit_msg>Add test for #185<commit_after>/*
 * enum.js
 */

const path = require('path')
const gi = require('../lib/')
const GLib = gi.require('GLib')
const Gdk = gi.require('Gdk')
const Gtk = gi.require('Gtk')
const Gst = gi.require('Gst')
const common = require('./__common__.js')

Gtk.init()
Gst.init()

common.describe('enum', () => {
  common.it('are defined', () => {
    common.assert(Gtk.Align !== undefined,      'Gtk.Align is undefined')
    common.assert(Gtk.Align.FILL !== undefined, 'Gtk.Align.FILL is undefined')
  })

  common.it('are passed as arguments', () => {
    const btn = new Gtk.Button()
    btn.setHalign(Gtk.Align.CENTER)
    common.expect(btn.halign, Gtk.Align.CENTER)
  })

  common.it('are returned', () => {
    const btn = new Gtk.Button()
    btn.setHalign(Gtk.Align.CENTER)
    const align = btn.getHalign()
    common.expect(align, Gtk.Align.CENTER)
    console.log({ align })
  })

  common.it('are return as output arguments', () => {
    const oldState = Gst.State.NULL
    const newState = Gst.State.PLAYING
    const pendingState = Gst.State.READY
    const msg = Gst.Message.newStateChanged(null, oldState, newState, pendingState)
    const [oldState_, newState_, pendingState_] = msg.parseStateChanged()
    common.expect(oldState_, oldState)
    common.expect(newState_, newState)
    common.expect(pendingState_, pendingState)
  })
})
<|endoftext|>


<commit_before>/**
 * Unit tests for checking that a full game works. It's tedious to repeat very
 * long sequence with GUI, but this module makes sure that basics are working.
 */

var chai = require("chai");
var expect = chai.expect;
var RG = require("../battles.js");

var RGTest = require("./roguetest.js");

var checkXY = RGTest.checkActorXY;

var Game = require("../src/game.js");
var Actor = RG.Actor.Rogue;
var Fact = RG.FACT;

var RGObjects = require("../data/battles_objects.js");
RG.Effects = require("../data/effects.js");

var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./battles_local_storage');

// Takes turns instead of real-player
var SurrogatePlayer = function() {

};

var game = new Game.Main();

var globalParser = new RG.ObjectShellParser();
globalParser.parseShellData(RG.Effects);
globalParser.parseShellData(RGObjects);

function checkMap(map, cols, rows) {
    for (var x = 0; x < cols; x++) {
        for (var y = 0; y < rows; y++) {
            //console.log("x :: " + x);
            expect(typeof map.getCell(x,y)).not.to.equal("undefined");
        }
    }
}

function getNewLevel(cols, rows) {
    var level = new RG.Map.Level(cols, rows);
    var mapGen = new RG.Map.Generator();
    mapGen.setGen("arena", cols, rows);
    var map = mapGen.getMap();
    level.setMap(map);
    return level;

}

/** Returns a level with initialized with given actors.*/
function getLevelWithNActors(cols, rows, nactors) {
    var level = getNewLevel(cols, rows);
    var actors = [];
    for (var i = 0; i < nactors; i++) {
        var actor = new Actor(false);
        actors.push(actor);
        level.addActorToFreeCell(actor);
    }
    return [level, actors];
}

describe('How game should proceed', function() {

    var movSystem = new RG.System.Movement("Movement", ["Movement"]);

    it('Initializes the game and adds player', function() {
        var cols = 50;
        var rows = 30;
        var level = getNewLevel(cols, rows);

        var actor = new Actor("Player"); // player
        actor.setIsPlayer(true);
        actor.setFOVRange(5);
        game.addLevel(level);
        expect(game.addPlayer(actor)).to.equal(true);

        expect(game.shownLevel()).to.equal(level);
        expect(actor.getLevel()).to.equal(level);

        var newMap = level.getMap();
        checkMap(newMap, cols, rows);

        var movComp = new RG.Component.Movement(12, 13, level);
        actor.add("Movement", movComp);
        movSystem.update();
        expect(actor.getX()).to.equal(12);
        expect(actor.getY()).to.equal(13);

        var explCells = level.exploreCells(actor);
        expect(explCells.length).to.equal(11*11);

        //expect(level.moveActorTo(actor, 11, 13)).to.equal(true);

    });
});

/** For listening actor killed events.*/
var KillListener = function(actor) {

    var _actor = actor;

    this.isAlive = actor.get("Health").isAlive();

    this.notify = function(evtName, obj) {
        if (evtName === RG.EVT_ACTOR_KILLED) {
            if (obj.actor === _actor) {
                this.isAlive = false;
            }
        }
    };
    RG.POOL.listenEvent(RG.EVT_ACTOR_KILLED, this);
};

describe('How combat should evolve', function() {

    it('Deals damage from attacker to defender', function() {
        var comSystem = new RG.System.Attack("Attack", ["Attack"]);
        var dmgSystem = new RG.System.Damage("Damage", ["Damage"]);

        var cols = 50;
        var rows = 30;
        var level = getNewLevel(cols, rows);

        var attacker = new Actor("Attacker");
        expect(attacker.get("Health").isAlive()).to.equal(true);
        var defender = new Actor("Defender");
        expect(defender.get("Health").isAlive()).to.equal(true);
        attacker.get("Combat").setAttack(10);
        attacker.get("Combat").setDamage("1d4");
        defender.get("Health").setHP(1);
        defender.get("Combat").setDefense(0);
        defender.get("Combat").setProtection(0);
        defender.get("Stats").setAgility(0);

        level.addActor(attacker, 1, 1);
        level.addActor(defender, 2, 2);

        var attackComp = new RG.Component.Attack(defender);
        attacker.add("Attack", attackComp);
        comSystem.update();
        expect(defender.has("Damage")).to.equal(true);
        dmgSystem.update();
        expect(attacker.has("Attack")).to.equal(false);
        expect(defender.has("Damage")).to.equal(false);

        expect(defender.get("Health").isAlive()).to.equal(false);

        var def2 = new Actor("defender2");
        level.addActor(def2, 2, 2);

        var attComp2 = new RG.Component.Attack(def2);
        attacker.add("Attack", attComp2);

        def2.get("Health").setHP(20);
        def2.get("Combat").setDefense(0);
        def2.get("Stats").setAgility(0);
        expect(def2.get("Health").isAlive()).to.equal(true);

        comSystem.update();
        expect(def2.has("Damage")).to.equal(true);
        dmgSystem.update();
        expect(def2.has("Damage")).to.equal(false);

        expect(def2.get("Health").getHP() < 20).to.equal(true);

        expect(def2.get("Health").isAlive()).to.equal(true);

        attacker.add("Attack", attComp2);
        comSystem.update();
        dmgSystem.update();

        expect(def2.get("Health").isAlive()).to.equal(true);

        var killListen = new KillListener(def2);
        while (killListen.isAlive) {
            attacker.add("Attack", attComp2);
            comSystem.update();
            dmgSystem.update();
        }
        expect(def2.get("Health").isAlive()).to.equal(false);

    });
});

describe('How AI brain works', function() {
    var cols = 30;
    var rows = 20;
    var level = getNewLevel(cols, rows);
    var mons1 = new Actor("Monster");
    var player = new Actor("Player");
    player.setType("player");
    player.setIsPlayer(true);

    it('Brain should find player cell', function() {
        expect(level.addActor(player, 2, 2)).to.equal(true);
        expect(level.addActor(mons1, 3, 5)).to.equal(true);

        var map = level.getMap();
        expect(map.isPassable(2,3)).to.equal(true);

        var brain = mons1.getBrain();
        var seenCells = level.getMap().getVisibleCells(mons1);
        expect(seenCells.length).to.not.equal(0);
        var playerCell = brain.findEnemyCell(seenCells);
        expect(playerCell.hasProp("actors")).to.equal(true);

        var pathCells = brain.getShortestPathTo(playerCell);
        expect(pathCells).to.be.an('array');
        expect(pathCells.length).to.not.equal(0);
    });

    var movSystem = new RG.System.Movement("Movement", ["Movement"]);

    it('Moves towards player when seen.', function() {
        expect(level.addActor(player, 2, 2)).to.equal(true);
        expect(level.addActor(mons1, 2, 4)).to.equal(true);
        var action = mons1.nextAction();
        action.doAction();
        movSystem.update();
        checkXY(mons1, 2, 3);
    });

});

describe('Game.Save how saving works', function() {

    // TODO add to RGTest
    var setupPlayer = function(name) {
        var level = RG.FACT.createLevel("arena", 10, 10);
        level.setLevelNumber(3);
        var player = new RG.Actor.Rogue(name);
        player.setType("player");
        player.setIsPlayer(true);
        level.addActor(player, 3, 3);
        return player;
    }

    it('Saves/restores player properly', function() {
        var gameSave = new RG.Game.Save();
        gameSave.setStorage(localStorage);
        var player = setupPlayer("Player1");

        player.get("Experience").setExpLevel(5);
        gameSave.savePlayer(player);

        var rest = gameSave.restorePlayer("Player1");
        expect(rest.getName()).to.equal(player.getName());
        expect(rest.get("Experience").getExpLevel()).to.equal(5);

        var playersAsObj = gameSave.getPlayersAsObj();
        expect(playersAsObj.hasOwnProperty("Player1")).to.equal(true);

        var die = rest.get("Combat").getDamageDie();
        expect(die !== null).to.equal(true);
        expect(typeof die !== "undefined").to.equal(true);
        expect(gameSave.getDungeonLevel()).to.equal(3);

        var playerList = gameSave.getPlayersAsList();
        var playerObj = playerList[0];
        expect(playerObj.hasOwnProperty("name")).to.equal(true);
        expect(playerObj.hasOwnProperty("expLevel")).to.equal(true);
        expect(playerObj.hasOwnProperty("dungeonLevel")).to.equal(true);

    });

    it('Saves/restores inventory properly', function() {
        var gameSave = new RG.Game.Save();
        gameSave.setStorage(localStorage);
        var player = setupPlayer("Player1");
        var invEq = player.getInvEq();

        // Test first with simple food
        var food = new RG.Item.Food("Habanero");
        invEq.addItem(food);

        gameSave.savePlayer(player);
        var rest = gameSave.restorePlayer("Player1");
        var invItems = rest.getInvEq().getInventory().getItems();
        expect(invItems.length).to.equal(1);
        expect(invItems[0].equals(food)).to.equal(true);

        // Create a new weapon
        var weapon = new RG.Item.Weapon("Sword");
        weapon.setAttack(10);
        weapon.setDamage("3d3+5");
        weapon.count = 2;

        // Add it, save player and then restore
        invEq.addItem(weapon);
        gameSave.savePlayer(player);
        rest = gameSave.restorePlayer("Player1");
        invItems = rest.getInvEq().getInventory().getItems();
        expect(invItems.length).to.equal(2);

        var sword = invItems[1];
        expect(sword.equals(weapon)).to.equal(true);
        expect(sword.count).to.equal(2);

        var armour = new RG.Item.Armour("Plate mail");
        armour.setDefense(11);
        invEq.addItem(armour);
        gameSave.savePlayer(player);
        rest = gameSave.restorePlayer("Player1");
        invItems = rest.getInvEq().getInventory().getItems();
        expect(invItems.length).to.equal(3);

        var plateMail = invItems[2];
        expect(armour.equals(plateMail)).to.equal(true);

    });

    it('Saves/restores and equips equipment correctly', function() {
        var gameSave = new RG.Game.Save();
        gameSave.setStorage(localStorage);
        var player = setupPlayer("HeroPlayer");
        var invEq = player.getInvEq();

        var weapon = new RG.Item.Weapon("Sword");
        weapon.setDefense(15);
        weapon.setAttack(1);
        weapon.setWeight(2.5);

        invEq.addItem(weapon);
        expect(invEq.equipItem(weapon)).to.equal(true);

        gameSave.savePlayer(player);
        var rest = gameSave.restorePlayer("HeroPlayer");
        var restWeapon = rest.getWeapon();
        expect(restWeapon.equals(weapon)).to.equal(true);

    });

});

describe('How poison item is used, and experience propagates', function() {
    it('Kills an actor after some time', function() {

        var game = new RG.Game.Main();
        var level = RG.FACT.createLevel("arena", 20, 20);
        var assassin = new Actor("assassin");
        var poison = globalParser.createActualObj("items", "Potion of frost poison");
        assassin.getInvEq().addItem(poison);

        var victim = new Actor("victim");
        victim.get("Health").setHP(5);

        level.addActor(assassin, 3, 5);
        level.addActor(victim, 6, 6);
        poison.useItem({target: level.getMap().getCell(6, 6)});

        var startExp = assassin.get("Experience").getExp();

        var count = 0;
        while (victim.get("Health").isAlive() && count < 100) {
            game.simulateGame();
            ++count;
        }
        var endExp = assassin.get("Experience").getExp();
        expect(endExp > startExp, "Exp. points given from poison").to.equal(true);

    });
});

<commit_msg>Added cure poison test.<commit_after>/**
 * Unit tests for checking that a full game works. It's tedious to repeat very
 * long sequence with GUI, but this module makes sure that basics are working.
 */

var chai = require("chai");
var expect = chai.expect;
var RG = require("../battles.js");

var RGTest = require("./roguetest.js");

var checkXY = RGTest.checkActorXY;

var Game = require("../src/game.js");
var Actor = RG.Actor.Rogue;
var Fact = RG.FACT;

var RGObjects = require("../data/battles_objects.js");
RG.Effects = require("../data/effects.js");

var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./battles_local_storage');

// Takes turns instead of real-player
var SurrogatePlayer = function() {

};

var game = new Game.Main();

var globalParser = new RG.ObjectShellParser();
globalParser.parseShellData(RG.Effects);
globalParser.parseShellData(RGObjects);

function checkMap(map, cols, rows) {
    for (var x = 0; x < cols; x++) {
        for (var y = 0; y < rows; y++) {
            //console.log("x :: " + x);
            expect(typeof map.getCell(x,y)).not.to.equal("undefined");
        }
    }
}

function getNewLevel(cols, rows) {
    var level = new RG.Map.Level(cols, rows);
    var mapGen = new RG.Map.Generator();
    mapGen.setGen("arena", cols, rows);
    var map = mapGen.getMap();
    level.setMap(map);
    return level;

}

/** Returns a level with initialized with given actors.*/
function getLevelWithNActors(cols, rows, nactors) {
    var level = getNewLevel(cols, rows);
    var actors = [];
    for (var i = 0; i < nactors; i++) {
        var actor = new Actor(false);
        actors.push(actor);
        level.addActorToFreeCell(actor);
    }
    return [level, actors];
}

describe('How game should proceed', function() {

    it('Initializes the game and adds player', function() {
        var movSystem = new RG.System.Movement("Movement", ["Movement"]);
        var cols = 50;
        var rows = 30;
        var level = getNewLevel(cols, rows);

        var actor = new Actor("Player"); // player
        actor.setIsPlayer(true);
        actor.setFOVRange(5);
        game.addLevel(level);
        expect(game.addPlayer(actor)).to.equal(true);

        expect(game.shownLevel()).to.equal(level);
        expect(actor.getLevel()).to.equal(level);

        var newMap = level.getMap();
        checkMap(newMap, cols, rows);

        var movComp = new RG.Component.Movement(12, 13, level);
        actor.add("Movement", movComp);
        movSystem.update();
        expect(actor.getX()).to.equal(12);
        expect(actor.getY()).to.equal(13);

        var explCells = level.exploreCells(actor);
        expect(explCells.length).to.equal(11*11);

        //expect(level.moveActorTo(actor, 11, 13)).to.equal(true);

    });
});

/** For listening actor killed events.*/
var KillListener = function(actor) {

    var _actor = actor;

    this.isAlive = actor.get("Health").isAlive();

    this.notify = function(evtName, obj) {
        if (evtName === RG.EVT_ACTOR_KILLED) {
            if (obj.actor === _actor) {
                this.isAlive = false;
            }
        }
    };
    RG.POOL.listenEvent(RG.EVT_ACTOR_KILLED, this);
};

describe('How combat should evolve', function() {

    it('Deals damage from attacker to defender', function() {
        var comSystem = new RG.System.Attack("Attack", ["Attack"]);
        var dmgSystem = new RG.System.Damage("Damage", ["Damage"]);

        var cols = 50;
        var rows = 30;
        var level = getNewLevel(cols, rows);

        var attacker = new Actor("Attacker");
        expect(attacker.get("Health").isAlive()).to.equal(true);
        var defender = new Actor("Defender");
        expect(defender.get("Health").isAlive()).to.equal(true);
        attacker.get("Combat").setAttack(10);
        attacker.get("Combat").setDamage("1d4");
        defender.get("Health").setHP(1);
        defender.get("Combat").setDefense(0);
        defender.get("Combat").setProtection(0);
        defender.get("Stats").setAgility(0);

        level.addActor(attacker, 1, 1);
        level.addActor(defender, 2, 2);

        var attackComp = new RG.Component.Attack(defender);
        attacker.add("Attack", attackComp);
        comSystem.update();
        expect(defender.has("Damage")).to.equal(true);
        dmgSystem.update();
        expect(attacker.has("Attack")).to.equal(false);
        expect(defender.has("Damage")).to.equal(false);

        expect(defender.get("Health").isAlive()).to.equal(false);

        var def2 = new Actor("defender2");
        level.addActor(def2, 2, 2);

        var attComp2 = new RG.Component.Attack(def2);
        attacker.add("Attack", attComp2);

        def2.get("Health").setHP(20);
        def2.get("Combat").setDefense(0);
        def2.get("Stats").setAgility(0);
        expect(def2.get("Health").isAlive()).to.equal(true);

        comSystem.update();
        expect(def2.has("Damage")).to.equal(true);
        dmgSystem.update();
        expect(def2.has("Damage")).to.equal(false);

        expect(def2.get("Health").getHP() < 20).to.equal(true);

        expect(def2.get("Health").isAlive()).to.equal(true);

        attacker.add("Attack", attComp2);
        comSystem.update();
        dmgSystem.update();

        expect(def2.get("Health").isAlive()).to.equal(true);

        var killListen = new KillListener(def2);
        while (killListen.isAlive) {
            attacker.add("Attack", attComp2);
            comSystem.update();
            dmgSystem.update();
        }
        expect(def2.get("Health").isAlive()).to.equal(false);

    });
});

describe('How AI brain works', function() {
    var cols = 30;
    var rows = 20;
    var level = getNewLevel(cols, rows);
    var mons1 = new Actor("Monster");
    var player = new Actor("Player");
    player.setType("player");
    player.setIsPlayer(true);

    it('Brain should find player cell', function() {
        expect(level.addActor(player, 2, 2)).to.equal(true);
        expect(level.addActor(mons1, 3, 5)).to.equal(true);

        var map = level.getMap();
        expect(map.isPassable(2,3)).to.equal(true);

        var brain = mons1.getBrain();
        var seenCells = level.getMap().getVisibleCells(mons1);
        expect(seenCells.length).to.not.equal(0);
        var playerCell = brain.findEnemyCell(seenCells);
        expect(playerCell.hasProp("actors")).to.equal(true);

        var pathCells = brain.getShortestPathTo(playerCell);
        expect(pathCells).to.be.an('array');
        expect(pathCells.length).to.not.equal(0);
    });

    it('Moves towards player when seen.', function() {
        var movSystem = new RG.System.Movement("Movement", ["Movement"]);
        expect(level.addActor(player, 2, 2)).to.equal(true);
        expect(level.addActor(mons1, 2, 4)).to.equal(true);
        var action = mons1.nextAction();
        action.doAction();
        movSystem.update();
        checkXY(mons1, 2, 3);
    });

});

describe('Game.Save how saving works', function() {

    // TODO add to RGTest
    var setupPlayer = function(name) {
        var level = RG.FACT.createLevel("arena", 10, 10);
        level.setLevelNumber(3);
        var player = new RG.Actor.Rogue(name);
        player.setType("player");
        player.setIsPlayer(true);
        level.addActor(player, 3, 3);
        return player;
    }

    it('Saves/restores player properly', function() {
        var gameSave = new RG.Game.Save();
        gameSave.setStorage(localStorage);
        var player = setupPlayer("Player1");

        player.get("Experience").setExpLevel(5);
        gameSave.savePlayer(player);

        var rest = gameSave.restorePlayer("Player1");
        expect(rest.getName()).to.equal(player.getName());
        expect(rest.get("Experience").getExpLevel()).to.equal(5);

        var playersAsObj = gameSave.getPlayersAsObj();
        expect(playersAsObj.hasOwnProperty("Player1")).to.equal(true);

        var die = rest.get("Combat").getDamageDie();
        expect(die !== null).to.equal(true);
        expect(typeof die !== "undefined").to.equal(true);
        expect(gameSave.getDungeonLevel()).to.equal(3);

        var playerList = gameSave.getPlayersAsList();
        var playerObj = playerList[0];
        expect(playerObj.hasOwnProperty("name")).to.equal(true);
        expect(playerObj.hasOwnProperty("expLevel")).to.equal(true);
        expect(playerObj.hasOwnProperty("dungeonLevel")).to.equal(true);

    });

    it('Saves/restores inventory properly', function() {
        var gameSave = new RG.Game.Save();
        gameSave.setStorage(localStorage);
        var player = setupPlayer("Player1");
        var invEq = player.getInvEq();

        // Test first with simple food
        var food = new RG.Item.Food("Habanero");
        invEq.addItem(food);

        gameSave.savePlayer(player);
        var rest = gameSave.restorePlayer("Player1");
        var invItems = rest.getInvEq().getInventory().getItems();
        expect(invItems.length).to.equal(1);
        expect(invItems[0].equals(food)).to.equal(true);

        // Create a new weapon
        var weapon = new RG.Item.Weapon("Sword");
        weapon.setAttack(10);
        weapon.setDamage("3d3+5");
        weapon.count = 2;

        // Add it, save player and then restore
        invEq.addItem(weapon);
        gameSave.savePlayer(player);
        rest = gameSave.restorePlayer("Player1");
        invItems = rest.getInvEq().getInventory().getItems();
        expect(invItems.length).to.equal(2);

        var sword = invItems[1];
        expect(sword.equals(weapon)).to.equal(true);
        expect(sword.count).to.equal(2);

        var armour = new RG.Item.Armour("Plate mail");
        armour.setDefense(11);
        invEq.addItem(armour);
        gameSave.savePlayer(player);
        rest = gameSave.restorePlayer("Player1");
        invItems = rest.getInvEq().getInventory().getItems();
        expect(invItems.length).to.equal(3);

        var plateMail = invItems[2];
        expect(armour.equals(plateMail)).to.equal(true);

    });

    it('Saves/restores and equips equipment correctly', function() {
        var gameSave = new RG.Game.Save();
        gameSave.setStorage(localStorage);
        var player = setupPlayer("HeroPlayer");
        var invEq = player.getInvEq();

        var weapon = new RG.Item.Weapon("Sword");
        weapon.setDefense(15);
        weapon.setAttack(1);
        weapon.setWeight(2.5);

        invEq.addItem(weapon);
        expect(invEq.equipItem(weapon)).to.equal(true);

        gameSave.savePlayer(player);
        var rest = gameSave.restorePlayer("HeroPlayer");
        var restWeapon = rest.getWeapon();
        expect(restWeapon.equals(weapon)).to.equal(true);

    });

});

describe('How poison item is used, and experience propagates', function() {
    it('Kills an actor after some time', function() {

        var game = new RG.Game.Main();
        var level = RG.FACT.createLevel("arena", 20, 20);
        var assassin = new Actor("assassin");
        var poison = globalParser.createActualObj("items", "Potion of frost poison");
        assassin.getInvEq().addItem(poison);

        var victim = new Actor("victim");
        victim.get("Health").setHP(5);

        level.addActor(assassin, 3, 5);
        level.addActor(victim, 6, 6);
        poison.useItem({target: level.getMap().getCell(6, 6)});

        var startExp = assassin.get("Experience").getExp();

        var count = 0;
        while (victim.get("Health").isAlive() && count < 100) {
            game.simulateGame();
            ++count;
        }
        var endExp = assassin.get("Experience").getExp();
        expect(endExp > startExp, "Exp. points given from poison").to.equal(true);

        var curePoison = globalParser.createActualObj("items", "Potion of cure poison");
        var frostPoison = globalParser.createActualObj("items", "Potion of frost poison");
        assassin.getInvEq().addItem(frostPoison);
        var curedVictim = new Actor("Cured victim");

        level.addActor(curedVictim, 4, 4);
        expect(frostPoison.useItem({target: level.getMap().getCell(4, 4)})).to.equal(true);
        expect(curedVictim.has("Poison")).to.equal(true);
        curedVictim.getInvEq().addItem(curePoison);
        game.simulateGame();
        expect(curePoison.useItem({target: level.getMap().getCell(4, 4)})).to.equal(true);
        expect(curedVictim.has("Poison")).to.equal(false);
        expect(curedVictim.get("Health").isAlive()).to.equal(true);

    });
});

<|endoftext|>