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


TypeScript ServiceTestContext.createService方法代码示例

本文整理汇总了TypeScript中test/specs/helpers.ServiceTestContext.createService方法的典型用法代码示例。如果您正苦于以下问题:TypeScript ServiceTestContext.createService方法的具体用法?TypeScript ServiceTestContext.createService怎么用?TypeScript ServiceTestContext.createService使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在test/specs/helpers.ServiceTestContext的用法示例。


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

示例1: describe

describe('historySrv', function() {
  var ctx = new helpers.ServiceTestContext();

  var versionsResponse = versions();
  var restoreResponse = restore;

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.services'));
  beforeEach(
    angularMocks.inject(function($httpBackend) {
      ctx.$httpBackend = $httpBackend;
      $httpBackend.whenRoute('GET', 'api/dashboards/id/:id/versions').respond(versionsResponse);
      $httpBackend
        .whenRoute('POST', 'api/dashboards/id/:id/restore')
        .respond(function(method, url, data, headers, params) {
          const parsedData = JSON.parse(data);
          return [200, restoreResponse(parsedData.version)];
        });
    })
  );

  beforeEach(ctx.createService('historySrv'));

  function wrapPromise(ctx, angularPromise) {
    return new Promise((resolve, reject) => {
      angularPromise.then(resolve, reject);
      ctx.$httpBackend.flush();
    });
  }

  describe('getHistoryList', function() {
    it('should return a versions array for the given dashboard id', function() {
      return wrapPromise(
        ctx,
        ctx.service.getHistoryList({ id: 1 }).then(function(versions) {
          expect(versions).to.eql(versionsResponse);
        })
      );
    });

    it('should return an empty array when not given an id', function() {
      return wrapPromise(
        ctx,
        ctx.service.getHistoryList({}).then(function(versions) {
          expect(versions).to.eql([]);
        })
      );
    });

    it('should return an empty array when not given a dashboard', function() {
      return wrapPromise(
        ctx,
        ctx.service.getHistoryList().then(function(versions) {
          expect(versions).to.eql([]);
        })
      );
    });
  });

  describe('restoreDashboard', function() {
    it('should return a success response given valid parameters', function() {
      let version = 6;
      return wrapPromise(
        ctx,
        ctx.service.restoreDashboard({ id: 1 }, version).then(function(response) {
          expect(response).to.eql(restoreResponse(version));
        })
      );
    });

    it('should return an empty object when not given an id', function() {
      return wrapPromise(
        ctx,
        ctx.service.restoreDashboard({}, 6).then(function(response) {
          expect(response).to.eql({});
        })
      );
    });
  });
});
开发者ID:GPegel,项目名称:grafana,代码行数:80,代码来源:history_srv_specs.ts

示例2: describe

describe('ElasticDatasource', function() {
  var ctx = new helpers.ServiceTestContext();

  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.services'));
  beforeEach(ctx.providePhase(['templateSrv', 'backendSrv']));
  beforeEach(ctx.createService('ElasticDatasource'));
  beforeEach(function() {
    ctx.ds = new ctx.service({jsonData: {}});
  });

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

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

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

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

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

    beforeEach(function() {
      ctx.ds = new ctx.service({
        url: 'http://es.com',
        index: '[asd-]YYYY.MM.DD',
        jsonData: { interval: 'Daily' }
      });

      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: [], 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.filtered.query.query_string.query).to.be('escape\\:test');
    });
  });

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

    beforeEach(function() {
      ctx.ds = new ctx.service({url: 'http://es.com', index: 'test', jsonData: {}});

      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');
    });

    it('should set size', function() {
//.........这里部分代码省略.........
开发者ID:eddawley,项目名称:grafana,代码行数:101,代码来源:datasource_specs.ts

示例3: describe

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

  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 formatted 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 formatted 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');
//.........这里部分代码省略.........
开发者ID:kwarunek,项目名称:grafana,代码行数:101,代码来源:time_srv_specs.ts

示例4: describe

describe('CloudWatchDatasource', function() {
  var ctx = new helpers.ServiceTestContext();

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

  beforeEach(ctx.providePhase(['templateSrv', 'backendSrv']));
  beforeEach(ctx.createService('CloudWatchDatasource'));

  beforeEach(function() {
    ctx.ds = new ctx.service({
      jsonData: {
        defaultRegion: 'us-east-1',
        access: 'proxy'
      }
    });
  });

  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 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();
      });
      ctx.$rootScope.$apply();
    });
  });

  function describeMetricFindQuery(query, func) {
    describe('metricFindQuery ' + query, () => {
      let scenario: any = {};
      scenario.setup = setupCallback => {
        beforeEach(() => {
//.........这里部分代码省略.........
开发者ID:eddawley,项目名称:grafana,代码行数:101,代码来源:datasource_specs.ts

示例5: beforeEach

 beforeEach(() => {
   ctx.createService('annotationsSrv');
 });
开发者ID:PaulMest,项目名称:grafana,代码行数:3,代码来源:annotations_srv_specs.ts

示例6: describe

describe('PrometheusDatasource', function() {

  var ctx = new helpers.ServiceTestContext();
  beforeEach(angularMocks.module('grafana.core'));
  beforeEach(angularMocks.module('grafana.services'));
  beforeEach(ctx.createService('PrometheusDatasource'));
  beforeEach(function() {
    ctx.ds = new ctx.service({ url: 'proxied', directUrl: 'direct', user: 'test', password: 'mupp' });
  });

  describe('When querying prometheus with one target using query editor target spec', function() {
    var results;
    var urlExpected = 'proxied/api/v1/query_range?query=' +
                      encodeURIComponent('test{job="testjob"}') +
                      '&start=1443438675&end=1443460275&step=60';
    var query = {
      range: { from: moment(1443438674760), to: moment(1443460274760) },
      targets: [{ expr: 'test{job="testjob"}' }],
      interval: '60s'
    };
    var response = {
      status: "success",
      data: {
        resultType: "matrix",
        result: [{
          metric: {"__name__": "test", job: "testjob"},
          values: [[1443454528, "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 performing metricFindQuery', function() {
    var results;
    var response;
    it('label_values(resource) should generate label search query', function() {
      response = {
        status: "success",
        data: ["value1", "value2", "value3"]
      };
      ctx.$httpBackend.expect('GET', 'proxied/api/v1/label/resource/values').respond(response);
      ctx.ds.metricFindQuery('label_values(resource)').then(function(data) { results = data; });
      ctx.$httpBackend.flush();
      ctx.$rootScope.$apply();
      expect(results.length).to.be(3);
    });
    it('label_values(metric, resource) should generate series query', function() {
      response = {
        status: "success",
        data: [
          {__name__: "metric", resource: "value1"},
          {__name__: "metric", resource: "value2"},
          {__name__: "metric", resource: "value3"}
        ]
      };
      ctx.$httpBackend.expect('GET', 'proxied/api/v1/series?match[]=metric').respond(response);
      ctx.ds.metricFindQuery('label_values(metric, resource)').then(function(data) { results = data; });
      ctx.$httpBackend.flush();
      ctx.$rootScope.$apply();
      expect(results.length).to.be(3);
    });
    it('metrics(metric.*) should generate metric name query', function() {
      response = {
        status: "success",
        data: ["metric1","metric2","metric3","nomatch"]
      };
      ctx.$httpBackend.expect('GET', 'proxied/api/v1/label/__name__/values').respond(response);
      ctx.ds.metricFindQuery('metrics(metric.*)').then(function(data) { results = data; });
      ctx.$httpBackend.flush();
      ctx.$rootScope.$apply();
      expect(results.length).to.be(3);
    });
  });
});
开发者ID:eddawley,项目名称:grafana,代码行数:85,代码来源:datasource_specs.ts

示例7: describe

describe('graphiteDatasource', function() {
  var ctx = new helpers.ServiceTestContext();

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

  beforeEach(ctx.providePhase(['backendSrv']));
  beforeEach(ctx.createService('GraphiteDatasource'));

  beforeEach(function() {
    ctx.ds = new ctx.service({ url: [''] });
  });

  describe('When querying influxdb with one target using query editor target spec', function() {
    var query = {
    rangeRaw: { from: 'now-1h', to: 'now' },
    targets: [{ target: 'prod1.count' }, {target: 'prod2.count'}],
    maxDataPoints: 500,
    };

    var results;
    var requestOptions;

    beforeEach(function() {
      ctx.backendSrv.datasourceRequest = function(options) {
        requestOptions = options;
        return ctx.$q.when({data: [{ target: 'prod1.count', datapoints: [[10, 1], [12,1]] }]});
      };

      ctx.ds.query(query).then(function(data) { results = data; });
      ctx.$rootScope.$apply();
    });

    it('should generate the correct query', function() {
      expect(requestOptions.url).to.be('/render');
    });

    it('should query correctly', function() {
      var params = requestOptions.data.split('&');
      expect(params).to.contain('target=prod1.count');
      expect(params).to.contain('target=prod2.count');
      expect(params).to.contain('from=-1h');
      expect(params).to.contain('until=now');
    });

    it('should exclude undefined params', function() {
      var params = requestOptions.data.split('&');
      expect(params).to.not.contain('cacheTimeout=undefined');
    });

    it('should return series list', function() {
      expect(results.data.length).to.be(1);
      expect(results.data[0].target).to.be('prod1.count');
    });

    it('should convert to millisecond resolution', function() {
      expect(results.data[0].datapoints[0][0]).to.be(10);
    });

  });

  describe('building graphite params', function() {
    it('should return empty array if no targets', function() {
      var results = ctx.ds.buildGraphiteParams({
        targets: [{}]
      });
      expect(results.length).to.be(0);
    });

    it('should uri escape targets', function() {
      var results = ctx.ds.buildGraphiteParams({
      targets: [{target: 'prod1.{test,test2}'}, {target: 'prod2.count'}]
      });
      expect(results).to.contain('target=prod1.%7Btest%2Ctest2%7D');
    });

    it('should replace target placeholder', function() {
      var results = ctx.ds.buildGraphiteParams({
      targets: [{target: 'series1'}, {target: 'series2'}, {target: 'asPercent(#A,#B)'}]
      });
      expect(results[2]).to.be('target=asPercent(series1%2Cseries2)');
    });

    it('should replace target placeholder for hidden series', function() {
      var results = ctx.ds.buildGraphiteParams({
      targets: [{target: 'series1', hide: true}, {target: 'sumSeries(#A)', hide: true}, {target: 'asPercent(#A,#B)'}]
      });
      expect(results[0]).to.be('target=' + encodeURIComponent('asPercent(series1,sumSeries(series1))'));
    });

    it('should replace target placeholder when nesting query references', function() {
      var results = ctx.ds.buildGraphiteParams({
      targets: [{target: 'series1'}, {target: 'sumSeries(#A)'}, {target: 'asPercent(#A,#B)'}]
      });
      expect(results[2]).to.be('target=' + encodeURIComponent("asPercent(series1,sumSeries(series1))"));
    });

    it('should fix wrong minute interval parameters', function() {
      var results = ctx.ds.buildGraphiteParams({
      targets: [{target: "summarize(prod.25m.count, '25m', 'sum')" }]
//.........这里部分代码省略.........
开发者ID:eddawley,项目名称:grafana,代码行数:101,代码来源:datasource_specs.ts

示例8: describe

describe('CloudWatchDatasource', function() {
  var ctx = new helpers.ServiceTestContext();
  var instanceSettings = {
    jsonData: { defaultRegion: 'us-east-1', access: 'proxy' },
  };

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

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

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

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

    var response = {
      timings: [null],
      results: {
        A: {
          error: '',
          refId: 'A',
          series: [
            {
              name: 'CPUUtilization_Average',
              points: [[1, 1483228800000], [2, 1483229100000], [5, 1483229700000]],
              tags: {
                InstanceId: 'i-12345678',
              },
            },
          ],
        },
      },
    };

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

    it('should generate the correct query', function(done) {
      ctx.ds.query(query).then(function() {
        var params = requestParams.queries[0];
        expect(params.namespace).to.be(query.targets[0].namespace);
        expect(params.metricName).to.be(query.targets[0].metricName);
        expect(params.dimensions['InstanceId']).to.be('i-12345678');
        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' },
        rangeRaw: { from: 1483228800, to: 1483232400 },
        targets: [
          {
            region: 'us-east-1',
            namespace: 'AWS/EC2',
            metricName: 'CPUUtilization',
            dimensions: {
              InstanceId: 'i-12345678',
            },
            statistics: ['Average'],
//.........这里部分代码省略.........
开发者ID:knoguchi,项目名称:grafana,代码行数:101,代码来源:datasource_specs.ts


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