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

couchTests.view_sandboxing = function(debug) {
  var db_name = get_random_db_name();
  var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
  db.createDb();
  if (debug) debugger;

  var doc = {integer: 1, string: "1", array: [1, 2, 3]};
  T(db.save(doc).ok);
/*
  // make sure that attempting to change the document throws an error
  var results = db.query(function(doc) {
    doc.integer = 2;
    emit(null, doc);
  });
  T(results.total_rows == 0);

  var results = db.query(function(doc) {
    doc.array[0] = 0;
    emit(null, doc);
  });
  T(results.total_rows == 0);
*/
  // make sure that a view cannot invoke interpreter internals such as the
  // garbage collector
  var results = db.query(function(doc) {
    gc();
    emit(null, doc);
  });
  T(results.total_rows == 0);

  // make sure that a view cannot access the map_funs array defined used by
  // the view server
  var results = db.query(function(doc) { map_funs.push(1); emit(null, doc); });
  T(results.total_rows == 0);

  // make sure that a view cannot access the map_results array defined used by
  // the view server
  var results = db.query(function(doc) { map_results.push(1); emit(null, doc); });
  T(results.total_rows == 0);

  // test for COUCHDB-925
  // altering 'doc' variable in map function affects other map functions
  var ddoc = {
    _id: "_design/foobar",
    language: "javascript",
    views: {
      view1: {
        map:
          (function(doc) {
            if (doc.values) {
              doc.values = [666];
            }
            if (doc.tags) {
              doc.tags.push("qwerty");
            }
            if (doc.tokens) {
              doc.tokens["c"] = 3;
            }
          }).toString()
      },
      view2: {
        map:
          (function(doc) {
            if (doc.values) {
              emit(doc._id, doc.values);
            }
            if (doc.tags) {
              emit(doc._id, doc.tags);
            }
            if (doc.tokens) {
              emit(doc._id, doc.tokens);
            }
          }).toString()
      }
    }
  };
  var doc1 = {
    _id: "doc1",
    values: [1, 2, 3]
  };
  var doc2 = {
    _id: "doc2",
    tags: ["foo", "bar"],
    tokens: {a: 1, b: 2}
  };

  db.deleteDb();
  db.createDb();
  T(db.save(ddoc).ok);
  T(db.save(doc1).ok);
  T(db.save(doc2).ok);

  var view1Results = db.view(
    "foobar/view1", {bypass_cache: Math.round(Math.random() * 1000)});
  var view2Results = db.view(
    "foobar/view2", {bypass_cache: Math.round(Math.random() * 1000)});

  TEquals(0, view1Results.rows.length, "view1 has 0 rows");
  TEquals(3, view2Results.rows.length, "view2 has 3 rows");

  TEquals(doc1._id, view2Results.rows[0].key);
  TEquals(doc2._id, view2Results.rows[1].key);
  TEquals(doc2._id, view2Results.rows[2].key);

  // https://bugzilla.mozilla.org/show_bug.cgi?id=449657
  TEquals(3, view2Results.rows[0].value.length,
    "Warning: installed SpiderMonkey version doesn't allow sealing of arrays");
  if (view2Results.rows[0].value.length === 3) {
    TEquals(1, view2Results.rows[0].value[0]);
    TEquals(2, view2Results.rows[0].value[1]);
    TEquals(3, view2Results.rows[0].value[2]);
  }

  TEquals(1, view2Results.rows[1].value["a"]);
  TEquals(2, view2Results.rows[1].value["b"]);
  TEquals('undefined', typeof view2Results.rows[1].value["c"],
    "doc2.tokens object was not sealed");

  TEquals(2, view2Results.rows[2].value.length,
    "Warning: installed SpiderMonkey version doesn't allow sealing of arrays");
  if (view2Results.rows[2].value.length === 2) {
    TEquals("foo", view2Results.rows[2].value[0]);
    TEquals("bar", view2Results.rows[2].value[1]);
  }

  // cleanup
  db.deleteDb();
};
<commit_msg>Harden view sandboxing test<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

couchTests.view_sandboxing = function(debug) {
  var db_name = get_random_db_name();
  var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"false"});
  db.createDb();
  if (debug) debugger;

  var doc = {integer: 1, string: "1", array: [1, 2, 3]};
  T(db.save(doc).ok);

  // make sure that attempting to change the document throws an error
  var results = db.query(function(doc) {
    doc.integer = 2;
    emit(null, doc);
  }, null, {"include_docs": true});
  // either we have an error or our doc is unchanged
  T(results.total_rows == 0 || results.rows[0].doc.integer == 1);

  var results = db.query(function(doc) {
    doc.array[0] = 0;
    emit(null, doc);
  }, null, {"include_docs": true});
  // either we have an error or our doc is unchanged
  T(results.total_rows == 0 || results.rows[0].doc.array[0] == 1);

  // make sure that a view cannot invoke interpreter internals such as the
  // garbage collector
  var results = db.query(function(doc) {
    gc();
    emit(null, doc);
  });
  T(results.total_rows == 0);

  // make sure that a view cannot access the map_funs array defined used by
  // the view server
  var results = db.query(function(doc) { map_funs.push(1); emit(null, doc); });
  T(results.total_rows == 0);

  // make sure that a view cannot access the map_results array defined used by
  // the view server
  var results = db.query(function(doc) { map_results.push(1); emit(null, doc); });
  T(results.total_rows == 0);

  // test for COUCHDB-925
  // altering 'doc' variable in map function affects other map functions
  var ddoc = {
    _id: "_design/foobar",
    language: "javascript",
    views: {
      view1: {
        map:
          (function(doc) {
            if (doc.values) {
              doc.values = [666];
            }
            if (doc.tags) {
              doc.tags.push("qwerty");
            }
            if (doc.tokens) {
              doc.tokens["c"] = 3;
            }
          }).toString()
      },
      view2: {
        map:
          (function(doc) {
            if (doc.values) {
              emit(doc._id, doc.values);
            }
            if (doc.tags) {
              emit(doc._id, doc.tags);
            }
            if (doc.tokens) {
              emit(doc._id, doc.tokens);
            }
          }).toString()
      }
    }
  };
  var doc1 = {
    _id: "doc1",
    values: [1, 2, 3]
  };
  var doc2 = {
    _id: "doc2",
    tags: ["foo", "bar"],
    tokens: {a: 1, b: 2}
  };

  db.deleteDb();
  db.createDb();
  T(db.save(ddoc).ok);
  T(db.save(doc1).ok);
  T(db.save(doc2).ok);

  var view1Results = db.view(
    "foobar/view1", {bypass_cache: Math.round(Math.random() * 1000)});
  var view2Results = db.view(
    "foobar/view2", {bypass_cache: Math.round(Math.random() * 1000)});

  TEquals(0, view1Results.rows.length, "view1 has 0 rows");
  TEquals(3, view2Results.rows.length, "view2 has 3 rows");

  TEquals(doc1._id, view2Results.rows[0].key);
  TEquals(doc2._id, view2Results.rows[1].key);
  TEquals(doc2._id, view2Results.rows[2].key);

  // https://bugzilla.mozilla.org/show_bug.cgi?id=449657
  TEquals(3, view2Results.rows[0].value.length,
    "Warning: installed SpiderMonkey version doesn't allow sealing of arrays");
  if (view2Results.rows[0].value.length === 3) {
    TEquals(1, view2Results.rows[0].value[0]);
    TEquals(2, view2Results.rows[0].value[1]);
    TEquals(3, view2Results.rows[0].value[2]);
  }

  // we can't be 100% sure about the order for the same key
  T(view2Results.rows[1].value["a"] == 1 || view2Results.rows[1].value[0] == "foo");
  T(view2Results.rows[1].value["b"] == 2 || view2Results.rows[1].value[1] == "bar");
  T(view2Results.rows[2].value["a"] == 1 || view2Results.rows[2].value[0] == "foo");
  T(view2Results.rows[2].value["b"] == 2 || view2Results.rows[2].value[1] == "bar");
  TEquals('undefined', typeof view2Results.rows[1].value["c"], "doc2.tokens object was not sealed");
  TEquals('undefined', typeof view2Results.rows[2].value["c"], "doc2.tokens object was not sealed");

/* (see above)
  TEquals(2, view2Results.rows[2].value.length,
    "Warning: installed SpiderMonkey version doesn't allow sealing of arrays");
  if (view2Results.rows[2].value.length === 2) {
    TEquals("foo", view2Results.rows[2].value[0]);
    TEquals("bar", view2Results.rows[2].value[1]);
  }
*/

  // cleanup
  db.deleteDb();
};
<|endoftext|>


<commit_before>require('../../../src/leaflet/overlay/GraphicLayer');

var url = "http://supermapiserver:8090/iserver/services/map-world/rest/maps/World";
describe('leaflet_GraphicLayer', function () {
    var originalTimeout;
    var testDiv, map;
    beforeAll(function () {
        testDiv = window.document.createElement("div");
        testDiv.setAttribute("id", "map");
        testDiv.style.styleFloat = "left";
        testDiv.style.marginLeft = "8px";
        testDiv.style.marginTop = "50px";
        testDiv.style.width = "500px";
        testDiv.style.height = "500px";
        window.document.body.appendChild(testDiv);

        map = L.map('map', {
            preferCanvas: true,
            crs: L.CRS.EPSG4326,
            center: {lon: 0, lat: 0},
            maxZoom: 18,
            zoom: 1
        });
        L.supermap.tiledMapLayer(url).addTo(map);
    });
    beforeEach(function () {
        originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
    });
    afterEach(function () {
        jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });
    afterAll(function () {
        //canvas渲染时由于Path 相关的子类 -> map.remove()会有重绘操作，从而引起刷新延迟会报错，故弃之
        map.off();
        map = null;
        window.document.body.removeChild(testDiv);
    });

    it('initialize', function (done) {
        var colorCount = 5, count = 5;
        var graphics = [];
        var e = 45;
        var randomCircleStyles = [];
        for (var i = 0; i < colorCount; i++) {
            randomCircleStyles.push(L.supermap.circleStyle({
                color: '#3388ff',
                opacity: 1,
                radius: 2,
                fill: true,
                fillColor: '#3388ff',
                fillOpacity: 1
            }));
        }
        for (var j = 0; j < count; ++j) {
            var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
            graphics[j] = L.supermap.graphic({
                _latlng: L.latLng(coordinates[0], coordinates[1]),
                _canvas: randomCircleStyles[Math.floor(Math.random() * colorCount)].getCanvas()
            });
        }
        var graphicLayer = L.supermap.graphicLayer(graphics).addTo(map);

        setTimeout(function () {
            expect(graphicLayer.graphics.length).toEqual(count);
            for (var i = 0; i < graphicLayer.graphics.length; i++) {
                expect(graphicLayer.graphics[i]._canvas).not.toBeNull();
                expect(graphicLayer.graphics[i]._latlng).not.toBeNull();
            }
            var isContainsPoint = graphicLayer._containsPoint();
            expect(isContainsPoint).not.toBe("false");
            graphicLayer.remove();
            done();
        }, 1000)
    });
});

<commit_msg>fix graphiclayer UT引起的问题<commit_after>require('../../../src/leaflet/overlay/GraphicLayer');

var url = "http://supermapiserver:8090/iserver/services/map-world/rest/maps/World";
describe('leaflet_GraphicLayer', function () {
    var originalTimeout;
    var testDiv, map;
    beforeAll(function () {
        testDiv = window.document.createElement("div");
        testDiv.setAttribute("id", "map");
        testDiv.style.styleFloat = "left";
        testDiv.style.marginLeft = "8px";
        testDiv.style.marginTop = "50px";
        testDiv.style.width = "500px";
        testDiv.style.height = "500px";
        window.document.body.appendChild(testDiv);

        map = L.map('map', {
            preferCanvas: true,
            crs: L.CRS.EPSG4326,
            center: {lon: 0, lat: 0},
            maxZoom: 18,
            zoom: 1
        });
        L.supermap.tiledMapLayer(url).addTo(map);
    });
    beforeEach(function () {
        originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
        jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
    });
    afterEach(function () {
        jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
    });
    afterAll(function () {
        map.remove();
        window.document.body.removeChild(testDiv);
    });

    it('initialize', function (done) {
        var colorCount = 5, count = 5;
        var graphics = [];
        var e = 45;
        var randomCircleStyles = [];
        for (var i = 0; i < colorCount; i++) {
            randomCircleStyles.push(L.supermap.circleStyle({
                color: '#3388ff',
                opacity: 1,
                radius: 2,
                fill: true,
                fillColor: '#3388ff',
                fillOpacity: 1
            }));
        }
        for (var j = 0; j < count; ++j) {
            var coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e];
            graphics[j] = L.supermap.graphic({
                _latlng: L.latLng(coordinates[0], coordinates[1]),
                _canvas: randomCircleStyles[Math.floor(Math.random() * colorCount)].getCanvas()
            });
        }
        var graphicLayer = L.supermap.graphicLayer(graphics).addTo(map);

        setTimeout(function () {
            expect(graphicLayer.graphics.length).toEqual(count);
            for (var i = 0; i < graphicLayer.graphics.length; i++) {
                expect(graphicLayer.graphics[i]._canvas).not.toBeNull();
                expect(graphicLayer.graphics[i]._latlng).not.toBeNull();
            }
            var isContainsPoint = graphicLayer._containsPoint();
            expect(isContainsPoint).not.toBe("false");
            //map.remove()时，canvas渲染的场景下render会先移除canvas的ctx，而path的移除会有重绘操作。
            //从而引起刷新延迟会报错，故在此移除重绘
            graphicLayer.on('remove', function () {
                var requestAnimId = map.getRenderer(graphicLayer)._redrawRequest;
                (requestAnimId != null) && L.Util.cancelAnimFrame(requestAnimId);
                done();
            });
            graphicLayer.remove();
        }, 1000)
    });
});

<|endoftext|>


<commit_before>'use strict';

/**
 * This initializes the ElasticSearch index.
 *
 * @param {Object} state The state of which we are about to initialize.
 */

var es = require('../../lib/services/elasticsearch');
var config = require('../../lib/config/config');

module.exports = function(state) {
  state.index = config.esAssetsIndex;
  console.log('Initializing the Elastic Search index: ' + state.index);

  return es.indices.exists({
    index: state.index
  }).then(function(exists) {
    if (exists) {
      console.log('Index was already created.');
      return state;
    } else {
      return es.indices.create({
        index: state.index,
        body: {
          'index': {
            'max_result_window': 100000 // We need this, so sitemaps can access all assets
          }
        }
      }).then(function() {
        console.log('Index created.');
        return state;
      }, function(err) {
        // TODO: Add a recursive check for this message.
        if (err.message === 'No Living connections') {
          throw new Error('Is the Elasticsearch server running?');
        } else {
          throw err;
        }
      });
    }
  });
};
<commit_msg>The index needs a proper mapping for date fields.<commit_after>'use strict';

/**
 * This initializes the ElasticSearch index.
 *
 * @param {Object} state The state of which we are about to initialize.
 */

var es = require('../../lib/services/elasticsearch');
var config = require('../../lib/config/config');

module.exports = function(state) {
  state.index = config.esAssetsIndex;
  console.log('Initializing the Elastic Search index: ' + state.index);

  return es.indices.exists({
    index: state.index
  }).then(function(exists) {
    if (exists) {
      console.log('Index was already created.');
      return state;
    } else {
      var fields = {};
      // Derive mappings from the asset field types
      config.assetFields.filter((field) => {
        return field.type;
      }).forEach((field) => {
        var fieldName = field.short;
        if (field.type === 'date') {
          fieldName += '.timestamp';
        }
        fields[fieldName] = {
          type: field.type
        };
      });
      // Create the actual index
      return es.indices.create({
        index: state.index,
        body: {
          'index': {
            'max_result_window': 100000 // We need this, so sitemaps can access all assets
          },
          'mappings': {
            'asset': {
              'properties': fields
            }
          }
        }
      }).then(function() {
        console.log('Index created.');
        return state;
      }, function(err) {
        // TODO: Add a recursive check for this message.
        if (err.message === 'No Living connections') {
          throw new Error('Is the Elasticsearch server running?');
        } else {
          throw err;
        }
      });
    }
  });
};
<|endoftext|>


<commit_before>
describe('Directive: ivhMultiSelect', function() {
  'use strict';

  beforeEach(module('ivh.multiSelect'));

  var ng = angular
    , $ = jQuery
    , scope
    , c; // compile

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();

    c = function(tpl, s) {
      s = s || scope;
      tpl = ng.isArray(tpl) ? tpl.join('\n') : tpl;
      var $el = $compile(ng.element(tpl))(s);
      s.$apply();
      return $el;
    };
  }));

  it('should create a button with text as the transcluded content', function() {
    var $el = c([
      '
',
        'Blargus',
      '
'
    ]);

    var tText = $el.text().trim();
    expect(tText).toBe('Blargus');
  });

  it('Its watcher count should be invariant in the number of list items while collapsed', function() {
    scope.items1 = [{label: 'foo'}];
    scope.items2 = [{label: 'foo'}, {label: 'bar'}, {label: 'wowza'}];

    var $el1 = c([
      '
',
        'Blargus',
      '
'
    ]);

    var $el2 = c([
      '
',
        'Blargus',
      '
'
    ]);

    var numWatchers1 = countWacthers($el1);
    var numWatchers2 = countWacthers($el2);

    expect(numWatchers1).toBe(numWatchers2);
  });
});
<commit_msg>test: Add test for showing items in menu<commit_after>
describe('Directive: ivhMultiSelect', function() {
  'use strict';

  beforeEach(module('ivh.multiSelect'));

  var ng = angular
    , $ = jQuery
    , scope
    , c; // compile

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();

    c = function(tpl, s) {
      s = s || scope;
      tpl = ng.isArray(tpl) ? tpl.join('\n') : tpl;
      var $el = $compile(ng.element(tpl))(s);
      s.$apply();
      return $el;
    };
  }));

  it('should create a button with text as the transcluded content', function() {
    var $el = c([
      '
',
        'Blargus',
      '
'
    ]);

    var tText = $el.text().trim();
    expect(tText).toBe('Blargus');
  });

  it('Its watcher count should be invariant in the number of list items while collapsed', function() {
    scope.items1 = [{label: 'foo'}];
    scope.items2 = [{label: 'foo'}, {label: 'bar'}, {label: 'wowza'}];

    var $el1 = c([
      '
',
        'Blargus',
      '
'
    ]);

    var $el2 = c([
      '
',
        'Blargus',
      '
'
    ]);

    var numWatchers1 = countWacthers($el1);
    var numWatchers2 = countWacthers($el2);

    expect(numWatchers1).toBe(numWatchers2);
  });

  it('should display items when the button is clicked', function() {
    scope.items = [{label: 'foo'}];

    var $el = c([
      '
',
        'Blargus',
      '
'
    ]);

    $el.find('button').click();

    var liText = $el.find('li.ms-item').first().text().trim();

    expect(liText).toBe('foo');
  });
});
<|endoftext|>


<commit_before>const expect = require('chai').expect;
const G6 = require('../../../../src');

const div = document.createElement('div');
div.id = 'state-controller';
document.body.appendChild(div);

describe('graph state controller', () => {
  const graph = new G6.Graph({
    container: div,
    width: 500,
    height: 500
  });
  const data = {
    nodes: [
      { id: 'node1', x: 100, y: 100 },
      { id: 'node2', x: 120, y: 80 },
      { id: 'node3', x: 150, y: 150 }
    ],
    edges: [
      { id: 'edge1', source: 'node1', target: 'node2' },
      { id: 'edge2', source: 'node1', target: 'node3' }
    ]
  };
  graph.read(data);
  it('set item state', done => {
    let graphCount = 0,
      itemCount = 0;
    graph.on('graphstatechange', () => {
      graphCount += 1;
    });
    graph.on('beforeitemstatechange', () => {
      itemCount += 1;
    });
    graph.setItemState('node1', 'selected', true);
    setTimeout(() => {
      expect(itemCount).to.equal(1);
      expect(graphCount).to.equal(1);
      expect(graph.get('states').selected).not.to.be.undefined;
      expect(graph.get('states').selected.length).to.equal(1);
      expect(graph.get('states').selected[0]).to.equal(graph.findById('node1'));
      graph.setItemState('node1', 'selected', false);
      graph.setItemState('node1', 'selected', true);
      graph.setItemState('node2', 'selected', true);
      graph.setItemState('node3', 'selected', true);
      setTimeout(() => {
        expect(itemCount).to.equal(5);
        expect(graphCount).to.equal(2);
        expect(graph.get('states').selected.length).to.equal(3);
        graph.setItemState('node1', 'selected', false);
        graph.setItemState('node2', 'selected', false);
        graph.setItemState('node3', 'selected', false);
        setTimeout(() => {
          expect(graph.get('states').selected.length).to.equal(0);
          done();
        }, 50);
      }, 50);
    }, 50);
  });
  it('state with behavior', done => {
    graph.removeEvent();
    graph.addBehaviors('activate-relations', 'default');
    let triggered = false;
    graph.emit('node:mouseenter', { item: graph.findById('node1') });
    setTimeout(() => {
      graph.emit('node:mouseenter', { item: graph.findById('node2') });
      triggered = true;
    }, 50);
    graph.on('graphstatechange', e => {
      if (!triggered) {
        expect(e.states.active).not.to.be.undefined;
        expect(e.states.active.length).to.equal(5);
        expect(e.states.inactive).not.to.be.undefined;
        expect(e.states.inactive.length).to.equal(0);
      } else {
        expect(e.states.active).not.to.be.undefined;
        expect(e.states.active.length).to.equal(3);
        expect(e.states.inactive).not.to.be.undefined;
        expect(e.states.inactive.length).to.equal(2);
        done();
      }
    });
  });
});
<commit_msg>chore(test): add test on graph state<commit_after>const expect = require('chai').expect;
const G6 = require('../../../../src');

const div = document.createElement('div');
div.id = 'state-controller';
document.body.appendChild(div);

describe('graph state controller', () => {
  const graph = new G6.Graph({
    container: div,
    width: 500,
    height: 500
  });
  const data = {
    nodes: [
      { id: 'node1', x: 100, y: 100 },
      { id: 'node2', x: 120, y: 80 },
      { id: 'node3', x: 150, y: 150 }
    ],
    edges: [
      { id: 'edge1', source: 'node1', target: 'node2' },
      { id: 'edge2', source: 'node1', target: 'node3' }
    ]
  };
  graph.read(data);
  it('set item state', done => {
    let graphCount = 0,
      itemCount = 0;
    graph.on('graphstatechange', () => {
      graphCount += 1;
    });
    graph.on('beforeitemstatechange', () => {
      itemCount += 1;
    });
    graph.setItemState('node1', 'selected', true);
    setTimeout(() => {
      expect(itemCount).to.equal(1);
      expect(graphCount).to.equal(1);
      expect(graph.get('states').selected).not.to.be.undefined;
      expect(graph.get('states').selected.length).to.equal(1);
      expect(graph.get('states').selected[0]).to.equal(graph.findById('node1'));
      graph.setItemState('node1', 'selected', false);
      graph.setItemState('node1', 'selected', true);
      graph.setItemState('node2', 'selected', true);
      graph.setItemState('node3', 'selected', true);
      setTimeout(() => {
        expect(itemCount).to.equal(5);
        expect(graphCount).to.equal(2);
        expect(graph.get('states').selected.length).to.equal(3);
        graph.setItemState('node1', 'selected', false);
        graph.setItemState('node2', 'selected', false);
        graph.setItemState('node3', 'selected', false);
        setTimeout(() => {
          expect(graph.get('states').selected.length).to.equal(0);
          done();
        }, 50);
      }, 50);
    }, 50);
  });
  it('state with activate-relations', done => {
    graph.removeEvent();
    graph.addBehaviors('activate-relations', 'default');
    let triggered = false;
    graph.emit('node:mouseenter', { item: graph.findById('node1') });
    setTimeout(() => {
      graph.emit('node:mouseenter', { item: graph.findById('node2') });
      triggered = true;
    }, 50);
    graph.on('graphstatechange', e => {
      if (!triggered) {
        expect(e.states.active).not.to.be.undefined;
        expect(e.states.active.length).to.equal(5);
        expect(e.states.inactive).not.to.be.undefined;
        expect(e.states.inactive.length).to.equal(0);
      } else {
        expect(e.states.active).not.to.be.undefined;
        expect(e.states.active.length).to.equal(3);
        expect(e.states.inactive).not.to.be.undefined;
        expect(e.states.inactive.length).to.equal(2);
        graph.removeBehaviors('activate-relations', 'default');
        done();
      }
    });
  });
  it('state with click-select', done => {
    graph.removeEvent();
    graph.addBehaviors('click-select', 'default');
    graph.emit('keydown', { keyCode: 17 });
    graph.emit('node:click', { item: graph.findById('node1') });
    graph.emit('node:click', { item: graph.findById('node2') });
    let finished = false;
    setTimeout(() => {
      graph.emit('node:click', { item: graph.findById('node2') });
      finished = true;
    }, 50);
    graph.on('graphstatechange', e => {
      if (!finished) {
        expect(e.states.selected).not.to.be.undefined;
        expect(e.states.selected.length).to.equal(2);
      } else {
        expect(e.states.selected).not.to.be.undefined;
        expect(e.states.selected.length).to.equal(1);
        done();
      }
    });
  });
});
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// <!-- saved from url=(0014)about:internet -->
/// <reference path="ms-appx://$(TargetFramework)/js/base.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/base.strings.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/ui.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/ui.strings.js" />
/// <reference path="ms-appx://$(TargetFramework)/css/ui-dark.css" />
/// <deploy src="../TestData/" />

var CorsicaTests = CorsicaTests || {};

CorsicaTests.SettingsFlyoutTests = function () {
    "use strict";

    this.tearDown = function () {
        LiveUnit.LoggingCore.logComment("In tearDown");
        OverlayHelpers.disposeAndRemove(document.querySelector("." + WinJS.UI._Overlay._clickEatingAppBarClass));
        OverlayHelpers.disposeAndRemove(document.querySelector("." + WinJS.UI._Overlay._clickEatingFlyoutClass));
        OverlayHelpers.disposeAndRemove(document.querySelector(".win-settingsflyout"));
    };

    // Test settings flyout Instantiation
    this.testSettingsFlyoutInstantiation = function () {
        // Get the settings flyout element from the DOM
        LiveUnit.LoggingCore.logComment("Attempt to Instantiate the settings flyout element");
        var flyoutElement = document.createElement('div');
        document.body.appendChild(flyoutElement);
        var settingsFlyout = new WinJS.UI.SettingsFlyout(flyoutElement);
        LiveUnit.LoggingCore.logComment("settings flyout has been instantiated.");
        LiveUnit.Assert.isNotNull(settingsFlyout, "settings flyout element should not be null when instantiated.");

        function verifyFunction(functionName) {
            LiveUnit.LoggingCore.logComment("Verifying that function " + functionName + " exists");
            if (settingsFlyout[functionName] === undefined) {
                LiveUnit.Assert.fail(functionName + " missing from settings flyout");
            }
            LiveUnit.Assert.isNotNull(settingsFlyout[functionName]);
            LiveUnit.Assert.isTrue(typeof (settingsFlyout[functionName]) === "function", functionName +
                " exists on flyout, but it isn't a function");
        }

        function verifyProperty(propertyName) {
            LiveUnit.LoggingCore.logComment("Verifying that property " + propertyName + " exists");
            for (var name in settingsFlyout) {
                if (name == propertyName) {
                    return;
                }
            }
            LiveUnit.Assert.fail(propertyName + " missing from settings flyout");
        }

        verifyFunction("show");
        verifyFunction("hide");
        verifyProperty("width");
        document.body.removeChild(flyoutElement);
    }

    // Test settings flyout Instantiation with null element
    this.testSettingsFlyoutNullInstantiation = function () {
        LiveUnit.LoggingCore.logComment("Attempt to Instantiate the settings flyout with null element");
        var settingsFlyout = new WinJS.UI.SettingsFlyout(null);
        LiveUnit.Assert.isNotNull(settingsFlyout, "settings flyout instantiation was null when sent a null settings flyout element.");
    }

    // Test multiple instantiation of the same settings flyout DOM element
    this.testSettingsFlyoutMultipleInstantiation = function () {
        // Get the settings flyout element from the DOM
        LiveUnit.LoggingCore.logComment("Attempt to instantiate the settings flyout element");
        var settingsFlyoutElement = document.createElement('div');
        document.body.appendChild(settingsFlyoutElement);
        var settingsFlyout = new WinJS.UI.SettingsFlyout(settingsFlyoutElement);
        LiveUnit.LoggingCore.logComment("settings flyout has been instantiated.");
        LiveUnit.Assert.isNotNull(settingsFlyout, "settings flyout element should not be null when instantiated.");
        new WinJS.UI.Flyout(settingsFlyoutElement);
        document.body.removeChild(settingsFlyoutElement);
    }

    this.testOverlayMultipleInstantiation["LiveUnit.ExpectedException"] = { message: WinJS.Resources._getWinJSString("ui/duplicateConstruction").value }; // This is the exception that is expected

    if (WinJS.Utilities.hasWinRT) {
        // Test settings flyout loading from fragment
        this.testSettingsFlyoutWithFragment = function (complete) {
            // Get the settings flyout element from the DOM
            LiveUnit.LoggingCore.logComment("Attempt to to load the settings flyout fragment");
            WinJS.UI.SettingsFlyout.showSettings("CustomSettings", "SettingsFlyoutFragment.html");

            // Yield so the flyout can be shown
            WinJS.Promise.timeout().
                then(function () {
                    var settingsFlyoutElement = document.getElementById("CustomSettings");
                    LiveUnit.Assert.isNotNull(settingsFlyoutElement, "loaded settings flyout element from fragment should not be null.");
                    var settingsControl = settingsFlyoutElement.winControl;
                    LiveUnit.Assert.isNotNull(settingsControl, "settings flyout control is invalid.");

                    // Verify the type of the flyout. Wide flyout width = 645px
                    var expectedFlyoutWidth = 645;
                    LiveUnit.Assert.areEqual(expectedFlyoutWidth, settingsFlyoutElement.clientWidth, "Not a wide flyout");

                    // unload the fragment and destruct the control
                    settingsControl._dismiss();

                    // Yield so the flyout can be dismissed
                    return WinJS.Promise.timeout(2000);
                }).
                then(function () {
                    var element = document.getElementById("CustomSettings");
                    LiveUnit.Assert.isNull(element, "failed to unload the settings flyout fragment");
                }).
                done(complete);
        }

        this.testSettingswithCommandProperty = function (complete) {
            // Get the settings flyout element from the DOM
            LiveUnit.LoggingCore.logComment("Attempt to to load the settings flyout fragment");
            WinJS.UI.SettingsFlyout.showSettings("CommandA", "SettingsFlyoutFragment.html");

            // Yield so the flyout can be shown
            WinJS.Promise.timeout().
                then(function () {
                    var settingsFlyoutElement = document.querySelector(".win-settingsflyout");
                    LiveUnit.Assert.isNotNull(settingsFlyoutElement, "loaded settings flyout element from fragment should not be null.");
                    var settingsControl = settingsFlyoutElement.winControl;
                    LiveUnit.Assert.isNotNull(settingsControl, "settings flyout control is invalid.");

                    LiveUnit.Assert.isTrue(settingsControl.settingsCommandId === "CommandA", "Expected right value in settingsCommandId");

                    // Verify the type of the flyout. Wide flyout width = 345px
                    var expectedFlyoutWidth = 345;
                    LiveUnit.Assert.areEqual(expectedFlyoutWidth, settingsFlyoutElement.clientWidth, "Not a narrow flyout");

                    // unload the fragment and destruct the control
                    settingsControl._dismiss();

                    // Yield so the flyout can dismissed
                    return WinJS.Promise.timeout(2000);
                }).
                then(function () {
                    var settingsFlyoutElement = document.getElementById("CommandA");
                    LiveUnit.Assert.isTrue(!settingsFlyoutElement, "failed to unload the settings flyout fragment");
                }).
                done(complete);
        }

    }

    this.testSettingsFlyoutDispose = function () {
        var sf = new WinJS.UI.SettingsFlyout();
        LiveUnit.Assert.isTrue(sf.dispose);
        LiveUnit.Assert.isFalse(sf._disposed);

        // Double dispose sentinel
        var sentinel = document.createElement("div");
        sentinel.disposed = false;
        WinJS.Utilities.addClass(sentinel, "win-disposable");
        sf.element.appendChild(sentinel);
        sentinel.dispose = function () {
            if (sentinel.disposed) {
                LiveUnit.Assert.fail("Unexpected double dispose occured.");
            }
            sentinel.disposed = true;
        };

        sf.dispose();
        LiveUnit.Assert.isTrue(sentinel.disposed);
        LiveUnit.Assert.isTrue(sf._disposed);
        sf.dispose();
    }
    this.testSettingsFlyoutDispose["Description"] = "Unit test for dispose requirements.";

    this.testDisposeRemovesAppBarClickEatingDiv = function (complete) {
        WinJS.UI._Overlay._clickEatingAppBarDiv = null;
        WinJS.UI._Overlay._clickEatingFlyoutDiv = null;

        var flyout = new WinJS.UI.SettingsFlyout();
        document.body.appendChild(flyout.element);
        flyout.show();

        // ClickEater add/remove are high priority scheduler jobs, so we schedule an idle priority asserts
        flyout.addEventListener("aftershow", function () {
            var clickEater = document.querySelector("." + WinJS.UI._Overlay._clickEatingAppBarClass);
            LiveUnit.Assert.isTrue(clickEater);
            LiveUnit.Assert.areNotEqual("none", clickEater.style.display);

            flyout.dispose();

            WinJS.Utilities.Scheduler.schedule(function () {
                LiveUnit.Assert.areEqual("none", clickEater.style.display);
                document.body.removeChild(flyout.element);
                complete();
            }, WinJS.Utilities.Scheduler.Priority.idle);
        });
    };
};

// register the object as a test class by passing in the name
LiveUnit.registerTestClass("CorsicaTests.SettingsFlyoutTests");

<commit_msg>Re-add two timeout properties that may be useful<commit_after>// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// <!-- saved from url=(0014)about:internet -->
/// <reference path="ms-appx://$(TargetFramework)/js/base.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/base.strings.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/ui.js" />
/// <reference path="ms-appx://$(TargetFramework)/js/en-us/ui.strings.js" />
/// <reference path="ms-appx://$(TargetFramework)/css/ui-dark.css" />
/// <deploy src="../TestData/" />

var CorsicaTests = CorsicaTests || {};

CorsicaTests.SettingsFlyoutTests = function () {
    "use strict";

    this.tearDown = function () {
        LiveUnit.LoggingCore.logComment("In tearDown");
        OverlayHelpers.disposeAndRemove(document.querySelector("." + WinJS.UI._Overlay._clickEatingAppBarClass));
        OverlayHelpers.disposeAndRemove(document.querySelector("." + WinJS.UI._Overlay._clickEatingFlyoutClass));
        OverlayHelpers.disposeAndRemove(document.querySelector(".win-settingsflyout"));
    };

    // Test settings flyout Instantiation
    this.testSettingsFlyoutInstantiation = function () {
        // Get the settings flyout element from the DOM
        LiveUnit.LoggingCore.logComment("Attempt to Instantiate the settings flyout element");
        var flyoutElement = document.createElement('div');
        document.body.appendChild(flyoutElement);
        var settingsFlyout = new WinJS.UI.SettingsFlyout(flyoutElement);
        LiveUnit.LoggingCore.logComment("settings flyout has been instantiated.");
        LiveUnit.Assert.isNotNull(settingsFlyout, "settings flyout element should not be null when instantiated.");

        function verifyFunction(functionName) {
            LiveUnit.LoggingCore.logComment("Verifying that function " + functionName + " exists");
            if (settingsFlyout[functionName] === undefined) {
                LiveUnit.Assert.fail(functionName + " missing from settings flyout");
            }
            LiveUnit.Assert.isNotNull(settingsFlyout[functionName]);
            LiveUnit.Assert.isTrue(typeof (settingsFlyout[functionName]) === "function", functionName +
                " exists on flyout, but it isn't a function");
        }

        function verifyProperty(propertyName) {
            LiveUnit.LoggingCore.logComment("Verifying that property " + propertyName + " exists");
            for (var name in settingsFlyout) {
                if (name == propertyName) {
                    return;
                }
            }
            LiveUnit.Assert.fail(propertyName + " missing from settings flyout");
        }

        verifyFunction("show");
        verifyFunction("hide");
        verifyProperty("width");
        document.body.removeChild(flyoutElement);
    }

    // Test settings flyout Instantiation with null element
    this.testSettingsFlyoutNullInstantiation = function () {
        LiveUnit.LoggingCore.logComment("Attempt to Instantiate the settings flyout with null element");
        var settingsFlyout = new WinJS.UI.SettingsFlyout(null);
        LiveUnit.Assert.isNotNull(settingsFlyout, "settings flyout instantiation was null when sent a null settings flyout element.");
    }

    // Test multiple instantiation of the same settings flyout DOM element
    this.testSettingsFlyoutMultipleInstantiation = function () {
        // Get the settings flyout element from the DOM
        LiveUnit.LoggingCore.logComment("Attempt to instantiate the settings flyout element");
        var settingsFlyoutElement = document.createElement('div');
        document.body.appendChild(settingsFlyoutElement);
        var settingsFlyout = new WinJS.UI.SettingsFlyout(settingsFlyoutElement);
        LiveUnit.LoggingCore.logComment("settings flyout has been instantiated.");
        LiveUnit.Assert.isNotNull(settingsFlyout, "settings flyout element should not be null when instantiated.");
        new WinJS.UI.Flyout(settingsFlyoutElement);
        document.body.removeChild(settingsFlyoutElement);
    }

    this.testOverlayMultipleInstantiation["LiveUnit.ExpectedException"] = { message: WinJS.Resources._getWinJSString("ui/duplicateConstruction").value }; // This is the exception that is expected

    if (WinJS.Utilities.hasWinRT) {
        // Test settings flyout loading from fragment
        this.testSettingsFlyoutWithFragment = function (complete) {
            // Get the settings flyout element from the DOM
            LiveUnit.LoggingCore.logComment("Attempt to to load the settings flyout fragment");
            WinJS.UI.SettingsFlyout.showSettings("CustomSettings", "SettingsFlyoutFragment.html");

            // Yield so the flyout can be shown
            WinJS.Promise.timeout().
                then(function () {
                    var settingsFlyoutElement = document.getElementById("CustomSettings");
                    LiveUnit.Assert.isNotNull(settingsFlyoutElement, "loaded settings flyout element from fragment should not be null.");
                    var settingsControl = settingsFlyoutElement.winControl;
                    LiveUnit.Assert.isNotNull(settingsControl, "settings flyout control is invalid.");

                    // Verify the type of the flyout. Wide flyout width = 645px
                    var expectedFlyoutWidth = 645;
                    LiveUnit.Assert.areEqual(expectedFlyoutWidth, settingsFlyoutElement.clientWidth, "Not a wide flyout");

                    // unload the fragment and destruct the control
                    settingsControl._dismiss();

                    // Yield so the flyout can be dismissed
                    return WinJS.Promise.timeout(2000);
                }).
                then(function () {
                    var element = document.getElementById("CustomSettings");
                    LiveUnit.Assert.isNull(element, "failed to unload the settings flyout fragment");
                }).
                done(complete);
        }

        this.testSettingsFlyoutWithFragment["timeout"] = 20000;

        this.testSettingswithCommandProperty = function (complete) {
            // Get the settings flyout element from the DOM
            LiveUnit.LoggingCore.logComment("Attempt to to load the settings flyout fragment");
            WinJS.UI.SettingsFlyout.showSettings("CommandA", "SettingsFlyoutFragment.html");

            // Yield so the flyout can be shown
            WinJS.Promise.timeout().
                then(function () {
                    var settingsFlyoutElement = document.querySelector(".win-settingsflyout");
                    LiveUnit.Assert.isNotNull(settingsFlyoutElement, "loaded settings flyout element from fragment should not be null.");
                    var settingsControl = settingsFlyoutElement.winControl;
                    LiveUnit.Assert.isNotNull(settingsControl, "settings flyout control is invalid.");

                    LiveUnit.Assert.isTrue(settingsControl.settingsCommandId === "CommandA", "Expected right value in settingsCommandId");

                    // Verify the type of the flyout. Wide flyout width = 345px
                    var expectedFlyoutWidth = 345;
                    LiveUnit.Assert.areEqual(expectedFlyoutWidth, settingsFlyoutElement.clientWidth, "Not a narrow flyout");

                    // unload the fragment and destruct the control
                    settingsControl._dismiss();

                    // Yield so the flyout can dismissed
                    return WinJS.Promise.timeout(2000);
                }).
                then(function () {
                    var settingsFlyoutElement = document.getElementById("CommandA");
                    LiveUnit.Assert.isTrue(!settingsFlyoutElement, "failed to unload the settings flyout fragment");
                }).
                done(complete);
        }

        this.testSettingswithCommandProperty["timeout"] = 20000;

    }

    this.testSettingsFlyoutDispose = function () {
        var sf = new WinJS.UI.SettingsFlyout();
        LiveUnit.Assert.isTrue(sf.dispose);
        LiveUnit.Assert.isFalse(sf._disposed);

        // Double dispose sentinel
        var sentinel = document.createElement("div");
        sentinel.disposed = false;
        WinJS.Utilities.addClass(sentinel, "win-disposable");
        sf.element.appendChild(sentinel);
        sentinel.dispose = function () {
            if (sentinel.disposed) {
                LiveUnit.Assert.fail("Unexpected double dispose occured.");
            }
            sentinel.disposed = true;
        };

        sf.dispose();
        LiveUnit.Assert.isTrue(sentinel.disposed);
        LiveUnit.Assert.isTrue(sf._disposed);
        sf.dispose();
    }
    this.testSettingsFlyoutDispose["Description"] = "Unit test for dispose requirements.";

    this.testDisposeRemovesAppBarClickEatingDiv = function (complete) {
        WinJS.UI._Overlay._clickEatingAppBarDiv = null;
        WinJS.UI._Overlay._clickEatingFlyoutDiv = null;

        var flyout = new WinJS.UI.SettingsFlyout();
        document.body.appendChild(flyout.element);
        flyout.show();

        // ClickEater add/remove are high priority scheduler jobs, so we schedule an idle priority asserts
        flyout.addEventListener("aftershow", function () {
            var clickEater = document.querySelector("." + WinJS.UI._Overlay._clickEatingAppBarClass);
            LiveUnit.Assert.isTrue(clickEater);
            LiveUnit.Assert.areNotEqual("none", clickEater.style.display);

            flyout.dispose();

            WinJS.Utilities.Scheduler.schedule(function () {
                LiveUnit.Assert.areEqual("none", clickEater.style.display);
                document.body.removeChild(flyout.element);
                complete();
            }, WinJS.Utilities.Scheduler.Priority.idle);
        });
    };
};

// register the object as a test class by passing in the name
LiveUnit.registerTestClass("CorsicaTests.SettingsFlyoutTests");

<|endoftext|>


<commit_before>import { test } from 'qunit';
import moduleForAcceptance from 'kube-admin/tests/helpers/module-for-acceptance';
import page from '../pages/service-details';

moduleForAcceptance('Acceptance | service details');

test('visiting service details', function(assert) {
  const service = server.create('service'),
        url = `/namespaces/${service.metadata.namespace}/services/${service.metadata.name}`;
  visit('/services');
  click('[data-autoid^=name] a');

  andThen(function() {
    assert.equal(currentURL(), url);
  });
});

test('service details are shown', function(assert) {
  assert.expect(8);
  // Add a few extra services to make sure we test against the correct one
  server.createList('service', 3);
  let service = server.create('service');
  service.metadata.labels = { a: 1, b: 2 };
  service.spec.ports = [
    { name: 'a', port: 4200, targetPort: 4300, protocol: 'TCP' },
    { name: 'b', port: 4201, targetPort: 4301, protocol: 'TCP' }
  ];
  server.db.services.update(service.id, service);

  page.visit({ namespace: service.metadata.namespace, name: service.metadata.name });

  andThen(function() {
    assert.equal(page.details.name, service.metadata.name);
    assert.equal(page.details.labels, 'a = 1 b = 2');
    assert.equal(page.details.ports(0).name, 'a');
    assert.equal(page.details.ports(0).protocol, 'TCP');
    assert.equal(page.details.ports(0).port, 4200);
    assert.equal(page.details.ports(0).targetPort, 4300);
    assert.equal(page.details.ports(0).link, service.spec.clusterIP);
    assert.equal(page.details.ports(1).name, 'b');
  });
});

test('service details with no labels', function(assert) {
  assert.expect(1);
  let service = server.create('service');
  service.metadata.labels = {};
  server.db.services.update(service.id, service);

  page.visit({ namespace: service.metadata.namespace, name: service.metadata.name });

  andThen(function() {
    assert.equal(page.details.labels, 'No labels');
  });
});

test('service details with no ports', function(assert) {
  assert.expect(2);
  let service = server.create('service');
  service.spec.ports = [];
  server.db.services.update(service.id, service);

  page.visit({ namespace: service.metadata.namespace, name: service.metadata.name });

  andThen(function() {
    assert.equal(page.isPortsSectionHidden, true);
    assert.equal(page.details.ports().isHidden, true);
  });
});
<commit_msg>trivial: fixed test that was failing randomly<commit_after>import { test } from 'qunit';
import moduleForAcceptance from 'kube-admin/tests/helpers/module-for-acceptance';
import page from '../pages/service-details';
import { getMetadata } from 'kube-admin/mirage/factories/fakers';

moduleForAcceptance('Acceptance | service details');

test('visiting service details', function(assert) {
  let metadata = getMetadata('Service', 0, 'default'),
      service = server.create('service', { metadata }),
      url = `/namespaces/${service.metadata.namespace}/services/${service.metadata.name}`;
  visit('/services');
  click('[data-autoid^=name] a');

  andThen(function() {
    assert.equal(currentURL(), url);
  });
});

test('service details are shown', function(assert) {
  assert.expect(8);
  // Add a few extra services to make sure we test against the correct one
  server.createList('service', 3);
  let service = server.create('service');
  service.metadata.labels = { a: 1, b: 2 };
  service.spec.ports = [
    { name: 'a', port: 4200, targetPort: 4300, protocol: 'TCP' },
    { name: 'b', port: 4201, targetPort: 4301, protocol: 'TCP' }
  ];
  server.db.services.update(service.id, service);

  page.visit({ namespace: service.metadata.namespace, name: service.metadata.name });

  andThen(function() {
    assert.equal(page.details.name, service.metadata.name);
    assert.equal(page.details.labels, 'a = 1 b = 2');
    assert.equal(page.details.ports(0).name, 'a');
    assert.equal(page.details.ports(0).protocol, 'TCP');
    assert.equal(page.details.ports(0).port, 4200);
    assert.equal(page.details.ports(0).targetPort, 4300);
    assert.equal(page.details.ports(0).link, service.spec.clusterIP);
    assert.equal(page.details.ports(1).name, 'b');
  });
});

test('service details with no labels', function(assert) {
  assert.expect(1);
  let service = server.create('service');
  service.metadata.labels = {};
  server.db.services.update(service.id, service);

  page.visit({ namespace: service.metadata.namespace, name: service.metadata.name });

  andThen(function() {
    assert.equal(page.details.labels, 'No labels');
  });
});

test('service details with no ports', function(assert) {
  assert.expect(2);
  let service = server.create('service');
  service.spec.ports = [];
  server.db.services.update(service.id, service);

  page.visit({ namespace: service.metadata.namespace, name: service.metadata.name });

  andThen(function() {
    assert.equal(page.isPortsSectionHidden, true);
    assert.equal(page.details.ports().isHidden, true);
  });
});
<|endoftext|>


<commit_before>const expect = require('chai').expect
const config = require('../../config/config')['test']
require('../../config/database')(config)  // load the DB models
const mongoose = require('mongoose')
const User = mongoose.model('User')
const Post = mongoose.model('Post')
const Photo = mongoose.model('Photo')
const Album = mongoose.model('Album')
const postController = require('../../controllers/post-controller')

let samplePhoto = {
  fieldname: 'addPhotoToPost',
  originalname: 'testpic.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: 'Somewhere',
  filename: 'somefile',
  path: 'somewhere',
  size: 2000
}
let requestMock = {
  body: {},
  user: {},
  files: [],
  headers: {},
  session: {}
}
let responseMock = {
  locals: {},
  redirected: false,
  redirect: function () { this.redirected = true }
}

describe('Post', function () {
  let username = 'dog'
  let email = 'dog@abv.bg'
  let owner = 'OwnerMan'
  let userCategory = 'Dog'
  let reqUser = null
  const publicPost = 'publicvisible'
  const nonPublicPost = 'groupvisible'
  const shortContentErrorMsg = "Your post's content is too short! It must be longer than 3 characters."
  let newsfeedAlbumName = null

  beforeEach(function (done) {
    User.register(username, email, owner, 'dogpass123', userCategory).then(dog => {
      User.populate(dog, { path: 'category', model: 'Category' }).then(user => {
        reqUser = user
        newsfeedAlbumName = 'newsfeed-photos-' + user.id
        requestMock.user = reqUser
        done()
      })
    })
  })

  it('normal post, should be saved in the DB', function (done) {
    let postContent = 'This post is a test :@'
    requestMock.body = { publicPost: publicPost, content: postContent }
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the post is there and has the correct values
      Post.findOne({ content: postContent }).then(post => {
        expect(post).to.not.be.null
        expect(post.content).to.equal(postContent)
        expect(post.public).to.be.true
        expect(post.author.toString()).to.equal(reqUser.id)
        expect(post.category.toString()).to.equal(reqUser.category.id)
        done()
      })
    }, 50)
  })
  it('post with photo, photo should be saved in the DB', function (done) {
    let postContent = 'This post is a test :@'
    requestMock.body = { publicPost: publicPost, content: postContent }
    requestMock.files = [samplePhoto]
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the post is there and has the correct values
      Post.findOne({ content: postContent }).then(post => {
        expect(post).to.not.be.null
        // the post should have a photo in his array
        expect(post.photos).to.be.a('array')
        expect(post.photos.length).to.be.equal(1)
        Photo.findById(post.photos[0]).then(photo => {
          expect(photo).to.not.be.null
          expect(photo.author.toString()).to.be.equal(reqUser.id)
          expect(photo.post.toString()).to.be.equal(post.id)
          // the reqUser should have the photo saved in his photos array
          User.findById(reqUser.id).then(user => {
            expect(user.photos).to.not.be.null
            expect(user.photos).to.be.a('array')
            expect(user.photos.length).to.be.equal(1)
            done()
          })
        })
      })
    }, 60)
  })

  it('multiple posts, should be saved in the DB', function (done) {
    let postContent = 'These posts are a test :@'
    requestMock.body = { publicPost: publicPost, content: postContent }
    postController.addPost(requestMock, responseMock)
    postController.addPost(requestMock, responseMock)
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the posts are there and that they have the same content
      Post.find({ content: postContent }).then(posts => {
        expect(posts).to.be.a('array')
        expect(posts.length).to.be.equal(3)
        expect(posts[0].content).to.be.equal(posts[1].content)
        expect(posts[0].content).to.be.equal(posts[2].content)
        done()
      })
    }, 100)
  })

  it('normal post WITHOUT photo, newsfeed album should be created', function (done) {
    requestMock.body = { publicPost: 'tetste', content: 'teststes' }
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the album is created
      Album.findOne({}).then(album => {
        expect(album).to.not.be.null
        expect(album.author.toString()).to.be.equal(reqUser.id)
        expect(album.name).to.be.equal(newsfeedAlbumName)
        done()
      })
    }, 50)
  })

  it('normal post with photo, newsfeed album should be correct', function (done) {
    requestMock.body = { publicPost: 'tetste', content: 'teststes' }
    requestMock.files = [samplePhoto]
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the album is created
      Post.findOne({}).then(post => {
        let photoId = post.photos[0]
        Photo.findById(photoId).then(photo => {
          Album.findOne({}).then(album => {
            expect(album).to.not.be.null
            expect(album.author.toString()).to.be.equal(reqUser.id)
            expect(album.name).to.be.equal(newsfeedAlbumName)
            expect(album.photos).to.be.a('array')
            expect(album.photos).to.not.be.null
            expect(album.photos.length).to.be.equal(1)
            expect(photo.album.toString()).to.be.equal(album.id)
            done()
          })
        })
      })
    }, 50)
  })

  it('multiple posts, there should be only one newsfeed album', function (done) {
    // we hold only one newsfeed album for each user
    requestMock.body = { publicPost: 'SOMETING', content: 'teats' }
    // Add the posts with some slight delay, otherwise multiple albums get created due to the asynchrocity
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      postController.addPost(requestMock, responseMock)
      setTimeout(function () {
        postController.addPost(requestMock, responseMock)
        setTimeout(function () {
          Album.find({}).then(albums => {
            expect(albums).to.be.a('array')
            expect(albums.length).to.be.equal(1)
            let album = albums[0]
            expect(album).to.not.be.null
            expect(album.author.toString()).to.be.equal(reqUser.id)
            expect(album.name).to.be.equal(newsfeedAlbumName)
            done()
          })
        }, 50)
      }, 5)
    }, 5)
  })

  it('non-public post, should not be public', function (done) {
    let postContent = 'I am not public'
    requestMock.body = {
      publicPost: nonPublicPost,
      content: postContent
    }
    requestMock.files = [samplePhoto]
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      Post.findOne({ content: postContent }).then(post => {
        Photo.findById(post.photos[0]).then(photo => {
          expect(photo.public).to.be.false
          expect(post.public).to.not.be.null
          expect(post.public).to.be.false
          done()
        })
      })
    }, 50)
  })

  it('short post content, should not be created', function (done) {
    let postContent = 'sh'
    requestMock.body = {
      publicPost: publicPost,
      content: postContent
    }
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      Post.findOne({ content: postContent }).then(post => {
        // the post should not be created
        expect(post).to.be.null
        // our request must have an errorMessage and the failed post attached to it!
        expect(requestMock.session.errorMsg).to.not.be.null
        expect(requestMock.session.errorMsg).to.be.equal(shortContentErrorMsg)
        expect(requestMock.session.failedPost).to.not.be.null
        expect(requestMock.session.failedPost.content).to.be.equal(postContent)
        expect(responseMock.redirected).to.be.true
        done()
      })
    })
  })
  // delete all the created models
  afterEach(function (done) {
    Post.remove({}).then(() => {
      User.remove({}).then(() => {
        Album.remove({}).then(() => {
          Photo.remove({}).then(() => {
            done()
          })
        })
      })
    })
  })
})<commit_msg>Updated the post with short content test<commit_after>const expect = require('chai').expect
const config = require('../../config/config')['test']
require('../../config/database')(config)  // load the DB models
const mongoose = require('mongoose')
const User = mongoose.model('User')
const Post = mongoose.model('Post')
const Photo = mongoose.model('Photo')
const Album = mongoose.model('Album')
const postController = require('../../controllers/post-controller')

let samplePhoto = {
  fieldname: 'addPhotoToPost',
  originalname: 'testpic.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  destination: 'Somewhere',
  filename: 'somefile',
  path: 'somewhere',
  size: 2000
}
let requestMock = {
  body: {},
  user: {},
  files: [],
  headers: {},
  session: {}
}
let responseMock = {
  locals: {},
  redirected: false,
  redirect: function () { this.redirected = true }
}

describe('Post', function () {
  let username = 'dog'
  let email = 'dog@abv.bg'
  let owner = 'OwnerMan'
  let userCategory = 'Dog'
  let reqUser = null
  const publicPost = 'publicvisible'
  const nonPublicPost = 'groupvisible'
  const shortContentErrorMsg = "Your post's content is too short! It must be longer than 3 characters."
  let newsfeedAlbumName = null

  beforeEach(function (done) {
    User.register(username, email, owner, 'dogpass123', userCategory).then(dog => {
      User.populate(dog, { path: 'category', model: 'Category' }).then(user => {
        reqUser = user
        newsfeedAlbumName = 'newsfeed-photos-' + user.id
        requestMock.user = reqUser
        done()
      })
    })
  })

  it('normal post, should be saved in the DB', function (done) {
    let postContent = 'This post is a test :@'
    requestMock.body = { publicPost: publicPost, content: postContent }
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the post is there and has the correct values
      Post.findOne({ content: postContent }).then(post => {
        expect(post).to.not.be.null
        expect(post.content).to.equal(postContent)
        expect(post.public).to.be.true
        expect(post.author.toString()).to.equal(reqUser.id)
        expect(post.category.toString()).to.equal(reqUser.category.id)
        done()
      })
    }, 50)
  })
  it('post with photo, photo should be saved in the DB', function (done) {
    let postContent = 'This post is a test :@'
    requestMock.body = { publicPost: publicPost, content: postContent }
    requestMock.files = [samplePhoto]
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the post is there and has the correct values
      Post.findOne({ content: postContent }).then(post => {
        expect(post).to.not.be.null
        // the post should have a photo in his array
        expect(post.photos).to.be.a('array')
        expect(post.photos.length).to.be.equal(1)
        Photo.findById(post.photos[0]).then(photo => {
          expect(photo).to.not.be.null
          expect(photo.author.toString()).to.be.equal(reqUser.id)
          expect(photo.post.toString()).to.be.equal(post.id)
          // the reqUser should have the photo saved in his photos array
          User.findById(reqUser.id).then(user => {
            expect(user.photos).to.not.be.null
            expect(user.photos).to.be.a('array')
            expect(user.photos.length).to.be.equal(1)
            done()
          })
        })
      })
    }, 60)
  })

  it('multiple posts, should be saved in the DB', function (done) {
    let postContent = 'These posts are a test :@'
    requestMock.body = { publicPost: publicPost, content: postContent }
    postController.addPost(requestMock, responseMock)
    postController.addPost(requestMock, responseMock)
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the posts are there and that they have the same content
      Post.find({ content: postContent }).then(posts => {
        expect(posts).to.be.a('array')
        expect(posts.length).to.be.equal(3)
        expect(posts[0].content).to.be.equal(posts[1].content)
        expect(posts[0].content).to.be.equal(posts[2].content)
        done()
      })
    }, 100)
  })

  it('normal post WITHOUT photo, newsfeed album should be created', function (done) {
    requestMock.body = { publicPost: 'tetste', content: 'teststes' }
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the album is created
      Album.findOne({}).then(album => {
        expect(album).to.not.be.null
        expect(album.author.toString()).to.be.equal(reqUser.id)
        expect(album.name).to.be.equal(newsfeedAlbumName)
        done()
      })
    }, 50)
  })

  it('normal post with photo, newsfeed album should be correct', function (done) {
    requestMock.body = { publicPost: 'tetste', content: 'teststes' }
    requestMock.files = [samplePhoto]
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      // assert that the album is created
      Post.findOne({}).then(post => {
        let photoId = post.photos[0]
        Photo.findById(photoId).then(photo => {
          Album.findOne({}).then(album => {
            expect(album).to.not.be.null
            expect(album.author.toString()).to.be.equal(reqUser.id)
            expect(album.name).to.be.equal(newsfeedAlbumName)
            expect(album.photos).to.be.a('array')
            expect(album.photos).to.not.be.null
            expect(album.photos.length).to.be.equal(1)
            expect(photo.album.toString()).to.be.equal(album.id)
            done()
          })
        })
      })
    }, 50)
  })

  it('multiple posts, there should be only one newsfeed album', function (done) {
    // we hold only one newsfeed album for each user
    requestMock.body = { publicPost: 'SOMETING', content: 'teats' }
    // Add the posts with some slight delay, otherwise multiple albums get created due to the asynchrocity
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      postController.addPost(requestMock, responseMock)
      setTimeout(function () {
        postController.addPost(requestMock, responseMock)
        setTimeout(function () {
          Album.find({}).then(albums => {
            expect(albums).to.be.a('array')
            expect(albums.length).to.be.equal(1)
            let album = albums[0]
            expect(album).to.not.be.null
            expect(album.author.toString()).to.be.equal(reqUser.id)
            expect(album.name).to.be.equal(newsfeedAlbumName)
            done()
          })
        }, 50)
      }, 5)
    }, 5)
  })

  it('non-public post, should not be public', function (done) {
    let postContent = 'I am not public'
    requestMock.body = {
      publicPost: nonPublicPost,
      content: postContent
    }
    requestMock.files = [samplePhoto]
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      Post.findOne({ content: postContent }).then(post => {
        Photo.findById(post.photos[0]).then(photo => {
          expect(photo.public).to.be.false
          expect(post.public).to.not.be.null
          expect(post.public).to.be.false
          done()
        })
      })
    }, 50)
  })

  it('short post content, should not be created', function (done) {
    let postContent = 'sh'
    requestMock.body = {
      publicPost: publicPost,
      content: postContent
    }
    postController.addPost(requestMock, responseMock)
    setTimeout(function () {
      Post.findOne({ content: postContent }).then(post => {
        // the post should not be created
        expect(post).to.be.null
        // our request must have an errorMessage and the failed post attached to it!
        expect(requestMock.session.errorMsg).to.not.be.null
        expect(requestMock.session.errorMsg).to.be.equal(shortContentErrorMsg)
        expect(requestMock.session.failedPost).to.not.be.null
        expect(requestMock.session.failedPost.content).to.be.equal(postContent)
        expect(responseMock.redirected).to.be.true
        // Assure that a newsfeed album has not been created
        Album.findOne({}).then(album => {
          expect(album).to.be.null
          done()
        })
      })
    })
  })
  // delete all the created models
  afterEach(function (done) {
    Post.remove({}).then(() => {
      User.remove({}).then(() => {
        Album.remove({}).then(() => {
          Photo.remove({}).then(() => {
            done()
          })
        })
      })
    })
  })
})<|endoftext|>


<commit_before>import { expect } from "chai";
import sinon from "sinon";
import RxPlayer from "../../../src";
import {
  manifestInfos,
  URLs,
} from "../../contents/DASH_dynamic_SegmentTimeline";
import mockRequests from "../../utils/mock_requests.js";
import sleep from "../../utils/sleep.js";

describe("DASH live content (SegmentTimeline)", function () {
  let player;
  let fakeServer;

  beforeEach(() => {
    player = new RxPlayer();
    fakeServer = sinon.createFakeServer();
  });

  afterEach(() => {
    player.dispose();
    fakeServer.restore();
  });

  it("should fetch and parse the manifest", async function () {
    mockRequests(fakeServer, URLs);

    player.loadVideo({
      url: manifestInfos.url,
      transport: manifestInfos.transport,
    });

    expect(fakeServer.requests.length).to.equal(1);
    await sleep(10);
    fakeServer.respond();
    await sleep(10);

    const manifest = player.getManifest();
    expect(manifest).not.to.equal(null);
    expect(typeof manifest).to.equal("object");
    expect(manifest.getDuration()).to.equal(undefined);
    expect(manifest.transport)
      .to.equal(manifestInfos.transport);
    expect(typeof manifest.id).to.equal("string");
    expect(manifest.isLive).to.equal(true);
    expect(manifest.suggestedPresentationDelay).to.equal(10);
    expect(manifest.timeShiftBufferDepth)
      .to.equal(manifestInfos.timeShiftBufferDepth);
    expect(manifest.getUrl()).to.equal(manifestInfos.url);
    expect(manifest.availabilityStartTime)
      .to.equal(manifestInfos.availabilityStartTime);

    const adaptations = manifest.periods[0].adaptations;
    const firstPeriodAdaptationsInfos = manifestInfos.periods[0].adaptations;

    expect(adaptations.audio.length)
      .to.equal(firstPeriodAdaptationsInfos.audio.length);
    expect(adaptations.video.length)
      .to.equal(firstPeriodAdaptationsInfos.video.length);

    const firstAudioAdaptationInfos = firstPeriodAdaptationsInfos.audio[0];
    expect(!!adaptations.audio[0].isAudioDescription)
      .to.equal(firstAudioAdaptationInfos.isAudioDescription);
    expect(adaptations.audio[0].language)
      .to.equal(firstAudioAdaptationInfos.language);
    expect(adaptations.audio[0].normalizedLanguage)
      .to.equal(firstAudioAdaptationInfos.normalizedLanguage);
    expect(adaptations.audio[0].type).to.equal("audio");
    expect(typeof adaptations.audio[0].id).to.equal("string");
    expect(adaptations.audio[0].id).to.not.equal(adaptations.video[0].id);
    expect(adaptations.audio[0].representations.length)
      .to.equal(firstAudioAdaptationInfos.representations.length);
    expect(adaptations.audio[0].getAvailableBitrates())
      .to.eql(firstAudioAdaptationInfos.representations
        .map(representation => representation.bitrate)
      );

    const firstVideoAdaptationInfos = firstPeriodAdaptationsInfos.video[0];
    expect(adaptations.video[0].type).to.equal("video");
    expect(adaptations.video[0].getAvailableBitrates())
      .to.eql(firstVideoAdaptationInfos.representations
        .map(representation => representation.bitrate)
      );

    const audioRepresentation = adaptations.audio[0].representations[0];
    const audioRepresentationInfos = firstAudioAdaptationInfos
      .representations[0];
    expect(audioRepresentation.bitrate)
      .to.equal(audioRepresentationInfos.bitrate);
    expect(audioRepresentation.codec)
      .to.equal(audioRepresentationInfos.codec);
    expect(typeof audioRepresentation.id).to.equal("string");
    expect(audioRepresentation.mimeType)
      .to.equal(audioRepresentationInfos.mimeType);
    expect(typeof audioRepresentation.index).to.equal("object");

    const audioRepresentationIndex = audioRepresentation.index;
    const audioRepresentationIndexInfos = audioRepresentationInfos.index;
    const initAudioSegment = audioRepresentationIndex.getInitSegment();
    expect(typeof initAudioSegment.id).to.equal("string");
    expect(initAudioSegment.mediaURL).to
      .equal(audioRepresentationIndexInfos.init.mediaURL);

    const nextAudioSegment1 = audioRepresentationIndex
      .getSegments(1527507762, 5);
    expect(nextAudioSegment1.length).to.equal(1);
    expect(nextAudioSegment1[0].duration)
      .to.equal(audioRepresentationIndexInfos.segments[0].duration);
    expect(typeof nextAudioSegment1[0].id).to.equal("string");
    expect(nextAudioSegment1[0].isInit).to.equal(false);
    expect(nextAudioSegment1[0].time)
      .to.equal(audioRepresentationIndexInfos.segments[0].time);
    expect(nextAudioSegment1[0].timescale)
      .to.equal(audioRepresentationIndexInfos.segments[0].timescale);
    expect(nextAudioSegment1[0].mediaURL)
      .to.equal(audioRepresentationIndexInfos.segments[0].mediaURL);

    const nextAudioSegment2 = audioRepresentationIndex
      .getSegments(1527507762, 11);
    expect(nextAudioSegment2.length).to.equal(2);
    expect(nextAudioSegment2[1].duration)
      .to.equal(audioRepresentationIndexInfos.segments[1].duration);
    expect(typeof nextAudioSegment2[1].id).to.equal("string");
    expect(nextAudioSegment2[1].isInit).to.equal(false);
    expect(nextAudioSegment2[1].time)
      .to.equal(audioRepresentationIndexInfos.segments[1].time);
    expect(nextAudioSegment2[1].timescale)
      .to.equal(audioRepresentationIndexInfos.segments[1].timescale);
    expect(nextAudioSegment2[1].mediaURL)
      .to.equal(audioRepresentationIndexInfos.segments[1].mediaURL);

    expect(audioRepresentationIndex.getSegments(1527507762, 294).length)
      .to.equal(49);
    expect(audioRepresentationIndex.getSegments(1527507762, 295).length)
      .to.equal(50);
    expect(
      audioRepresentationIndex.getSegments(1527507762, 300000000000).length
    ).to.equal(50);

    const videoRepresentation = adaptations.video[0].representations[0];
    const videoRepresentationInfos = firstVideoAdaptationInfos
      .representations[0];

    expect(videoRepresentation.bitrate)
      .to.equal(videoRepresentationInfos.bitrate);
    expect(videoRepresentation.codec)
      .to.equal(videoRepresentationInfos.codec);
    expect(typeof videoRepresentation.id).to.equal("string");
    expect(videoRepresentation.height)
      .to.equal(videoRepresentationInfos.height);
    expect(videoRepresentation.width)
      .to.equal(videoRepresentationInfos.width);
    expect(videoRepresentation.mimeType)
      .to.equal(videoRepresentationInfos.mimeType);
    expect(typeof videoRepresentation.index)
      .to.equal("object");

    const videoRepresentationIndex = videoRepresentation.index;
    const videoRepresentationIndexInfos = videoRepresentationInfos.index;

    const initVideoSegment = videoRepresentationIndex.getInitSegment();
    expect(typeof initVideoSegment.id).to.equal("string");
    expect(initVideoSegment.mediaURL)
      .to.equal(videoRepresentationIndexInfos.init.mediaURL);

    const nextVideoSegment1 = videoRepresentationIndex
      .getSegments(1527507762, 5);
    expect(nextVideoSegment1.length).to.equal(1);
    expect(nextVideoSegment1[0].duration)
      .to.equal(videoRepresentationIndexInfos.segments[0].duration);
    expect(typeof nextVideoSegment1[0].id).to.equal("string");
    expect(nextVideoSegment1[0].isInit).to.equal(false);
    expect(nextVideoSegment1[0].time)
      .to.equal(videoRepresentationIndexInfos.segments[0].time);
    expect(nextVideoSegment1[0].timescale)
      .to.equal(videoRepresentationIndexInfos.segments[0].timescale);
    expect(nextVideoSegment1[0].mediaURL)
      .to.equal(videoRepresentationIndexInfos.segments[0].mediaURL);

    const nextVideoSegment2 = videoRepresentationIndex
      .getSegments(1527507762, 11);
    expect(nextVideoSegment2.length).to.equal(2);
    expect(nextVideoSegment2[1].duration)
      .to.equal(videoRepresentationIndexInfos.segments[1].duration);
    expect(typeof nextVideoSegment2[1].id).to.equal("string");
    expect(nextVideoSegment2[1].isInit).to.equal(false);
    expect(nextVideoSegment2[1].time)
      .to.equal(videoRepresentationIndexInfos.segments[1].time);
    expect(nextVideoSegment2[1].timescale)
      .to.equal(videoRepresentationIndexInfos.segments[1].timescale);
    expect(nextVideoSegment2[1].mediaURL)
      .to.equal(videoRepresentationIndexInfos.segments[1].mediaURL);

    expect(videoRepresentationIndex.getSegments(1527507762, 294).length)
      .to.equal(49);
    expect(videoRepresentationIndex.getSegments(1527507762, 295).length)
      .to.equal(50);
    expect(
      videoRepresentationIndex.getSegments(1527507762, 300000000000).length
    ).to.equal(50);

    expect(fakeServer.requests.length).to.be.at.least(3);
    const requestsDone = fakeServer.requests.map(r => r.url);
    expect(requestsDone)
      .to.include(videoRepresentationIndexInfos.init.mediaURL);
    expect(requestsDone)
      .to.include(audioRepresentationIndexInfos.init.mediaURL);
  });

  it("should list the right bitrates", async function () {
    mockRequests(fakeServer, URLs);

    player.loadVideo({
      url: manifestInfos.url,
      transport: manifestInfos.transport,
    });

    await sleep(5);
    fakeServer.respond();
    await sleep(5);

    expect(player.getAvailableAudioBitrates()).to.eql([48000]);
    expect(player.getAvailableVideoBitrates()).to.eql([300000]);
  });

  describe("getAvailableAudioTracks", () => {
    it("should list the right audio languages", async function () {
      mockRequests(fakeServer, URLs);

      player.loadVideo({
        url: manifestInfos.url,
        transport: manifestInfos.transport,
      });
      expect(player.getAvailableAudioTracks()).to.eql([]);

      await sleep(1);
      expect(player.getAvailableAudioTracks()).to.eql([]);
      fakeServer.respond();
      await sleep(1);

      const audioTracks = player.getAvailableAudioTracks();

      const currentPeriod = player.getManifest().periods[0];
      const audioAdaptations = currentPeriod.adaptations.audio;
      expect(audioTracks.length).to
        .equal(audioAdaptations ? audioAdaptations.length : 0);

      if (audioAdaptations) {
        for (let i = 0; i < audioAdaptations.length; i++) {
          const adaptation = audioAdaptations[i];

          for (let j = 0; j < audioTracks.length; j++) {
            let found = false;
            const audioTrack = audioTracks[j];
            if (audioTrack.id === adaptation.id) {
              found = true;
              expect(audioTrack.language).to.equal(adaptation.language || "");
              expect(audioTrack.normalized).to
                .equal(adaptation.normalizedLanguage || "");
              expect(audioTrack.audioDescription)
                .to.equal(!!adaptation.isAudioDescription);

              const activeAudioTrack = player.getAudioTrack();
              expect(audioTrack.active).to
                .equal(activeAudioTrack ?
                  activeAudioTrack.id === audioTrack.id : false);
            }
            expect(found).to.equal(true);
          }
        }
      }
    });
  });

  describe("getAvailableTextTracks", () => {
    it("should list the right text languages", async function () {
      mockRequests(fakeServer, URLs);

      player.loadVideo({
        url: manifestInfos.url,
        transport: manifestInfos.transport,
      });
      expect(player.getAvailableTextTracks()).to.eql([]);

      await sleep(1);
      expect(player.getAvailableTextTracks()).to.eql([]);
      fakeServer.respond();
      await sleep(1);

      const textTracks = player.getAvailableTextTracks();

      const currentPeriod = player.getManifest().periods[0];
      const textAdaptations = currentPeriod.adaptations.text;
      expect(textTracks.length).to
        .equal(textAdaptations ? textAdaptations.length : 0);

      if (textAdaptations) {
        for (let i = 0; i < textAdaptations.length; i++) {
          const adaptation = textAdaptations[i];

          for (let j = 0; j < textTracks.length; j++) {
            let found = false;
            const textTrack = textTracks[j];
            if (textTrack.id === adaptation.id) {
              found = true;
              expect(textTrack.language).to.equal(adaptation.language || "");
              expect(textTrack.normalized).to
                .equal(adaptation.normalizedLanguage || "");
              expect(textTrack.closedCaption)
                .to.equal(!!adaptation.isClosedCaption);

              const activeTextTrack = player.getTextTrack();
              expect(textTrack.active).to
                .equal(activeTextTrack ?
                  activeTextTrack.id === textTrack.id : false);
            }
            expect(found).to.equal(true);
          }
        }
      }
    });
  });

  describe("getAvailableVideoTracks", () => {
    it("should list the right video tracks", async function () {
      mockRequests(fakeServer, URLs);

      player.loadVideo({
        url: manifestInfos.url,
        transport:manifestInfos.transport,
      });
      expect(player.getAvailableVideoTracks()).to.eql([]);

      await sleep(1);
      expect(player.getAvailableVideoTracks()).to.eql([]);
      fakeServer.respond();
      await sleep(1);

      const videoTracks = player.getAvailableVideoTracks();

      const currentPeriod = player.getManifest().periods[0];
      const videoAdaptations = currentPeriod.adaptations.video;
      expect(videoTracks.length).to
        .equal(videoAdaptations ? videoAdaptations.length : 0);

      if (videoAdaptations) {
        for (let i = 0; i < videoAdaptations.length; i++) {
          const adaptation = videoAdaptations[i];

          for (let j = 0; j < videoTracks.length; j++) {
            let found = false;
            const videoTrack = videoTracks[j];
            if (videoTrack.id === adaptation.id) {
              found = true;

              for (
                let representationIndex = 0;
                representationIndex < videoTrack.representations.length;
                representationIndex++
              ) {
                const reprTrack = videoTrack
                  .representations[representationIndex];
                const representation =
                  adaptation.getRepresentation(reprTrack.id);
                expect(reprTrack.bitrate).to.equal(representation.bitrate);
                expect(reprTrack.frameRate).to
                  .equal(representation.frameRate);
                expect(reprTrack.width).to.equal(representation.width);
                expect(reprTrack.height).to.equal(representation.height);
              }

              const activeVideoTrack = player.getVideoTrack();
              expect(videoTrack.active).to
                .equal(activeVideoTrack ?
                  activeVideoTrack.id === videoTrack.id : false);
            }
            expect(found).to.equal(true);
          }
        }
      }
    });
  });
});
<commit_msg>tests: raise live contents tests tolerance for appveyor<commit_after>import { expect } from "chai";
import sinon from "sinon";
import RxPlayer from "../../../src";
import {
  manifestInfos,
  URLs,
} from "../../contents/DASH_dynamic_SegmentTimeline";
import mockRequests from "../../utils/mock_requests.js";
import sleep from "../../utils/sleep.js";

describe("DASH live content (SegmentTimeline)", function () {
  let player;
  let fakeServer;

  beforeEach(() => {
    player = new RxPlayer();
    fakeServer = sinon.createFakeServer();
  });

  afterEach(() => {
    player.dispose();
    fakeServer.restore();
  });

  it("should fetch and parse the manifest", async function () {
    mockRequests(fakeServer, URLs);

    player.loadVideo({
      url: manifestInfos.url,
      transport: manifestInfos.transport,
    });

    expect(fakeServer.requests.length).to.equal(1);
    await sleep(10);
    fakeServer.respond();
    await sleep(10);

    const manifest = player.getManifest();
    expect(manifest).not.to.equal(null);
    expect(typeof manifest).to.equal("object");
    expect(manifest.getDuration()).to.equal(undefined);
    expect(manifest.transport)
      .to.equal(manifestInfos.transport);
    expect(typeof manifest.id).to.equal("string");
    expect(manifest.isLive).to.equal(true);
    expect(manifest.suggestedPresentationDelay).to.equal(10);
    expect(manifest.timeShiftBufferDepth)
      .to.equal(manifestInfos.timeShiftBufferDepth);
    expect(manifest.getUrl()).to.equal(manifestInfos.url);
    expect(manifest.availabilityStartTime)
      .to.equal(manifestInfos.availabilityStartTime);

    const adaptations = manifest.periods[0].adaptations;
    const firstPeriodAdaptationsInfos = manifestInfos.periods[0].adaptations;

    expect(adaptations.audio.length)
      .to.equal(firstPeriodAdaptationsInfos.audio.length);
    expect(adaptations.video.length)
      .to.equal(firstPeriodAdaptationsInfos.video.length);

    const firstAudioAdaptationInfos = firstPeriodAdaptationsInfos.audio[0];
    expect(!!adaptations.audio[0].isAudioDescription)
      .to.equal(firstAudioAdaptationInfos.isAudioDescription);
    expect(adaptations.audio[0].language)
      .to.equal(firstAudioAdaptationInfos.language);
    expect(adaptations.audio[0].normalizedLanguage)
      .to.equal(firstAudioAdaptationInfos.normalizedLanguage);
    expect(adaptations.audio[0].type).to.equal("audio");
    expect(typeof adaptations.audio[0].id).to.equal("string");
    expect(adaptations.audio[0].id).to.not.equal(adaptations.video[0].id);
    expect(adaptations.audio[0].representations.length)
      .to.equal(firstAudioAdaptationInfos.representations.length);
    expect(adaptations.audio[0].getAvailableBitrates())
      .to.eql(firstAudioAdaptationInfos.representations
        .map(representation => representation.bitrate)
      );

    const firstVideoAdaptationInfos = firstPeriodAdaptationsInfos.video[0];
    expect(adaptations.video[0].type).to.equal("video");
    expect(adaptations.video[0].getAvailableBitrates())
      .to.eql(firstVideoAdaptationInfos.representations
        .map(representation => representation.bitrate)
      );

    const audioRepresentation = adaptations.audio[0].representations[0];
    const audioRepresentationInfos = firstAudioAdaptationInfos
      .representations[0];
    expect(audioRepresentation.bitrate)
      .to.equal(audioRepresentationInfos.bitrate);
    expect(audioRepresentation.codec)
      .to.equal(audioRepresentationInfos.codec);
    expect(typeof audioRepresentation.id).to.equal("string");
    expect(audioRepresentation.mimeType)
      .to.equal(audioRepresentationInfos.mimeType);
    expect(typeof audioRepresentation.index).to.equal("object");

    const audioRepresentationIndex = audioRepresentation.index;
    const audioRepresentationIndexInfos = audioRepresentationInfos.index;
    const initAudioSegment = audioRepresentationIndex.getInitSegment();
    expect(typeof initAudioSegment.id).to.equal("string");
    expect(initAudioSegment.mediaURL).to
      .equal(audioRepresentationIndexInfos.init.mediaURL);

    const nextAudioSegment1 = audioRepresentationIndex
      .getSegments(1527507762, 5);
    expect(nextAudioSegment1.length).to.equal(1);
    expect(nextAudioSegment1[0].duration)
      .to.equal(audioRepresentationIndexInfos.segments[0].duration);
    expect(typeof nextAudioSegment1[0].id).to.equal("string");
    expect(nextAudioSegment1[0].isInit).to.equal(false);
    expect(nextAudioSegment1[0].time)
      .to.equal(audioRepresentationIndexInfos.segments[0].time);
    expect(nextAudioSegment1[0].timescale)
      .to.equal(audioRepresentationIndexInfos.segments[0].timescale);
    expect(nextAudioSegment1[0].mediaURL)
      .to.equal(audioRepresentationIndexInfos.segments[0].mediaURL);

    const nextAudioSegment2 = audioRepresentationIndex
      .getSegments(1527507762, 11);
    expect(nextAudioSegment2.length).to.equal(2);
    expect(nextAudioSegment2[1].duration)
      .to.equal(audioRepresentationIndexInfos.segments[1].duration);
    expect(typeof nextAudioSegment2[1].id).to.equal("string");
    expect(nextAudioSegment2[1].isInit).to.equal(false);
    expect(nextAudioSegment2[1].time)
      .to.equal(audioRepresentationIndexInfos.segments[1].time);
    expect(nextAudioSegment2[1].timescale)
      .to.equal(audioRepresentationIndexInfos.segments[1].timescale);
    expect(nextAudioSegment2[1].mediaURL)
      .to.equal(audioRepresentationIndexInfos.segments[1].mediaURL);

    expect(audioRepresentationIndex.getSegments(1527507762, 294).length)
      .to.equal(49);
    expect(audioRepresentationIndex.getSegments(1527507762, 295).length)
      .to.equal(50);
    expect(
      audioRepresentationIndex.getSegments(1527507762, 300000000000).length
    ).to.equal(50);

    const videoRepresentation = adaptations.video[0].representations[0];
    const videoRepresentationInfos = firstVideoAdaptationInfos
      .representations[0];

    expect(videoRepresentation.bitrate)
      .to.equal(videoRepresentationInfos.bitrate);
    expect(videoRepresentation.codec)
      .to.equal(videoRepresentationInfos.codec);
    expect(typeof videoRepresentation.id).to.equal("string");
    expect(videoRepresentation.height)
      .to.equal(videoRepresentationInfos.height);
    expect(videoRepresentation.width)
      .to.equal(videoRepresentationInfos.width);
    expect(videoRepresentation.mimeType)
      .to.equal(videoRepresentationInfos.mimeType);
    expect(typeof videoRepresentation.index)
      .to.equal("object");

    const videoRepresentationIndex = videoRepresentation.index;
    const videoRepresentationIndexInfos = videoRepresentationInfos.index;

    const initVideoSegment = videoRepresentationIndex.getInitSegment();
    expect(typeof initVideoSegment.id).to.equal("string");
    expect(initVideoSegment.mediaURL)
      .to.equal(videoRepresentationIndexInfos.init.mediaURL);

    const nextVideoSegment1 = videoRepresentationIndex
      .getSegments(1527507762, 5);
    expect(nextVideoSegment1.length).to.equal(1);
    expect(nextVideoSegment1[0].duration)
      .to.equal(videoRepresentationIndexInfos.segments[0].duration);
    expect(typeof nextVideoSegment1[0].id).to.equal("string");
    expect(nextVideoSegment1[0].isInit).to.equal(false);
    expect(nextVideoSegment1[0].time)
      .to.equal(videoRepresentationIndexInfos.segments[0].time);
    expect(nextVideoSegment1[0].timescale)
      .to.equal(videoRepresentationIndexInfos.segments[0].timescale);
    expect(nextVideoSegment1[0].mediaURL)
      .to.equal(videoRepresentationIndexInfos.segments[0].mediaURL);

    const nextVideoSegment2 = videoRepresentationIndex
      .getSegments(1527507762, 11);
    expect(nextVideoSegment2.length).to.equal(2);
    expect(nextVideoSegment2[1].duration)
      .to.equal(videoRepresentationIndexInfos.segments[1].duration);
    expect(typeof nextVideoSegment2[1].id).to.equal("string");
    expect(nextVideoSegment2[1].isInit).to.equal(false);
    expect(nextVideoSegment2[1].time)
      .to.equal(videoRepresentationIndexInfos.segments[1].time);
    expect(nextVideoSegment2[1].timescale)
      .to.equal(videoRepresentationIndexInfos.segments[1].timescale);
    expect(nextVideoSegment2[1].mediaURL)
      .to.equal(videoRepresentationIndexInfos.segments[1].mediaURL);

    expect(videoRepresentationIndex.getSegments(1527507762, 294).length)
      .to.equal(49);
    expect(videoRepresentationIndex.getSegments(1527507762, 295).length)
      .to.equal(50);
    expect(
      videoRepresentationIndex.getSegments(1527507762, 300000000000).length
    ).to.equal(50);

    expect(fakeServer.requests.length).to.be.at.least(3);
    const requestsDone = fakeServer.requests.map(r => r.url);
    expect(requestsDone)
      .to.include(videoRepresentationIndexInfos.init.mediaURL);
    expect(requestsDone)
      .to.include(audioRepresentationIndexInfos.init.mediaURL);
  });

  it("should list the right bitrates", async function () {
    mockRequests(fakeServer, URLs);

    player.loadVideo({
      url: manifestInfos.url,
      transport: manifestInfos.transport,
    });

    await sleep(5);
    fakeServer.respond();
    await sleep(5);

    expect(player.getAvailableAudioBitrates()).to.eql([48000]);
    expect(player.getAvailableVideoBitrates()).to.eql([300000]);
  });

  describe("getAvailableAudioTracks", () => {
    it("should list the right audio languages", async function () {
      mockRequests(fakeServer, URLs);

      player.loadVideo({
        url: manifestInfos.url,
        transport: manifestInfos.transport,
      });
      expect(player.getAvailableAudioTracks()).to.eql([]);

      await sleep(5);
      expect(player.getAvailableAudioTracks()).to.eql([]);
      fakeServer.respond();
      await sleep(5);

      const audioTracks = player.getAvailableAudioTracks();

      const currentPeriod = player.getManifest().periods[0];
      const audioAdaptations = currentPeriod.adaptations.audio;
      expect(audioTracks.length).to
        .equal(audioAdaptations ? audioAdaptations.length : 0);

      if (audioAdaptations) {
        for (let i = 0; i < audioAdaptations.length; i++) {
          const adaptation = audioAdaptations[i];

          for (let j = 0; j < audioTracks.length; j++) {
            let found = false;
            const audioTrack = audioTracks[j];
            if (audioTrack.id === adaptation.id) {
              found = true;
              expect(audioTrack.language).to.equal(adaptation.language || "");
              expect(audioTrack.normalized).to
                .equal(adaptation.normalizedLanguage || "");
              expect(audioTrack.audioDescription)
                .to.equal(!!adaptation.isAudioDescription);

              const activeAudioTrack = player.getAudioTrack();
              expect(audioTrack.active).to
                .equal(activeAudioTrack ?
                  activeAudioTrack.id === audioTrack.id : false);
            }
            expect(found).to.equal(true);
          }
        }
      }
    });
  });

  describe("getAvailableTextTracks", () => {
    it("should list the right text languages", async function () {
      mockRequests(fakeServer, URLs);

      player.loadVideo({
        url: manifestInfos.url,
        transport: manifestInfos.transport,
      });
      expect(player.getAvailableTextTracks()).to.eql([]);

      await sleep(5);
      expect(player.getAvailableTextTracks()).to.eql([]);
      fakeServer.respond();
      await sleep(5);

      const textTracks = player.getAvailableTextTracks();

      const currentPeriod = player.getManifest().periods[0];
      const textAdaptations = currentPeriod.adaptations.text;
      expect(textTracks.length).to
        .equal(textAdaptations ? textAdaptations.length : 0);

      if (textAdaptations) {
        for (let i = 0; i < textAdaptations.length; i++) {
          const adaptation = textAdaptations[i];

          for (let j = 0; j < textTracks.length; j++) {
            let found = false;
            const textTrack = textTracks[j];
            if (textTrack.id === adaptation.id) {
              found = true;
              expect(textTrack.language).to.equal(adaptation.language || "");
              expect(textTrack.normalized).to
                .equal(adaptation.normalizedLanguage || "");
              expect(textTrack.closedCaption)
                .to.equal(!!adaptation.isClosedCaption);

              const activeTextTrack = player.getTextTrack();
              expect(textTrack.active).to
                .equal(activeTextTrack ?
                  activeTextTrack.id === textTrack.id : false);
            }
            expect(found).to.equal(true);
          }
        }
      }
    });
  });

  describe("getAvailableVideoTracks", () => {
    it("should list the right video tracks", async function () {
      mockRequests(fakeServer, URLs);

      player.loadVideo({
        url: manifestInfos.url,
        transport:manifestInfos.transport,
      });
      expect(player.getAvailableVideoTracks()).to.eql([]);

      await sleep(1);
      expect(player.getAvailableVideoTracks()).to.eql([]);
      fakeServer.respond();
      await sleep(1);

      const videoTracks = player.getAvailableVideoTracks();

      const currentPeriod = player.getManifest().periods[0];
      const videoAdaptations = currentPeriod.adaptations.video;
      expect(videoTracks.length).to
        .equal(videoAdaptations ? videoAdaptations.length : 0);

      if (videoAdaptations) {
        for (let i = 0; i < videoAdaptations.length; i++) {
          const adaptation = videoAdaptations[i];

          for (let j = 0; j < videoTracks.length; j++) {
            let found = false;
            const videoTrack = videoTracks[j];
            if (videoTrack.id === adaptation.id) {
              found = true;

              for (
                let representationIndex = 0;
                representationIndex < videoTrack.representations.length;
                representationIndex++
              ) {
                const reprTrack = videoTrack
                  .representations[representationIndex];
                const representation =
                  adaptation.getRepresentation(reprTrack.id);
                expect(reprTrack.bitrate).to.equal(representation.bitrate);
                expect(reprTrack.frameRate).to
                  .equal(representation.frameRate);
                expect(reprTrack.width).to.equal(representation.width);
                expect(reprTrack.height).to.equal(representation.height);
              }

              const activeVideoTrack = player.getVideoTrack();
              expect(videoTrack.active).to
                .equal(activeVideoTrack ?
                  activeVideoTrack.id === videoTrack.id : false);
            }
            expect(found).to.equal(true);
          }
        }
      }
    });
  });
});
<|endoftext|>