当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript common.beforeEach函数代码示例

本文整理汇总了TypeScript中test/lib/common.beforeEach函数的典型用法代码示例。如果您正苦于以下问题:TypeScript beforeEach函数的具体用法?TypeScript beforeEach怎么用?TypeScript beforeEach使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了beforeEach函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: describe

describe('timeSrv', function() {
  var ctx = new helpers.ServiceTestContext();
  var _dashboard: any = {
    time: {from: 'now-6h', to: 'now'},
  };

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.services'));
  beforeEach(ctx.createService('timeSrv'));

  beforeEach(function() {
    ctx.service.init(_dashboard);
  });

  describe('timeRange', function() {
    it('should return unparsed when parse is false', function() {
      ctx.service.setTime({from: 'now', to: 'now-1h' });
      var time = ctx.service.timeRange();
      expect(time.raw.from).to.be('now');
      expect(time.raw.to).to.be('now-1h');
    });

    it('should return parsed when parse is true', function() {
      ctx.service.setTime({from: 'now', to: 'now-1h' });
      var time = ctx.service.timeRange();
      expect(moment.isMoment(time.from)).to.be(true);
      expect(moment.isMoment(time.to)).to.be(true);
    });
  });

  describe('init time from url', function() {
    it('should handle relative times', function() {
      ctx.$location.search({from: 'now-2d', to: 'now'});
      ctx.service.init(_dashboard);
      var time = ctx.service.timeRange();
      expect(time.raw.from).to.be('now-2d');
      expect(time.raw.to).to.be('now');
    });

    it('should handle formated dates', function() {
      ctx.$location.search({from: '20140410T052010', to: '20140520T031022'});
      ctx.service.init(_dashboard);
      var time = ctx.service.timeRange(true);
      expect(time.from.valueOf()).to.equal(new Date("2014-04-10T05:20:10Z").getTime());
      expect(time.to.valueOf()).to.equal(new Date("2014-05-20T03:10:22Z").getTime());
    });

    it('should handle formated dates without time', function() {
      ctx.$location.search({from: '20140410', to: '20140520'});
      ctx.service.init(_dashboard);
      var time = ctx.service.timeRange(true);
      expect(time.from.valueOf()).to.equal(new Date("2014-04-10T00:00:00Z").getTime());
      expect(time.to.valueOf()).to.equal(new Date("2014-05-20T00:00:00Z").getTime());
    });

    it('should handle epochs', function() {
      ctx.$location.search({from: '1410337646373', to: '1410337665699'});
      ctx.service.init(_dashboard);
      var time = ctx.service.timeRange(true);
      expect(time.from.valueOf()).to.equal(1410337646373);
      expect(time.to.valueOf()).to.equal(1410337665699);
    });

    it('should handle bad dates', function() {
      ctx.$location.search({from: '20151126T00010%3C%2Fp%3E%3Cspan%20class', to: 'now'});
      _dashboard.time.from = 'now-6h';
      ctx.service.init(_dashboard);
      expect(ctx.service.time.from).to.equal('now-6h');
      expect(ctx.service.time.to).to.equal('now');
    });
  });

  describe('setTime', function() {
    it('should return disable refresh if refresh is disabled for any range', function() {
      _dashboard.refresh = false;

      ctx.service.setTime({from: '2011-01-01', to: '2015-01-01' });
      expect(_dashboard.refresh).to.be(false);
    });

    it('should restore refresh for absolute time range', function() {
      _dashboard.refresh = '30s';

      ctx.service.setTime({from: '2011-01-01', to: '2015-01-01' });
      expect(_dashboard.refresh).to.be('30s');
    });

    it('should restore refresh after relative time range is set', function() {
      _dashboard.refresh = '10s';
      ctx.service.setTime({from: moment([2011,1,1]), to: moment([2015,1,1])});
      expect(_dashboard.refresh).to.be(false);
      ctx.service.setTime({from: '2011-01-01', to: 'now' });
      expect(_dashboard.refresh).to.be('10s');
    });

    it('should keep refresh after relative time range is changed and now delay exists', function() {
      _dashboard.refresh = '10s';
      ctx.service.setTime({from: 'now-1h', to: 'now-10s' });
      expect(_dashboard.refresh).to.be('10s');
    });
//.........这里部分代码省略.........
开发者ID:Sensetif,项目名称:grafana,代码行数:101,代码来源:time_srv_specs.ts

示例2: describe

  describe('single group by with alias pattern', function() {
    var result;

    beforeEach(function() {
      targets = [{
        refId: 'A',
        metrics: [{type: 'count', id: '1'}],
        alias: '{{term @host}} {{metric}} and {{not_exist}} {{@host}}',
        bucketAggs: [
        {type: 'terms', field: '@host', id: '2'},
        {type: 'date_histogram', field: '@timestamp', id: '3'}
        ],
      }];
      response =  {
        responses: [{
          aggregations: {
            "2": {
              buckets: [
              {
                "3": {
                  buckets: [
                  {doc_count: 1, key: 1000},
                  {doc_count: 3, key: 2000}
                  ]
                },
                doc_count: 4,
                key: 'server1',
              },
              {
                "3": {
                  buckets: [
                  {doc_count: 2, key: 1000},
                  {doc_count: 8, key: 2000}
                  ]
                },
                doc_count: 10,
                key: 'server2',
              },
              {
                "3": {
                  buckets: [
                  {doc_count: 2, key: 1000},
                  {doc_count: 8, key: 2000}
                  ]
                },
                doc_count: 10,
                key: 0,
              },
              ]
            }
          }
        }]
      };

      result = new ElasticResponse(targets, response).getTimeSeries();
    });

    it('should return 2 series', function() {
      expect(result.data.length).to.be(3);
      expect(result.data[0].datapoints.length).to.be(2);
      expect(result.data[0].target).to.be('server1 Count and {{not_exist}} server1');
      expect(result.data[1].target).to.be('server2 Count and {{not_exist}} server2');
      expect(result.data[2].target).to.be('0 Count and {{not_exist}} 0');
    });
  });
开发者ID:PaulMest,项目名称:grafana,代码行数:65,代码来源:elastic_response_specs.ts

示例3: describe

describe('unsavedChangesSrv', function() {
  var _dashboardSrv;
  var _contextSrvStub = { isEditor: true };
  var _rootScope;
  var _location;
  var _timeout;
  var _window;
  var tracker;
  var dash;
  var scope;

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.services'));
  beforeEach(
    angularMocks.module(function($provide) {
      $provide.value('contextSrv', _contextSrvStub);
      $provide.value('$window', {});
    })
  );

  beforeEach(
    angularMocks.inject(function($location, $rootScope, dashboardSrv, $timeout, $window) {
      _dashboardSrv = dashboardSrv;
      _rootScope = $rootScope;
      _location = $location;
      _timeout = $timeout;
      _window = $window;
    })
  );

  beforeEach(function() {
    dash = _dashboardSrv.create({
      refresh: false,
      panels: [{ test: 'asd', legend: {} }],
      rows: [
        {
          panels: [{ test: 'asd', legend: {} }],
        },
      ],
    });
    scope = _rootScope.$new();
    scope.appEvent = sinon.spy();
    scope.onAppEvent = sinon.spy();

    tracker = new Tracker(dash, scope, undefined, _location, _window, _timeout, contextSrv, _rootScope);
  });

  it('No changes should not have changes', function() {
    expect(tracker.hasChanges()).to.be(false);
  });

  it('Simple change should be registered', function() {
    dash.property = 'google';
    expect(tracker.hasChanges()).to.be(true);
  });

  it('Should ignore a lot of changes', function() {
    dash.time = { from: '1h' };
    dash.refresh = true;
    dash.schemaVersion = 10;
    expect(tracker.hasChanges()).to.be(false);
  });

  it.skip('Should ignore row collapse change', function() {
    dash.rows[0].collapse = true;
    expect(tracker.hasChanges()).to.be(false);
  });

  it('Should ignore panel legend changes', function() {
    dash.panels[0].legend.sortDesc = true;
    dash.panels[0].legend.sort = 'avg';
    expect(tracker.hasChanges()).to.be(false);
  });

  it.skip('Should ignore panel repeats', function() {
    dash.rows[0].panels.push({ repeatPanelId: 10 });
    expect(tracker.hasChanges()).to.be(false);
  });

  it.skip('Should ignore row repeats', function() {
    dash.addEmptyRow();
    dash.rows[1].repeatRowId = 10;
    expect(tracker.hasChanges()).to.be(false);
  });
});
开发者ID:GPegel,项目名称:grafana,代码行数:85,代码来源:unsaved_changes_srv_specs.ts

示例4: describe

describe('ElasticQueryBuilder', function() {
  var builder;

  beforeEach(function() {
    builder = new ElasticQueryBuilder({timeField: '@timestamp'});
  });

  it('with defaults', function() {
    var query = builder.build({
      metrics: [{type: 'Count', id: '0'}],
      timeField: '@timestamp',
      bucketAggs: [{type: 'date_histogram', field: '@timestamp', id: '1'}],
    });

    expect(query.query.filtered.filter.bool.must[0].range["@timestamp"].gte).to.be("$timeFrom");
    expect(query.aggs["1"].date_histogram.extended_bounds.min).to.be("$timeFrom");
  });

  it('with raw query', function() {
    var query = builder.build({
      rawQuery: '{"query": "$lucene_query"}',
    });

    expect(query.query).to.be("$lucene_query");
  });

  it('with multiple bucket aggs', function() {
    var query = builder.build({
      metrics: [{type: 'count', id: '1'}],
      timeField: '@timestamp',
      bucketAggs: [
        {type: 'terms', field: '@host', id: '2'},
        {type: 'date_histogram', field: '@timestamp', id: '3'}
      ],
    });

    expect(query.aggs["2"].terms.field).to.be("@host");
    expect(query.aggs["2"].aggs["3"].date_histogram.field).to.be("@timestamp");
  });

  it('with select field', function() {
    var query = builder.build({
      metrics: [{type: 'avg', field: '@value', id: '1'}],
      bucketAggs: [{type: 'date_histogram', field: '@timestamp', id: '2'}],
    }, 100, 1000);

    var aggs = query.aggs["2"].aggs;
    expect(aggs["1"].avg.field).to.be("@value");
  });

  it('with term agg and order by metric agg', function() {
    var query = builder.build({
      metrics: [
        {type: 'count', id: '1'},
        {type: 'avg', field: '@value', id: '5'}
      ],
      bucketAggs: [
        {type: 'terms', field: '@host', settings: {size: 5, order: 'asc', orderBy: '5'}, id: '2' },
        {type: 'date_histogram', field: '@timestamp', id: '3'}
      ],
    }, 100, 1000);

    var firstLevel = query.aggs["2"];
    var secondLevel = firstLevel.aggs["3"];

    expect(firstLevel.aggs["5"].avg.field).to.be("@value");
    expect(secondLevel.aggs["5"].avg.field).to.be("@value");
  });

  it('with metric percentiles', function() {
    var query = builder.build({
      metrics: [
        {
          id: '1',
          type: 'percentiles',
          field: '@load_time',
          settings: {
            percents: [1,2,3,4]
          }
        }
      ],
      bucketAggs: [
        {type: 'date_histogram', field: '@timestamp', id: '3'}
      ],
    }, 100, 1000);

    var firstLevel = query.aggs["3"];

    expect(firstLevel.aggs["1"].percentiles.field).to.be("@load_time");
    expect(firstLevel.aggs["1"].percentiles.percents).to.eql([1,2,3,4]);
  });

  it('with filters aggs', function() {
    var query = builder.build({
      metrics: [{type: 'count', id: '1'}],
      timeField: '@timestamp',
      bucketAggs: [
        {
          id: '2',
          type: 'filters',
//.........这里部分代码省略.........
开发者ID:aather,项目名称:abyss,代码行数:101,代码来源:query_builder_specs.ts

示例5: describe

  describe('When performing CloudWatch query', function() {
    var requestParams;

    var query = {
      range: { from: 'now-1h', to: 'now' },
      targets: [
        {
          region: 'us-east-1',
          namespace: 'AWS/EC2',
          metricName: 'CPUUtilization',
          dimensions: {
            InstanceId: 'i-12345678'
          },
          statistics: ['Average'],
          period: 300
        }
      ]
    };

    var response = {
      Datapoints: [
        {
          Average: 1,
          Timestamp: 'Wed Dec 31 1969 16:00:00 GMT-0800 (PST)'
        },
        {
          Average: 2,
          Timestamp: 'Wed Dec 31 1969 16:05:00 GMT-0800 (PST)'
        },
        {
          Average: 5,
          Timestamp: 'Wed Dec 31 1969 16:15:00 GMT-0800 (PST)'
        }
      ],
      Label: 'CPUUtilization'
    };

    beforeEach(function() {
      ctx.backendSrv.datasourceRequest = function(params) {
        requestParams = params;
        return ctx.$q.when({data: response});
      };
    });

    it('should generate the correct query', function(done) {
      ctx.ds.query(query).then(function() {
        var params = requestParams.data.parameters;
        expect(params.namespace).to.be(query.targets[0].namespace);
        expect(params.metricName).to.be(query.targets[0].metricName);
        expect(params.dimensions[0].Name).to.be(Object.keys(query.targets[0].dimensions)[0]);
        expect(params.dimensions[0].Value).to.be(query.targets[0].dimensions[Object.keys(query.targets[0].dimensions)[0]]);
        expect(params.statistics).to.eql(query.targets[0].statistics);
        expect(params.period).to.be(query.targets[0].period);
        done();
      });
      ctx.$rootScope.$apply();
    });

    it('should generate the correct query with interval variable', function(done) {
      ctx.templateSrv.data = {
        period: '10m'
      };

      var query = {
        range: { from: 'now-1h', to: 'now' },
        targets: [
          {
            region: 'us-east-1',
            namespace: 'AWS/EC2',
            metricName: 'CPUUtilization',
            dimensions: {
              InstanceId: 'i-12345678'
            },
            statistics: ['Average'],
            period: '[[period]]'
          }
        ]
      };

      ctx.ds.query(query).then(function() {
        var params = requestParams.data.parameters;
        expect(params.period).to.be(600);
        done();
      });
      ctx.$rootScope.$apply();
    });

    it('should return series list', function(done) {
      ctx.ds.query(query).then(function(result) {
        expect(result.data[0].target).to.be('CPUUtilization_Average');
        expect(result.data[0].datapoints[0][0]).to.be(response.Datapoints[0]['Average']);
        done();
      });
      ctx.$rootScope.$apply();
    });

    it('should return null for missing data point', function(done) {
      ctx.ds.query(query).then(function(result) {
        expect(result.data[0].datapoints[2][0]).to.be(null);
        done();
//.........这里部分代码省略.........
开发者ID:Sensetif,项目名称:grafana,代码行数:101,代码来源:datasource_specs.ts

示例6: describe

describe('DashImportCtrl', function() {
  var ctx: any = {};
  var backendSrv = {
    search: sinon.stub().returns(Promise.resolve([])),
    get: sinon.stub()
  };

  beforeEach(angularMocks.module('grafana.core'));

  beforeEach(angularMocks.inject(($rootScope, $controller, $q) => {
    ctx.$q = $q;
    ctx.scope = $rootScope.$new();
    ctx.ctrl = $controller(DashImportCtrl, {
      $scope: ctx.scope,
      backendSrv: backendSrv,
    });
  }));

  describe('when uploading json', function() {
    beforeEach(function() {
      config.datasources = {
        ds: {
          type: 'test-db',
        }
      };

      ctx.ctrl.onUpload({
        '__inputs': [
          {name: 'ds', pluginId: 'test-db', type: 'datasource', pluginName: 'Test DB'}
        ]
      });
    });

    it('should build input model', function() {
      expect(ctx.ctrl.inputs.length).to.eql(1);
      expect(ctx.ctrl.inputs[0].name).to.eql('ds');
      expect(ctx.ctrl.inputs[0].info).to.eql('Select a Test DB data source');
    });

    it('should set inputValid to false', function() {
      expect(ctx.ctrl.inputsValid).to.eql(false);
    });
  });

  describe('when specifing grafana.com url', function() {
    beforeEach(function() {
      ctx.ctrl.gnetUrl = 'http://grafana.com/dashboards/123';
      // setup api mock
      backendSrv.get = sinon.spy(() => {
        return Promise.resolve({
          json: {}
        });
      });
      return ctx.ctrl.checkGnetDashboard();
    });

    it('should call gnet api with correct dashboard id', function() {
      expect(backendSrv.get.getCall(0).args[0]).to.eql('api/gnet/dashboards/123');
    });
  });

  describe('when specifing dashbord id', function() {
    beforeEach(function() {
      ctx.ctrl.gnetUrl = '2342';
      // setup api mock
      backendSrv.get = sinon.spy(() => {
        return Promise.resolve({
          json: {}
        });
      });
      return ctx.ctrl.checkGnetDashboard();
    });

    it('should call gnet api with correct dashboard id', function() {
      expect(backendSrv.get.getCall(0).args[0]).to.eql('api/gnet/dashboards/2342');
    });
  });

});
开发者ID:PaulMest,项目名称:grafana,代码行数:79,代码来源:dash_import_ctrl_specs.ts

示例7: describe

describe('ElasticDatasource', function() {
  var ctx = new helpers.ServiceTestContext();
  var instanceSettings: any = {jsonData: {}};

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.services'));
  beforeEach(ctx.providePhase(['templateSrv', 'backendSrv', 'timeSrv']));

  beforeEach(angularMocks.inject(function($q, $rootScope, $httpBackend, $injector) {
    ctx.$q = $q;
    ctx.$httpBackend =  $httpBackend;
    ctx.$rootScope = $rootScope;
    ctx.$injector = $injector;
    $httpBackend.when('GET', /\.html$/).respond('');
  }));

  function createDatasource(instanceSettings) {
    instanceSettings.jsonData = instanceSettings.jsonData || {};
    ctx.ds = ctx.$injector.instantiate(ElasticDatasource, {instanceSettings: instanceSettings});
  }

  describe('When testing datasource with index pattern', function() {
    beforeEach(function() {
      createDatasource({url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: {interval: 'Daily', esVersion: '2'}});
    });

    it('should translate index pattern to current day', function() {
      var requestOptions;
      ctx.backendSrv.datasourceRequest = function(options) {
        requestOptions = options;
        return ctx.$q.when({data: {}});
      };

      ctx.ds.testDatasource();
      ctx.$rootScope.$apply();

      var today = moment.utc().format("YYYY.MM.DD");
      expect(requestOptions.url).to.be("http://es.com/asd-" + today + '/_mapping');
    });
  });

  describe('When issueing metric query with interval pattern', function() {
    var requestOptions, parts, header;

    beforeEach(function() {
      createDatasource({url: 'http://es.com', index: '[asd-]YYYY.MM.DD', jsonData: {interval: 'Daily', esVersion: '2'}});

      ctx.backendSrv.datasourceRequest = function(options) {
        requestOptions = options;
        return ctx.$q.when({data: {responses: []}});
      };

      ctx.ds.query({
        range: {
          from: moment.utc([2015, 4, 30, 10]),
          to: moment.utc([2015, 5, 1, 10])
        },
        targets: [{ bucketAggs: [], metrics: [], query: 'escape\\:test' }]
      });

      ctx.$rootScope.$apply();

      parts = requestOptions.data.split('\n');
      header = angular.fromJson(parts[0]);
    });

    it('should translate index pattern to current day', function() {
      expect(header.index).to.eql(['asd-2015.05.30', 'asd-2015.05.31', 'asd-2015.06.01']);
    });

    it('should json escape lucene query', function() {
      var body = angular.fromJson(parts[1]);
      expect(body.query.bool.filter[1].query_string.query).to.be('escape\\:test');
    });
  });

  describe('When issueing document query', function() {
    var requestOptions, parts, header;

    beforeEach(function() {
      createDatasource({url: 'http://es.com', index: 'test', jsonData: {esVersion: '2'}});

      ctx.backendSrv.datasourceRequest = function(options) {
        requestOptions = options;
        return ctx.$q.when({data: {responses: []}});
      };

      ctx.ds.query({
        range: { from: moment([2015, 4, 30, 10]), to: moment([2015, 5, 1, 10]) },
        targets: [{ bucketAggs: [], metrics: [{type: 'raw_document'}], query: 'test' }]
      });

      ctx.$rootScope.$apply();
      parts = requestOptions.data.split('\n');
      header = angular.fromJson(parts[0]);
    });

    it('should set search type to query_then_fetch', function() {
      expect(header.search_type).to.eql('query_then_fetch');
    });
//.........这里部分代码省略.........
开发者ID:martinwalsh,项目名称:grafana,代码行数:101,代码来源:datasource_specs.ts

示例8: describe

describe('GraphiteQueryCtrl', function() {
  var ctx = new helpers.ControllerTestContext();

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.controllers'));
  beforeEach(angularMocks.module('grafana.services'));

  beforeEach(ctx.providePhase());
  beforeEach(ctx.createControllerPhase('GraphiteQueryCtrl'));

  beforeEach(function() {
    ctx.scope.target = {target: 'aliasByNode(scaleToSeconds(test.prod.*,1),2)'};

    ctx.scope.datasource = ctx.datasource;
    ctx.scope.datasource.metricFindQuery = sinon.stub().returns(ctx.$q.when([]));
  });

  describe('init', function() {
    beforeEach(function() {
      ctx.scope.init();
      ctx.scope.$digest();
    });

    it('should validate metric key exists', function() {
      expect(ctx.scope.datasource.metricFindQuery.getCall(0).args[0]).to.be('test.prod.*');
    });

    it('should delete last segment if no metrics are found', function() {
      expect(ctx.scope.segments[2].value).to.be('select metric');
    });

    it('should parse expression and build function model', function() {
      expect(ctx.scope.functions.length).to.be(2);
    });
  });

  describe('when adding function', function() {
    beforeEach(function() {
      ctx.scope.target.target = 'test.prod.*.count';
      ctx.scope.datasource.metricFindQuery.returns(ctx.$q.when([{expandable: false}]));
      ctx.scope.init();
      ctx.scope.$digest();

      ctx.scope.$parent = { get_data: sinon.spy() };
      ctx.scope.addFunction(gfunc.getFuncDef('aliasByNode'));
    });

    it('should add function with correct node number', function() {
      expect(ctx.scope.functions[0].params[0]).to.be(2);
    });

    it('should update target', function() {
      expect(ctx.scope.target.target).to.be('aliasByNode(test.prod.*.count, 2)');
    });

    it('should call get_data', function() {
      expect(ctx.scope.$parent.get_data.called).to.be(true);
    });
  });

  describe('when adding function before any metric segment', function() {
    beforeEach(function() {
      ctx.scope.target.target = '';
      ctx.scope.datasource.metricFindQuery.returns(ctx.$q.when([{expandable: true}]));
      ctx.scope.init();
      ctx.scope.$digest();

      ctx.scope.$parent = { get_data: sinon.spy() };
      ctx.scope.addFunction(gfunc.getFuncDef('asPercent'));
    });

    it('should add function and remove select metric link', function() {
      expect(ctx.scope.segments.length).to.be(0);
    });
  });

  describe('when initalizing target without metric expression and only function', function() {
    beforeEach(function() {
      ctx.scope.target.target = 'asPercent(#A, #B)';
      ctx.scope.datasource.metricFindQuery.returns(ctx.$q.when([]));
      ctx.scope.init();
      ctx.scope.$digest();
      ctx.scope.$parent = { get_data: sinon.spy() };
    });

    it('should not add select metric segment', function() {
      expect(ctx.scope.segments.length).to.be(0);
    });

    it('should add both series refs as params', function() {
      expect(ctx.scope.functions[0].params.length).to.be(2);
    });

  });

  describe('when initializing a target with single param func using variable', function() {
    beforeEach(function() {
      ctx.scope.target.target = 'movingAverage(prod.count, $var)';
      ctx.scope.datasource.metricFindQuery.returns(ctx.$q.when([]));
      ctx.scope.init();
//.........这里部分代码省略.........
开发者ID:3r1ccc,项目名称:grafana,代码行数:101,代码来源:query_ctrl_specs.ts

示例9: describe

describe('PrometheusDatasource', function() {
  var ctx = new helpers.ServiceTestContext();
  var instanceSettings = {
    url: 'proxied',
    directUrl: 'direct',
    user: 'test',
    password: 'mupp',
    jsonData: { httpMethod: 'GET' },
  };

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.services'));
  beforeEach(ctx.providePhase(['timeSrv']));

  beforeEach(
    angularMocks.inject(function($q, $rootScope, $httpBackend, $injector) {
      ctx.$q = $q;
      ctx.$httpBackend = $httpBackend;
      ctx.$rootScope = $rootScope;
      ctx.ds = $injector.instantiate(PrometheusDatasource, {
        instanceSettings: instanceSettings,
      });
      $httpBackend.when('GET', /\.html$/).respond('');
    })
  );
  describe('When querying prometheus with one target using query editor target spec', function() {
    var results;
    var query = {
      range: { from: time({ seconds: 63 }), to: time({ seconds: 183 }) },
      targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
      interval: '60s',
    };
    // Interval alignment with step
    var urlExpected =
      'proxied/api/v1/query_range?query=' + encodeURIComponent('test{job="testjob"}') + '&start=60&end=240&step=60';
    var response = {
      status: 'success',
      data: {
        resultType: 'matrix',
        result: [
          {
            metric: { __name__: 'test', job: 'testjob' },
            values: [[60, '3846']],
          },
        ],
      },
    };
    beforeEach(function() {
      ctx.$httpBackend.expect('GET', urlExpected).respond(response);
      ctx.ds.query(query).then(function(data) {
        results = data;
      });
      ctx.$httpBackend.flush();
    });
    it('should generate the correct query', function() {
      ctx.$httpBackend.verifyNoOutstandingExpectation();
    });
    it('should return series list', function() {
      expect(results.data.length).to.be(1);
      expect(results.data[0].target).to.be('test{job="testjob"}');
    });
  });
  describe('When querying prometheus with one target which return multiple series', function() {
    var results;
    var start = 60;
    var end = 360;
    var step = 60;
    var urlExpected =
      'proxied/api/v1/query_range?query=' +
      encodeURIComponent('test{job="testjob"}') +
      '&start=' +
      start +
      '&end=' +
      end +
      '&step=' +
      step;
    var query = {
      range: { from: time({ seconds: start }), to: time({ seconds: end }) },
      targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
      interval: '60s',
    };
    var response = {
      status: 'success',
      data: {
        resultType: 'matrix',
        result: [
          {
            metric: { __name__: 'test', job: 'testjob', series: 'series 1' },
            values: [[start + step * 1, '3846'], [start + step * 3, '3847'], [end - step * 1, '3848']],
          },
          {
            metric: { __name__: 'test', job: 'testjob', series: 'series 2' },
            values: [[start + step * 2, '4846']],
          },
        ],
      },
    };
    beforeEach(function() {
      ctx.$httpBackend.expect('GET', urlExpected).respond(response);
      ctx.ds.query(query).then(function(data) {
//.........这里部分代码省略.........
开发者ID:fangjianfeng,项目名称:grafana,代码行数:101,代码来源:datasource_specs.ts

示例10: describe

describe('VariableSrv', function() {
  var ctx = new helpers.ControllerTestContext();

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.controllers'));
  beforeEach(angularMocks.module('grafana.services'));

  beforeEach(ctx.providePhase(['datasourceSrv', 'timeSrv', 'templateSrv', '$location']));
  beforeEach(angularMocks.inject(($rootScope, $q, $location, $injector) => {
    ctx.$q = $q;
    ctx.$rootScope = $rootScope;
    ctx.$location = $location;
    ctx.variableSrv = $injector.get('variableSrv');
    ctx.variableSrv.init({
      templating: {list: []},
      events: new Emitter(),
    });
    ctx.$rootScope.$digest();
  }));

  function describeUpdateVariable(desc, fn) {
    describe(desc, function() {
      var scenario: any = {};
      scenario.setup = function(setupFn) {
        scenario.setupFn = setupFn;
      };

      beforeEach(function() {
        scenario.setupFn();
        var ds: any = {};
        ds.metricFindQuery = sinon.stub().returns(ctx.$q.when(scenario.queryResult));
        ctx.datasourceSrv.get = sinon.stub().returns(ctx.$q.when(ds));
        ctx.datasourceSrv.getMetricSources = sinon.stub().returns(scenario.metricSources);


        scenario.variable = ctx.variableSrv.addVariable(scenario.variableModel);
        ctx.variableSrv.updateOptions(scenario.variable);
        ctx.$rootScope.$digest();
      });

      fn(scenario);
    });
  }

  describeUpdateVariable('interval variable without auto', scenario => {
    scenario.setup(() => {
      scenario.variableModel = {type: 'interval', query: '1s,2h,5h,1d', name: 'test'};
    });

    it('should update options array', () => {
      expect(scenario.variable.options.length).to.be(4);
      expect(scenario.variable.options[0].text).to.be('1s');
      expect(scenario.variable.options[0].value).to.be('1s');
    });
  });

  //
  // Interval variable update
  //
  describeUpdateVariable('interval variable with auto', scenario => {
    scenario.setup(() => {
      scenario.variableModel = {type: 'interval', query: '1s,2h,5h,1d', name: 'test', auto: true, auto_count: 10 };

      var range = {
        from: moment(new Date()).subtract(7, 'days').toDate(),
        to: new Date()
      };

      ctx.timeSrv.timeRange = sinon.stub().returns(range);
      ctx.templateSrv.setGrafanaVariable = sinon.spy();
    });

    it('should update options array', function() {
      expect(scenario.variable.options.length).to.be(5);
      expect(scenario.variable.options[0].text).to.be('auto');
      expect(scenario.variable.options[0].value).to.be('$__auto_interval');
    });

    it('should set $__auto_interval', function() {
      var call = ctx.templateSrv.setGrafanaVariable.getCall(0);
      expect(call.args[0]).to.be('$__auto_interval');
      expect(call.args[1]).to.be('12h');
    });
  });

  //
  // Query variable update
  //
  describeUpdateVariable('query variable with empty current object and refresh', function(scenario) {
    scenario.setup(function() {
      scenario.variableModel = {type: 'query', query: '', name: 'test', current: {}};
      scenario.queryResult = [{text: 'backend1'}, {text: 'backend2'}];
    });

    it('should set current value to first option', function() {
      expect(scenario.variable.options.length).to.be(2);
      expect(scenario.variable.current.value).to.be('backend1');
    });
  });

//.........这里部分代码省略.........
开发者ID:Sensetif,项目名称:grafana,代码行数:101,代码来源:variable_srv_specs.ts


注:本文中的test/lib/common.beforeEach函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。