<commit_before>"use strict";

const       assert = require('chai').assert;
const        jsdom = require('jsdom');
const   browserify = require('browserify');
const browserifyFn = require('browserify-string');
const         path = require('path');
const           fs = require('fs');
const Apoco=require('../declare').Apoco;

global.document=require("jsdom").jsdom(undefined,
                                           {virtualConsole: jsdom.createVirtualConsole().sendTo(console)});
global.window=document.defaultView;
global.navigator=global.window.navigator;

describe("DisplayGrid-(start without rows)",function(){

    var t;
    require("../DisplayGrid.js");
    it("creates a grid display object",function(){
        var b=document.createElement("div");
        b.id="test";
        document.getElementsByTagName("body")[0].appendChild(b);
        //$("body").append("

");
        t=Apoco.display.grid({id:"test_grid",DOM:"test",cols:[{name: "name",type:"string"}]});
        assert.isObject(t);
    });
    it("has a getElement method",function(){
        var b=t.getElement();
        assert.isObject(b);
    });
    it("has a show method which adds the root element to the DOM",function(){
        var b=document.getElementById("test_grid");
        assert.isNotObject(b);
        t.show();
        var b=document.getElementById("test_grid");
        assert.isObject(b);
    });
    it("cannot add column if it does not have a unique name",function(){
        var fn=function(){
            t.addCol({name: "name",type:"string"});
        };
        assert.throws(fn,"Columns must have unique names");
    });
    it("has added a column if a uniqueKey is not specified",function(){
        var v=t.getCol();
        assert.strictEqual(v.length,2);
    });
    it("can add a column ",function(){
        t.addCol({name: "index",type:"integer"});
        assert.strictEqual(t.getColIndex("index"),2);
    });
    it("can add a row",function(){
        var b=t.addRow({name:"Bill",index:10});
        assert.notStrictEqual(b,null);
    });
    it("creates a grid",function(){
        assert.notStrictEqual(t.getGrid(),null);
        assert.notStrictEqual(t.getGrid(),undefined);
    });
    it("creates a row array",function(){
       // var n=t.getGrid();
        assert.notStrictEqual(t.getGrid().rows.length,0);
    });
    it("getRow throws an error if key is not unique",function(){
        t.addRow({name:"Homer",index:6});
        var fn=function(){
            var b=t.getRow({name:"Homer",index:6},null,{val:-1});
        };
        assert.throws(fn,"getRow: key is not unique" );
    });
    it("can add more columns ",function(){
        t.addCol({name: "job",type:"string"});
        assert.strictEqual(t.getColIndex("job"),3);
    });
    it("can add yet another row",function(){
        t.addRow({name:"Sam",job:"Manager"});
    });
    it("can add a column with a label",function(){
        t.addCol({name: "things",label:"whatever",type:"string"});
        assert.strictEqual(t.getColIndex("things"),4);
    });

    it("dumps the contents of the grid as a JSON object",function(){
        var b=t.getJSON();
        assert.isObject(b);
//        console.log("JSON %j",b);
    });
    it("updates a row only if unique key",function(){
        var fn=function(){
            t.updateRow({name:"Sam",index:12});
        };
        assert.throws(fn,"getRow: key is not unique");
    });
    it("has a delete method",function(){
        var b=document.getElementById("test_grid");
//        console.log("delete grid got element" + b);
        t.delete();
        assert.strictEqual(document.body.contains(b),false);
//        console.log("t is now " + t);
    });
});

describe("DisplayGrid-(start with data and subgrids)",function(){
    var t;
    require("../DisplayGrid.js");

    //var data=require("./data/data.js");
    require("./data/data.js");
    var data=window.data;
    it("has got some data",function(){
        assert.isObject(data);
    });
    it("creates a grid display object",function(){
        //$("body").append("

");
        var b=document.createElement("div");
        b.id="Content";
        document.body.appendChild(b);
        assert.strictEqual(document.body.contains(b),true);
        t=Apoco.display.grid(data);
        assert.isObject(t);
    });

    it("has sorted all the grids",function(){
        var b=t.getGrid();
        for(var i=0;i<b.length;i++){
            assert.strictEqual(b[i].sorted,true);
        }
    });

     it("can add a row",function(){
        var b=t.getGrid("swaps").rows.length;
        b++;
        var n=t.addRow({stock:"FG63",class: "swaps",bid:10,maturity:"2020-05-21"});
        var c=t.getGrid("swaps").rows.length;
//        console.log("b is " + b +  " and c " + c);
        //var b=t.getRow({stock:"FG63",subclass: 1,bid:10});
        assert.strictEqual(b,c);
       // console.log("JSON %j",n);
    });
    it("can add another row",function(){
        var b=t.getGrid("swaps").rows.length;
        b++;
        var n=t.addRow({stock:"XXX",class: "swaps",bid:109,maturity:"2016-08-30"});
        var c=t.getGrid("swaps").rows.length;
        assert.strictEqual(b,c);

    });
    it("can retrieve a row that has been added after initialisation",function(){
//        console.log("trying to find a row");
        var b=t.getRow({stock:"XXX",maturity:"2016-08-30"});
        assert.notStrictEqual(b,null);
    });
    it("has a show method which adds the root element to the DOM",function(){
        var b=document.getElementById("Blotter");
        assert.strictEqual(document.body.contains(b),false);
        t.show();
        var b=document.getElementById("Blotter");
        assert.strictEqual(document.body.contains(b),true);
    });
    it("can update a row",function(){
        t.updateRow({stock:"FG63",bid:40,class:"swaps",maturity:"2020-05-21"});
        var b=t.getRow({stock:"FG63",maturity:"2020-05-21"});
        assert.equal(b["bid"].getValue(),40.000);
    });
    it("has added a row to the dom",function(){
        var b=document.getElementById("straight").getElementsByTagName("tr")[0].getElementsByTagName("td")[0];//querySelector("#1 tr:first td:first");
        assert.isObject(b);
        var c=b.textContent;
//        console.log("td is " + c);
    });
    it("can add a column using the field option instead of a type",function(){
        var b=t.getCol().length;
        b++;
        t.addCol({name:"selection",field:"select",editable:true,options:["one","two","three"]});
        var c=t.getCol().length;
        assert.strictEqual(b,c);
    });
    it("can get a row",function(){
        var b=t.getRow({stock:'AAB',maturity:"2017-03-27"});
        assert.notStrictEqual(b,null);
       /* console.log("row is %j",b);
        for(var k in b){
            console.log("cell " + k + " values %j",b[k]);
            for(var m in b[k]){
                console.log("cell values " + m + " values %j " ,b[k][m]);
            }
        } */
    });
    it("can get a cell",function(){
        var b=t.getRow({stock:'AAB',maturity:"2017-03-27"});
        assert.notStrictEqual(b,null);
//        console.log("got cell " + b['selection']);
        var c=b['selection'];
        assert.notStrictEqual(c,null);
    });
    it("has added the options to the select cell",function(){
        var b=t.getRow({stock:'AAB',maturity:"2017-03-27"});
        assert.notStrictEqual(b,null);
//        console.log("got cell " + b['selection']);
        var c=b['selection'];
        assert.notStrictEqual(c,null);
        var d=b['selection'].select;
        assert.strictEqual(d.length,3);
//        console.log("options is %j",d);
    });

    it("can add a column",function(){
        var b=t.getCol().length;
        b++;
        t.addCol({name:"other",type:"string",editable:true});
        var c=t.getCol().length;
        assert.strictEqual(b,c);
    });
    it("updates an existing row",function(){
        //  t.updateRow({stock:"XXX",subclass:1,maturity:20160830,other:"something"});
        t.updateRow({stock:"AAB",class:"index_linked",maturity:"2017-03-27",other:"something"});
        var b=t.getRow({stock:"AAB",class:"index_linked",maturity:"2017-03-27"});
//        console.log("displayGrid:update row got %j",b);
     /*   for(var k in b){
            console.log("row key is " + k + " value " + b[k]);
            for (var n in b[k]){
                console.log("value object has key " + n + " value " + b[k][n]);
            }
        } */
        assert.notStrictEqual(b,null);
        assert.strictEqual(b["other"].getValue(),"something");
    });
    it("deletes a row",function(){
        t.deleteRow({stock:"AAC",class: "swaps",maturity:"2018-04-22"});

    });
    it("deletes a column",function(){
        t.deleteCol("bid");
    });
    it("can delete itself with hidden cols",function(){
        var b=document.getElementById("Blotter");
//        console.log("delete grid got element" + b);
        t.delete();
        assert.strictEqual(document.body.contains(b),false);
//        console.log("t is now " + t);

    });

});

describe("DisplayGrid-(start with data but no subgrids)",function(){
    var t;
    require("../DisplayGrid.js");
    var data={ id:"test_grid",DOM:"test",
               uniqueKey: ["one"],
               cols:[{name:"one",type: "integer" },
                     {name: "two",type: "string"}],
               rows:[{one: 20 ,two: "hat"},
                     {one: 22, two: "big"}]
             };
    it("creates a grid display object",function(){
        var b=document.createElement("div");
        b.id="test";
        document.body.appendChild(b);
        assert.strictEqual(document.contains(b),true);
        t=Apoco.display.grid(data);
        assert.isObject(t);
        t.show();
    });
    it("creates htmldiv container",function(){
        var b=document.getElementById("test_grid");
        assert.strictEqual(document.contains(b),true);
    });
    it("has sorted all the grids",function(){
        var b=t.getGrid();
        for(var i=0;i<b.length;i++){
            assert.strictEqual(b[i].sorted,true);
        }
    });
    it("can add a row",function(){
        var b=t.getGrid("all").rows.length;
        b++;
        var n=t.addRow({one:33, two: "fig"});
        assert.isObject(n);
        var c=t.getGrid("all").rows.length;
//        console.log("b is " + b +  " and c " + c);
        assert.strictEqual(b,c);
    });
    it("can create a rowEditPopup",function(){
        var b=t.getRow({one:20});
        assert.notStrictEqual(b,null);
        var f=t.rowEditPopup(b);
        assert.isObject(f);
        f.show();
        var b=document.getElementById("rowEditPopup");
        assert.strictEqual(document.contains(b),true);

    });
    it("rowEditpopup recreates itself it already in DOM",function(){
        var b=t.getRow({one:22});
        assert.notStrictEqual(b,null);
        var f=t.rowEditPopup(b);
        assert.isObject(f);
        f.show();
        var b=document.getElementById("rowEditPopup");
        assert.strictEqual(document.contains(b),true);
    });
   it("can delete itself",function(){
        var b=document.getElementById("test_grid");
        t.delete();
        assert.strictEqual(document.body.contains(b),false);

    });

});
describe("DisplayGrid-(start with data but no subgrids and no unique key)",function(){
    var t;
    require("../DisplayGrid.js");
    var data={ id:"test_grid",DOM:"test",
               userSortable:["two"],
               cols:[{name:"one",type: "integer" },
                     {name: "two",type: "string"}],
               rows:[{one: 20 ,two: "hat"},
                     {one: 22, two: "big"}]
             };
    it("creates a grid display object",function(){
        var b=document.createElement("div");
        b.id="test";
        document.body.appendChild(b);
        assert.strictEqual(document.contains(b),true);
        t=Apoco.display.grid(data);
        assert.isObject(t);
        t.show();
    });
    it("can get the grid",function(){
        var b=t.getGrid("all");
        assert.isObject(b);
    });
    it("can add a row",function(){
        var p=t.addRow({one: 36, two:"haha"});
        assert.notStrictEqual(p,null);
    });
    it("can add another row",function(){
        var b=t.getGrid("all").rows.length;
        b++;
        t.addRow({one: 44,two: "bigger"});
        var c=t.getGrid("all").rows.length;
        assert.strictEqual(b,c);
    });
    it("can get a row from data in row element",function(){
        var c=document.getElementById("test_grid").getElementsByTagName("tr");
        assert.strictEqual(c.length,4);
        var p=c[0];
        assert.isObject(p);
//        console.log("got data " + p.getAttribute("data-_aid"));
        var b=t.getRowFromElement(p);
        assert.isObject(b);
        assert.strictEqual(b["one"].value,20);
    });
    it("creates up and down buttons on user sortable columns",function(){
        var c=document.getElementById("test_grid").getElementsByClassName("head")[0];
        assert.isObject(c);
       // var b=c.getElementsByName("two")[0];
        var d=c.getElementsByClassName("arrows")[0];
        assert.isObject(d);
    });
    it("can sort a column if the buttom is clicked",function(){
        var s=t.sortOrder;
//        console.log("sort order is %j",s);
        var e=document.getElementsByClassName("arrows")[0]; //.getElementsByTagName("li")[1];
        assert.isObject(e);
        var up=e.querySelector("span.up");
       // var down=e.getElemenstByClassName("down")[0];
        assert.isObject(up);
        up.focus();
        up.click();
        var v=t.sortOrder;
//        console.log("sort order is %j",v);
        assert.notDeepEqual(v,s);
        assert.oneOf("two",v);
    });

    it("can get a row from data in row element after user sort",function(){
        var c=document.getElementById("test_grid").getElementsByTagName("tr");
        assert.strictEqual(c.length,4);
        var p=c[0];
        assert.isObject(p);
//        console.log("got data " + p.getAttribute("data-_aid"));
        var b=t.getRowFromElement(p);
        assert.isObject(b);
        assert.strictEqual(b["one"].value,22);
    });
    it("can delete itsef",function(){
        var b=document.getElementById("test_grid");
        var c=document.getElementsByClassName("head");
        t.delete();
        assert.strictEqual(document.body.contains(b),false);
        assert.strictEqual(c.length,0);
        //assert.strictEqual(document.body.contains(b),false);

    });

});
<commit_msg>add test for new method in grid findRow<commit_after>"use strict";

const       assert = require('chai').assert;
const        jsdom = require('jsdom');
const   browserify = require('browserify');
const browserifyFn = require('browserify-string');
const         path = require('path');
const           fs = require('fs');
const Apoco=require('../declare').Apoco;

global.document=require("jsdom").jsdom(undefined,
                                           {virtualConsole: jsdom.createVirtualConsole().sendTo(console)});
global.window=document.defaultView;
global.navigator=global.window.navigator;

describe("DisplayGrid-(start without rows)",function(){

    var t;
    require("../DisplayGrid.js");
    it("creates a grid display object",function(){
        var b=document.createElement("div");
        b.id="test";
        document.getElementsByTagName("body")[0].appendChild(b);
        //$("body").append("

");
        t=Apoco.display.grid({id:"test_grid",DOM:"test",cols:[{name: "name",type:"string"}]});
        assert.isObject(t);
    });
    it("has a getElement method",function(){
        var b=t.getElement();
        assert.isObject(b);
    });
    it("has a show method which adds the root element to the DOM",function(){
        var b=document.getElementById("test_grid");
        assert.isNotObject(b);
        t.show();
        var b=document.getElementById("test_grid");
        assert.isObject(b);
    });
    it("cannot add column if it does not have a unique name",function(){
        var fn=function(){
            t.addCol({name: "name",type:"string"});
        };
        assert.throws(fn,"Columns must have unique names");
    });
    it("has added a column if a uniqueKey is not specified",function(){
        var v=t.getCol();
        assert.strictEqual(v.length,2);
    });
    it("can add a column ",function(){
        t.addCol({name: "index",type:"integer"});
        assert.strictEqual(t.getColIndex("index"),2);
    });
    it("can add a row",function(){
        var b=t.addRow({name:"Bill",index:10});
        assert.notStrictEqual(b,null);
    });
    it("creates a grid",function(){
        assert.notStrictEqual(t.getGrid(),null);
        assert.notStrictEqual(t.getGrid(),undefined);
    });
    it("creates a row array",function(){
       // var n=t.getGrid();
        assert.notStrictEqual(t.getGrid().rows.length,0);
    });
    it("getRow throws an error if key is not unique",function(){
        t.addRow({name:"Homer",index:6});
        var fn=function(){
            var b=t.getRow({name:"Homer",index:6},null,{val:-1});
        };
        assert.throws(fn,"getRow: key is not unique" );
    });
    it("can add more columns ",function(){
        t.addCol({name: "job",type:"string"});
        assert.strictEqual(t.getColIndex("job"),3);
    });
    it("can add yet another row",function(){
        t.addRow({name:"Sam",job:"Manager"});
    });
    it("can add a column with a label",function(){
        t.addCol({name: "things",label:"whatever",type:"string"});
        assert.strictEqual(t.getColIndex("things"),4);
    });

    it("dumps the contents of the grid as a JSON object",function(){
        var b=t.getJSON();
        assert.isObject(b);
//        console.log("JSON %j",b);
    });
    it("updates a row only if unique key",function(){
        var fn=function(){
            t.updateRow({name:"Sam",index:12});
        };
        assert.throws(fn,"getRow: key is not unique");
    });
    it("has a delete method",function(){
        var b=document.getElementById("test_grid");
//        console.log("delete grid got element" + b);
        t.delete();
        assert.strictEqual(document.body.contains(b),false);
//        console.log("t is now " + t);
    });
});

describe("DisplayGrid-(start with data and subgrids)",function(){
    var t;
    require("../DisplayGrid.js");

    //var data=require("./data/data.js");
    require("./data/data.js");
    var data=window.data;
    it("has got some data",function(){
        assert.isObject(data);
    });
    it("creates a grid display object",function(){
        //$("body").append("

");
        var b=document.createElement("div");
        b.id="Content";
        document.body.appendChild(b);
        assert.strictEqual(document.body.contains(b),true);
        t=Apoco.display.grid(data);
        assert.isObject(t);
    });

    it("has sorted all the grids",function(){
        var b=t.getGrid();
        for(var i=0;i<b.length;i++){
            assert.strictEqual(b[i].sorted,true);
        }
    });

     it("can add a row",function(){
        var b=t.getGrid("swaps").rows.length;
        b++;
        var n=t.addRow({stock:"FG63",class: "swaps",bid:10,maturity:"2020-05-21"});
        var c=t.getGrid("swaps").rows.length;
//        console.log("b is " + b +  " and c " + c);
        //var b=t.getRow({stock:"FG63",subclass: 1,bid:10});
        assert.strictEqual(b,c);
       // console.log("JSON %j",n);
    });
    it("can add another row",function(){
        var b=t.getGrid("swaps").rows.length;
        b++;
        var n=t.addRow({stock:"XXX",class: "swaps",bid:109,maturity:"2016-08-30"});
        var c=t.getGrid("swaps").rows.length;
        assert.strictEqual(b,c);

    });
    it("can retrieve a row that has been added after initialisation",function(){
//        console.log("trying to find a row");
        var b=t.getRow({stock:"XXX",maturity:"2016-08-30"});
        assert.notStrictEqual(b,null);
    });
    it("has a show method which adds the root element to the DOM",function(){
        var b=document.getElementById("Blotter");
        assert.strictEqual(document.body.contains(b),false);
        t.show();
        var b=document.getElementById("Blotter");
        assert.strictEqual(document.body.contains(b),true);
    });
    it("can update a row",function(){
        t.updateRow({stock:"FG63",bid:40,class:"swaps",maturity:"2020-05-21"});
        var b=t.getRow({stock:"FG63",maturity:"2020-05-21"});
        assert.equal(b["bid"].getValue(),40.000);
    });
    it("has added a row to the dom",function(){
        var b=document.getElementById("straight").getElementsByTagName("tr")[0].getElementsByTagName("td")[0];//querySelector("#1 tr:first td:first");
        assert.isObject(b);
        var c=b.textContent;
//        console.log("td is " + c);
    });
    it("can add a column using the field option instead of a type",function(){
        var b=t.getCol().length;
        b++;
        t.addCol({name:"selection",field:"select",editable:true,options:["one","two","three"]});
        var c=t.getCol().length;
        assert.strictEqual(b,c);
    });
    it("can get a row",function(){
        var b=t.getRow({stock:'AAB',maturity:"2017-03-27"});
        assert.notStrictEqual(b,null);
       /* console.log("row is %j",b);
        for(var k in b){
            console.log("cell " + k + " values %j",b[k]);
            for(var m in b[k]){
                console.log("cell values " + m + " values %j " ,b[k][m]);
            }
        } */
    });
    it("can get a cell",function(){
        var b=t.getRow({stock:'AAB',maturity:"2017-03-27"});
        assert.notStrictEqual(b,null);
//        console.log("got cell " + b['selection']);
        var c=b['selection'];
        assert.notStrictEqual(c,null);
    });
    it("has added the options to the select cell",function(){
        var b=t.getRow({stock:'AAB',maturity:"2017-03-27"});
        assert.notStrictEqual(b,null);
//        console.log("got cell " + b['selection']);
        var c=b['selection'];
        assert.notStrictEqual(c,null);
        var d=b['selection'].select;
        assert.strictEqual(d.length,3);
//        console.log("options is %j",d);
    });

    it("can add a column",function(){
        var b=t.getCol().length;
        b++;
        t.addCol({name:"other",type:"string",editable:true});
        var c=t.getCol().length;
        assert.strictEqual(b,c);
    });
    it("updates an existing row",function(){
        //  t.updateRow({stock:"XXX",subclass:1,maturity:20160830,other:"something"});
        t.updateRow({stock:"AAB",class:"index_linked",maturity:"2017-03-27",other:"something"});
        var b=t.getRow({stock:"AAB",class:"index_linked",maturity:"2017-03-27"});
//        console.log("displayGrid:update row got %j",b);
     /*   for(var k in b){
            console.log("row key is " + k + " value " + b[k]);
            for (var n in b[k]){
                console.log("value object has key " + n + " value " + b[k][n]);
            }
        } */
        assert.notStrictEqual(b,null);
        assert.strictEqual(b["other"].getValue(),"something");
    });
    it("deletes a row",function(){
        t.deleteRow({stock:"AAC",class: "swaps",maturity:"2018-04-22"});

    });
    it("deletes a column",function(){
        t.deleteCol("bid");
    });
    it("can delete itself with hidden cols",function(){
        var b=document.getElementById("Blotter");
//        console.log("delete grid got element" + b);
        t.delete();
        assert.strictEqual(document.body.contains(b),false);
//        console.log("t is now " + t);

    });

});

describe("DisplayGrid-(start with data but no subgrids)",function(){
    var t;
    require("../DisplayGrid.js");
    var data={ id:"test_grid",DOM:"test",
               uniqueKey: ["one"],
               cols:[{name:"one",type: "integer" },
                     {name: "two",type: "string"}],
               rows:[{one: 20 ,two: "hat"},
                     {one: 22, two: "big"}]
             };
    it("creates a grid display object",function(){
        var b=document.createElement("div");
        b.id="test";
        document.body.appendChild(b);
        assert.strictEqual(document.contains(b),true);
        t=Apoco.display.grid(data);
        assert.isObject(t);
        t.show();
    });
    it("creates htmldiv container",function(){
        var b=document.getElementById("test_grid");
        assert.strictEqual(document.contains(b),true);
    });
    it("has sorted all the grids",function(){
        var b=t.getGrid();
        for(var i=0;i<b.length;i++){
            assert.strictEqual(b[i].sorted,true);
        }
    });
    it("can add a row",function(){
        var b=t.getGrid("all").rows.length;
        b++;
        var n=t.addRow({one:33, two: "fig"});
        assert.isObject(n);
        var c=t.getGrid("all").rows.length;
//        console.log("b is " + b +  " and c " + c);
        assert.strictEqual(b,c);
    });
    it("can create a rowEditPopup",function(){
        var b=t.getRow({one:20});
        assert.notStrictEqual(b,null);
        var f=t.rowEditPopup(b);
        assert.isObject(f);
        f.show();
        var b=document.getElementById("rowEditPopup");
        assert.strictEqual(document.contains(b),true);

    });
    it("can get row data from an event callback",function(){
        var b=t.getGrid();
        b.element.addEventListener("click",function(self){
            return function(e){
                var row;
                row=self.findRow(e,self);
                assert.isObject(row);
                assert.strictEqual(row,{one:"one",two:"hat"});
            };
        }(b),false);
        var h=document.getElementsByTagName("TR");
        assert.isObject(h);
        h[0].click();

    });
    it("rowEditpopup recreates itself it already in DOM",function(){
        var b=t.getRow({one:22});
        assert.notStrictEqual(b,null);
        var f=t.rowEditPopup(b);
        assert.isObject(f);
        f.show();
        var b=document.getElementById("rowEditPopup");
        assert.strictEqual(document.contains(b),true);
    });
   it("can delete itself",function(){
        var b=document.getElementById("test_grid");
        t.delete();
        assert.strictEqual(document.body.contains(b),false);

    });

});
describe("DisplayGrid-(start with data but no subgrids and no unique key)",function(){
    var t;
    require("../DisplayGrid.js");
    var data={ id:"test_grid",DOM:"test",
               userSortable:["two"],
               cols:[{name:"one",type: "integer" },
                     {name: "two",type: "string"}],
               rows:[{one: 20 ,two: "hat"},
                     {one: 22, two: "big"}]
             };
    it("creates a grid display object",function(){
        var b=document.createElement("div");
        b.id="test";
        document.body.appendChild(b);
        assert.strictEqual(document.contains(b),true);
        t=Apoco.display.grid(data);
        assert.isObject(t);
        t.show();
    });
    it("can get the grid",function(){
        var b=t.getGrid("all");
        assert.isObject(b);
    });
    it("can add a row",function(){
        var p=t.addRow({one: 36, two:"haha"});
        assert.notStrictEqual(p,null);
    });
    it("can add another row",function(){
        var b=t.getGrid("all").rows.length;
        b++;
        t.addRow({one: 44,two: "bigger"});
        var c=t.getGrid("all").rows.length;
        assert.strictEqual(b,c);
    });
    it("can get a row from data in row element",function(){
        var c=document.getElementById("test_grid").getElementsByTagName("tr");
        assert.strictEqual(c.length,4);
        var p=c[0];
        assert.isObject(p);
//        console.log("got data " + p.getAttribute("data-_aid"));
        var b=t.getRowFromElement(p);
        assert.isObject(b);
        assert.strictEqual(b["one"].value,20);
    });
    it("creates up and down buttons on user sortable columns",function(){
        var c=document.getElementById("test_grid").getElementsByClassName("head")[0];
        assert.isObject(c);
       // var b=c.getElementsByName("two")[0];
        var d=c.getElementsByClassName("arrows")[0];
        assert.isObject(d);
    });
    it("can sort a column if the buttom is clicked",function(){
        var s=t.sortOrder;
//        console.log("sort order is %j",s);
        var e=document.getElementsByClassName("arrows")[0]; //.getElementsByTagName("li")[1];
        assert.isObject(e);
        var up=e.querySelector("span.up");
       // var down=e.getElemenstByClassName("down")[0];
        assert.isObject(up);
        up.focus();
        up.click();
        var v=t.sortOrder;
//        console.log("sort order is %j",v);
        assert.notDeepEqual(v,s);
        assert.oneOf("two",v);
    });

    it("can get a row from data in row element after user sort",function(){
        var c=document.getElementById("test_grid").getElementsByTagName("tr");
        assert.strictEqual(c.length,4);
        var p=c[0];
        assert.isObject(p);
//        console.log("got data " + p.getAttribute("data-_aid"));
        var b=t.getRowFromElement(p);
        assert.isObject(b);
        assert.strictEqual(b["one"].value,22);
    });
    it("can delete itsef",function(){
        var b=document.getElementById("test_grid");
        var c=document.getElementsByClassName("head");
        t.delete();
        assert.strictEqual(document.body.contains(b),false);
        assert.strictEqual(c.length,0);
        //assert.strictEqual(document.body.contains(b),false);

    });

});
<|endoftext|>


<commit_before>import { test } from 'substance-test'
import setupTestApp from './shared/setupTestApp'
import { openMetadataEditor, selectCard, clickUndo, getSelection } from './shared/integrationTestHelpers'
import { doesNotThrowInNodejs } from './shared/testHelpers'

test(`Entity: add author`, t => {
  _entityTest(t, 'person', 'author')
})

test(`Entity: add editor`, t => {
  _entityTest(t, 'person', 'editor')
})

test(`Entity: add group`, t => {
  _entityTest(t, 'group')
})

test(`Entity: add affiliation`, t => {
  _entityTest(t, 'organisation')
})

test(`Entity: add award`, t => {
  _entityTest(t, 'award')
})

test(`Entity: add keyword`, t => {
  _entityTest(t, 'keyword')
})

test(`Entity: add subject`, t => {
  _entityTest(t, 'subject')
})

test(`Entity: add footnote`, t => {
  _entityTest(t, 'footnote')
})

function _entityTest (t, entityType, entityName) {
  entityName = entityName || entityType

  let { app } = setupTestApp(t, { archiveId: 'blank' })
  let editor = openMetadataEditor(app)

  const CARD_SELECTOR = `.sc-card.sm-${entityType}`
  const _hasCard = () => { return Boolean(editor.find(CARD_SELECTOR)) }
  const _getModelId = () => { return editor.find(CARD_SELECTOR).getAttribute('data-id') }

  doesNotThrowInNodejs(t, () => {
    _insertEntity(editor, entityName)
  })
  t.ok(_hasCard(), 'there should be a card for the new entitiy')
  // Note: checking the selection as good as we can. The selected field us derived from the node schema and settings
  // TODO: we could apply a specific configuration so that we know the field name
  let sel = getSelection(editor)
  t.deepEqual({
    type: sel.type,
    nodeId: sel.getNodeId()
  }, {
    type: 'property',
    nodeId: _getModelId()
  }, 'a field in the new entity should be selected')

  // in addition to the plain 'Add Entity' we also test 'Remove+Undo'
  selectCard(editor, _getModelId())
  _removeEntity(editor, entityName)
  t.notOk(_hasCard(), 'card should have been removed')
  clickUndo(editor)
  t.ok(_hasCard(), 'card should be back again')

  t.end()
}

function _insertEntity (editor, entityName) {
  // open the corresponding dropdown
  let menu = editor.find('.sc-tool-dropdown.sm-insert')
  menu.find('button').el.click()
  let addButton = menu.find(`.sc-menu-item.sm-insert-${entityName}`).el
  return addButton.click()
}

function _removeEntity (editor, entityName) {
  let collectionTools = editor.find('.sc-tool-dropdown.sm-collection-tools')
  collectionTools.refs.toggle.el.click()
  editor.find(`.sc-menu-item.sm-remove-${entityName}`).el.click()
}
<commit_msg>Fix Entity.test<commit_after>import { test } from 'substance-test'
import setupTestApp from './shared/setupTestApp'
import { openMetadataEditor, selectCard, clickUndo, getSelection, getSelectionState } from './shared/integrationTestHelpers'
import { doesNotThrowInNodejs } from './shared/testHelpers'

test(`Entity: add author`, t => {
  _entityTest(t, 'person', 'author')
})

test(`Entity: add editor`, t => {
  _entityTest(t, 'person', 'editor')
})

test(`Entity: add group`, t => {
  _entityTest(t, 'group')
})

test(`Entity: add affiliation`, t => {
  _entityTest(t, 'organisation')
})

test(`Entity: add award`, t => {
  _entityTest(t, 'award')
})

test(`Entity: add keyword`, t => {
  _entityTest(t, 'keyword')
})

test(`Entity: add subject`, t => {
  _entityTest(t, 'subject')
})

test(`Entity: add footnote`, t => {
  _entityTest(t, 'footnote', 'footnote', (t, sel, selState) => {
    t.equal(sel.type, 'property', 'selection should be an property selection')
    t.ok(Boolean(selState.xpath.find(e => e.type === 'paragraph')), '.. inside a paragraph')
  })
})

function _entityTest (t, entityType, entityName, checkSelection) {
  entityName = entityName || entityType

  let { app } = setupTestApp(t, { archiveId: 'blank' })
  let editor = openMetadataEditor(app)

  const CARD_SELECTOR = `.sc-card.sm-${entityType}`
  const _hasCard = () => { return Boolean(editor.find(CARD_SELECTOR)) }
  const _getModelId = () => { return editor.find(CARD_SELECTOR).getAttribute('data-id') }
  function _defaultCheckSelection (t, sel) {
    t.deepEqual({
      type: sel.type,
      nodeId: sel.getNodeId()
    }, {
      type: 'property',
      nodeId: _getModelId()
    }, 'a field in the new entity should be selected')
  }

  doesNotThrowInNodejs(t, () => {
    _insertEntity(editor, entityName)
  })
  t.ok(_hasCard(), 'there should be a card for the new entitiy')
  // Note: checking the selection as good as we can. The selected field us derived from the node schema and settings
  // TODO: we could apply a specific configuration so that we know the field name
  let sel = getSelection(editor)
  let selState = getSelectionState(editor)
  let _checkSelection = checkSelection || _defaultCheckSelection
  _checkSelection(t, sel, selState)

  // in addition to the plain 'Add Entity' we also test 'Remove+Undo'
  selectCard(editor, _getModelId())
  _removeEntity(editor, entityName)
  t.notOk(_hasCard(), 'card should have been removed')
  clickUndo(editor)
  t.ok(_hasCard(), 'card should be back again')

  t.end()
}

function _insertEntity (editor, entityName) {
  // open the corresponding dropdown
  let menu = editor.find('.sc-tool-dropdown.sm-insert')
  menu.find('button').el.click()
  let addButton = menu.find(`.sc-menu-item.sm-insert-${entityName}`).el
  return addButton.click()
}

function _removeEntity (editor, entityName) {
  let collectionTools = editor.find('.sc-tool-dropdown.sm-collection-tools')
  collectionTools.refs.toggle.el.click()
  editor.find(`.sc-menu-item.sm-remove-${entityName}`).el.click()
}
<|endoftext|>


<commit_before>// @flow

import React from 'react';
import { render } from 'react-dom';
import { match } from 'react-router';
import Root from './Root';
import { AppContainer } from 'react-hot-loader';
import routes from 'app/routes';
import type { Store } from 'app/types';

const renderApp = (store: Store, history: any) => {
  match({ history, routes }, (error, redirectLocation, renderProps) => {
    const rootElement: HTMLElement = (document.getElementById('root'): any);
    render(
      <AppContainer>
        <Root {...{ store, history, routes }} {...renderProps} />
      </AppContainer>,
      rootElement
    );
  });
};

export default renderApp;
<commit_msg>use hydrate() instead of render() on the client<commit_after>// @flow

import React from 'react';
// $FlowFixMe hydrate() is missing in flow-typed react-dom
import { hydrate } from 'react-dom';
import { match } from 'react-router';
import Root from './Root';
import { AppContainer } from 'react-hot-loader';
import routes from 'app/routes';
import type { Store } from 'app/types';

const renderApp = (store: Store, history: any) => {
  match({ history, routes }, (error, redirectLocation, renderProps) => {
    const rootElement: HTMLElement = (document.getElementById('root'): any);
    hydrate(
      <AppContainer>
        <Root {...{ store, history, routes }} {...renderProps} />
      </AppContainer>,
      rootElement
    );
  });
};

export default renderApp;
<|endoftext|>


<commit_before>pref("extensions.weave.engine.inforss", true);
<commit_msg>Add default prefs and some documentation<commit_after>pref("extensions.weave.engine.inforss", true);

pref("inforss.debug.alert", false);
pref("inforss.debug.log", false);
pref("inforss.debug.statusbar", false);

//Traces on entry/exit to various functions. Must run <browser> --console
//Needs to be set manually and is only processed on startup.
pref("inforss.debug.traceinconsole", false);

//Don't know about these yet

//Syncing of something to/from a repository
//pref("inforss.repository.autosync", false);
//pref("inforss.repository.directory", "");
//pref("inforss.repository.protocol", "ftp:");
//pref("inforss.repository.server", "");
//pref("inforss.repository.user", "");

//Whether or not the bar is visible?
//pref("inforss.toolbar.collapsed", false);
<|endoftext|>


<commit_before>'use strict';

process.env.NODE_ENV = 'development';

console.time('=====> testing gray pam diffs with 4 regions set');

const assert = require('assert');

const P2P = require('pipe2pam');

const PamDiff = require('../index');

const ffmpegPath = require('ffmpeg-static').path;

const spawn = require('child_process').spawn;

const pamCount = 10;

let pamCounter = 0;

let pamDiffCounter = 0;

const pamDiffResults = [17, 18, 15, 16, 16, 14, 18, 17, 14];

const params = [
    /* log info to console */
    '-loglevel',
    'quiet',
    //'-stats',

    /* use an artificial video input */
    //'-re',
    '-f',
    'lavfi',
    '-i',
    'testsrc=size=1920x1080:rate=15',

    /* set output flags */
    '-an',
    '-c:v',
    'pam',
    '-pix_fmt',
    'gray',
    '-f',
    'image2pipe',
    '-vf',
    'fps=1,scale=400:225',
    '-frames',
    pamCount,
    'pipe:1'
];

const p2p = new P2P();

p2p.on('pam', (data) => {
    pamCounter++;
});

const region1 = {name: 'region1', difference: 1, percent: 1, polygon: [{x: 0, y: 0}, {x: 0, y: 225}, {x: 100, y: 225}, {x: 100, y: 0}]};

const region2 = {name: 'region2', difference: 1, percent: 1, polygon: [{x: 100, y: 0}, {x: 100, y: 225}, {x: 200, y: 225}, {x: 200, y: 0}]};

const region3 = {name: 'region3', difference: 1, percent: 1, polygon: [{x: 200, y: 0}, {x: 200, y: 225}, {x: 300, y: 225}, {x: 300, y: 0}]};

const region4 = {name: 'region4', difference: 1, percent: 1, polygon: [{x: 300, y: 0}, {x: 300, y: 225}, {x: 400, y: 225}, {x: 400, y: 0}]};

const regions = [region1, region2, region3, region4];

const pamDiff = new PamDiff({regions : regions});

pamDiff.on('diff', (data) => {
    assert(data.trigger[3].name === 'region4', 'trigger name is not correct');
    assert(data.trigger[3].percent === pamDiffResults[pamDiffCounter++], 'trigger percent is not correct');
});

const ffmpeg = spawn(ffmpegPath, params, {stdio: ['ignore', 'pipe', 'inherit']});

ffmpeg.on('error', (error) => {
    console.log(error);
});

ffmpeg.on('exit', (code, signal) => {
    assert(code === 0, `FFMPEG exited with code ${code} and signal ${signal}`);
    assert(pamDiffCounter === pamCount - 1, `did not get ${pamCount - 1} pam diffs`);
    console.timeEnd('=====> testing gray pam diffs with 4 regions set');
});

ffmpeg.stdout.pipe(p2p).pipe(pamDiff);<commit_msg>increased duration of test<commit_after>'use strict';

process.env.NODE_ENV = 'development';

console.time('=====> testing gray pam diffs with 4 regions set');

const assert = require('assert');

const P2P = require('pipe2pam');

const PamDiff = require('../index');

const ffmpegPath = require('ffmpeg-static').path;

const spawn = require('child_process').spawn;

const pamCount = 100;

let pamCounter = 0;

let pamDiffCounter = 0;

const pamDiffResults = [17,18,15,16,16,14,18,17,14,21,17,19,15,16,16,14,18,18,14,17,18,18,15,16,16,14,19,17,14,16,17,18,15,16,16,14,18,17,14,16,17,19,15,16,16,14,18,18,14,17,18,18,15,16,16,14,19,17,14,15,17,18,15,16,16,14,18,17,14,17,17,19,15,16,16,14,18,18,14,16,18,18,15,16,16,14,19,17,14,15,17,18,15,16,16,14,18,17,14];

const params = [
    /* log info to console */
    '-loglevel',
    'quiet',
    //'-stats',

    /* use an artificial video input */
    //'-re',
    '-f',
    'lavfi',
    '-i',
    'testsrc=size=1920x1080:rate=15',

    /* set output flags */
    '-an',
    '-c:v',
    'pam',
    '-pix_fmt',
    'gray',
    '-f',
    'image2pipe',
    '-vf',
    'fps=1,scale=400:225',
    '-frames',
    pamCount,
    'pipe:1'
];

const p2p = new P2P();

p2p.on('pam', (data) => {
    pamCounter++;
});

const region1 = {name: 'region1', difference: 1, percent: 1, polygon: [{x: 0, y: 0}, {x: 0, y: 225}, {x: 100, y: 225}, {x: 100, y: 0}]};

const region2 = {name: 'region2', difference: 1, percent: 1, polygon: [{x: 100, y: 0}, {x: 100, y: 225}, {x: 200, y: 225}, {x: 200, y: 0}]};

const region3 = {name: 'region3', difference: 1, percent: 1, polygon: [{x: 200, y: 0}, {x: 200, y: 225}, {x: 300, y: 225}, {x: 300, y: 0}]};

const region4 = {name: 'region4', difference: 1, percent: 1, polygon: [{x: 300, y: 0}, {x: 300, y: 225}, {x: 400, y: 225}, {x: 400, y: 0}]};

const regions = [region1, region2, region3, region4];

const pamDiff = new PamDiff({regions : regions});

pamDiff.on('diff', (data) => {
    assert(data.trigger[3].name === 'region4', 'trigger name is not correct');
    assert(data.trigger[3].percent === pamDiffResults[pamDiffCounter++], 'trigger percent is not correct');
});

const ffmpeg = spawn(ffmpegPath, params, {stdio: ['ignore', 'pipe', 'inherit']});

ffmpeg.on('error', (error) => {
    console.log(error);
});

ffmpeg.on('exit', (code, signal) => {
    assert(code === 0, `FFMPEG exited with code ${code} and signal ${signal}`);
    assert(pamDiffCounter === pamCount - 1, `did not get ${pamCount - 1} pam diffs`);
    console.timeEnd('=====> testing gray pam diffs with 4 regions set');
});

ffmpeg.stdout.pipe(p2p).pipe(pamDiff);<|endoftext|>


<commit_before>const Configuration = Jymfony.Bundle.FrameworkBundle.DependencyInjection.Configuration;
const InvalidConfigurationException = Jymfony.Component.Config.Definition.Exception.InvalidConfigurationException;
const FileLocator = Jymfony.Component.Config.FileLocator;
const Alias = Jymfony.Component.DependencyInjection.Alias;
const ChildDefinition = Jymfony.Component.DependencyInjection.ChildDefinition;
const Reference = Jymfony.Component.DependencyInjection.Reference;
const JsFileLoader = Jymfony.Component.DependencyInjection.Loader.JsFileLoader;
const Extension = Jymfony.Component.DependencyInjection.Extension.Extension;
const path = require('path');

/**
 * @memberOf Jymfony.Bundle.FrameworkBundle.DependencyInjection
 */
class FrameworkExtension extends Extension {
    /**
     * Load a configuration
     *
     * @param {*} configs
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     */
    load(configs, container) {
        const loader = new JsFileLoader(container, new FileLocator(path.join(__dirname, '..', 'Resources', 'config')));
        loader.load('services.js');

        const configuration = this.getConfiguration(container);
        const config = this._processConfiguration(configuration, configs);

        if (config.test) {
            loader.load('test.js');
        }

        this._registerConsoleConfiguration(config.console, container, loader);
        this._registerLoggerConfiguration(config.logger, container, loader);
        this._registerRouterConfiguration(config.router, container, loader);
        this._registerHttpServerConfiguration(config.http_server, container, loader);
    }

    /**
     * @inheritDoc
     *
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     */
    getConfiguration(container) {
        return new Configuration(container.getParameter('kernel.debug'));
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.DependencyInjection.Loader.LoaderInterface} loader
     */
    _registerConsoleConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config)) {
            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.Console.Application')) {
            throw new InvalidConfigurationException('Console component is not installed');
        }

        loader.load('console.js');
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param loader
     */
    _registerLoggerConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config) || ! config.handlers) {
            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.Logger.Logger')) {
            throw new InvalidConfigurationException('Logger component is not installed');
        }

        loader.load('logger.js');

        const handlers = new PriorityQueue();
        const handlersToChannels = {};
        for (const [ name, handler ] of __jymfony.getEntries(config.handlers)) {
            const serviceId = this._buildLoggerHandler(container, name, handler);
            handlers.push(new Reference(serviceId), handler.priority);

            if (undefined === handler.channels) {
                continue;
            }

            handlersToChannels[serviceId] = handler.channels;
        }

        const definition = (new ChildDefinition('jymfony.logger_prototype'))
            .setPublic(false)
            .replaceArgument(0, 'app')
        ;

        container.setParameter('jymfony.logger.handlers_to_channels', handlersToChannels);
        container.setDefinition('jymfony.logger', definition);
    }

    _buildLoggerHandler(container, name, handler) {
        const handlerId = 'jymfony.logger.handler.'+name;
        if ('service' === handler.type) {
            container.setAlias(handler, handler.id);

            return handlerId;
        }

        const definition = new ChildDefinition('jymfony.logger.handler_prototype.'+handler.type);
        handler.level = isNumber(handler.level) ? handler.level : Jymfony.Component.Logger.LogLevel[handler.level.toUpperCase()];

        switch (handler.type) {
            case 'stream':
                definition.setArguments([
                    handler.path,
                    handler.level,
                    handler.bubble,
                    handler.file_permission,
                ]);
                break;

            case 'console':
                definition.setArguments([
                    undefined,
                    handler.bubble,
                    handler.verbosity_levels,
                ]);
                definition.addTag('kernel.event_subscriber');
                break;

            case 'mongodb':
                definition.setArguments([
                    new Reference('jymfony.logger.mongodb.connection.'+name),
                    handler.mongo.collection,
                    handler.level,
                    handler.bubble,
                ]);

                if (!!handler.mongo.id) {
                    container.setAlias('jymfony.logger.mongodb.connection.'+name, new Alias(handler.mongo.id));
                } else {
                    container.register('jymfony.logger.mongodb.connection.'+name)
                        .setModule('mongodb', 'MongoClient')
                        .setArguments(handler.mongo.url, {
                            auto_reconnect: false,
                        })
                        .setPublic(true)
                    ;
                }
                break;

            case 'null':
                definition.setArguments([
                    handler.level,
                    handler.bubble,
                ]);
                break;

            default:
                throw new InvalidArgumentException(
                    __jymfony.sprintf('Invalid handler type "%s" given for handler "%s"', handler.type, name)
                );
        }

        if (handler.formatter) {
            definition.addProperty('formatter', new Reference(handler.formatter));
        }

        container.setDefinition(handlerId, definition);

        return handlerId;
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.DependencyInjection.Loader.LoaderInterface} loader
     */
    _registerRouterConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config)) {
            container.removeDefinition('console.command.router_debug');
            container.removeDefinition('console.command.router_match');

            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.Routing.RouterInterface')) {
            throw new InvalidConfigurationException('Router component is not installed');
        }

        loader.load('routing.js');

        container.setParameter('router.resource', config['resource']);
        const definition = container.getDefinition('router.default');

        const options = definition.getArgument(3);
        if (config.type) {
            options.resource_type = config.type;
        }

        definition.replaceArgument(3, options);
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.DependencyInjection.Loader.LoaderInterface} loader
     */
    _registerHttpServerConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config)) {
            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.HttpServer.HttpServer')) {
            throw new InvalidConfigurationException('HttpServer component is not installed');
        }

        loader.load('http-server.js');
    }
}

module.exports = FrameworkExtension;
<commit_msg>[FrameworkBundle] fix argument set on mongodb connection definition<commit_after>const Configuration = Jymfony.Bundle.FrameworkBundle.DependencyInjection.Configuration;
const InvalidConfigurationException = Jymfony.Component.Config.Definition.Exception.InvalidConfigurationException;
const FileLocator = Jymfony.Component.Config.FileLocator;
const Alias = Jymfony.Component.DependencyInjection.Alias;
const ChildDefinition = Jymfony.Component.DependencyInjection.ChildDefinition;
const Reference = Jymfony.Component.DependencyInjection.Reference;
const JsFileLoader = Jymfony.Component.DependencyInjection.Loader.JsFileLoader;
const Extension = Jymfony.Component.DependencyInjection.Extension.Extension;
const path = require('path');

/**
 * @memberOf Jymfony.Bundle.FrameworkBundle.DependencyInjection
 */
class FrameworkExtension extends Extension {
    /**
     * Load a configuration
     *
     * @param {*} configs
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     */
    load(configs, container) {
        const loader = new JsFileLoader(container, new FileLocator(path.join(__dirname, '..', 'Resources', 'config')));
        loader.load('services.js');

        const configuration = this.getConfiguration(container);
        const config = this._processConfiguration(configuration, configs);

        if (config.test) {
            loader.load('test.js');
        }

        this._registerConsoleConfiguration(config.console, container, loader);
        this._registerLoggerConfiguration(config.logger, container, loader);
        this._registerRouterConfiguration(config.router, container, loader);
        this._registerHttpServerConfiguration(config.http_server, container, loader);
    }

    /**
     * @inheritDoc
     *
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     */
    getConfiguration(container) {
        return new Configuration(container.getParameter('kernel.debug'));
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.DependencyInjection.Loader.LoaderInterface} loader
     */
    _registerConsoleConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config)) {
            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.Console.Application')) {
            throw new InvalidConfigurationException('Console component is not installed');
        }

        loader.load('console.js');
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param loader
     */
    _registerLoggerConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config) || ! config.handlers) {
            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.Logger.Logger')) {
            throw new InvalidConfigurationException('Logger component is not installed');
        }

        loader.load('logger.js');

        const handlers = new PriorityQueue();
        const handlersToChannels = {};
        for (const [ name, handler ] of __jymfony.getEntries(config.handlers)) {
            const serviceId = this._buildLoggerHandler(container, name, handler);
            handlers.push(new Reference(serviceId), handler.priority);

            if (undefined === handler.channels) {
                continue;
            }

            handlersToChannels[serviceId] = handler.channels;
        }

        const definition = (new ChildDefinition('jymfony.logger_prototype'))
            .setPublic(false)
            .replaceArgument(0, 'app')
        ;

        container.setParameter('jymfony.logger.handlers_to_channels', handlersToChannels);
        container.setDefinition('jymfony.logger', definition);
    }

    _buildLoggerHandler(container, name, handler) {
        const handlerId = 'jymfony.logger.handler.'+name;
        if ('service' === handler.type) {
            container.setAlias(handler, handler.id);

            return handlerId;
        }

        const definition = new ChildDefinition('jymfony.logger.handler_prototype.'+handler.type);
        handler.level = isNumber(handler.level) ? handler.level : Jymfony.Component.Logger.LogLevel[handler.level.toUpperCase()];

        switch (handler.type) {
            case 'stream':
                definition.setArguments([
                    handler.path,
                    handler.level,
                    handler.bubble,
                    handler.file_permission,
                ]);
                break;

            case 'console':
                definition.setArguments([
                    undefined,
                    handler.bubble,
                    handler.verbosity_levels,
                ]);
                definition.addTag('kernel.event_subscriber');
                break;

            case 'mongodb':
                definition.setArguments([
                    new Reference('jymfony.logger.mongodb.connection.'+name),
                    handler.mongo.collection,
                    handler.level,
                    handler.bubble,
                ]);

                if (!!handler.mongo.id) {
                    container.setAlias('jymfony.logger.mongodb.connection.'+name, new Alias(handler.mongo.id));
                } else {
                    container.register('jymfony.logger.mongodb.connection.'+name)
                        .setModule('mongodb', 'MongoClient')
                        .setArguments([
                            handler.mongo.url,
                            {
                                auto_reconnect: false,
                            },
                        ])
                        .setPublic(true)
                    ;
                }
                break;

            case 'null':
                definition.setArguments([
                    handler.level,
                    handler.bubble,
                ]);
                break;

            default:
                throw new InvalidArgumentException(
                    __jymfony.sprintf('Invalid handler type "%s" given for handler "%s"', handler.type, name)
                );
        }

        if (handler.formatter) {
            definition.addProperty('formatter', new Reference(handler.formatter));
        }

        container.setDefinition(handlerId, definition);

        return handlerId;
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.DependencyInjection.Loader.LoaderInterface} loader
     */
    _registerRouterConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config)) {
            container.removeDefinition('console.command.router_debug');
            container.removeDefinition('console.command.router_match');

            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.Routing.RouterInterface')) {
            throw new InvalidConfigurationException('Router component is not installed');
        }

        loader.load('routing.js');

        container.setParameter('router.resource', config['resource']);
        const definition = container.getDefinition('router.default');

        const options = definition.getArgument(3);
        if (config.type) {
            options.resource_type = config.type;
        }

        definition.replaceArgument(3, options);
    }

    /**
     * @param {*} config
     * @param {Jymfony.Component.DependencyInjection.ContainerBuilder} container
     * @param {Jymfony.Component.DependencyInjection.Loader.LoaderInterface} loader
     */
    _registerHttpServerConfiguration(config, container, loader) {
        if (! this._isConfigEnabled(container, config)) {
            return;
        }

        if (! ReflectionClass.exists('Jymfony.Component.HttpServer.HttpServer')) {
            throw new InvalidConfigurationException('HttpServer component is not installed');
        }

        loader.load('http-server.js');
    }
}

module.exports = FrameworkExtension;
<|endoftext|>


<commit_before>var m = require('mithril');
var xhr = require('../studyXhr');
var embedYoutube = require('../studyComments').embedYoutube;
var makeSuccess = require('./studyPracticeSuccess');

var readOnlyProp = function(value) {
  return function() {
    return value;
  };
};

var commentYoutubeRegex = /(?:https?:\/\/)(?:www\.)(?:youtube\.com|youtu\.be)\/(?:watch)?(?:\?v=)?([^"&?\/ ]{11})/gi;

module.exports = function(root, studyData, data) {

  var goal = m.prop();
  var comment = m.prop();
  var nbMoves = m.prop(0);
  var success = m.prop(null); // null = ongoing, true = win, false = fail

  var makeComment = function(treeRoot) {
    if (!treeRoot.comments) return;
    var c = embedYoutube(treeRoot.comments[0].text);
    delete treeRoot.comments;
    return c;
  };

  var onLoad = function() {
    root.vm.showAutoShapes = readOnlyProp(true);
    root.vm.showGauge = readOnlyProp(true);
    root.vm.showComputer = readOnlyProp(true);
    goal(root.data.practiceGoal);
    nbMoves(0);
    success(null);
    comment(makeComment(root.tree.root));
    var chapter = studyData.chapter;
    // history.replaceState(null, chapter.name, data.url + '/' + chapter.id);
  };
  onLoad();

  var computeNbMoves = function() {
    var plies = root.vm.node.ply - root.tree.root.ply;
    if (root.bottomColor() !== root.data.player.color) plies--;
    return Math.ceil(plies / 2);
  };

  var checkSuccess = function() {
    if (success() !== null) return;
    nbMoves(computeNbMoves());
    success(makeSuccess(root, goal(), nbMoves()));
    if (success()) onVictory();
  };

  var onVictory = function() {
    var chapterId = root.study.currentChapter().id;
    var former = data.completion[chapterId] || 999;
    if (nbMoves() < former) {
      data.completion[chapterId] = nbMoves();
      xhr.practiceComplete(chapterId, nbMoves());
    }
  };

  var findNextOngoingChapter = function() {
    return root.study.data.chapters.filter(function(c) {
      return !data.completion[c.id];
    })[0];
  };
  var findNextChapter = function() {
    var chapters = root.study.data.chapters;
    var currentId = root.study.currentChapter().id;
    for (var i in chapters)
      if (chapters[i].id === currentId) return chapters[(i + 1) % chapters.length];
    return chapters[0];
  };

  return {
    onReload: onLoad,
    onJump: checkSuccess,
    onCeval: checkSuccess,
    data: data,
    goal: goal,
    success: success,
    comment: comment,
    nbMoves: nbMoves,
    nextChapter: function() {
      return findNextOngoingChapter() || findNextChapter();
    },
    reset: function() {
      root.tree.root.children = [];
      root.userJump('');
      onLoad();
    }
  };
};
<commit_msg>set practice chapter url<commit_after>var m = require('mithril');
var xhr = require('../studyXhr');
var embedYoutube = require('../studyComments').embedYoutube;
var makeSuccess = require('./studyPracticeSuccess');

var readOnlyProp = function(value) {
  return function() {
    return value;
  };
};

var commentYoutubeRegex = /(?:https?:\/\/)(?:www\.)(?:youtube\.com|youtu\.be)\/(?:watch)?(?:\?v=)?([^"&?\/ ]{11})/gi;

module.exports = function(root, studyData, data) {

  var goal = m.prop();
  var comment = m.prop();
  var nbMoves = m.prop(0);
  var success = m.prop(null); // null = ongoing, true = win, false = fail

  var makeComment = function(treeRoot) {
    if (!treeRoot.comments) return;
    var c = embedYoutube(treeRoot.comments[0].text);
    delete treeRoot.comments;
    return c;
  };

  var onLoad = function() {
    root.vm.showAutoShapes = readOnlyProp(true);
    root.vm.showGauge = readOnlyProp(true);
    root.vm.showComputer = readOnlyProp(true);
    goal(root.data.practiceGoal);
    nbMoves(0);
    success(null);
    comment(makeComment(root.tree.root));
    var chapter = studyData.chapter;
    history.replaceState(null, chapter.name, data.url + '/' + chapter.id);
  };
  onLoad();

  var computeNbMoves = function() {
    var plies = root.vm.node.ply - root.tree.root.ply;
    if (root.bottomColor() !== root.data.player.color) plies--;
    return Math.ceil(plies / 2);
  };

  var checkSuccess = function() {
    if (success() !== null) return;
    nbMoves(computeNbMoves());
    success(makeSuccess(root, goal(), nbMoves()));
    if (success()) onVictory();
  };

  var onVictory = function() {
    var chapterId = root.study.currentChapter().id;
    var former = data.completion[chapterId] || 999;
    if (nbMoves() < former) {
      data.completion[chapterId] = nbMoves();
      xhr.practiceComplete(chapterId, nbMoves());
    }
  };

  var findNextOngoingChapter = function() {
    return root.study.data.chapters.filter(function(c) {
      return !data.completion[c.id];
    })[0];
  };
  var findNextChapter = function() {
    var chapters = root.study.data.chapters;
    var currentId = root.study.currentChapter().id;
    for (var i in chapters)
      if (chapters[i].id === currentId) return chapters[(i + 1) % chapters.length];
    return chapters[0];
  };

  return {
    onReload: onLoad,
    onJump: checkSuccess,
    onCeval: checkSuccess,
    data: data,
    goal: goal,
    success: success,
    comment: comment,
    nbMoves: nbMoves,
    nextChapter: function() {
      return findNextOngoingChapter() || findNextChapter();
    },
    reset: function() {
      root.tree.root.children = [];
      root.userJump('');
      onLoad();
    }
  };
};
<|endoftext|>


<commit_before>"use strict";

/*globals describe it */
const should = require("should");
const path = require("path");

const webpack = require("../lib/webpack");

const base = path.join(__dirname, "fixtures", "errors");

describe("Errors", () => {
	function customOutputFilesystem(c) {
		const files = {};
		c.outputFileSystem = {
			join: path.join.bind(path),
			mkdirp: function(path, callback) {
				callback();
			},
			writeFile: function(name, content, callback) {
				files[name] = content.toString("utf8");
				callback();
			}
		};
		return files;
	}

	function getErrors(options, callback) {
		options.context = base;
		const c = webpack(options);
		customOutputFilesystem(c);
		c.run((err, stats) => {
			if(err) throw err;
			should.strictEqual(typeof stats, "object");
			stats = stats.toJson({
				errorDetails: false
			});
			should.strictEqual(typeof stats, "object");
			stats.should.have.property("errors");
			stats.should.have.property("warnings");
			Array.isArray(stats.errors).should.be.ok(); // eslint-disable-line no-unused-expressions
			Array.isArray(stats.warnings).should.be.ok(); // eslint-disable-line no-unused-expressions
			callback(stats.errors, stats.warnings);
		});
	}
	function getErrorsPromise(options, callback) {
		return new Promise((resolve, reject) => {
			getErrors(options, (errors, warnings) => {
				callback(errors, warnings);
				resolve();
			});
		});
	}
	it("should throw an error if file doesn't exist", (done) => {
		getErrors({
			mode: "development",
			entry: "./missingFile"
		}, (errors, warnings) => {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			errors.sort();
			let lines = errors[0].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/dir\/missing2/);
			lines[2].should.match(/missingFile.js 12:9/);
			lines = errors[1].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/missing/);
			lines[2].should.match(/missingFile.js 4:0/);
			done();
		});
	});
	it("should report require.extensions as unsupported", (done) => {
		getErrors({
			mode: "development",
			entry: "./require.extensions"
		}, (errors, warnings) => {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(1);
			const lines = warnings[0].split("\n");
			lines[0].should.match(/require.extensions\.js/);
			lines[1].should.match(/require.extensions is not supported by webpack/);
			done();
		});
	});
	it("should warn about case-sensitive module names", (done) => {
		getErrors({
			mode: "development",
			entry: "./case-sensitive"
		}, (errors, warnings) => {
			if(errors.length === 0) {
				warnings.length.should.be.eql(1);
				const lines = warnings[0].split("\n");
				lines[4].should.match(/FILE\.js/);
				lines[5].should.match(/Used by/);
				lines[6].should.match(/case-sensitive/);
				lines[7].should.match(/file\.js/);
				lines[8].should.match(/Used by/);
				lines[9].should.match(/case-sensitive/);
			} else {
				errors.length.should.be.eql(1);
				warnings.length.should.be.eql(0);
			}
			done();
		});
	});
	it("should warn when not using mode", (done) => {
		getErrors({
			entry: "./entry-point",
		}, (errors, warnings) => {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(1);
			let lines = warnings[0].split("\n");
			lines[0].should.match(/configuration/);
			lines[1].should.match(/mode/);
			lines[1].should.match(/development/);
			lines[1].should.match(/production/);
			done();
		});
	});
	it("should not warn if the NoEmitOnErrorsPlugin is used over the NoErrorsPlugin", (done) => {
		getErrors({
			mode: "production",
			entry: "./no-errors-deprecate"
		}, (errors, warnings) => {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(0);
			done();
		});
	});
	it("should not not emit if NoEmitOnErrorsPlugin is used and there is an error", (done) => {
		getErrors({
			mode: "production",
			entry: "./missingFile"
		}, (errors, warnings) => {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			errors.sort();
			let lines = errors[0].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/dir\/missing2/);
			lines[2].should.match(/missingFile.js 12:9/);
			lines = errors[1].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/missing/);
			lines[2].should.match(/missingFile.js 4:0/);
			done();
		});
	});
	it("should throw an error when trying to use [chunkhash] when it's invalid", (done) => {
		getErrors({
			mode: "development",
			entry: {
				a: "./entry-point",
				b: "./entry-point",
				c: "./entry-point"
			},
			output: {
				filename: "[chunkhash].js"
			},
			plugins: [
				new webpack.HotModuleReplacementPlugin()
			]
		}, (errors, warnings) => {
			errors.length.should.be.eql(3);
			warnings.length.should.be.eql(0);
			errors.forEach((error) => {
				const lines = error.split("\n");
				lines[0].should.match(/chunk (a|b|c)/);
				lines[2].should.match(/\[chunkhash\].js/);
				lines[2].should.match(/use \[hash\] instead/);
			});
			done();
		});
	});
	it.only("should show loader name when emit/throw an error or warning from a loader", () => {
		return Promise.all([
			getErrorsPromise({
				mode: "development",
				entry: "./not-a-json.js",
				module: {
					rules: [{
						test: /not-a-json\.js$/,
						use: [
							"json-loader",
							{
								loader: path.resolve(base, "./emit-error-loader")
							}
						]
					}]
				}

			}, (errors, warnings) => {
				warnings.length.should.be.eql(1);
				warnings[0].split("\n")[1].should.match(/^Module Warning \(from emit-error-loader\)/);
				errors.length.should.be.eql(2);
				errors[0].split("\n")[1].should.match(/^Module Error \(from emit-error-loader\)/);
				errors[1].split("\n")[1].should.match(/^Module build failed \(from json-loader\)/);
			}),
			getErrorsPromise({
				mode: "development",
				entry: "./entry-point.js",
				module: {
					rules: [{
						test: /entry-point\.js$/,
						use: path.resolve(base, "./async-error-loader")
					}]
				}

			}, (errors, warnings) => {
				errors.length.should.be.eql(1);
				errors[0].split("\n")[1].should.match(/^Module build failed \(from async-error-loader\)/);
			}),
			getErrorsPromise({
				mode: "development",
				entry: "./entry-point.js",
				module: {
					rules: [{
						test: /entry-point\.js$/,
						use: path.resolve(base, "./throw-error-loader")
					}]
				}

			}, (errors, warnings) => {
				errors.length.should.be.eql(1);
				errors[0].split("\n")[1].should.match(/^Module build failed \(from throw-error-loader\)/);
			}),

		]);
	});
});
<commit_msg>fix beautify-lint<commit_after>"use strict";

/*globals describe it */
const should = require("should");
const path = require("path");

const webpack = require("../lib/webpack");

const base = path.join(__dirname, "fixtures", "errors");

describe("Errors", () => {
	function customOutputFilesystem(c) {
		const files = {};
		c.outputFileSystem = {
			join: path.join.bind(path),
			mkdirp: function(path, callback) {
				callback();
			},
			writeFile: function(name, content, callback) {
				files[name] = content.toString("utf8");
				callback();
			}
		};
		return files;
	}

	function getErrors(options, callback) {
		options.context = base;
		const c = webpack(options);
		customOutputFilesystem(c);
		c.run((err, stats) => {
			if(err) throw err;
			should.strictEqual(typeof stats, "object");
			stats = stats.toJson({
				errorDetails: false
			});
			should.strictEqual(typeof stats, "object");
			stats.should.have.property("errors");
			stats.should.have.property("warnings");
			Array.isArray(stats.errors).should.be.ok(); // eslint-disable-line no-unused-expressions
			Array.isArray(stats.warnings).should.be.ok(); // eslint-disable-line no-unused-expressions
			callback(stats.errors, stats.warnings);
		});
	}

	function getErrorsPromise(options, callback) {
		return new Promise((resolve, reject) => {
			getErrors(options, (errors, warnings) => {
				callback(errors, warnings);
				resolve();
			});
		});
	}
	it("should throw an error if file doesn't exist", (done) => {
		getErrors({
			mode: "development",
			entry: "./missingFile"
		}, (errors, warnings) => {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			errors.sort();
			let lines = errors[0].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/dir\/missing2/);
			lines[2].should.match(/missingFile.js 12:9/);
			lines = errors[1].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/missing/);
			lines[2].should.match(/missingFile.js 4:0/);
			done();
		});
	});
	it("should report require.extensions as unsupported", (done) => {
		getErrors({
			mode: "development",
			entry: "./require.extensions"
		}, (errors, warnings) => {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(1);
			const lines = warnings[0].split("\n");
			lines[0].should.match(/require.extensions\.js/);
			lines[1].should.match(/require.extensions is not supported by webpack/);
			done();
		});
	});
	it("should warn about case-sensitive module names", (done) => {
		getErrors({
			mode: "development",
			entry: "./case-sensitive"
		}, (errors, warnings) => {
			if(errors.length === 0) {
				warnings.length.should.be.eql(1);
				const lines = warnings[0].split("\n");
				lines[4].should.match(/FILE\.js/);
				lines[5].should.match(/Used by/);
				lines[6].should.match(/case-sensitive/);
				lines[7].should.match(/file\.js/);
				lines[8].should.match(/Used by/);
				lines[9].should.match(/case-sensitive/);
			} else {
				errors.length.should.be.eql(1);
				warnings.length.should.be.eql(0);
			}
			done();
		});
	});
	it("should warn when not using mode", (done) => {
		getErrors({
			entry: "./entry-point",
		}, (errors, warnings) => {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(1);
			let lines = warnings[0].split("\n");
			lines[0].should.match(/configuration/);
			lines[1].should.match(/mode/);
			lines[1].should.match(/development/);
			lines[1].should.match(/production/);
			done();
		});
	});
	it("should not warn if the NoEmitOnErrorsPlugin is used over the NoErrorsPlugin", (done) => {
		getErrors({
			mode: "production",
			entry: "./no-errors-deprecate"
		}, (errors, warnings) => {
			errors.length.should.be.eql(0);
			warnings.length.should.be.eql(0);
			done();
		});
	});
	it("should not not emit if NoEmitOnErrorsPlugin is used and there is an error", (done) => {
		getErrors({
			mode: "production",
			entry: "./missingFile"
		}, (errors, warnings) => {
			errors.length.should.be.eql(2);
			warnings.length.should.be.eql(0);
			errors.sort();
			let lines = errors[0].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/dir\/missing2/);
			lines[2].should.match(/missingFile.js 12:9/);
			lines = errors[1].split("\n");
			lines[0].should.match(/missingFile.js/);
			lines[1].should.match(/^Module not found/);
			lines[1].should.match(/\.\/missing/);
			lines[2].should.match(/missingFile.js 4:0/);
			done();
		});
	});
	it("should throw an error when trying to use [chunkhash] when it's invalid", (done) => {
		getErrors({
			mode: "development",
			entry: {
				a: "./entry-point",
				b: "./entry-point",
				c: "./entry-point"
			},
			output: {
				filename: "[chunkhash].js"
			},
			plugins: [
				new webpack.HotModuleReplacementPlugin()
			]
		}, (errors, warnings) => {
			errors.length.should.be.eql(3);
			warnings.length.should.be.eql(0);
			errors.forEach((error) => {
				const lines = error.split("\n");
				lines[0].should.match(/chunk (a|b|c)/);
				lines[2].should.match(/\[chunkhash\].js/);
				lines[2].should.match(/use \[hash\] instead/);
			});
			done();
		});
	});
	it.only("should show loader name when emit/throw an error or warning from a loader", () => {
		return Promise.all([
			getErrorsPromise({
				mode: "development",
				entry: "./not-a-json.js",
				module: {
					rules: [{
						test: /not-a-json\.js$/,
						use: [
							"json-loader",
							{
								loader: path.resolve(base, "./emit-error-loader")
							}
						]
					}]
				}

			}, (errors, warnings) => {
				warnings.length.should.be.eql(1);
				warnings[0].split("\n")[1].should.match(/^Module Warning \(from emit-error-loader\)/);
				errors.length.should.be.eql(2);
				errors[0].split("\n")[1].should.match(/^Module Error \(from emit-error-loader\)/);
				errors[1].split("\n")[1].should.match(/^Module build failed \(from json-loader\)/);
			}),
			getErrorsPromise({
				mode: "development",
				entry: "./entry-point.js",
				module: {
					rules: [{
						test: /entry-point\.js$/,
						use: path.resolve(base, "./async-error-loader")
					}]
				}

			}, (errors, warnings) => {
				errors.length.should.be.eql(1);
				errors[0].split("\n")[1].should.match(/^Module build failed \(from async-error-loader\)/);
			}),
			getErrorsPromise({
				mode: "development",
				entry: "./entry-point.js",
				module: {
					rules: [{
						test: /entry-point\.js$/,
						use: path.resolve(base, "./throw-error-loader")
					}]
				}

			}, (errors, warnings) => {
				errors.length.should.be.eql(1);
				errors[0].split("\n")[1].should.match(/^Module build failed \(from throw-error-loader\)/);
			}),

		]);
	});
});
<|endoftext|>