<commit_before>import { expect } from 'chai';
import Pivot from '../../src';

const dataArray = [
 ['name', 'gender', 'house', 'age'],
 ['Jon', 'm', 'Stark', 14],
 ['Arya', 'f', 'Stark', 10],
 ['Cersei', 'f', 'Baratheon', 38],
 ['Tywin', 'm', 'Lannister', 67],
 ['Tyrion', 'm', 'Lannister', 34],
 ['Joffrey', 'm', 'Baratheon', 18],
 ['Bran', 'm', 'Stark', 8],
 ['Jaime', 'm', 'Lannister', 32],
 ['Sansa', 'f', 'Stark', 12],
];
const rowsToPivotTestOne = ['house', 'gender', 'name'];
const colsToPivotTestOne = [];
const aggregationCategory = 'age';
const aggregationType = 'sum';

export default () => {
  it('should return an unmodified pivot if parameters are wrong type', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );
    const originalTable = [...pivot.data.table];

    pivot.filter(['house', 'name'], ['Stark', 'Jon', 'Sanza']);
    expect(pivot.data.table).to.deep.equal(originalTable);
  });

  it('should take a fieldName string, filterValues array, filterType', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 30 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 3 },
      { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 4 },
      { value: [ 'm', 8 ], depth: 1, type: 'rowHeader', row: 5 },
      { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 6 },
      { value: [ 'Baratheon', 56 ], depth: 0, type: 'rowHeader', row: 7 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 8 },
      { value: [ 'Cersei', 38 ], type: 'data', depth: 2, row: 9 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 10 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 11 },
      { value: [ 'Lannister', 133 ], depth: 0, type: 'rowHeader', row: 12 },
      { value: [ 'm', 133 ], depth: 1, type: 'rowHeader', row: 13 },
      { value: [ 'Tywin', 67 ], type: 'data', depth: 2, row: 14 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 15 },
      { value: [ 'Jaime', 32 ], type: 'data', depth: 2, row: 16 },
    ];

    pivot.filter('name', ['Jon'], 'exclude');
    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should take a fieldName string and filterValues array', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 30 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 3 },
      { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 4 },
      { value: [ 'm', 8 ], depth: 1, type: 'rowHeader', row: 5 },
      { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 6 },
      { value: [ 'Baratheon', 56 ], depth: 0, type: 'rowHeader', row: 7 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 8 },
      { value: [ 'Cersei', 38 ], type: 'data', depth: 2, row: 9 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 10 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 11 },
      { value: [ 'Lannister', 133 ], depth: 0, type: 'rowHeader', row: 12 },
      { value: [ 'm', 133 ], depth: 1, type: 'rowHeader', row: 13 },
      { value: [ 'Tywin', 67 ], type: 'data', depth: 2, row: 14 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 15 },
      { value: [ 'Jaime', 32 ], type: 'data', depth: 2, row: 16 },
    ];

    pivot.filter('name', ['Jon']);
    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should take a callback function', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'm', 22 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Jon', 14 ], type: 'data', depth: 2, row: 3 },
      { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 4 },
      { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 5 },
      { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 6 },
      { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 7 },
    ];

    function filterFunc(dataRow) {
      return dataRow.age < 15;
    }

    pivot.filter(filterFunc);

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should maintain collapsed state if filtering after collapse', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 30 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'Baratheon', 56 ],
        depth: 0,
        type: 'rowHeader',
        row: 7 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 8 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 10 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 11 },
      { value: [ 'Lannister', 133 ],
        depth: 0,
        type: 'rowHeader',
        row: 12 },
      { value: [ 'm', 133 ], depth: 1, type: 'rowHeader', row: 13 },
      { value: [ 'Tywin', 67 ], type: 'data', depth: 2, row: 14 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 15 },
      { value: [ 'Jaime', 32 ], type: 'data', depth: 2, row: 16 },
    ];

    pivot.collapse(2).collapse(3).collapse(1);
    pivot.filter('name', ['Jon'], 'exclude');

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should maintain collapsed state even when categories are filtered ' +
    'out', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
    ];

    function filterFunc(dataRow) {
      return dataRow.age < 15;
    }

    pivot.collapse(2).collapse(3).collapse(1);
    pivot.filter(filterFunc);

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should progressively filter, when the filter method is called in succession', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Baratheon', 38 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Cersei', 38 ], type: 'data', depth: 2, row: 3 }
    ]

    pivot.filter('house', ['Stark'], 'exclude').filter('gender', ['m'], 'exclude');

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });
  it('should progressively filter, when the filter method is called in succession and then collapse', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [ { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'Lannister', 34 ], depth: 0, type: 'rowHeader', row: 8 },
      { value: [ 'm', 34 ], depth: 1, type: 'rowHeader', row: 9 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 10 },
      { value: [ 'Baratheon', 18 ], depth: 0, type: 'rowHeader', row: 11 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 12 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 13 } ];

    pivot.filter('name', ['Cersei'], 'exclude')
         .filter('name', ['Jaime'], 'exclude')
         .collapse(1)
         .filter('name', ['Tywin'], 'exclude');

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });
  it('should progressively filter, when the filter method is called in succession and then collapse and then expand', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [ { value: [ 'sum age', 'sum age' ],depth: 0,type: 'colHeader',row: 0 },
        { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
        { value: [ 'm', 22 ], depth: 1, type: 'rowHeader', row: 2 },
        { value: [ 'Jon', 14 ], type: 'data', depth: 2, row: 3 },
        { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 4 },
        { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 5 },
        { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 6 },
        { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 7 },
        { value: [ 'Lannister', 34 ],depth: 0,type: 'rowHeader',row: 8 },
        { value: [ 'm', 34 ], depth: 1, type: 'rowHeader', row: 9 },
        { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 10 },
        { value: [ 'Baratheon', 18 ],depth: 0,type: 'rowHeader',row: 11 },
        { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 12 },
        { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 13 } ];

    pivot.filter('name', ['Cersei'], 'exclude')
         .filter('name', ['Jaime'], 'exclude')
         .collapse(1)
         .filter('name', ['Tywin'], 'exclude')
         .expand(1);

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });
};
<commit_msg>codeclimate code formatting<commit_after>import { expect } from 'chai';
import Pivot from '../../src';

const dataArray = [
 ['name', 'gender', 'house', 'age'],
 ['Jon', 'm', 'Stark', 14],
 ['Arya', 'f', 'Stark', 10],
 ['Cersei', 'f', 'Baratheon', 38],
 ['Tywin', 'm', 'Lannister', 67],
 ['Tyrion', 'm', 'Lannister', 34],
 ['Joffrey', 'm', 'Baratheon', 18],
 ['Bran', 'm', 'Stark', 8],
 ['Jaime', 'm', 'Lannister', 32],
 ['Sansa', 'f', 'Stark', 12],
];
const rowsToPivotTestOne = ['house', 'gender', 'name'];
const colsToPivotTestOne = [];
const aggregationCategory = 'age';
const aggregationType = 'sum';

export default () => {
  it('should return an unmodified pivot if parameters are wrong type', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );
    const originalTable = [...pivot.data.table];

    pivot.filter(['house', 'name'], ['Stark', 'Jon', 'Sanza']);
    expect(pivot.data.table).to.deep.equal(originalTable);
  });

  it('should take a fieldName string, filterValues array, filterType', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 30 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 3 },
      { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 4 },
      { value: [ 'm', 8 ], depth: 1, type: 'rowHeader', row: 5 },
      { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 6 },
      { value: [ 'Baratheon', 56 ], depth: 0, type: 'rowHeader', row: 7 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 8 },
      { value: [ 'Cersei', 38 ], type: 'data', depth: 2, row: 9 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 10 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 11 },
      { value: [ 'Lannister', 133 ], depth: 0, type: 'rowHeader', row: 12 },
      { value: [ 'm', 133 ], depth: 1, type: 'rowHeader', row: 13 },
      { value: [ 'Tywin', 67 ], type: 'data', depth: 2, row: 14 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 15 },
      { value: [ 'Jaime', 32 ], type: 'data', depth: 2, row: 16 },
    ];

    pivot.filter('name', ['Jon'], 'exclude');
    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should take a fieldName string and filterValues array', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 30 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 3 },
      { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 4 },
      { value: [ 'm', 8 ], depth: 1, type: 'rowHeader', row: 5 },
      { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 6 },
      { value: [ 'Baratheon', 56 ], depth: 0, type: 'rowHeader', row: 7 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 8 },
      { value: [ 'Cersei', 38 ], type: 'data', depth: 2, row: 9 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 10 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 11 },
      { value: [ 'Lannister', 133 ], depth: 0, type: 'rowHeader', row: 12 },
      { value: [ 'm', 133 ], depth: 1, type: 'rowHeader', row: 13 },
      { value: [ 'Tywin', 67 ], type: 'data', depth: 2, row: 14 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 15 },
      { value: [ 'Jaime', 32 ], type: 'data', depth: 2, row: 16 },
    ];

    pivot.filter('name', ['Jon']);
    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should take a callback function', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'm', 22 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Jon', 14 ], type: 'data', depth: 2, row: 3 },
      { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 4 },
      { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 5 },
      { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 6 },
      { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 7 },
    ];

    function filterFunc(dataRow) {
      return dataRow.age < 15;
    }

    pivot.filter(filterFunc);

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should maintain collapsed state if filtering after collapse', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 30 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'Baratheon', 56 ],
        depth: 0,
        type: 'rowHeader',
        row: 7 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 8 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 10 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 11 },
      { value: [ 'Lannister', 133 ],
        depth: 0,
        type: 'rowHeader',
        row: 12 },
      { value: [ 'm', 133 ], depth: 1, type: 'rowHeader', row: 13 },
      { value: [ 'Tywin', 67 ], type: 'data', depth: 2, row: 14 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 15 },
      { value: [ 'Jaime', 32 ], type: 'data', depth: 2, row: 16 },
    ];

    pivot.collapse(2).collapse(3).collapse(1);
    pivot.filter('name', ['Jon'], 'exclude');

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should maintain collapsed state even when categories are filtered ' +
    'out', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
    ];

    function filterFunc(dataRow) {
      return dataRow.age < 15;
    }

    pivot.collapse(2).collapse(3).collapse(1);
    pivot.filter(filterFunc);

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });

  it('should progressively filter, when the filter method is called in' +
    'succession', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Baratheon', 38 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'f', 38 ], depth: 1, type: 'rowHeader', row: 2 },
      { value: [ 'Cersei', 38 ], type: 'data', depth: 2, row: 3 }
    ];

    pivot.filter('house', ['Stark'], 'exclude')
         .filter('gender', ['m'], 'exclude');

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });
  it('should progressively filter, when the filter method is called in' +
    'succession and then collapse', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
      { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
      { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
      { value: [ 'Lannister', 34 ], depth: 0, type: 'rowHeader', row: 8 },
      { value: [ 'm', 34 ], depth: 1, type: 'rowHeader', row: 9 },
      { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 10 },
      { value: [ 'Baratheon', 18 ], depth: 0, type: 'rowHeader', row: 11 },
      { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 12 },
      { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 13 }
    ];

    pivot.filter('name', ['Cersei'], 'exclude')
         .filter('name', ['Jaime'], 'exclude')
         .collapse(1)
         .filter('name', ['Tywin'], 'exclude');

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });
  it('should progressively filter, when the filter method is called in' +
    'succession and then collapse and then expand', () => {
    const pivot = new Pivot(
      dataArray,
      rowsToPivotTestOne,
      colsToPivotTestOne,
      aggregationCategory,
      aggregationType,
    );

    const expectedResult = [
        { value: [ 'sum age', 'sum age' ], depth: 0, type: 'colHeader', row: 0 },
        { value: [ 'Stark', 44 ], depth: 0, type: 'rowHeader', row: 1 },
        { value: [ 'm', 22 ], depth: 1, type: 'rowHeader', row: 2 },
        { value: [ 'Jon', 14 ], type: 'data', depth: 2, row: 3 },
        { value: [ 'Bran', 8 ], type: 'data', depth: 2, row: 4 },
        { value: [ 'f', 22 ], depth: 1, type: 'rowHeader', row: 5 },
        { value: [ 'Arya', 10 ], type: 'data', depth: 2, row: 6 },
        { value: [ 'Sansa', 12 ], type: 'data', depth: 2, row: 7 },
        { value: [ 'Lannister', 34 ], depth: 0, type: 'rowHeader', row: 8 },
        { value: [ 'm', 34 ], depth: 1, type: 'rowHeader', row: 9 },
        { value: [ 'Tyrion', 34 ], type: 'data', depth: 2, row: 10 },
        { value: [ 'Baratheon', 18 ], depth: 0, type: 'rowHeader', row: 11 },
        { value: [ 'm', 18 ], depth: 1, type: 'rowHeader', row: 12 },
        { value: [ 'Joffrey', 18 ], type: 'data', depth: 2, row: 13 }
      ];

    pivot.filter('name', ['Cersei'], 'exclude')
         .filter('name', ['Jaime'], 'exclude')
         .collapse(1)
         .filter('name', ['Tywin'], 'exclude')
         .expand(1);

    expect(pivot.data.table).to.deep.equal(expectedResult);
  });
};
<|endoftext|>


<commit_before>/*global require */
/* jshint -W106 */

'use strict';
require(['jquery', 'underscore', 'backbone', 'humanize', 'views/application-view', 'models/application-model', 'helpers/config-loader', 'poller', 'helpers/generate-osds', 'collections/osd-collection', 'views/userdropdown', 'views/clusterdropdown', 'helpers/animation', 'views/graphwall-view', 'helpers/graph-utils', 'statemachine', 'marionette', 'bootstrap'], function($, _, Backbone, humanize, views, models, configloader, Poller, Generate, Collection, UserDropDown, ClusterDropDown, animation, GraphWall, helpers, StateMachine) {
    /* Default Configuration */
    var hostname = document.location.hostname;
    var config = {
        offline: true,
        'delta-osd-api': false,
        'graphite-host': 'http://' + hostname + ':8080'
    };

    /* Default Configuration */
    var AppRouter = Backbone.Router.extend({
        routes: {
            'workbench': 'workbench',
            'dashboard': 'dashboard',
            'graph/:host(/:osd)': 'graph'
        }
    });
    var appRouter = new AppRouter();
    /* Load Config.json first before starting app */
    var promise = configloader('scripts/config.json').then(function(result) {
        _.extend(config, result);
    });
    /* Load Config.json first before starting app */

    // TODO replace this with CSS version
    var replaceText = function($el, text, removeClass, addClass) {
            $el.css('display', 'none').text(text);
            if (removeClass !== undefined) {
                $el.removeClass(removeClass);
            }
            if (addClass !== undefined) {
                $el.addClass(addClass);
            }
            $el.fadeIn().css('display', '');
        };

    var App, userMenu, clusterMenu;
    promise.then(function() {
        App = new Backbone.Marionette.Application();
        App.ReqRes = new Backbone.Wreqr.RequestResponse();
        App.Config = config;
        userMenu = new UserDropDown({
            el: $('.usermenu'),
            App: App
        });
        userMenu.fetch();
        /* Demo Code */
        App.vent.listenTo(App.vent, 'status:healthok', function() {
            replaceText($('.warn-pg, .warn-osd, .warn-pool'), '0');
            replaceText($('.ok-pg'), 2400);
            replaceText($('.ok-pool'), 10);
        });
        App.vent.listenTo(App.vent, 'status:healthwarn', function() {
            var pg = Math.round(Math.random() * 45) + 5;
            var pool = Math.round(Math.random() * 1) + 1;
            replaceText($('.warn-pg'), pg);
            replaceText($('.warn-pool'), pool);
            replaceText($('.ok-pg'), 2400 - pg);
            replaceText($('.ok-pool'), 10 - pool);
        });
        App.vent.listenTo(App.vent, 'updateTotals', function() {
            var ONE_GIGABYTE = 1024 * 1024 * 1024;
            var totalUsed = 0,
                totalCapacity = 0,
                totalObj = 0,
                totalObjSpace = 0;
            viz.collection.each(function(m) {
                totalUsed += m.get('used');
                totalCapacity += m.get('capacity');
                totalObj += Math.random(Date.now()) * 100;
            });

            var settings = {
                cluster: 1,
                space: {
                    free_bytes: totalCapacity * ONE_GIGABYTE,
                    capacity_bytes: totalCapacity * ONE_GIGABYTE,
                    used_bytes: totalUsed * ONE_GIGABYTE
                }
            };
            gauge.set(new models.UsageModel(settings));
            $('.objcount').text(Math.floor(totalObj));
            totalObjSpace = totalObj * 50;
            totalObjSpace = humanize.filesize(Math.floor(totalObjSpace)).replace(' Kb', 'K');
            $('.objspace').text(totalObjSpace);
        });
        /* Demo Code */

        /* Widget Setup */
        var gaugesLayout = new views.GaugesLayout({
            el: '.gauges'
        });
        gaugesLayout.render();
        var healthView = new views.HealthView({
            App: App,
            model: new models.HealthModel({})
        });
        gaugesLayout.health.show(healthView);
        var gauge = new views.UsageView({
            App: App,
            model: new models.UsageModel({}),
            title: 'Usage'
        });
        gauge.listenTo(gauge, 'item:postrender', function() {
            App.vent.trigger('updateTotals');
        });

        var statusView = new views.StatusView({
            App: App,
            model: new models.StatusModel({})
        });
        gaugesLayout.status.show(statusView);

        var collection;
        if (config.offline) {
            collection = Generate.osds(160);
        } else {
            collection = new Collection([], {});
        }
        var viz = new views.OSDVisualization({
            App: App,
            collection: collection,
            el: '.raphael-one'
        });

        $('body').on('keyup', function(evt) {
            App.vent.trigger('keyup', evt);
        });

        _.extend(humanize.catalog, {
            'about_a_minute_ago': '1m',
            'minutes_ago': 'm',
            'about_an_hour_ago': '1h',
            'hours_ago': 'h',
            'one_day_ago': '1d',
            'days_ago': 'd',
            'about_a_month_ago': '1M',
            'months_ago': 'M',
            'a_year_ago': '1y',
            'years_ago': 'y'
        });
        views.NotificationCardView.view.setElement($('.notifications')).render();
        views.NotificationCardView.collection.add(
        [{
            title: 'OSD',
            message: 'OSD.100 has stopped responding',
            timestamp: humanize.time() - 24 * 60 * 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 is online',
            timestamp: humanize.time() - 60 * 60,
            priority: 0
        }, {
            title: 'Processes',
            message: 'OSD.10 has stopped responding',
            timestamp: humanize.time() - 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 has become unreachable',
            timestamp: humanize.time(),
            priority: 1
        }]);
        /* Widget Setup */

        /* Defer Visualization startup to after loading the cluster metadata */
        var clusterDeferred = $.Deferred();
        clusterMenu = new ClusterDropDown({
            el: $('.clustermenu'),
            App: App
        });
        clusterMenu.fetch().done(function() {
            clusterDeferred.resolve(clusterMenu.collection.at(0));
        });
        clusterDeferred.promise().done(function(cluster) {
            var poller = new Poller({
                App: App,
                cluster: cluster.get('id')
            });
            var graphWall = new GraphWall({
                App: App,
                graphiteHost: config['graphite-host']
            });

            viz.render().then(function() {
                gaugesLayout.usage.show(gauge);
                if (!config.offline) {
                    poller.start();
                }
            });

            var toWorkBenchAnimation = animation.single('toWorkBenchAnim');
            App.onentergraphmode = function( /*event, from, to, host, osd */ ) {
                $('.row').css('visibility', 'hidden');
                graphWall.render();
                $('.container').append(graphWall.$el);
            };
            App.ongraph = function(event, from, to, host, osd) {
                console.log('ongraph>> host: ' + host + ' osd: ' + osd);
                graphWall.hideGraphs();
                var hosts;
                if (host === 'all') {
                    graphWall.populateAll('CPU Load for Cluster', graphWall.makeHostUrls(graphWall.makeCPUGraphUrl));
                } else if (osd === 'cpudetail') {
                    graphWall.makeCPUDetail(host).then(function(result) {
                        graphWall.populateAll('Host ' + host + ' CPU Detail Host Graphs', function() {
                            return result;
                        }).fail(function(result) {
                            // TODO Handle errors gracefully
                            console.log('failed! ', result);
                        });
                    });
                } else {
                    hosts = App.ReqRes.request('get:hosts');
                    if (_.contains(hosts, host)) {
                        graphWall.populateAll('Host Graphs for ' + host, graphWall.makeHostOverviewGraphUrl(host));
                    }
                }
            };
            App.onleavegraphmode = function() {
                graphWall.close();
                $('.row').css('visibility', 'visible');
            };
            App.onentervizmode = function(event, from) {
                var d = $.Deferred();
                var $body = $('body');
                var vent = App.vent;
                if (from === 'dashmode') {
                    vent.trigger('gauges:disappear', function() {
                        d.resolve();
                    });
                } else {
                    d.resolve();
                }

                d.promise().then(function() {
                    $body.addClass('workbench-mode');
                    toWorkBenchAnimation($body);
                    vent.trigger('viz:fullscreen', function() {
                        vent.trigger('gauges:collapse');
                    });
                });
            };
            var toDashboardAnimation = animation.single('toDashboardAnim');
            App.onleavevizmode = function(event, from, to) {
                var $body = $('body');
                var vent = App.vent;
                $body.removeClass('workbench-mode');
                var d = $.Deferred();
                if (to === 'dashmode') {
                    toDashboardAnimation($body).then(function() {
                        vent.trigger('viz:dashboard', function() {
                            d.resolve();
                        });
                    });

                } else {
                    vent.trigger('viz:dashboard', function() {
                        d.resolve();
                    });
                }
                d.promise().then(function() {
                    vent.trigger('gauges:expand', function() {
                        vent.trigger('gauges:reappear');
                    });
                });
            };
            App.onenterdashmode = function() {};

            App.onleavedashmode = function() {};

            var breadcrumbView = new views.BreadCrumbView({
                App: App,
                AppRouter: appRouter,
                el: '.inknav'
            });
            breadcrumbView.render();

            appRouter.on('route:workbench', function() {
                App.fsm.viz();
            });
            appRouter.on('route:dashboard', function() {
                App.fsm.dashboard();
            });
            appRouter.on('route:graph', function(host, osd) {
                console.log('router>> host: ' + host + ' osd: ' + osd);
                App.fsm.graph(host, osd);
            });

            appRouter.navigate('dashboard');

            App.fsm = StateMachine.create({
                initial: 'dashmode',
                events: [{
                    name: 'dashboard',
                    from: ['vizmode', 'graphmode'],
                    to: 'dashmode'
                }, {
                    name: 'viz',
                    from: ['dashmode', 'graphmode'],
                    to: 'vizmode'
                }, {
                    name: 'graph',
                    from: ['dashmode', 'vizmode', 'graphmode'],
                    to: 'graphmode'
                }],
                callbacks: {
                    onentervizmode: App.onentervizmode,
                    onleavevizmode: App.onleavevizmode,
                    onentergraphmode: App.onentergraphmode,
                    onleavegraphmode: App.onleavegraphmode,
                    onenterdashmode: App.onenterdashmode,
                    onleavedashmode: App.onleavedashmode,
                    ongraph: App.ongraph
                }
            });

            _.bindAll(App.fsm);

            App.listenTo(App.vent, 'app:fullscreen', function() {
                appRouter.navigate('workbench', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:dashboard', function() {
                appRouter.navigate('dashboard', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:graph', function(host) {
                if (host === undefined) {
                    host = 'all';
                }
                appRouter.navigate('graph/' + host, {
                    trigger: true
                });
            });

            // Global Exports
            window.inktank = {
                App: App,
                Router: appRouter,
                ClusterMenu: clusterMenu,
                Gauge: gauge,
                Gauges: gaugesLayout,
                GraphWallView: graphWall,
                HealthView: healthView,
                Poller: poller,
                StatusView: statusView,
                UserMenu: userMenu,
                Viz: viz,
                models: models,
                helpers: helpers
            };
        });
        /* Defer Visualization startup to after loading the cluster metadata */
    });

    Backbone.history.start();

});
<commit_msg>Move fail block to correct return<commit_after>/*global require */
/* jshint -W106 */

'use strict';
require(['jquery', 'underscore', 'backbone', 'humanize', 'views/application-view', 'models/application-model', 'helpers/config-loader', 'poller', 'helpers/generate-osds', 'collections/osd-collection', 'views/userdropdown', 'views/clusterdropdown', 'helpers/animation', 'views/graphwall-view', 'helpers/graph-utils', 'statemachine', 'marionette', 'bootstrap'], function($, _, Backbone, humanize, views, models, configloader, Poller, Generate, Collection, UserDropDown, ClusterDropDown, animation, GraphWall, helpers, StateMachine) {
    /* Default Configuration */
    var hostname = document.location.hostname;
    var config = {
        offline: true,
        'delta-osd-api': false,
        'graphite-host': 'http://' + hostname + ':8080'
    };

    /* Default Configuration */
    var AppRouter = Backbone.Router.extend({
        routes: {
            'workbench': 'workbench',
            'dashboard': 'dashboard',
            'graph/:host(/:osd)': 'graph'
        }
    });
    var appRouter = new AppRouter();
    /* Load Config.json first before starting app */
    var promise = configloader('scripts/config.json').then(function(result) {
        _.extend(config, result);
    });
    /* Load Config.json first before starting app */

    // TODO replace this with CSS version
    var replaceText = function($el, text, removeClass, addClass) {
            $el.css('display', 'none').text(text);
            if (removeClass !== undefined) {
                $el.removeClass(removeClass);
            }
            if (addClass !== undefined) {
                $el.addClass(addClass);
            }
            $el.fadeIn().css('display', '');
        };

    var App, userMenu, clusterMenu;
    promise.then(function() {
        App = new Backbone.Marionette.Application();
        App.ReqRes = new Backbone.Wreqr.RequestResponse();
        App.Config = config;
        userMenu = new UserDropDown({
            el: $('.usermenu'),
            App: App
        });
        userMenu.fetch();
        /* Demo Code */
        App.vent.listenTo(App.vent, 'status:healthok', function() {
            replaceText($('.warn-pg, .warn-osd, .warn-pool'), '0');
            replaceText($('.ok-pg'), 2400);
            replaceText($('.ok-pool'), 10);
        });
        App.vent.listenTo(App.vent, 'status:healthwarn', function() {
            var pg = Math.round(Math.random() * 45) + 5;
            var pool = Math.round(Math.random() * 1) + 1;
            replaceText($('.warn-pg'), pg);
            replaceText($('.warn-pool'), pool);
            replaceText($('.ok-pg'), 2400 - pg);
            replaceText($('.ok-pool'), 10 - pool);
        });
        App.vent.listenTo(App.vent, 'updateTotals', function() {
            var ONE_GIGABYTE = 1024 * 1024 * 1024;
            var totalUsed = 0,
                totalCapacity = 0,
                totalObj = 0,
                totalObjSpace = 0;
            viz.collection.each(function(m) {
                totalUsed += m.get('used');
                totalCapacity += m.get('capacity');
                totalObj += Math.random(Date.now()) * 100;
            });

            var settings = {
                cluster: 1,
                space: {
                    free_bytes: totalCapacity * ONE_GIGABYTE,
                    capacity_bytes: totalCapacity * ONE_GIGABYTE,
                    used_bytes: totalUsed * ONE_GIGABYTE
                }
            };
            gauge.set(new models.UsageModel(settings));
            $('.objcount').text(Math.floor(totalObj));
            totalObjSpace = totalObj * 50;
            totalObjSpace = humanize.filesize(Math.floor(totalObjSpace)).replace(' Kb', 'K');
            $('.objspace').text(totalObjSpace);
        });
        /* Demo Code */

        /* Widget Setup */
        var gaugesLayout = new views.GaugesLayout({
            el: '.gauges'
        });
        gaugesLayout.render();
        var healthView = new views.HealthView({
            App: App,
            model: new models.HealthModel({})
        });
        gaugesLayout.health.show(healthView);
        var gauge = new views.UsageView({
            App: App,
            model: new models.UsageModel({}),
            title: 'Usage'
        });
        gauge.listenTo(gauge, 'item:postrender', function() {
            App.vent.trigger('updateTotals');
        });

        var statusView = new views.StatusView({
            App: App,
            model: new models.StatusModel({})
        });
        gaugesLayout.status.show(statusView);

        var collection;
        if (config.offline) {
            collection = Generate.osds(160);
        } else {
            collection = new Collection([], {});
        }
        var viz = new views.OSDVisualization({
            App: App,
            collection: collection,
            el: '.raphael-one'
        });

        $('body').on('keyup', function(evt) {
            App.vent.trigger('keyup', evt);
        });

        _.extend(humanize.catalog, {
            'about_a_minute_ago': '1m',
            'minutes_ago': 'm',
            'about_an_hour_ago': '1h',
            'hours_ago': 'h',
            'one_day_ago': '1d',
            'days_ago': 'd',
            'about_a_month_ago': '1M',
            'months_ago': 'M',
            'a_year_ago': '1y',
            'years_ago': 'y'
        });
        views.NotificationCardView.view.setElement($('.notifications')).render();
        views.NotificationCardView.collection.add(
        [{
            title: 'OSD',
            message: 'OSD.100 has stopped responding',
            timestamp: humanize.time() - 24 * 60 * 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 is online',
            timestamp: humanize.time() - 60 * 60,
            priority: 0
        }, {
            title: 'Processes',
            message: 'OSD.10 has stopped responding',
            timestamp: humanize.time() - 60,
            priority: 2
        }, {
            title: 'Processes',
            message: 'MDS 192.168.20.2 has become unreachable',
            timestamp: humanize.time(),
            priority: 1
        }]);
        /* Widget Setup */

        /* Defer Visualization startup to after loading the cluster metadata */
        var clusterDeferred = $.Deferred();
        clusterMenu = new ClusterDropDown({
            el: $('.clustermenu'),
            App: App
        });
        clusterMenu.fetch().done(function() {
            clusterDeferred.resolve(clusterMenu.collection.at(0));
        });
        clusterDeferred.promise().done(function(cluster) {
            var poller = new Poller({
                App: App,
                cluster: cluster.get('id')
            });
            var graphWall = new GraphWall({
                App: App,
                graphiteHost: config['graphite-host']
            });

            viz.render().then(function() {
                gaugesLayout.usage.show(gauge);
                if (!config.offline) {
                    poller.start();
                }
            });

            var toWorkBenchAnimation = animation.single('toWorkBenchAnim');
            App.onentergraphmode = function( /*event, from, to, host, osd */ ) {
                $('.row').css('visibility', 'hidden');
                graphWall.render();
                $('.container').append(graphWall.$el);
            };
            App.ongraph = function(event, from, to, host, osd) {
                console.log('ongraph>> host: ' + host + ' osd: ' + osd);
                graphWall.hideGraphs();
                var hosts;
                if (host === 'all') {
                    graphWall.populateAll('CPU Load for Cluster', graphWall.makeHostUrls(graphWall.makeCPUGraphUrl));
                } else if (osd === 'cpudetail') {
                    graphWall.makeCPUDetail(host).then(function(result) {
                        graphWall.populateAll('Host ' + host + ' CPU Detail Host Graphs', function() {
                            return result;
                        });
                    }).fail(function(result) {
                        // TODO Handle errors gracefully
                        console.log('failed! ', result);
                    });
                } else {
                    hosts = App.ReqRes.request('get:hosts');
                    if (_.contains(hosts, host)) {
                        graphWall.populateAll('Host Graphs for ' + host, graphWall.makeHostOverviewGraphUrl(host));
                    }
                }
            };
            App.onleavegraphmode = function() {
                graphWall.close();
                $('.row').css('visibility', 'visible');
            };
            App.onentervizmode = function(event, from) {
                var d = $.Deferred();
                var $body = $('body');
                var vent = App.vent;
                if (from === 'dashmode') {
                    vent.trigger('gauges:disappear', function() {
                        d.resolve();
                    });
                } else {
                    d.resolve();
                }

                d.promise().then(function() {
                    $body.addClass('workbench-mode');
                    toWorkBenchAnimation($body);
                    vent.trigger('viz:fullscreen', function() {
                        vent.trigger('gauges:collapse');
                    });
                });
            };
            var toDashboardAnimation = animation.single('toDashboardAnim');
            App.onleavevizmode = function(event, from, to) {
                var $body = $('body');
                var vent = App.vent;
                $body.removeClass('workbench-mode');
                var d = $.Deferred();
                if (to === 'dashmode') {
                    toDashboardAnimation($body).then(function() {
                        vent.trigger('viz:dashboard', function() {
                            d.resolve();
                        });
                    });

                } else {
                    vent.trigger('viz:dashboard', function() {
                        d.resolve();
                    });
                }
                d.promise().then(function() {
                    vent.trigger('gauges:expand', function() {
                        vent.trigger('gauges:reappear');
                    });
                });
            };
            App.onenterdashmode = function() {};

            App.onleavedashmode = function() {};

            var breadcrumbView = new views.BreadCrumbView({
                App: App,
                AppRouter: appRouter,
                el: '.inknav'
            });
            breadcrumbView.render();

            appRouter.on('route:workbench', function() {
                App.fsm.viz();
            });
            appRouter.on('route:dashboard', function() {
                App.fsm.dashboard();
            });
            appRouter.on('route:graph', function(host, osd) {
                console.log('router>> host: ' + host + ' osd: ' + osd);
                App.fsm.graph(host, osd);
            });

            appRouter.navigate('dashboard');

            App.fsm = StateMachine.create({
                initial: 'dashmode',
                events: [{
                    name: 'dashboard',
                    from: ['vizmode', 'graphmode'],
                    to: 'dashmode'
                }, {
                    name: 'viz',
                    from: ['dashmode', 'graphmode'],
                    to: 'vizmode'
                }, {
                    name: 'graph',
                    from: ['dashmode', 'vizmode', 'graphmode'],
                    to: 'graphmode'
                }],
                callbacks: {
                    onentervizmode: App.onentervizmode,
                    onleavevizmode: App.onleavevizmode,
                    onentergraphmode: App.onentergraphmode,
                    onleavegraphmode: App.onleavegraphmode,
                    onenterdashmode: App.onenterdashmode,
                    onleavedashmode: App.onleavedashmode,
                    ongraph: App.ongraph
                }
            });

            _.bindAll(App.fsm);

            App.listenTo(App.vent, 'app:fullscreen', function() {
                appRouter.navigate('workbench', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:dashboard', function() {
                appRouter.navigate('dashboard', {
                    trigger: true
                });
            });
            App.listenTo(App.vent, 'app:graph', function(host) {
                if (host === undefined) {
                    host = 'all';
                }
                appRouter.navigate('graph/' + host, {
                    trigger: true
                });
            });

            // Global Exports
            window.inktank = {
                App: App,
                Router: appRouter,
                ClusterMenu: clusterMenu,
                Gauge: gauge,
                Gauges: gaugesLayout,
                GraphWallView: graphWall,
                HealthView: healthView,
                Poller: poller,
                StatusView: statusView,
                UserMenu: userMenu,
                Viz: viz,
                models: models,
                helpers: helpers
            };
        });
        /* Defer Visualization startup to after loading the cluster metadata */
    });

    Backbone.history.start();

});
<|endoftext|>


<commit_before>/**
 * This spec tests that removal of the old siesta.install() step that was required before use has been removed correctly
 */

var assert = require('chai').assert,
  internal = siesta._internal,
  CollectionRegistry = internal.CollectionRegistry,
  RelationshipType = siesta.RelationshipType;

describe('install step', function() {
  var MyCollection, Person;

  beforeEach(function(done) {
    siesta.reset(done);
  });

  describe('no storage', function() {
    before(function() {
      siesta.ext.storageEnabled = false;
    });

    beforeEach(function() {
      MyCollection = siesta.collection('MyCollection');
      Person = MyCollection.model('Person', {
        id: 'id',
        attributes: ['name', 'age', 'index']
      });
    });

    it('map', function(done) {
      Person.graph({name: 'Mike', age: 24})
        .then(function() {
          done();
        })
        .catch(done);
    });

    it('query', function(done) {
      Person.query({age__gt: 23})
        .then(function(res) {
          assert.notOk(res.length, 'Should be no results');
          done();
        })
        .catch(done);
    });

    it('reactive query', function(done) {
      var rq = Person._reactiveQuery({age__lt: 30});
      rq.init()
        .then(function() {
          assert.notOk(rq.results.length);
          rq.terminate();
          done();
        })
        .catch(done);
    });

    it('arranged reactive query', function(done) {
      var rq = Person._arrangedReactiveQuery({age__lt: 30});
      rq.init()
        .then(function() {
          assert.notOk(rq.results.length);
          rq.terminate();
          done();
        })
        .catch(done);
    });

  });

  describe('storage', function() {
    before(function() {
      siesta.ext.storageEnabled = true;
    });

    after(function(done) {
      siesta.reset(function() {
        siesta.ext.storageEnabled = false;
        siesta.ext.storage._pouch.allDocs().then(function(resp) {
          done();
        });
      })
    });

    beforeEach(function() {
      MyCollection = siesta.collection('MyCollection');
      Person = MyCollection.model('Person', {
        id: 'id',
        attributes: ['name', 'age', 'index']
      });
    });

    it('map', function(done) {
      Person.graph({name: 'Mike', age: 24})
        .then(function() {
          done();
        })
        .catch(done);
    });

    it('query', function(done) {
      siesta.ext.storage._pouch.bulkDocs([
        {collection: 'MyCollection', model: 'Person', name: 'Mike', age: 24},
        {collection: 'MyCollection', model: 'Person', name: 'Bob', age: 21}
      ]).then(function() {
        Person.query({age__gt: 23})
          .then(function(res) {
            assert.equal(res.length, 1, 'Should have installed and loaded before returning from the query');
            done();
          })
          .catch(done);
      }).catch(done);
    });

    it('reactive query', function(done) {
      siesta.ext.storage._pouch.bulkDocs([
        {collection: 'MyCollection', model: 'Person', name: 'Mike', age: 24},
        {collection: 'MyCollection', model: 'Person', name: 'Bob', age: 21}
      ]).then(function() {
        var rq = Person._reactiveQuery({age__gt: 23});
        rq.init()
          .then(function() {
            assert.equal(rq.results.length, 1, 'Should have installed and loaded before returning from the query');
            rq.terminate();
            done();
          })
          .catch(done);
      }).catch(done);
    });

    it('arranged reactive query', function(done) {
      siesta.ext.storage._pouch.bulkDocs([
        {collection: 'MyCollection', model: 'Person', name: 'Mike', age: 24},
        {collection: 'MyCollection', model: 'Person', name: 'Bob', age: 21}
      ]).then(function() {
        var rq = Person._arrangedReactiveQuery({age__gt: 23});
        rq.init()
          .then(function() {
            assert.equal(rq.results.length, 1, 'Should have installed and loaded before returning from the query');
            rq.terminate();
            done();
          })
          .catch(done);
      }).catch(done);
    });

  });

  describe('install relationships', function() {
    before(function() {
      siesta.ext.storageEnabled = false;
    });

    beforeEach(function(done) {
      siesta.reset(done);
    });

    var Collection, Car, Person;

    function configureAPI(type, done) {
      Collection = siesta.collection('myCollection');
      Car = Collection.model('Car', {
        id: 'id',
        attributes: ['colour', 'name'],
        relationships: {
          owner: {
            model: 'Person',
            type: type,
            reverse: 'cars'
          }
        }
      });
      Person = Collection.model('Person', {
        id: 'id',
        attributes: ['name', 'age']
      });
      siesta.install(done);
    }

    describe('valid', function() {
      describe('Foreign Key', function() {

        beforeEach(function(done) {
          configureAPI(RelationshipType.OneToMany, function(err) {
            if (err) done(err);
            done();
          });
        });

        it('configures reverse mapping', function() {
          assert.equal(Car.relationships.owner.reverseModel, Person);
        });

        it('configures reverse name', function() {
          assert.equal(Car.relationships.owner.reverseName, 'cars');

          it('configures forward mapping', function() {
            assert.equal(Car.relationships.owner.forwardModel, Car);
          });

        });
        it('configures forward name', function() {
          assert.equal(Car.relationships.owner.forwardName, 'owner');
        });

        it('installs on reverse', function() {
          var keys = Object.keys(Person.relationships.cars);
          for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (key != 'isForward' && key != 'isReverse') {
              assert.equal(Person.relationships.cars[key], Car.relationships.owner[key]);
            }
          }
        });

      });

      describe('OneToOne', function() {

        beforeEach(function(done) {
          configureAPI(RelationshipType.OneToOne, function(err) {
            if (err) done(err);
            done();
          });

        });
        it('configures reverse mapping', function() {
          assert.equal(Car.relationships.owner.reverseModel, Person);
        });

        it('configures reverse name', function() {
          assert.equal(Car.relationships.owner.reverseName, 'cars');

        });

        it('configures forward mapping', function() {
          assert.equal(Car.relationships.owner.forwardModel, Car);
        });
        it('configures forward name', function() {
          assert.equal(Car.relationships.owner.forwardName, 'owner');
        });

        it('installs on reverse', function() {
          var keys = Object.keys(Person.relationships.cars);
          for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (key != 'isForward' && key != 'isReverse') {
              assert.equal(Person.relationships.cars[key], Car.relationships.owner[key]);
            }
          }
        });
      });
    });

    describe('invalid', function() {
      it('No such relationship type', function(done) {
        var collection = siesta.collection('myCollection');
        collection.model('Car', {
          id: 'id',
          attributes: ['colour', 'name'],
          relationships: {
            owner: {
              model: 'Person',
              type: 'invalidtype',
              reverse: 'cars'
            }
          }
        });
        collection.model('Person', {
          id: 'id',
          attributes: ['name', 'age']
        });

        siesta.install(function(err) {
          assert.ok(err);
          done();
        });

      });
    });
  });
});

describe('add stuff after install', function() {

  beforeEach(function(done) {
    siesta.reset(done);
  });
  it('add collection', function(done) {
    var MyCollection = siesta.collection('MyCollection'),
      Person = MyCollection.model('Person', {
        id: 'id',
        attributes: ['name', 'age', 'index']
      });
    siesta
      .install()
      .then(function() {
        var AnotherCollection = siesta.collection('AnotherCollection');
        assert.equal(siesta.AnotherCollection, AnotherCollection);
        assert.equal(CollectionRegistry.AnotherCollection, AnotherCollection);
        done();
      }).catch(done);
  });

  describe('add simple model', function() {
    var MyCollection, Car;
    beforeEach(function(done) {
      MyCollection = siesta.collection('MyCollection');
      siesta
        .install()
        .then(function() {
          Car = MyCollection.model('Car', {
            attributes: ['type']
          });
          done();
        })
        .catch(done);
    });

    it('is available on the collection', function() {
      assert.equal(MyCollection.Car, Car);
    });

    //it('graph works', function(done) {
    //  Car.graph({type: 'red'})
    //    .then(function(car) {
    //      assert.ok(car);
    //      done();
    //    })
    //    .catch(done);
    //});

  });

});<commit_msg>get rid of arranged reactive queries<commit_after>/**
 * This spec tests that removal of the old siesta.install() step that was required before use has been removed correctly
 */

var assert = require('chai').assert,
  internal = siesta._internal,
  CollectionRegistry = internal.CollectionRegistry,
  RelationshipType = siesta.RelationshipType;

describe('install step', function() {
  var MyCollection, Person;

  beforeEach(function(done) {
    siesta.reset(done);
  });

  describe('no storage', function() {
    before(function() {
      siesta.ext.storageEnabled = false;
    });

    beforeEach(function() {
      MyCollection = siesta.collection('MyCollection');
      Person = MyCollection.model('Person', {
        id: 'id',
        attributes: ['name', 'age', 'index']
      });
    });

    it('map', function(done) {
      Person.graph({name: 'Mike', age: 24})
        .then(function() {
          done();
        })
        .catch(done);
    });

    it('query', function(done) {
      Person.query({age__gt: 23})
        .then(function(res) {
          assert.notOk(res.length, 'Should be no results');
          done();
        })
        .catch(done);
    });

    it('reactive query', function(done) {
      var rq = Person._reactiveQuery({age__lt: 30});
      rq.init()
        .then(function() {
          assert.notOk(rq.results.length);
          rq.terminate();
          done();
        })
        .catch(done);
    });

  });

  describe('storage', function() {
    before(function() {
      siesta.ext.storageEnabled = true;
    });

    after(function(done) {
      siesta.reset(function() {
        siesta.ext.storageEnabled = false;
        siesta.ext.storage._pouch.allDocs().then(function(resp) {
          done();
        });
      })
    });

    beforeEach(function() {
      MyCollection = siesta.collection('MyCollection');
      Person = MyCollection.model('Person', {
        id: 'id',
        attributes: ['name', 'age', 'index']
      });
    });

    it('map', function(done) {
      Person.graph({name: 'Mike', age: 24})
        .then(function() {
          done();
        })
        .catch(done);
    });

    it('query', function(done) {
      siesta.ext.storage._pouch.bulkDocs([
        {collection: 'MyCollection', model: 'Person', name: 'Mike', age: 24},
        {collection: 'MyCollection', model: 'Person', name: 'Bob', age: 21}
      ]).then(function() {
        Person.query({age__gt: 23})
          .then(function(res) {
            assert.equal(res.length, 1, 'Should have installed and loaded before returning from the query');
            done();
          })
          .catch(done);
      }).catch(done);
    });

    it('reactive query', function(done) {
      siesta.ext.storage._pouch.bulkDocs([
        {collection: 'MyCollection', model: 'Person', name: 'Mike', age: 24},
        {collection: 'MyCollection', model: 'Person', name: 'Bob', age: 21}
      ]).then(function() {
        var rq = Person._reactiveQuery({age__gt: 23});
        rq.init()
          .then(function() {
            assert.equal(rq.results.length, 1, 'Should have installed and loaded before returning from the query');
            rq.terminate();
            done();
          })
          .catch(done);
      }).catch(done);
    });

    it('arranged reactive query', function(done) {
      siesta.ext.storage._pouch.bulkDocs([
        {collection: 'MyCollection', model: 'Person', name: 'Mike', age: 24},
        {collection: 'MyCollection', model: 'Person', name: 'Bob', age: 21}
      ]).then(function() {
        var rq = Person._arrangedReactiveQuery({age__gt: 23});
        rq.init()
          .then(function() {
            assert.equal(rq.results.length, 1, 'Should have installed and loaded before returning from the query');
            rq.terminate();
            done();
          })
          .catch(done);
      }).catch(done);
    });

  });

  describe('install relationships', function() {
    before(function() {
      siesta.ext.storageEnabled = false;
    });

    beforeEach(function(done) {
      siesta.reset(done);
    });

    var Collection, Car, Person;

    function configureAPI(type, done) {
      Collection = siesta.collection('myCollection');
      Car = Collection.model('Car', {
        id: 'id',
        attributes: ['colour', 'name'],
        relationships: {
          owner: {
            model: 'Person',
            type: type,
            reverse: 'cars'
          }
        }
      });
      Person = Collection.model('Person', {
        id: 'id',
        attributes: ['name', 'age']
      });
      siesta.install(done);
    }

    describe('valid', function() {
      describe('Foreign Key', function() {

        beforeEach(function(done) {
          configureAPI(RelationshipType.OneToMany, function(err) {
            if (err) done(err);
            done();
          });
        });

        it('configures reverse mapping', function() {
          assert.equal(Car.relationships.owner.reverseModel, Person);
        });

        it('configures reverse name', function() {
          assert.equal(Car.relationships.owner.reverseName, 'cars');

          it('configures forward mapping', function() {
            assert.equal(Car.relationships.owner.forwardModel, Car);
          });

        });
        it('configures forward name', function() {
          assert.equal(Car.relationships.owner.forwardName, 'owner');
        });

        it('installs on reverse', function() {
          var keys = Object.keys(Person.relationships.cars);
          for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (key != 'isForward' && key != 'isReverse') {
              assert.equal(Person.relationships.cars[key], Car.relationships.owner[key]);
            }
          }
        });

      });

      describe('OneToOne', function() {

        beforeEach(function(done) {
          configureAPI(RelationshipType.OneToOne, function(err) {
            if (err) done(err);
            done();
          });

        });
        it('configures reverse mapping', function() {
          assert.equal(Car.relationships.owner.reverseModel, Person);
        });

        it('configures reverse name', function() {
          assert.equal(Car.relationships.owner.reverseName, 'cars');

        });

        it('configures forward mapping', function() {
          assert.equal(Car.relationships.owner.forwardModel, Car);
        });
        it('configures forward name', function() {
          assert.equal(Car.relationships.owner.forwardName, 'owner');
        });

        it('installs on reverse', function() {
          var keys = Object.keys(Person.relationships.cars);
          for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (key != 'isForward' && key != 'isReverse') {
              assert.equal(Person.relationships.cars[key], Car.relationships.owner[key]);
            }
          }
        });
      });
    });

    describe('invalid', function() {
      it('No such relationship type', function(done) {
        var collection = siesta.collection('myCollection');
        collection.model('Car', {
          id: 'id',
          attributes: ['colour', 'name'],
          relationships: {
            owner: {
              model: 'Person',
              type: 'invalidtype',
              reverse: 'cars'
            }
          }
        });
        collection.model('Person', {
          id: 'id',
          attributes: ['name', 'age']
        });

        siesta.install(function(err) {
          assert.ok(err);
          done();
        });

      });
    });
  });
});

describe('add stuff after install', function() {

  beforeEach(function(done) {
    siesta.reset(done);
  });
  it('add collection', function(done) {
    var MyCollection = siesta.collection('MyCollection'),
      Person = MyCollection.model('Person', {
        id: 'id',
        attributes: ['name', 'age', 'index']
      });
    siesta
      .install()
      .then(function() {
        var AnotherCollection = siesta.collection('AnotherCollection');
        assert.equal(siesta.AnotherCollection, AnotherCollection);
        assert.equal(CollectionRegistry.AnotherCollection, AnotherCollection);
        done();
      }).catch(done);
  });

  describe('add simple model', function() {
    var MyCollection, Car;
    beforeEach(function(done) {
      MyCollection = siesta.collection('MyCollection');
      siesta
        .install()
        .then(function() {
          Car = MyCollection.model('Car', {
            attributes: ['type']
          });
          done();
        })
        .catch(done);
    });

    it('is available on the collection', function() {
      assert.equal(MyCollection.Car, Car);
    });

    //it('graph works', function(done) {
    //  Car.graph({type: 'red'})
    //    .then(function(car) {
    //      assert.ok(car);
    //      done();
    //    })
    //    .catch(done);
    //});

  });

});<|endoftext|>


<commit_before>var SideNavItemView;
(function ($, _, Backbone, Marionette, sideNavItemTpl, EventAggregator, TreeCompositeView, sideNavChildrenTpl) {
    SideNavItemView = Marionette.SideNavItemView = TreeCompositeView.extend({
        template: sideNavItemTpl,
        tagName: 'li',
        className: 'list-group-item',
        onRender: function () {
            if (!_.isNull(this.model.get('id'))) {
                this.$el.attr('data-target', '#toggle-' + this.model.get('id'));
            }

            if (this.hasChildren()) {
                this.$el.addClass('secondary-nav-item-pf');
            }

            this.$el.attr('data-type', this.model.get('type'));
        },
        events: function () {
            var events = {
                'click a:first-child': 'listItemClick'
            };

            var newEvents = _.extend(TreeCompositeView.prototype.events.call(this), events);
            return newEvents;
        },
        listItemClick: function (e) {
            var $target = $(e.target);

            if (!$target.is('li')) {
                $target = $target.closest('li');
            }

            EventAggregator.trigger('side-nav:click:' + $target.data('type'), this.model, e, $target.attr('href'));
            this.trigger('item-clicked', $target);
        },
        templateContext: function () {
            var routeUrl = _.isUndefined(this.model.get('route')) ? '#' : this.model.get('route'),
                type = this.model.collection.type,
                icon = this.model.get('icon');

            if (_.isUndefined(type) || _.isNull(type)) {
                type = this.model.get('type');
            }

            if (_.isUndefined(icon)) {
                icon = 'pficon-screen';
            }

            return {
                routeUrl: _.isNull(routeUrl) ? '' : routeUrl,
                type: type,
                icon: icon
            };
        },
        renderChildrenTpl: function () {
            var data = {
                    name: this.model.get('name'),
                    id: this.model.get('id')
                },
                html = Marionette.Renderer.render(sideNavChildrenTpl, data);

            this.$el.append(html);
        }
    });

})(jQuery, _, Backbone, Marionette, this['EntityView']['Templates']['./templates/sideNav/sideNavItemTemplate.html'], EventAggregator, TreeCompositeView, this['FastTrack']["Templates"]["./templates/sideNav/sideNavChildrenTpl.html"]);
<commit_msg>fix for template naming<commit_after>var SideNavItemView;
(function ($, _, Backbone, Marionette, sideNavItemTpl, EventAggregator, TreeCompositeView, sideNavChildrenTpl) {
    SideNavItemView = Marionette.SideNavItemView = TreeCompositeView.extend({
        template: sideNavItemTpl,
        tagName: 'li',
        className: 'list-group-item',
        onRender: function () {
            if (!_.isNull(this.model.get('id'))) {
                this.$el.attr('data-target', '#toggle-' + this.model.get('id'));
            }

            if (this.hasChildren()) {
                this.$el.addClass('secondary-nav-item-pf');
            }

            this.$el.attr('data-type', this.model.get('type'));
        },
        events: function () {
            var events = {
                'click a:first-child': 'listItemClick'
            };

            var newEvents = _.extend(TreeCompositeView.prototype.events.call(this), events);
            return newEvents;
        },
        listItemClick: function (e) {
            var $target = $(e.target);

            if (!$target.is('li')) {
                $target = $target.closest('li');
            }

            EventAggregator.trigger('side-nav:click:' + $target.data('type'), this.model, e, $target.attr('href'));
            this.trigger('item-clicked', $target);
        },
        templateContext: function () {
            var routeUrl = _.isUndefined(this.model.get('route')) ? '#' : this.model.get('route'),
                type = this.model.collection.type,
                icon = this.model.get('icon');

            if (_.isUndefined(type) || _.isNull(type)) {
                type = this.model.get('type');
            }

            if (_.isUndefined(icon)) {
                icon = 'pficon-screen';
            }

            return {
                routeUrl: _.isNull(routeUrl) ? '' : routeUrl,
                type: type,
                icon: icon
            };
        },
        renderChildrenTpl: function () {
            var data = {
                    name: this.model.get('name'),
                    id: this.model.get('id')
                },
                html = Marionette.Renderer.render(sideNavChildrenTpl, data);

            this.$el.append(html);
        }
    });

})(jQuery, _, Backbone, Marionette, this['EntityView']['Templates']['./templates/sideNav/sideNavItemTemplate.html'], EventAggregator, TreeCompositeView, this['EntityView']["Templates"]["./templates/sideNav/sideNavChildrenTpl.html"]);
<|endoftext|>


<commit_before>/**
 * @file TableBody
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

export TableBody from './TableBody';<commit_msg>update TableBody<commit_after>/**
 * @file TableBody
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

export default from './TableBody';<|endoftext|>


<commit_before>var gulp = require('gulp'),
  chai = require('chai'),
  expect = chai.expect,
  fs = require('fs'),
  multiline = require('multiline'),
  kssSplitter = require('../lib/modules/kss-splitter');

describe('KSS splitter', function() {

  describe('Parse KSS to AST of code blocks', function() {
  it('should parse single KSS block', function() {
    var str = multiline(function() {
      /*
// Comment
// Styleguide 1.0

.a { b: c }
      */
    }),
    result = [
      {
        'kss': '// Comment\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should be agnostic to spaces in reference declaration', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should take multiline code', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }
$a: b;

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }\n$a: b;\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should allow code blocks to have comments', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }

// Simple comment

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }\n\n// Simple comment\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse several blocks', function(){
    var str = multiline(function() {
      /*
// Comment1
// Styleguide 1.0

.a { b: c }

// Comment2
// Styleguide 2.0

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment1\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }\n'
      },
      {
        'kss': '// Comment2\n// Styleguide 2.0',
        'code': '\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should allow blocks with no code', function(){
    var str = multiline(function() {
      /*
// Comment1
// Styleguide 1.0

.a { b: c }

// Comment2
// Styleguide 2.0

// Comment3
// Styleguide 3.0

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment1\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }\n'
      },
      {
        'kss': '// Comment2\n// Styleguide 2.0',
        'code': '\n'
      },
      {
        'kss': '// Comment3\n// Styleguide 3.0',
        'code': '\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should take any reference number', function(){
    var str = multiline(function() {
      /*
// Comment
// Styleguide 1

.a { b: c }

// Comment
// Styleguide 1.1

// Comment
// Styleguide 5.1.2.6
      */
    }),
    result = [
      {
        'kss': '// Comment\n// Styleguide 1',
        'code': '\n\n.a { b: c }\n'
      },
      {
        'kss': '// Comment\n// Styleguide 1.1',
        'code': '\n'
      },
      {
        'kss': '// Comment\n// Styleguide 5.1.2.6',
        'code': ''
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should take code before first KSS block', function() {
    var str = multiline(function() {
      /*
.x { y: x }

// Comment
// Styleguide 1.0

.a { b: c }
      */
    }),
    result = [
      {
        kss: '',
        code: '.x { y: x }'
      },
      {
        'kss': '// Comment\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse single KSS block in multiline comments', function() {
    var str = '' +
'/* Comment\n' +
'Styleguide 1.0\n' +
'*/\n' +
'\n' +
'.a { b: c }',
    result = [
      [
        'block',
        [
          'kss',
          '/* Comment\nStyleguide 1.0\n*/'
        ],
        [
          'code',
          '.a { b: c }'
        ]
      ]
    ],
    kssBlocks = kssSplitter.getAst(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse multiline KSS with no ending linebreak', function() {
    var str = '' +
'/* Comment\n' +
'Styleguide 1.0    */' +
'\n' +
'.a { b: c }',
    result = [
      {
        'kss': '/* Comment\nStyleguide 1.0    */',
        'code': '.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });
  it('should parse multiline KSS with string prefixes', function() {
    var str = '' +
'/* Comment\n' +
' * Styleguide 1.0\n' +
'*/' +
'\n' +
'.a { b: c }',
    result = [
      {
        'kss': '/* Comment\n * Styleguide 1.0\n*/',
        'code': '.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should allow code blocks to have multiline comments', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }
      */}) +
'\n\n/* Simple comment */\n\n' +
multiline(function() {
    /*
.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }\n\n/* Simple comment */\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse several KSS blocks with multiline comments', function(){
    var str = '/*\n' +
'Comment1\n' +
'Styleguide 1.0\n' +
'*/\n' +
'.a { b: c }\n' +
'\n' +
'/*\n' +
'Comment2\n' +
'Styleguide 2.0\n' +
'*/'
    '',
    result = [
      {
        'kss': '/*\nComment1\nStyleguide 1.0\n*/',
        'code': '.a { b: c }\n\n'
      },
      {
        'kss': '/*\nComment2\nStyleguide 2.0\n*/',
        'code': ''
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  /* TODO: Parser does not work with code after 2nd code block */
  });

  describe('Parse KSS to array of code blocks', function() {
  it('should return array of blocks', function() {
    var str = multiline(function() {
      /*
@import "test";
// Comment
// Styleguide 1.0

.a { b: c }

// Comment
// Styleguide 2
//

// Comment
// Styleguide 2.0

.a { b: c }

      */
    }),
    result = [
      {
        kss: '// Comment\n// Styleguide 1.0\n',
        code: '.a { b: c }\n\n'
      },
      {
        kss: '// Comment\n// Styleguide 2\n',
        code: '//\n\n'
      },
      {
        kss: '// Comment\n// Styleguide 2.0\n',
        code: '.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });
  });

});
<commit_msg>Breaklines goes to code<commit_after>var gulp = require('gulp'),
  chai = require('chai'),
  expect = chai.expect,
  fs = require('fs'),
  multiline = require('multiline'),
  kssSplitter = require('../lib/modules/kss-splitter');

describe('KSS splitter', function() {

  describe('Parse KSS to AST of code blocks', function() {
  it('should parse single KSS block', function() {
    var str = multiline(function() {
      /*
// Comment
// Styleguide 1.0

.a { b: c }
      */
    }),
    result = [
      {
        'kss': '// Comment\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should be agnostic to spaces in reference declaration', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should take multiline code', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }
$a: b;

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }\n$a: b;\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should allow code blocks to have comments', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }

// Simple comment

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }\n\n// Simple comment\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse several blocks', function(){
    var str = multiline(function() {
      /*
// Comment1
// Styleguide 1.0

.a { b: c }

// Comment2
// Styleguide 2.0

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment1\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }\n'
      },
      {
        'kss': '// Comment2\n// Styleguide 2.0',
        'code': '\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should allow blocks with no code', function(){
    var str = multiline(function() {
      /*
// Comment1
// Styleguide 1.0

.a { b: c }

// Comment2
// Styleguide 2.0

// Comment3
// Styleguide 3.0

.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment1\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }\n'
      },
      {
        'kss': '// Comment2\n// Styleguide 2.0',
        'code': '\n'
      },
      {
        'kss': '// Comment3\n// Styleguide 3.0',
        'code': '\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should take any reference number', function(){
    var str = multiline(function() {
      /*
// Comment
// Styleguide 1

.a { b: c }

// Comment
// Styleguide 1.1

// Comment
// Styleguide 5.1.2.6
      */
    }),
    result = [
      {
        'kss': '// Comment\n// Styleguide 1',
        'code': '\n\n.a { b: c }\n'
      },
      {
        'kss': '// Comment\n// Styleguide 1.1',
        'code': '\n'
      },
      {
        'kss': '// Comment\n// Styleguide 5.1.2.6',
        'code': ''
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should take code before first KSS block', function() {
    var str = multiline(function() {
      /*
.x { y: x }

// Comment
// Styleguide 1.0

.a { b: c }
      */
    }),
    result = [
      {
        kss: '',
        code: '\n.x { y: x }\n'
      },
      {
        'kss': '// Comment\n// Styleguide 1.0',
        'code': '\n\n.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse single KSS block in multiline comments', function() {
    var str = '' +
'/* Comment\n' +
'Styleguide 1.0\n' +
'*/\n' +
'\n' +
'.a { b: c }',
    result = [
      [
        'block',
        [
          'kss',
          '/* Comment\nStyleguide 1.0\n*/'
        ],
        [
          'code',
          '.a { b: c }'
        ]
      ]
    ],
    kssBlocks = kssSplitter.getAst(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse multiline KSS with no ending linebreak', function() {
    var str = '' +
'/* Comment\n' +
'Styleguide 1.0    */' +
'\n' +
'.a { b: c }',
    result = [
      {
        'kss': '/* Comment\nStyleguide 1.0    */',
        'code': '.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });
  it('should parse multiline KSS with string prefixes', function() {
    var str = '' +
'/* Comment\n' +
' * Styleguide 1.0\n' +
'*/' +
'\n' +
'.a { b: c }',
    result = [
      {
        'kss': '/* Comment\n * Styleguide 1.0\n*/',
        'code': '.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should allow code blocks to have multiline comments', function(){
    var str = multiline(function() {
      /*
// Comment
//Styleguide 1.0

.a { b: c }
      */}) +
'\n\n/* Simple comment */\n\n' +
multiline(function() {
    /*
.x { y: z }
      */
    }),
    result = [
      {
        'kss': '// Comment\n//Styleguide 1.0 ',
        'code': '\n\n.a { b: c }\n\n/* Simple comment */\n\n.x { y: z }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  it('should parse several KSS blocks with multiline comments', function(){
    var str = '/*\n' +
'Comment1\n' +
'Styleguide 1.0\n' +
'*/\n' +
'.a { b: c }\n' +
'\n' +
'/*\n' +
'Comment2\n' +
'Styleguide 2.0\n' +
'*/'
    '',
    result = [
      {
        'kss': '/*\nComment1\nStyleguide 1.0\n*/',
        'code': '.a { b: c }\n\n'
      },
      {
        'kss': '/*\nComment2\nStyleguide 2.0\n*/',
        'code': ''
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });

  /* TODO: Parser does not work with code after 2nd code block */
  });

  describe('Parse KSS to array of code blocks', function() {
  it('should return array of blocks', function() {
    var str = multiline(function() {
      /*
@import "test";
// Comment
// Styleguide 1.0

.a { b: c }

// Comment
// Styleguide 2
//

// Comment
// Styleguide 2.0

.a { b: c }

      */
    }),
    result = [
      {
        kss: '',
        code: '\n@import "test";'
      },
      {
        kss: '// Comment\n// Styleguide 1.0',
        code: '\n\n.a { b: c }\n'
      },
      {
        kss: '// Comment\n// Styleguide 2\n//',
        code: '\n'
      },
      {
        kss: '// Comment\n// Styleguide 2.0',
        code: '\n\n\n.a { b: c }'
      }
    ],
    kssBlocks = kssSplitter.getBlocks(str);
    expect(kssBlocks).eql(result);
  });
  });

});
<|endoftext|>


<commit_before>/*
 * @fileOverview Main testing helper lib.
 */
var axios = require('axios');
var Promise = require('bluebird');
var bunyan = require('bunyan');

var fmt = require('bunyan-format');

// override to enable logging
process.env.KAFKA_AVRO_LOG_LEVEL = 'debug';

var KafkaAvro = require('../..');

var schemaFix = require('../fixtures/schema.fix');

var testLib = module.exports = {};

testLib.log = bunyan.createLogger({
  name: 'KafkaAvroTest',
  level: 'trace',
  // stream: {write: function() {}},
  stream: fmt({
    outputMode: 'long',
    levelInString: true,
  }),
});

testLib.KAFKA_SCHEMA_REGISTRY_URL = 'http://localhost:8081';
testLib.KAFKA_BROKER_URL = 'localhost:9092';

testLib.topic = schemaFix.name;
testLib.topicTwo = schemaFix.name + 'Two';

var testBoot = false;

/**
 * Require from all test scripts, prepares kafka for testing.
 *
 */
testLib.init = function() {
  beforeEach(function() {
    if (testBoot) {
      return;
    }
    testBoot = true;

    let kafkaAvroLog = KafkaAvro.getLogger();

    kafkaAvroLog.addStream({
      type: 'stream',
      stream: fmt({
        outputMode: 'long',
        levelInString: true,
      }),
      level: 'debug',
    }, 'debug');

    this.timeout(180000); // wait up to 3' for the SR to come up

    return Promise.all([
      testLib.registerSchema(testLib.topic, schemaFix),
      testLib.registerSchema(testLib.topicTwo, schemaFix),
    ]);
  });

  beforeEach(function() {
    let kafkaAvro = new KafkaAvro({
      kafkaBroker: testLib.KAFKA_BROKER_URL,
      schemaRegistry: testLib.KAFKA_SCHEMA_REGISTRY_URL,
    });

    testLib.log.info('test.beforeEach 2: Invoking kafkaAvro.init()...');

    return kafkaAvro.init()
      .then(() => {
        testLib.log.info('test.beforeEach 2: kafkaAvro.init() done!');
        this.kafkaAvro = kafkaAvro;
      });
  });

};

/**
 * Register a schema on SR.
 *
 * @param {string} The topic.
 * @param {schema} Object The schema to register.
 * @param {number=} retries how many times has retried.
 * @return {Promise} A Promise.
 */
testLib.registerSchema = Promise.method(function(topic, schema, retries) {
  var schemaCreateUrl = testLib.KAFKA_SCHEMA_REGISTRY_URL +
    '/subjects/' + topic + '-value/versions';

  var data = {
    schema: JSON.stringify(schema),
  };

  retries = retries || 0;

  testLib.log.info('TEST :: Registering schema:', topic, 'on SR:', schemaCreateUrl);

  return axios({
    url: schemaCreateUrl,
    method: 'post',
    headers: {
      'Content-Type': 'application/vnd.schemaregistry.v1+json',
    },
    data: data,
  })
    .catch(function(err) {
      testLib.log.error('Axios SR creation failed:', retries, err.message);
      retries++;
      return new Promise(function(resolve) {
        setTimeout(function() {
          testLib.registerSchema(topic, schema, retries)
            .then(resolve);
        }, 1000);
      });
    });
});

/**
 * Have a Cooldown period between tests.
 *
 * @param {number} seconds cooldown in seconds.
 * @return {Function} use is beforeEach().
 */
testLib.cooldown = function(seconds) {
  return function(done) {
    setTimeout(done, seconds);
  };
};
<commit_msg>populate sr on testing<commit_after>/*
 * @fileOverview Main testing helper lib.
 */
var axios = require('axios');
var Promise = require('bluebird');
var bunyan = require('bunyan');

var fmt = require('bunyan-format');

// override to enable logging
process.env.KAFKA_AVRO_LOG_LEVEL = 'debug';

var KafkaAvro = require('../..');

var schemaFix = require('../fixtures/schema.fix');

var testLib = module.exports = {};

testLib.log = bunyan.createLogger({
  name: 'KafkaAvroTest',
  level: 'trace',
  // stream: {write: function() {}},
  stream: fmt({
    outputMode: 'long',
    levelInString: true,
  }),
});

testLib.KAFKA_SCHEMA_REGISTRY_URL = 'http://localhost:8081';
// testLib.KAFKA_SCHEMA_REGISTRY_URL = 'http://schema-registry-confluent.internal.dev.waldo.photos';
testLib.KAFKA_BROKER_URL = 'localhost:9092';

testLib.topic = schemaFix.name;
testLib.topicTwo = schemaFix.name + 'Two';

var testBoot = false;

/**
 * Require from all test scripts, prepares kafka for testing.
 *
 */
testLib.init = function() {
  beforeEach(function() {
    if (testBoot) {
      return;
    }
    testBoot = true;

    let kafkaAvroLog = KafkaAvro.getLogger();

    kafkaAvroLog.addStream({
      type: 'stream',
      stream: fmt({
        outputMode: 'long',
        levelInString: true,
      }),
      level: 'debug',
    }, 'debug');

    this.timeout(180000); // wait up to 3' for the SR to come up

    return Promise.all([
      testLib.registerSchema(testLib.topic, schemaFix),
      testLib.registerSchema(testLib.topicTwo, schemaFix),
    ]);
  });

  beforeEach(function() {
    let kafkaAvro = new KafkaAvro({
      kafkaBroker: testLib.KAFKA_BROKER_URL,
      schemaRegistry: testLib.KAFKA_SCHEMA_REGISTRY_URL,
    });

    testLib.log.info('test.beforeEach 2: Invoking kafkaAvro.init()...');

    return kafkaAvro.init()
      .then(() => {
        testLib.log.info('test.beforeEach 2: kafkaAvro.init() done!');
        this.kafkaAvro = kafkaAvro;
        this.sr = kafkaAvro.sr;
      });
  });
};

/**
 * Register a schema on SR.
 *
 * @param {string} The topic.
 * @param {schema} Object The schema to register.
 * @param {number=} retries how many times has retried.
 * @return {Promise} A Promise.
 */
testLib.registerSchema = Promise.method(function(topic, schema, retries) {
  var schemaCreateUrl = testLib.KAFKA_SCHEMA_REGISTRY_URL +
    '/subjects/' + topic + '-value/versions';

  var data = {
    schema: JSON.stringify(schema),
  };

  retries = retries || 0;

  testLib.log.info('TEST :: Registering schema:', topic, 'on SR:', schemaCreateUrl);

  return axios({
    url: schemaCreateUrl,
    method: 'post',
    headers: {
      'Content-Type': 'application/vnd.schemaregistry.v1+json',
    },
    data: data,
  })
    .catch(function(err) {
      testLib.log.error('Axios SR creation failed:', retries, err.message);
      retries++;
      return new Promise(function(resolve) {
        setTimeout(function() {
          testLib.registerSchema(topic, schema, retries)
            .then(resolve);
        }, 1000);
      });
    });
});

/**
 * Have a Cooldown period between tests.
 *
 * @param {number} seconds cooldown in seconds.
 * @return {Function} use is beforeEach().
 */
testLib.cooldown = function(seconds) {
  return function(done) {
    setTimeout(done, seconds);
  };
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Dependencies
 */
var path = require('path');
var should = require('should');
var EventEmitter = require('events').EventEmitter;
var Zaz = require('../../lib/zaz');
var config = require('../fixtures/zaz.json');
var cwd = process.cwd();

describe('Zaz', function() {
  before(function(done) {
    process.chdir(path.join(cwd, 'test', 'fixtures'));

    done();
  });

  after(function(done) {
    process.chdir(cwd);

    done();
  });

  it('is an EventEmitter', function(done) {
    var zaz = new Zaz(config.stages.valid);
    zaz.should.be.an.instanceOf(EventEmitter);

    done();
  });

  describe('verifies the stage config and', function() {
    it('fails if the user is missing');
    it('fails if the git repository is missing');
    it('fails if the deployment path is missing');
    it('fails if the host list is missing');
    it('fails if the host list is empty');
  });

  describe('has `deploy` method which', function() {
    it('creates separate child processes for every server');
  });
});
<commit_msg>Main object tests modified.<commit_after>'use strict';

/**
 * Dependencies
 */
var path = require('path');
var should = require('should');
var EventEmitter = require('events').EventEmitter;
var Zaz = require('../../lib/zaz');
var config = require('../fixtures/zaz.json');
var cwd = process.cwd();
var fixtureFolder = path.join(cwd, 'test', 'fixtures');

describe('Zaz', function() {
  before(function(done) {
    process.chdir(fixtureFolder);

    done();
  });

  after(function(done) {
    process.chdir(cwd);

    done();
  });

  it('is an EventEmitter', function(done) {
    var zaz = new Zaz("valid");
    zaz.should.be.an.instanceOf(EventEmitter);

    done();
  });

  describe('has `deploy` method which', function() {
    describe('verifies the stage config and fails', function() {
      it('if the config file is missing', function(done) {
        process.chdir(cwd);
        var zaz = new Zaz("whatever");
        zaz.deploy(function(err) {
          err.should.be.an.Error;
          err.message.should.be.eql('Configuration file (`zaz.json`) not found!');

          process.chdir(fixtureFolder);
          done();
        });
      });

      it('if the user is missing', function(done) {
        var zaz = new Zaz("missingUser");
        zaz.deploy(function(err) {
          err.should.be.an.Error;
          err.message.should.be.eql('Stage configuration is incomplete: the deployment user is missing!');

          done();
        });
      });

      it('if the Git repository is missing', function(done) {
        var zaz = new Zaz("missingGit");
        zaz.deploy(function(err) {
          err.should.be.an.Error;
          err.message.should.be.eql('Stage configuration is incomplete: the source repository is missing!');

          done();
        });
      });

      it('if the deployment path is missing', function(done) {
        var zaz = new Zaz("missingPath");
        zaz.deploy(function(err) {
          err.should.be.an.Error;
          err.message.should.be.eql('Stage configuration is incomplete: the destination path is missing!');

          done();
        });
      });

      it('if the host list is missing', function(done) {
        var zaz = new Zaz("missingHosts");
        zaz.deploy(function(err) {
          err.should.be.an.Error;
          err.message.should.be.eql('Stage configuration is incomplete: the host list is missing!');

          done();
        });
      });

      it('if the host list is empty', function(done) {
        var zaz = new Zaz("emptyHosts");
        zaz.deploy(function(err) {
          err.should.be.an.Error;
          err.message.should.be.eql('Stage configuration is incomplete: the host list is empty!');

          done();
        });
      });
    });

    it('creates separate child processes for every host');
  });
});
<|endoftext|>