<commit_before>import {HttpClient} from '../src/index';
import {HttpRequestMessage} from '../src/index';
import {Headers} from '../src/index';

describe('http client', () => {

  var baseUrl = "http://example.com/";

  beforeEach(() => {
      jasmine.Ajax.install();
    });

    afterEach(() => {
      jasmine.Ajax.uninstall();
    });

  describe('get', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('GET');
        expect(request.data()).toEqual({});
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.get('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 200 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

  });

  describe('put', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.put('some/cool/path', content);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('PUT');
        expect(request.data()).toEqual(content);
      });

      it('should only include content properties specified in the replacer array', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.put('some/cool/path', content, ['firstName']);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.data()).not.toEqual(content);
        expect(request.data()).toEqual({ firstName: "John" });
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.put('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 200 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.put('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.put('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

  });

  describe('patch', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.patch('some/cool/path', content);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('PATCH');
        expect(request.data()).toEqual(content);
      });

      it('should only include content properties specified in the replacer array', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.patch('some/cool/path', content, ['firstName']);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.data()).not.toEqual(content);
        expect(request.data()).toEqual({ firstName: "John" });
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.patch('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 200 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.put('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.patch('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.patch('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

  });

  describe('post', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.post('some/cool/path', content);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('POST');
        expect(request.data()).toEqual(content);
      });

      it('should only include content properties specified in the replacer array', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.post('some/cool/path', content, ['firstName']);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.data()).not.toEqual(content);
        expect(request.data()).toEqual({ firstName: "John" });
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.post('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 201 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.post('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 201 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.post('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 201, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.post('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

    describe('delete', () => {

      describe('request', () => {

        it('should make expected request', () => {
          var client = new HttpClient(baseUrl);

          client.delete('some/cool/path');

          var request = jasmine.Ajax.requests.mostRecent();

          expect(request.url).toBe(`${baseUrl}some/cool/path`);
          expect(request.method).toBe('DELETE');
          expect(request.data()).toEqual({});
        });

        it('should provide expected request headers', () => {
          var headers = new Headers();
          headers.add('Authorization', 'bearer 123');
          var client = new HttpClient(undefined, headers);

          client.delete('some/cool/path');

          var request = jasmine.Ajax.requests.mostRecent();

          expect(request.requestHeaders['Authorization']).toBe('bearer 123');
        });

      });

      describe('response', () => {

        it('should succeed on 200 response', (done) => {
          var client = new HttpClient(baseUrl);

          client.delete('some/cool/path').then(response => {
            expect(response.isSuccess).toBe(true);
            done();
          });

          var request = jasmine.Ajax.requests.mostRecent();

          request.respondWith({ status: 200 });
        });

        it('should not succeed on 500 response', (done) => {
          var client = new HttpClient(baseUrl);

          client.delete('some/cool/path').then(response => {
            expect(response.isSuccess).toBe(false);
            done();
          });

          var request = jasmine.Ajax.requests.mostRecent();

          request.respondWith({ status: 500 });

        });

      });

    });

  });

  describe('send', () => {

    it('should reject on onerror', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {

      }, error => {
        expect(error instanceof Error).toBe(true);
        done();
      });

      jasmine.Ajax.requests.mostRecent().responseError();

    });

    it('should reject on ontimeout', (done) => {
        jasmine.clock().install()
        var client = new HttpClient();

        client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        }, error => {
          expect(error instanceof Error).toBe(true);
          done();
        });

        jasmine.Ajax.requests.mostRecent().responseTimeout();
        jasmine.clock().uninstall();
    });

    it('can parse request headers', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        expect(response.headers.get('Access-Control-Allow-Origin')).toBe('http://www.example.com');
        done();
      });

      var request = jasmine.Ajax.requests.mostRecent();
      request.respondWith({
        responseHeaders: [{ name: 'Access-Control-Allow-Origin', value: 'http://www.example.com'}]
      });

    });

    it('can parse multiple request headers', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        expect(response.headers.get('Access-Control-Allow-Origin')).toBe('http://www.example.com');
        expect(response.headers.get('Content-Type')).toBe('application/json');
        done();
      });

      var request = jasmine.Ajax.requests.mostRecent();
      request.respondWith({
        responseHeaders: [
          { name: 'Access-Control-Allow-Origin', value: 'http://www.example.com'},
          { name: 'Content-Type', value: 'application/json'}
        ]
      });

    });

    it('can parse header values containing :', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        expect(response.headers.get('Some-Cosy-Header')).toBe('foo:bar');
        done();
      });

      var request = jasmine.Ajax.requests.mostRecent();
      request.respondWith({
        responseHeaders: [{ name: 'Some-Cosy-Header', value: 'foo:bar'}]
      });
    });

  });

});<commit_msg>test(http-client): test for upload progress<commit_after>import {HttpClient} from '../src/index';
import {HttpRequestMessage} from '../src/index';
import {Headers} from '../src/index';

describe('http client', () => {

  var baseUrl = "http://example.com/";

  beforeEach(() => {
      jasmine.Ajax.install();
    });

    afterEach(() => {
      jasmine.Ajax.uninstall();
    });

  describe('get', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('GET');
        expect(request.data()).toEqual({});
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.get('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 200 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

  });

  describe('put', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.put('some/cool/path', content);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('PUT');
        expect(request.data()).toEqual(content);
      });

      it('should only include content properties specified in the replacer array', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.put('some/cool/path', content, ['firstName']);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.data()).not.toEqual(content);
        expect(request.data()).toEqual({ firstName: "John" });
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.put('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 200 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.get('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.put('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.put('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

  });

  describe('patch', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.patch('some/cool/path', content);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('PATCH');
        expect(request.data()).toEqual(content);
      });

      it('should only include content properties specified in the replacer array', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.patch('some/cool/path', content, ['firstName']);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.data()).not.toEqual(content);
        expect(request.data()).toEqual({ firstName: "John" });
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.patch('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 200 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.put('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.patch('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 200, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.patch('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

  });

  describe('post', () => {

    describe('request', () => {

      it('should make expected request', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.post('some/cool/path', content);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.url).toBe(`${baseUrl}some/cool/path`);
        expect(request.method).toBe('POST');
        expect(request.data()).toEqual(content);
      });

      it('should only include content properties specified in the replacer array', () => {
        var content = { firstName: "John", lastName: "Doe" };
        var headers = new Headers();
        headers.add('Content-Type', 'application/json');
        var client = new HttpClient(baseUrl, headers);

        client.post('some/cool/path', content, ['firstName']);

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.data()).not.toEqual(content);
        expect(request.data()).toEqual({ firstName: "John" });
      });

      it('should provide expected request headers', () => {
        var headers = new Headers();
        headers.add('Authorization', 'bearer 123');
        var client = new HttpClient(undefined, headers);

        client.post('some/cool/path');

        var request = jasmine.Ajax.requests.mostRecent();

        expect(request.requestHeaders['Authorization']).toBe('bearer 123');
      });

    });

    describe('response', () => {

      it('should succeed on 201 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.post('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(true);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 201 });
      });

      it('should retrieve correct content', (done) => {
        var client = new HttpClient(baseUrl);

        client.post('some/cool/path').then(response => {
          expect(response.content.name).toBe('Martin');
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 201, responseText: '{"name":"Martin"}' });
      });

      it('should not succeed on 500 response', (done) => {
        var client = new HttpClient(baseUrl);

        client.post('some/cool/path').then(response => {
          expect(response.isSuccess).toBe(false);
          done();
        });

        var request = jasmine.Ajax.requests.mostRecent();

        request.respondWith({ status: 500 });

      });

    });

    describe('delete', () => {

      describe('request', () => {

        it('should make expected request', () => {
          var client = new HttpClient(baseUrl);

          client.delete('some/cool/path');

          var request = jasmine.Ajax.requests.mostRecent();

          expect(request.url).toBe(`${baseUrl}some/cool/path`);
          expect(request.method).toBe('DELETE');
          expect(request.data()).toEqual({});
        });

        it('should provide expected request headers', () => {
          var headers = new Headers();
          headers.add('Authorization', 'bearer 123');
          var client = new HttpClient(undefined, headers);

          client.delete('some/cool/path');

          var request = jasmine.Ajax.requests.mostRecent();

          expect(request.requestHeaders['Authorization']).toBe('bearer 123');
        });

      });

      describe('response', () => {

        it('should succeed on 200 response', (done) => {
          var client = new HttpClient(baseUrl);

          client.delete('some/cool/path').then(response => {
            expect(response.isSuccess).toBe(true);
            done();
          });

          var request = jasmine.Ajax.requests.mostRecent();

          request.respondWith({ status: 200 });
        });

        it('should not succeed on 500 response', (done) => {
          var client = new HttpClient(baseUrl);

          client.delete('some/cool/path').then(response => {
            expect(response.isSuccess).toBe(false);
            done();
          });

          var request = jasmine.Ajax.requests.mostRecent();

          request.respondWith({ status: 500 });

        });

      });

    });

  });

  describe('send', () => {

    it('should reject on onerror', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {

      }, error => {
        expect(error instanceof Error).toBe(true);
        done();
      });

      jasmine.Ajax.requests.mostRecent().responseError();

    });

    it('should reject on ontimeout', (done) => {
        jasmine.clock().install()
        var client = new HttpClient();

        client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        }, error => {
          expect(error instanceof Error).toBe(true);
          done();
        });

        jasmine.Ajax.requests.mostRecent().responseTimeout();
        jasmine.clock().uninstall();
    });

    it('can parse request headers', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        expect(response.headers.get('Access-Control-Allow-Origin')).toBe('http://www.example.com');
        done();
      });

      var request = jasmine.Ajax.requests.mostRecent();
      request.respondWith({
        responseHeaders: [{ name: 'Access-Control-Allow-Origin', value: 'http://www.example.com'}]
      });

    });

    it('can parse multiple request headers', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        expect(response.headers.get('Access-Control-Allow-Origin')).toBe('http://www.example.com');
        expect(response.headers.get('Content-Type')).toBe('application/json');
        done();
      });

      var request = jasmine.Ajax.requests.mostRecent();
      request.respondWith({
        responseHeaders: [
          { name: 'Access-Control-Allow-Origin', value: 'http://www.example.com'},
          { name: 'Content-Type', value: 'application/json'}
        ]
      });

    });

    it('can parse header values containing :', (done) => {
      var client = new HttpClient();

      client.send(new HttpRequestMessage('GET', 'some/cool/url')).then(response => {
        expect(response.headers.get('Some-Cosy-Header')).toBe('foo:bar');
        done();
      });

      var request = jasmine.Ajax.requests.mostRecent();
      request.respondWith({
        responseHeaders: [{ name: 'Some-Cosy-Header', value: 'foo:bar'}]
      });
    });

    it('should set callback on upload progress', () => {
      var client = new HttpClient();
      var callback = function(){};

      client.send(new HttpRequestMessage('GET', 'some/cool/url'), callback);

      var response = jasmine.Ajax.requests.mostRecent();
      expect(response.upload.onprogress).toBe(callback);
    });

  });

});<|endoftext|>


<commit_before>var injection = require('../services/injection.js');
var Q = require('q');
var mongoose = require('mongoose');

module.exports = function (test, fixtureName, testFn) {
    var dbUrl = 'mongodb://localhost:27017/' + fixtureName;

    var cleanUp = function () {
        return Q.nbind(mongoose.connect, mongoose)(dbUrl).then(function () {
            var db = mongoose.connection.db;
            return Q.nbind(db.dropDatabase, db)().then(function () {
                db.close();
            });
        });
    };

    cleanUp().then(function () {
        var allcountServer = require('../allcount-server.js');

        injection.resetInjection();
        injection.bindFactory('port', 9080);
        injection.bindFactory('dbUrl', dbUrl);
        injection.bindFactory('gitRepoUrl', 'test-fixtures/' + fixtureName);

        allcountServer.reconfigureAllcount();
        return allcountServer.inject('allcountServerStartup');
    }).then(function (server) {
        return Q.nbind(server.startup, server)().then(function (errors) {
            if (errors) {
                throw new Error(errors.join('\n'));
            }
            return Q(testFn()).then(function () {
                return server.stop().then(function () {
                    injection.resetInjection();
                });
            });
        });
    }).finally(cleanUp).done(function () {
        test.done();
    });
};<commit_msg>Fix endless execution of integration tests<commit_after>var injection = require('../services/injection.js');
var Q = require('q');
var mongoose = require('mongoose');

module.exports = function (test, fixtureName, testFn) {
    var dbUrl = 'mongodb://localhost:27017/' + fixtureName;

    var cleanUp = function () {
        return Q.nbind(mongoose.connect, mongoose)(dbUrl).then(function () {
            var db = mongoose.connection.db;
            return Q.nbind(db.dropDatabase, db)().then(function () {
                db.close();
            });
        });
    };

    cleanUp().then(function () {
        var allcountServer = require('../allcount-server.js');

        injection.resetInjection();
        injection.bindFactory('port', 9080);
        injection.bindFactory('dbUrl', dbUrl);
        injection.bindFactory('gitRepoUrl', 'test-fixtures/' + fixtureName);

        allcountServer.reconfigureAllcount();
        return allcountServer.inject('allcountServerStartup');
    }).then(function (server) {
        return Q.nbind(server.startup, server)().then(function (errors) {
            if (errors) {
                throw new Error(errors.join('\n'));
            }
            return Q(testFn()).then(function () {
                return server.stop().then(function () {
                    injection.resetInjection();
                });
            });
        });
    }).finally(cleanUp).finally(function () {
        test.done();
    }).done();
};<|endoftext|>


<commit_before>module.exports = {
  displayName: 'unit',
  rootDir: '../',
  collectCoverage: true,
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!**/*.constant.js',
    '!**/*.config.js',
    '!**/*.{integration}.test.{js,jsx}',
    '!**/*.mock.js',
    '!**/index.js',
    '!src/*.js',
    '!src/.*.js'
  ],
  coverageDirectory: 'coverage',
  coverageThreshold: {
    global: {
      statements: 79,
      branches: 73,
      functions: 79,
      lines: 80
    }
  },
  coverageReporters: process.env.CI ? [
    'html',
    'text'
  ] : ['lcov'],
  moduleNameMapper: {
    '^.+\\.(css|scss)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/test/file-mock.js',
    '\\.(svg)$': '<rootDir>/test/file-svg-mock.js'
  },
  setupFiles: [
    'raf/polyfill',
    './test/setup-jest.js'
  ],
  snapshotSerializers: [
    'enzyme-to-json/serializer'
  ],
  testMatch: [
    '**/!(*.integration).test.js?(x)'
    // Do match:
    // foo.test.jsx
    // barService.test.js
    // Do not match:
    // fooService.jsx
    // foo.integration.test.jsx
  ],
  testURL: 'http://localhost:8080/',
  testEnvironment: 'jest-environment-jsdom-global',
  testPathIgnorePatterns: [
    '/modules/',
    '/node_modules/'
  ],
  watchPathIgnorePatterns: [
    '/modules/'
  ]
};
<commit_msg>DP-6202 set temporarly the threshold lower of jest<commit_after>module.exports = {
  displayName: 'unit',
  rootDir: '../',
  collectCoverage: true,
  collectCoverageFrom: [
    'src/**/*.{js,jsx}',
    '!**/*.constant.js',
    '!**/*.config.js',
    '!**/*.{integration}.test.{js,jsx}',
    '!**/*.mock.js',
    '!**/index.js',
    '!src/*.js',
    '!src/.*.js'
  ],
  coverageDirectory: 'coverage',
  coverageThreshold: {
    global: {
      statements: 79,
      branches: 72,
      functions: 79,
      lines: 80
    }
  },
  coverageReporters: process.env.CI ? [
    'html',
    'text'
  ] : ['lcov'],
  moduleNameMapper: {
    '^.+\\.(css|scss)$': 'identity-obj-proxy',
    '\\.(jpg|jpeg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': '<rootDir>/test/file-mock.js',
    '\\.(svg)$': '<rootDir>/test/file-svg-mock.js'
  },
  setupFiles: [
    'raf/polyfill',
    './test/setup-jest.js'
  ],
  snapshotSerializers: [
    'enzyme-to-json/serializer'
  ],
  testMatch: [
    '**/!(*.integration).test.js?(x)'
    // Do match:
    // foo.test.jsx
    // barService.test.js
    // Do not match:
    // fooService.jsx
    // foo.integration.test.jsx
  ],
  testURL: 'http://localhost:8080/',
  testEnvironment: 'jest-environment-jsdom-global',
  testPathIgnorePatterns: [
    '/modules/',
    '/node_modules/'
  ],
  watchPathIgnorePatterns: [
    '/modules/'
  ]
};
<|endoftext|>


<commit_before>const {assert} = require('chai');
const Token = require('../../src/lexer/Token');

describe('Lexer::Token', () => {
  it('Should properly create a Token instance', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.instanceOf(token, Token);
  });

  it('Should properly return a type of a token', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.equal(token.getType(), 'INTEGER');
  });

  it('Should properly return a value of a token', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.equal(token.getValue(), '2');
  });

  it('Should properly convert a token into string representation', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.equal(token.toString(), 'Token(INTEGER, 2)');
  });

  it('Should properly create a new token via static create method', () => {
    const token = Token.create(Token.INTEGER, '2');

    assert.instanceOf(token, Token);
    assert.equal(token.getType(), 'INTEGER');
    assert.equal(token.getValue(), '2');
  });

  it('Should properly return a token types from static getters', () => {
    assert.equal(Token.INTEGER, 'INTEGER');
    assert.equal(Token.PLUS, 'PLUS');
    assert.equal(Token.EOF, 'EOF');
  });
});
<commit_msg>tests(lexer): add minor test for token types<commit_after>const {assert} = require('chai');
const Token = require('../../src/lexer/Token');

describe('Lexer::Token', () => {
  it('Should properly create a Token instance', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.instanceOf(token, Token);
  });

  it('Should properly return a type of a token', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.equal(token.getType(), 'INTEGER');
  });

  it('Should properly return a value of a token', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.equal(token.getValue(), '2');
  });

  it('Should properly convert a token into string representation', () => {
    const token = new Token(Token.INTEGER, '2');

    assert.equal(token.toString(), 'Token(INTEGER, 2)');
  });

  it('Should properly create a new token via static create method', () => {
    const token = Token.create(Token.INTEGER, '2');

    assert.instanceOf(token, Token);
    assert.equal(token.getType(), 'INTEGER');
    assert.equal(token.getValue(), '2');
  });

  it('Should properly return a token types from static getters', () => {
    assert.equal(Token.INTEGER, 'INTEGER');
    assert.equal(Token.PLUS, 'PLUS');
    assert.equal(Token.MINUS, 'MINUS');
    assert.equal(Token.EOF, 'EOF');
  });
});
<|endoftext|>


<commit_before>describe.only('Levelup persistence layer', function () {
  'use strict';

  var common = require('../common')
    , expect = common.expect
    , sinon = common.sinon
    , Dynamis = common.Dynamis
    , Persist = common.persist('levelup')
    , levelup = common.levelup()
    , persist, dynamis;

  beforeEach(function () {
    dynamis = new Dynamis('levelup', levelup, { interface: require('leveldown') });
    persist = new Persist(dynamis, levelup);
  });

  afterEach(function () {
    dynamis = null;
    persist = null;
  });

  after(function (done) {
    levelup.close(done);
  });

  it('is constructor that can be provided with persistence layer', function () {
    expect(Persist).to.be.a('function');
    expect(persist).to.be.an.instanceof(Persist);
  });

  it('registers an error event listener that emits on dynamis', function (done) {
    dynamis.once('error', function (error) {
      expect(error).to.be.an.instanceof(Error);
      expect(error.message).to.equal('this is a test message');
      done();
    });

    persist.database.emit('error', new Error('this is a test message'));
  });

  it('will open the database or use the provided instance', function () {
    expect(persist.database.db).to.be.an('object');
    expect(persist.database.db).to.have.property('location', '/tmp/test');

    persist = new Persist(dynamis, require('levelup')('/tmp/different'));

    expect(persist.database.db).to.be.an('object');
    expect(persist.database.db).to.have.property('location', '/tmp/different');
  });

  it('will store the persistence connection to `database`', function () {
    expect(persist).to.have.property('database');
    expect(persist.database).to.be.an('object');
  });

  it('will extend the API of dynamis', function () {
    expect(persist).to.have.property('api');
    expect(persist.api).to.be.a('function');

    expect(dynamis).to.have.property('get');
    expect(dynamis).to.have.property('flush');
    expect(dynamis).to.have.property('set');
    expect(dynamis).to.have.property('expire');
    expect(dynamis).to.have.property('del');
  });

  describe('#set', function () {
    var key = 'test';

    afterEach(function (done) {
      levelup.del(key, done);
    });

    it('is a function', function () {
      expect(dynamis.set).to.be.a('function');
    });

    it('will store a key:value in LevelDB', function (done) {
      var data = 'any value';

      dynamis.set(key, data, function (error) {
        expect(error).to.equal(undefined);

        levelup.get(key, function (error, result) {
          expect(error).to.equal(null);
          expect(result).to.equal(JSON.stringify(data));
          done();
        });
      });
    });

    it('will JSON.stringify object values', function (done) {
      var data = { json: 'data' };

      dynamis.set(key, data, function (error, result) {
        expect(error).to.equal(undefined);

        levelup.get(key, function (error, result) {
          expect(error).to.equal(null);
          expect(result).to.equal(JSON.stringify(data));
          done();
        });
      });
    });

    // it('has optional 3rd argument for TTL in seconds', function (done) {
    //   var ttl = 10
    //     , data = { json: 'data' };

    //   dynamis.set(key, data, ttl, function (error, result) {
    //     expect(error).to.equal(null);
    //     expect(result).to.equal('OK');

    //     redis.ttl(key, function (error, result) {
    //       expect(error).to.equal(null);

    //       // be a bit defensive, the test can't run longer than 2 seconds.
    //       expect(result).to.be.above(7);
    //       done();
    //     });
    //   });
    // });

    it('will return an error when data cannot be JSON.stringified', function (done) {
      var cyclic = {};
      cyclic.data = cyclic;

      dynamis.set(key, cyclic, function (error, result) {
        expect(error).to.be.an.instanceof(Error);
        expect(error.message).to.equal('Converting circular structure to JSON');
        expect(result).to.equal(undefined);
        done();
      });
    });
  });

  describe('#get', function () {
    var key = 'test'
      , data = JSON.stringify('value');

    beforeEach(function (done) {
      levelup.put(key, data, done);
    });

    afterEach(function (done) {
      levelup.del(key, done);
    });

    it('is a function', function () {
      expect(dynamis.get).to.be.a('function');
    });

    it('will fetch the data from LevelDB by key', function (done) {
      dynamis.get(key, function (error, result) {
        expect(error).to.equal(null);
        expect(result).to.equal('value');
        done();
      });
    });

    it('will return status 404 when key does not exist', function (done) {
      dynamis.get('random', function (error, result) {
        expect(error).to.be.an('object');
        expect(error).to.have.property('notFound', true);
        expect(error).to.have.property('status', 404);
        expect(result).to.equal(undefined);
        done();
      });
    });
  });

  describe('#del', function () {
    var key = 'test'
      , data = JSON.stringify('value');

    beforeEach(function (done) {
      levelup.put(key, data, done);
    });

    afterEach(function (done) {
      levelup.del(key, done);
    });

    it('is a function', function () {
      expect(dynamis.del).to.be.a('function');
    });

    it('will delete the key from LevelDB', function (done) {
      dynamis.del(key, function (error) {
        expect(error).to.equal(undefined);

        levelup.get(key, function (error, result) {
          expect(error).to.be.an('object');
          expect(error).to.have.property('notFound', true);
          expect(error).to.have.property('status', 404);
          expect(result).to.equal(undefined);
          done();
        });
      });
    });

    it('will do nothing if the key does not exist', function (done) {
      dynamis.del('random', function (error, result) {
        expect(error).to.equal(undefined);
        done();
      });
    });
  });

  // describe('#expire', function () {
  //   var key = 'test'
  //     , data = JSON.stringify('value');

  //   beforeEach(function (done) {
  //     redis.set(key, data, done);
  //   });

  //   afterEach(function (done) {
  //     redis.del(key, done);
  //   });

  //   it('is a function', function () {
  //     expect(dynamis.expire).to.be.a('function');
  //   });

  //   it('will add TTL to key', function (done) {
  //     dynamis.expire(key, 10, function (error, result) {
  //       expect(error).to.equal(null);
  //       expect(result).to.equal(1);

  //       redis.ttl(key, function (error, time) {
  //         expect(error).to.equal(null);
  //         expect(time).to.be.above(8);
  //         done();
  //       });
  //     });
  //   });

  //   it('will return 0 if the key does not exist', function (done) {
  //     dynamis.expire('random', 100, function (error, result) {
  //       expect(error).to.equal(null);
  //       expect(result).to.equal(0);

  //       redis.ttl(key, function (error, time) {
  //         expect(error).to.equal(null);
  //         expect(time).to.equal(-1);
  //         done();
  //       });
  //     });
  //   });
  // });

  describe('#flush', function () {
    var key = 'test'
      , data = JSON.stringify('value');

    beforeEach(function (done) {
      levelup.put(key, data, done);
    });

    it('is a function', function () {
      expect(dynamis.flush).to.be.a('function');
    });

    it('will flush the entire database', function (done) {
      levelup.get('test', function (error, result) {
        expect(error).to.equal(null);
        expect(result).to.equal(data);

        dynamis.flush(function (error, result) {
          expect(error).to.equal(undefined);

          //
          // Flush will close to db to actually destroy it, make sure to reopen,
          // do not do this in production.
          //
          levelup.open(function () {
            levelup.get('test', function (error, result) {
              expect(error).to.be.an('object');
              expect(error).to.have.property('notFound', true);
              expect(error).to.have.property('status', 404);
              expect(result).to.equal(undefined);
              done();
            });
          });
        });
      });
    });
  });
});<commit_msg>[test] remove only<commit_after>describe('Levelup persistence layer', function () {
  'use strict';

  var common = require('../common')
    , expect = common.expect
    , sinon = common.sinon
    , Dynamis = common.Dynamis
    , Persist = common.persist('levelup')
    , levelup = common.levelup()
    , persist, dynamis;

  beforeEach(function () {
    dynamis = new Dynamis('levelup', levelup, { interface: require('leveldown') });
    persist = new Persist(dynamis, levelup);
  });

  afterEach(function () {
    dynamis = null;
    persist = null;
  });

  after(function (done) {
    levelup.close(done);
  });

  it('is constructor that can be provided with persistence layer', function () {
    expect(Persist).to.be.a('function');
    expect(persist).to.be.an.instanceof(Persist);
  });

  it('registers an error event listener that emits on dynamis', function (done) {
    dynamis.once('error', function (error) {
      expect(error).to.be.an.instanceof(Error);
      expect(error.message).to.equal('this is a test message');
      done();
    });

    persist.database.emit('error', new Error('this is a test message'));
  });

  it('will open the database or use the provided instance', function () {
    expect(persist.database.db).to.be.an('object');
    expect(persist.database.db).to.have.property('location', '/tmp/test');

    persist = new Persist(dynamis, require('levelup')('/tmp/different'));

    expect(persist.database.db).to.be.an('object');
    expect(persist.database.db).to.have.property('location', '/tmp/different');
  });

  it('will store the persistence connection to `database`', function () {
    expect(persist).to.have.property('database');
    expect(persist.database).to.be.an('object');
  });

  it('will extend the API of dynamis', function () {
    expect(persist).to.have.property('api');
    expect(persist.api).to.be.a('function');

    expect(dynamis).to.have.property('get');
    expect(dynamis).to.have.property('flush');
    expect(dynamis).to.have.property('set');
    expect(dynamis).to.have.property('expire');
    expect(dynamis).to.have.property('del');
  });

  describe('#set', function () {
    var key = 'test';

    afterEach(function (done) {
      levelup.del(key, done);
    });

    it('is a function', function () {
      expect(dynamis.set).to.be.a('function');
    });

    it('will store a key:value in LevelDB', function (done) {
      var data = 'any value';

      dynamis.set(key, data, function (error) {
        expect(error).to.equal(undefined);

        levelup.get(key, function (error, result) {
          expect(error).to.equal(null);
          expect(result).to.equal(JSON.stringify(data));
          done();
        });
      });
    });

    it('will JSON.stringify object values', function (done) {
      var data = { json: 'data' };

      dynamis.set(key, data, function (error, result) {
        expect(error).to.equal(undefined);

        levelup.get(key, function (error, result) {
          expect(error).to.equal(null);
          expect(result).to.equal(JSON.stringify(data));
          done();
        });
      });
    });

    // it('has optional 3rd argument for TTL in seconds', function (done) {
    //   var ttl = 10
    //     , data = { json: 'data' };

    //   dynamis.set(key, data, ttl, function (error, result) {
    //     expect(error).to.equal(null);
    //     expect(result).to.equal('OK');

    //     redis.ttl(key, function (error, result) {
    //       expect(error).to.equal(null);

    //       // be a bit defensive, the test can't run longer than 2 seconds.
    //       expect(result).to.be.above(7);
    //       done();
    //     });
    //   });
    // });

    it('will return an error when data cannot be JSON.stringified', function (done) {
      var cyclic = {};
      cyclic.data = cyclic;

      dynamis.set(key, cyclic, function (error, result) {
        expect(error).to.be.an.instanceof(Error);
        expect(error.message).to.equal('Converting circular structure to JSON');
        expect(result).to.equal(undefined);
        done();
      });
    });
  });

  describe('#get', function () {
    var key = 'test'
      , data = JSON.stringify('value');

    beforeEach(function (done) {
      levelup.put(key, data, done);
    });

    afterEach(function (done) {
      levelup.del(key, done);
    });

    it('is a function', function () {
      expect(dynamis.get).to.be.a('function');
    });

    it('will fetch the data from LevelDB by key', function (done) {
      dynamis.get(key, function (error, result) {
        expect(error).to.equal(null);
        expect(result).to.equal('value');
        done();
      });
    });

    it('will return status 404 when key does not exist', function (done) {
      dynamis.get('random', function (error, result) {
        expect(error).to.be.an('object');
        expect(error).to.have.property('notFound', true);
        expect(error).to.have.property('status', 404);
        expect(result).to.equal(undefined);
        done();
      });
    });
  });

  describe('#del', function () {
    var key = 'test'
      , data = JSON.stringify('value');

    beforeEach(function (done) {
      levelup.put(key, data, done);
    });

    afterEach(function (done) {
      levelup.del(key, done);
    });

    it('is a function', function () {
      expect(dynamis.del).to.be.a('function');
    });

    it('will delete the key from LevelDB', function (done) {
      dynamis.del(key, function (error) {
        expect(error).to.equal(undefined);

        levelup.get(key, function (error, result) {
          expect(error).to.be.an('object');
          expect(error).to.have.property('notFound', true);
          expect(error).to.have.property('status', 404);
          expect(result).to.equal(undefined);
          done();
        });
      });
    });

    it('will do nothing if the key does not exist', function (done) {
      dynamis.del('random', function (error, result) {
        expect(error).to.equal(undefined);
        done();
      });
    });
  });

  // describe('#expire', function () {
  //   var key = 'test'
  //     , data = JSON.stringify('value');

  //   beforeEach(function (done) {
  //     redis.set(key, data, done);
  //   });

  //   afterEach(function (done) {
  //     redis.del(key, done);
  //   });

  //   it('is a function', function () {
  //     expect(dynamis.expire).to.be.a('function');
  //   });

  //   it('will add TTL to key', function (done) {
  //     dynamis.expire(key, 10, function (error, result) {
  //       expect(error).to.equal(null);
  //       expect(result).to.equal(1);

  //       redis.ttl(key, function (error, time) {
  //         expect(error).to.equal(null);
  //         expect(time).to.be.above(8);
  //         done();
  //       });
  //     });
  //   });

  //   it('will return 0 if the key does not exist', function (done) {
  //     dynamis.expire('random', 100, function (error, result) {
  //       expect(error).to.equal(null);
  //       expect(result).to.equal(0);

  //       redis.ttl(key, function (error, time) {
  //         expect(error).to.equal(null);
  //         expect(time).to.equal(-1);
  //         done();
  //       });
  //     });
  //   });
  // });

  describe('#flush', function () {
    var key = 'test'
      , data = JSON.stringify('value');

    beforeEach(function (done) {
      levelup.put(key, data, done);
    });

    it('is a function', function () {
      expect(dynamis.flush).to.be.a('function');
    });

    it('will flush the entire database', function (done) {
      levelup.get('test', function (error, result) {
        expect(error).to.equal(null);
        expect(result).to.equal(data);

        dynamis.flush(function (error, result) {
          expect(error).to.equal(undefined);

          //
          // Flush will close to db to actually destroy it, make sure to reopen,
          // do not do this in production.
          //
          levelup.open(function () {
            levelup.get('test', function (error, result) {
              expect(error).to.be.an('object');
              expect(error).to.have.property('notFound', true);
              expect(error).to.have.property('status', 404);
              expect(result).to.equal(undefined);
              done();
            });
          });
        });
      });
    });
  });
});<|endoftext|>


<commit_before>// create jsdom environment
const { JSDOM } = require("jsdom");
const dom = new JSDOM(`<!DOCTYPE html>`, {
  url: "http://localhost",
});
const window = dom.window;

global.URLSearchParams = window.URLSearchParams;

// Copy over all properties from window that do not yet exist on nodes global
// over to the global object.
// Later we might want to filter some of them, but for now it seems to work just
// fine when copying everything over like this.
Object.keys(window).forEach((key) => {
  if (typeof global[key] === "undefined") {
    global[key] = window[key];
  }
});

// Setup fetch polyfill and copy the references the polyfill installs into the
// window over into the global object.
require("whatwg-fetch");
global.fetch = window.fetch;
global.Headers = window.Headers;
global.Request = window.Request;
global.Response = window.Response;
<commit_msg>Fix test setup<commit_after>// create jsdom environment
const { JSDOM } = require("jsdom");
const dom = new JSDOM(`<!DOCTYPE html>`, {
  url: "http://localhost",
});
const window = dom.window;

global.URLSearchParams = window.URLSearchParams;

// Copy over all properties from window that do not yet exist on nodes global
// over to the global object.
// Later we might want to filter some of them, but for now it seems to work just
// fine when copying everything over like this.
Object.keys(window).forEach((key) => {
  if (typeof global[key] === "undefined") {
    global[key] = window[key];
  }
});

// Setup fetch polyfill and copy the references the polyfill installs into the
// window over into the global object.
const wwgFetch = require("whatwg-fetch");

global.fetch = wwgFetch.fetch;
global.Headers = wwgFetch.Headers;
global.Request = wwgFetch.Request;
global.Response = wwgFetch.Response;
<|endoftext|>


<commit_before>import { expect } from "chai";

import { checkStatus, parseJSON } from "../src";

describe("Parsing Responses", function() {
	beforeEach(function() {
		this.result = new Promise((resolve, reject) => {
			this.resolve = resolve;
			this.reject = reject;
		})
			.then(checkStatus)
			.then(parseJSON);
	});

	describe("when parsing a 200-level response", function() {
		beforeEach(function() {
			this.resolve({
				status: 200,
				statusText: "OK",
				json: () =>
					new Promise(resolve =>
						resolve({
							username: "homer.simpson",
							age: 42
						})
					)
			});
		});

		it("should parse the response json as a successful result", function(done) {
			this.result.then(user => {
				expect(user).to.be.ok;
				expect(user.username).to.equal("homer.simpson");
				expect(user.age).to.equal(42);

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

	describe("when parsing a non-200-level response", function() {
		function shouldRejectWithError(statusCode) {
			it("should reject the promise with an error", function(done) {
				this.result.catch(err => {
					expect(err).to.be.ok;
					expect(err).to.be.an("error");
					done();
				});
			});

			it("should include the original response with the error", function(done) {
				this.result.catch(err => {
					expect(err.response).to.be.ok;
					expect(err.response.status).to.equal(statusCode);
					done();
				});
			});
		}

		describe("with an error message", function() {
			beforeEach(function() {
				this.resolve({
					status: 404,
					statusText: "Not Found",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Couldn't find the dude, man"
							})
						)
				});
			});

			shouldRejectWithError(404);

			it("should parse the error message from the response", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("Couldn't find the dude, man");
					done();
				});
			});
		});

		describe("with a pascal-cased error message", function() {
			beforeEach(function() {
				this.resolve({
					status: 400,
					statusText: "Bad Request",
					json: () =>
						new Promise(resolve =>
							resolve({
								Message: "shiitake mushrooms"
							})
						)
				});
			});

			shouldRejectWithError(400);

			it("should parse the error message from the response", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("shiitake mushrooms");
					done();
				});
			});
		});

		describe("without an error message", function() {
			beforeEach(function() {
				this.resolve({
					status: 301,
					statusText: "Moved Permanently",
					json: () => new Promise(resolve => resolve({}))
				});
			});

			shouldRejectWithError(301);

			it("should use the status text as the error message", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("Moved Permanently");
					done();
				});
			});
		});

		describe("with a .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Invalid Operation",
								exceptionMessage:
									"Cannot do the thing you wanted to do because of some important reason.",
								exceptionType: "System.InvalidOperationException",
								stackTrace: "bla bla bla"
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the exception message as the error message", function(
				done
			) {
				this.result.catch(err => {
					expect(err.message).to.equal(
						"Cannot do the thing you wanted to do because of some important reason."
					);
					done();
				});
			});
		});

		describe("with a pascal-cased .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								Message: "Invalid Operation",
								ExceptionMessage:
									"Cannot do the thing you wanted to do because of some important reason.",
								ExceptionType: "System.InvalidOperationException",
								StackTrace: "bla bla bla"
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the exception message as the error message", function(
				done
			) {
				this.result.catch(err => {
					expect(err.message).to.equal(
						"Cannot do the thing you wanted to do because of some important reason."
					);
					done();
				});
			});
		});

		describe("with a nested .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Bad Thing Happened",
								exceptionMessage: "Some useless message",
								exceptionType: "System.InvocationException",
								stackTrace: "bla bla bla",
								innerException: {
									message: "One or more errors occurred",
									exceptionMessage: "Another useless message",
									exceptionType: "System.AggregateException",
									stackTrace: "bla bla bla",
									innerException: {
										message: "Invalid Operation",
										exceptionMessage:
											"Cannot do the thing you wanted to do because of some important reason.",
										exceptionType: "System.InvalidOperationException",
										stackTrace: "bla bla bla"
									}
								}
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the inner-most exception message as the error message", function(
				done
			) {
				this.result.catch(err => {
					expect(err.message).to.equal(
						"Cannot do the thing you wanted to do because of some important reason."
					);
					done();
				});
			});
		});

		describe("with a nested .net exception message with varying detail", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Bad Thing Happened",
								exceptionMessage: "Some useless message",
								exceptionType: "System.InvocationException",
								stackTrace: "bla bla bla",
								innerException: {
									message: "One or more errors occurred",
									exceptionMessage: "Another useless message",
									exceptionType: "System.AggregateException",
									stackTrace: "bla bla bla",
									innerException: {
										message: "Cannot do the thing",
										exceptionType: "System.InvalidOperationException",
										stackTrace: "bla bla bla"
									}
								}
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the inner-most exception message as the error message", function(
				done
			) {
				this.result.catch(err => {
					expect(err.message).to.equal("Cannot do the thing");
					done();
				});
			});
		});

		describe("with a nested malformed .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Bad Thing Happened",
								exceptionMessage: "Some useless message",
								exceptionType: "System.InvocationException",
								stackTrace: "bla bla bla",
								innerException: {
									message: "One or more errors occurred",
									exceptionMessage: "Not a useless message",
									exceptionType: "System.AggregateException",
									stackTrace: "bla bla bla",
									innerException: {
										// no messages here
										exceptionType: "System.InvalidOperationException",
										stackTrace: "bla bla bla"
									}
								}
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the inner-most exception message as the error message", function(
				done
			) {
				this.result.catch(err => {
					expect(err.message).to.equal("Not a useless message");
					done();
				});
			});
		});
	});
});
<commit_msg>Delint due to prettier upgrade<commit_after>import { expect } from "chai";

import { checkStatus, parseJSON } from "../src";

describe("Parsing Responses", function() {
	beforeEach(function() {
		this.result = new Promise((resolve, reject) => {
			this.resolve = resolve;
			this.reject = reject;
		})
			.then(checkStatus)
			.then(parseJSON);
	});

	describe("when parsing a 200-level response", function() {
		beforeEach(function() {
			this.resolve({
				status: 200,
				statusText: "OK",
				json: () =>
					new Promise(resolve =>
						resolve({
							username: "homer.simpson",
							age: 42
						})
					)
			});
		});

		it("should parse the response json as a successful result", function(done) {
			this.result.then(user => {
				expect(user).to.be.ok;
				expect(user.username).to.equal("homer.simpson");
				expect(user.age).to.equal(42);

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

	describe("when parsing a non-200-level response", function() {
		function shouldRejectWithError(statusCode) {
			it("should reject the promise with an error", function(done) {
				this.result.catch(err => {
					expect(err).to.be.ok;
					expect(err).to.be.an("error");
					done();
				});
			});

			it("should include the original response with the error", function(done) {
				this.result.catch(err => {
					expect(err.response).to.be.ok;
					expect(err.response.status).to.equal(statusCode);
					done();
				});
			});
		}

		describe("with an error message", function() {
			beforeEach(function() {
				this.resolve({
					status: 404,
					statusText: "Not Found",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Couldn't find the dude, man"
							})
						)
				});
			});

			shouldRejectWithError(404);

			it("should parse the error message from the response", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("Couldn't find the dude, man");
					done();
				});
			});
		});

		describe("with a pascal-cased error message", function() {
			beforeEach(function() {
				this.resolve({
					status: 400,
					statusText: "Bad Request",
					json: () =>
						new Promise(resolve =>
							resolve({
								Message: "shiitake mushrooms"
							})
						)
				});
			});

			shouldRejectWithError(400);

			it("should parse the error message from the response", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("shiitake mushrooms");
					done();
				});
			});
		});

		describe("without an error message", function() {
			beforeEach(function() {
				this.resolve({
					status: 301,
					statusText: "Moved Permanently",
					json: () => new Promise(resolve => resolve({}))
				});
			});

			shouldRejectWithError(301);

			it("should use the status text as the error message", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("Moved Permanently");
					done();
				});
			});
		});

		describe("with a .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Invalid Operation",
								exceptionMessage:
									"Cannot do the thing you wanted to do because of some important reason.",
								exceptionType: "System.InvalidOperationException",
								stackTrace: "bla bla bla"
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the exception message as the error message", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal(
						"Cannot do the thing you wanted to do because of some important reason."
					);
					done();
				});
			});
		});

		describe("with a pascal-cased .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								Message: "Invalid Operation",
								ExceptionMessage:
									"Cannot do the thing you wanted to do because of some important reason.",
								ExceptionType: "System.InvalidOperationException",
								StackTrace: "bla bla bla"
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the exception message as the error message", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal(
						"Cannot do the thing you wanted to do because of some important reason."
					);
					done();
				});
			});
		});

		describe("with a nested .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Bad Thing Happened",
								exceptionMessage: "Some useless message",
								exceptionType: "System.InvocationException",
								stackTrace: "bla bla bla",
								innerException: {
									message: "One or more errors occurred",
									exceptionMessage: "Another useless message",
									exceptionType: "System.AggregateException",
									stackTrace: "bla bla bla",
									innerException: {
										message: "Invalid Operation",
										exceptionMessage:
											"Cannot do the thing you wanted to do because of some important reason.",
										exceptionType: "System.InvalidOperationException",
										stackTrace: "bla bla bla"
									}
								}
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the inner-most exception message as the error message", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal(
						"Cannot do the thing you wanted to do because of some important reason."
					);
					done();
				});
			});
		});

		describe("with a nested .net exception message with varying detail", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Bad Thing Happened",
								exceptionMessage: "Some useless message",
								exceptionType: "System.InvocationException",
								stackTrace: "bla bla bla",
								innerException: {
									message: "One or more errors occurred",
									exceptionMessage: "Another useless message",
									exceptionType: "System.AggregateException",
									stackTrace: "bla bla bla",
									innerException: {
										message: "Cannot do the thing",
										exceptionType: "System.InvalidOperationException",
										stackTrace: "bla bla bla"
									}
								}
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the inner-most exception message as the error message", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("Cannot do the thing");
					done();
				});
			});
		});

		describe("with a nested malformed .net exception message", function() {
			beforeEach(function() {
				this.resolve({
					status: 500,
					statusText: "Server Error",
					json: () =>
						new Promise(resolve =>
							resolve({
								message: "Bad Thing Happened",
								exceptionMessage: "Some useless message",
								exceptionType: "System.InvocationException",
								stackTrace: "bla bla bla",
								innerException: {
									message: "One or more errors occurred",
									exceptionMessage: "Not a useless message",
									exceptionType: "System.AggregateException",
									stackTrace: "bla bla bla",
									innerException: {
										// no messages here
										exceptionType: "System.InvalidOperationException",
										stackTrace: "bla bla bla"
									}
								}
							})
						)
				});
			});

			shouldRejectWithError(500);

			it("should use the inner-most exception message as the error message", function(done) {
				this.result.catch(err => {
					expect(err.message).to.equal("Not a useless message");
					done();
				});
			});
		});
	});
});
<|endoftext|>


<commit_before>'use strict';

const chalk = require('chalk');

process.on('message', (message) => {
    let worker = false;
    let data = {};

    if (message.scenario && !worker) {
        let scenario = message.scenario;
        console.log(`${chalk.green(`[syrup.${scenario.name}]`)} scenario ${scenario.name} received by ${scenario.worker}Worker#${process.pid}`);
        console.log(`${chalk.green(`[syrup.${scenario.name}]`)} ${scenario.worker}Worker#${process.pid} received data for the test: ${JSON.stringify(scenario.data)}`);

        const Worker = require(`./Workers/${scenario.worker}Worker`);

        worker = new Worker(scenario);

        worker.setup(() =>
            worker.run(() =>
                worker.teardown(() =>
                    process.send({ teardown: true })
                )
            )
        );
    }
});
<commit_msg>Better worker logging and debug switch for workers<commit_after>'use strict';

const chalk = require('chalk');

process.on('message', (message) => {
    let worker = false;
    let data = {};

    if (message.scenario && !worker) {
        let scenario = message.scenario;

        if (scenario.debug) {
            console.log(`${chalk.blue(`[${scenario.worker}Worker#${process.pid}]`)} scenario ${scenario.name} received with data: ${JSON.stringify(scenario)}`);
        }

        const Worker = require(`./Workers/${scenario.worker}Worker`);

        worker = new Worker(scenario);

        worker.setup(() =>
            worker.run(() =>
                worker.teardown(() =>
                    process.send({ teardown: true })
                )
            )
        );
    }
});
<|endoftext|>


<commit_before>describe('Performance', function () {
	var isNode = typeof module !== 'undefined' && module.exports;
	var cpus = isNode && require('os').cpus().length > 2 ? 2 : 1;

	it('.map() should be using multi-threading (could fail on single-core)', function () {
		var slowSquare = function (n) {
			var i = 0;
			while (++i < n * n) { }
			return i;
		};

		var Thread = require('../lib/thread.js');
		var p = new Thread([1000, 2000, 3000]);
		var p2 = new Thread([1000, 2000, 3000]);

		var start = Date.now();
		var start2 = Date.now();

		var time = null;
		var time2 = null;

		runs(function () {
			p.spawn(function (data) {
				for (var i = 0; i < data.length; ++i) {
					var n = data[i];
					var square;
					for (square = 0; square < n * n; ++square) { }
					data[i] = square;
				}
				return data;
			}).then(function (data) {
				time = Date.now() - start;
				result = data;
			});

			p2.map(slowSquare).then(function (data) {
				time2 = Date.now() - start2;
				result = data;
			});
		});

		waitsFor(function () {
			return time != null && time2 != null;
		}, "it should finish", 5000);

		runs(function () {
			expect(time2).toBeLessThan(time / cpus);
		});
	});
});<commit_msg>fixing performance test for dual core machine<commit_after>describe('Performance', function () {
	var isNode = typeof module !== 'undefined' && module.exports;
	var cpus = isNode && require('os').cpus().length > 2 ? 2 : 1;

	it('.map() should be using multi-threading (could fail on single-core)', function () {
		var slowSquare = function (n) {
			var i = 0;
			while (++i < n * n) { }
			return i;
		};

		var Thread = require('../lib/thread.js');
		var p = new Thread([1000, 2000, 3000]);
		var p2 = new Thread([1000, 2000, 3000]);

		var start = Date.now();
		var time = null;

		runs(function () {
			p.spawn(function (data) {
				for (var i = 0; i < data.length; ++i) {
					var n = data[i];
					var square;
					for (square = 0; square < n * n; ++square) { }
					data[i] = square;
				}
				return data;
			}).then(function (data) {
				time = Date.now() - start;
				result = data;
			});
		});

		waitsFor(function () {
			return time != null;
		}, "Sequential should finish", 5000);

		var start2 = Date.now();
		var time2 = null;

		runs(function () {
			p2.map(slowSquare).then(function (data) {
				time2 = Date.now() - start2;
				result = data;
			});
		});

		waitsFor(function () {
			return time2 != null;
		}, "Parallel should finish", 5000);

		runs(function () {
			expect(time2).toBeLessThan(time / cpus);
		});
	});
});<|endoftext|>


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

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import IconButton from '../IconButton';

import HorizontalAlign from '../_statics/HorizontalAlign';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';

class Td extends Component {

    static Align = HorizontalAlign;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    stringContentRenderer = (data, template) => {

        if (!data) {
            return template;
        }

        if (/\$\{.+\}/.test(template)) { // handle replacement in template
            let result = template;
            for (let key in data) {
                result = result.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), data[key]);
            }
            return result;
        } else { // show prop value directly
            return data[template];
        }

    };

    handleCollapseButtonClick = () => {
        const {data, collapsed, onExpandChange} = this.props;
        onExpandChange && onExpandChange(!collapsed, data);
    };

    handleRenderer = () => {

        const {renderer, rowIndex, colIndex, data} = this.props;

        switch (typeof renderer) {
            case 'string':
                return this.stringContentRenderer(data, renderer);
            case 'function':
                return renderer(data, rowIndex, colIndex);
            default:
                return renderer;
        }

    };

    handleClick = e => {
        const {data, rowIndex, colIndex, disabled, onCellClick} = this.props;
        !disabled && onCellClick && onCellClick(data, rowIndex, colIndex, e);
    };

    render() {

        const {
            className, style, align, span, hasChildren, isExpandColumn, depth,
            sortable, sortingProp, sorting
        } = this.props;

        return (
            <td className={classNames({
                [`align-${align}`]: align && align !== HorizontalAlign.LEFT,
                'table-expand-column': isExpandColumn,
                sorting: sortable && sortingProp && sorting && sorting.prop && sorting.prop === sortingProp,
                [className]: className
            })}
                style={style}
                colSpan={span || null}
                onClick={this.handleClick}>

                {
                    isExpandColumn ?
                        <span className={classNames('table-indent', `indent-level-${depth}`)}
                              style={{paddingLeft: depth * 20}}>
                        :
                        null
                }

                {
                    isExpandColumn ?
                        <IconButton className={classNames('collapse-button', {
                            hidden: !hasChildren
                        })}
                                    iconCls="fas fa-chevron-down"
                                    disableTouchRipple={true}
                                    onClick={this.handleCollapseButtonClick}/>
                        :
                        null
                }

                {this.handleRenderer()}

        );

    }
}

Td.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    rowIndex: PropTypes.number,
    colIndex: PropTypes.number,

    data: PropTypes.object,
    renderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),
    span: PropTypes.number,

    isChecked: PropTypes.bool,
    disabled: PropTypes.bool,
    hasChildren: PropTypes.bool,
    collapsed: PropTypes.bool,
    isExpandColumn: PropTypes.bool,
    depth: PropTypes.number,

    /**
     * sorting
     */
    sortable: PropTypes.bool,
    sortingProp: PropTypes.string,
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),

    /**
     * callback
     */
    onRowClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onExpandChange: PropTypes.func

};

Td.defaultProps = {

    rowIndex: 0,
    colIndex: 0,

    isChecked: false,
    disabled: false,
    hasChildren: false,
    collapsed: true,
    isExpandColumn: false,
    depth: 0

};

export default Td;
<commit_msg>update Td<commit_after>/**
 * @file Td component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import IconButton from '../IconButton';

import HorizontalAlign from '../_statics/HorizontalAlign';
import SortingType from '../_statics/SortingType';

import Util from '../_vendors/Util';

class Td extends Component {

    static Align = HorizontalAlign;

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    handleCollapseButtonClick = () => {
        const {data, collapsed, onExpandChange} = this.props;
        onExpandChange && onExpandChange(!collapsed, data);
    };

    handleRenderer = () => {

        const {renderer, rowIndex, colIndex, data} = this.props;

        switch (typeof renderer) {
            case 'function':
                return renderer(data, rowIndex, colIndex);
            default:
                return renderer;
        }

    };

    handleClick = e => {
        const {data, rowIndex, colIndex, disabled, onCellClick} = this.props;
        !disabled && onCellClick && onCellClick(data, rowIndex, colIndex, e);
    };

    render() {

        const {
            className, style, align, span, hasChildren, isExpandColumn, depth,
            sortable, sortingProp, sorting
        } = this.props;

        return (
            <td className={classNames({
                [`align-${align}`]: align && align !== HorizontalAlign.LEFT,
                'table-expand-column': isExpandColumn,
                sorting: sortable && sortingProp && sorting && sorting.prop && sorting.prop === sortingProp,
                [className]: className
            })}
                style={style}
                colSpan={span || null}
                onClick={this.handleClick}>

                {
                    isExpandColumn ?
                        <span className={classNames('table-indent', `indent-level-${depth}`)}
                              style={{paddingLeft: depth * 20}}>
                        :
                        null
                }

                {
                    isExpandColumn ?
                        <IconButton className={classNames('collapse-button', {
                            hidden: !hasChildren
                        })}
                                    iconCls="fas fa-chevron-down"
                                    disableTouchRipple={true}
                                    onClick={this.handleCollapseButtonClick}/>
                        :
                        null
                }

                {this.handleRenderer()}

        );

    }
}

Td.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    rowIndex: PropTypes.number,
    colIndex: PropTypes.number,

    data: PropTypes.object,
    renderer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    align: PropTypes.oneOf(Util.enumerateValue(HorizontalAlign)),
    span: PropTypes.number,

    isChecked: PropTypes.bool,
    disabled: PropTypes.bool,
    hasChildren: PropTypes.bool,
    collapsed: PropTypes.bool,
    isExpandColumn: PropTypes.bool,
    depth: PropTypes.number,

    /**
     * sorting
     */
    sortable: PropTypes.bool,
    sortingProp: PropTypes.string,
    sorting: PropTypes.shape({
        prop: PropTypes.string,
        type: PropTypes.oneOf(Util.enumerateValue(SortingType))
    }),

    /**
     * callback
     */
    onRowClick: PropTypes.func,
    onCellClick: PropTypes.func,
    onExpandChange: PropTypes.func

};

Td.defaultProps = {

    rowIndex: 0,
    colIndex: 0,

    isChecked: false,
    disabled: false,
    hasChildren: false,
    collapsed: true,
    isExpandColumn: false,
    depth: 0

};

export default Td;
<|endoftext|>