Best Python code snippet using green
datasource.js
Source:datasource.js  
...80  it('should be able to retrieve data', function () {81    var ds = datasource.create(scope, scope.loadOptions);82    // load data83    $rootScope.$digest();84    $timeout.flush();85    $httpBackend.flush();86    $rootScope.$digest();87    expect(ds.data).toEqual(sampleData);88  });89  it('should cancel data request if scope is destroyed', function () {90    scope.loadOptions.autoLoad = false;91    var ds = datasource.create(scope, scope.loadOptions);92    // should not do anything until there is a request to cancel93    scope.$broadcast('$destroy');94    $rootScope.$digest();95    expect($httpBackend.flush).toThrow();96    ds.loadData();97    // load data98    $rootScope.$digest();99    $timeout.flush();100    scope.$broadcast('$destroy');101    $rootScope.$digest();102    expect($httpBackend.flush).toThrow();103    expect(ds.data).toEqual([]);104    scope.$broadcast('$destroy');105    $rootScope.$digest();106  });107  it('should be able to retrieve data asyncronously', function () {108    scope.loadOptions = {109      request: { url: '/sampleAsyncData' }110    };111    var ds = datasource.create(scope, scope.loadOptions);112    // load data113    $rootScope.$digest();114    $timeout.flush();115    $httpBackend.flush();116    $rootScope.$digest();117    $timeout.flush();118    $httpBackend.flush();119    ds.pause();120    $rootScope.$digest();121    $timeout.flush();122    $httpBackend.flush();123    // first two records should be in the data at this point124    expect(ds.data).toEqual([sampleData[0], sampleData[1]]);125    // puase will have occured before the first records data is moved to the view126    expect(ds.viewData).toEqual([]);127    ds.resume();128    $rootScope.$digest();129    $timeout.flush();130    $httpBackend.flush();131    // data should be moved to view at this point132    expect(ds.viewData).toEqual([sampleData[0], sampleData[1]]);133    // data should be one step ahead of view this cycle (won't be moved to view till next timeout)134    expect(ds.data).toEqual([sampleData[0], sampleData[1], sampleData[2]]);135    $rootScope.$digest();136    $timeout.flush();137    expect(ds.viewData).toEqual([sampleData[0], sampleData[1], sampleData[2]]);138    $httpBackend.flush();139    $timeout.flush();140    expect(ds.data).toEqual(sampleData);141    expect(ds.viewData).toEqual(sampleData);142  });143  it('should be able to pause and resume async data loading', function () {144    scope.loadOptions = {145      request: { url: '/sampleAsyncData' }146    };147    var ds = datasource.create(scope, scope.loadOptions);148    // load data149    $rootScope.$digest();150    $timeout.flush();151    $httpBackend.flush();152    $rootScope.$digest();153    $timeout.flush();154    $httpBackend.flush();155    $rootScope.$digest();156    $timeout.flush();157    $httpBackend.flush();158    // first two rows should be loaded + 3rd row pending159    $rootScope.$digest();160    $timeout.flush();161    ds.pause();162    expect(ds.viewData).toEqual( [ sampleData[0], sampleData[1] ] );163    $httpBackend.flush();164    $rootScope.$digest();165    $timeout.flush();166    $httpBackend.flush();167    expect(ds.viewData).toEqual( [ sampleData[0], sampleData[1] ] );168    ds.resume();169    $rootScope.$digest();170    $timeout.flush();171    expect(ds.viewData).toEqual(sampleData);172  });173  it('should update the data even if no records are returned (and thus no notify events)', function () {174    var ds = datasource.create(scope, scope.loadOptions);175    // load data176    $rootScope.$digest();177    $timeout.flush();178    $httpBackend.flush();179    expect(ds.data).toEqual(sampleData);180    scope.loadOptions.request.url = '/noData';181    $rootScope.$digest();182    $timeout.flush();183    $httpBackend.flush();184    expect(ds.data).toEqual([]);185  });186  it('should set loading flag correctly', function () {187    var ds = datasource.create(scope, scope.loadOptions);188    expect(ds.bLoading).toBe(false);189    $rootScope.$digest();190    $timeout.flush();191    expect(ds.bLoading).toBe(true);192    // complete loading data193    $httpBackend.flush();194    $timeout.flush();195    expect(ds.bLoading).toBe(false);196    expect(ds.data).toEqual(sampleData);197  });198  it('should be able to filter the data', function(){199    scope.loadOptions.filter = scope.filter;200    var ds = datasource.create(scope, scope.loadOptions);201    scope.filter.values.name = 'bob';202    // load data203    $rootScope.$digest();204    $timeout.flush();205    $httpBackend.flush();206    // process filter207    $timeout.flush();208    expect(ds.viewData).toEqual([209      { name: 'bob smith', someId: 7, otherField: 'x'},210      { name: 'bob jones', someId: 9, otherField: 'a'}211    ]);212  });213  it('should only filter the view data when the datasource is paused', function(){214    scope.loadOptions.filter = scope.filter;215    var ds = datasource.create(scope, scope.loadOptions);216    scope.filter.values.name = 'bob';217    // load data218    $rootScope.$digest();219    $timeout.flush();220    $httpBackend.flush();221    // process filter222    $timeout.flush();223    expect(ds.viewData).toEqual([224      { name: 'bob smith', someId: 7, otherField: 'x'},225      { name: 'bob jones', someId: 9, otherField: 'a'}226    ]);227    ds.pause();228    scope.filter.values.name = 'i';229    $rootScope.$digest();230    $timeout.flush();231    expect(ds.viewData).toEqual([232      { name: 'bob smith', someId: 7, otherField: 'x'}233    ]);234  });235  it('should filter results if the filter data changes', function(){236    scope.loadOptions.filter = scope.filter;237    var ds = datasource.create(scope, scope.loadOptions);238    scope.filter.values.name = 'bob';239    // load data240    $rootScope.$digest();241    $timeout.flush();242    $httpBackend.flush();243    // process filter244    $timeout.flush();245    expect(ds.viewData).toEqual([246      { name: 'bob smith', someId: 7, otherField: 'x'},247      { name: 'bob jones', someId: 9, otherField: 'a'}248    ]);249    scope.filter.values.name = 'mary';250    $rootScope.$digest();251    $timeout.flush();252    expect(ds.viewData).toEqual([253      { name : 'elsbith maryface', someId : 5, otherField : 'b' }254    ]);255  });256  it('should filter results only if the optional filter valid expression evaluates to true', function(){257    scope.loadOptions.filter = scope.filter;258    scope.loadOptions.filterValid = 'isFilterValid';259    var ds = datasource.create(scope, scope.loadOptions);260    scope.filter.values.name = 'bob';261    scope.isFilterValid = true;262    $rootScope.$digest();263    $timeout.flush();264    $httpBackend.flush();265    $timeout.flush();266    // expect initial data to be loaded. this is the only load request...267    expect(ds.viewData).toEqual([268      { name: 'bob smith', someId: 7, otherField: 'x'},269      { name: 'bob jones', someId: 9, otherField: 'a'}270    ]);271    scope.isFilterValid = false;272    scope.filter.values.name = 'mary';273    $rootScope.$digest();274    expect(ds.viewData).toEqual([275      { name: 'bob smith', someId: 7, otherField: 'x'},276      { name: 'bob jones', someId: 9, otherField: 'a'}277    ]);278    scope.isFilterValid = true;279    $rootScope.$digest();280    $timeout.flush();281    expect(ds.viewData).toEqual([282      { name : 'elsbith maryface', someId : 5, otherField : 'b' }283    ]);284  });285  it('should request new data if filter options/params change', function(){286    scope.loadOptions.filter = scope.filter;287    scope.loadOptions.request.url =  '/simple/2';288    scope.loadOptions.request.params = { foo: 'bar' };289    var ds = datasource.create(scope, scope.loadOptions);290    expect(ds.data).toEqual([]);291    // load data292    $rootScope.$digest();293    $timeout.flush();294    $httpBackend.flush();295    expect(ds.data).toEqual(data2);296    scope.loadOptions.request.url = '/simple';297    delete scope.loadOptions.request.params;298    $rootScope.$digest();299    $timeout.flush();300    $httpBackend.flush();301    expect(ds.data).toEqual(sampleData);302  });303  it('should not request new data if filter options/params change and update is set to manual request only', function(){304    scope.loadOptions.autoLoad = false;305    // this will trigger param change refresh306    scope.loadOptions.request.params = {id: 37};307    // this will trigger request option change request + filter okay request308    var ds = datasource.create(scope, scope.loadOptions);309    // load data310    $rootScope.$digest();311    // should not be any data loads triggered312    expect($timeout.flush).toThrow();313    expect($httpBackend.flush).toThrow();314    // should not have loaded any data yet...315    expect(ds.data).toEqual([]);316    // remove param as it isn't configured to return data317    delete scope.loadOptions.request.params;318    scope.$digest();319    // param change shouldn't of trigger a load320    expect($timeout.flush).toThrow();321    expect($httpBackend.flush).toThrow();322    // manually load data...323    ds.loadData();324    $rootScope.$digest();325    $timeout.flush();326    $httpBackend.flush();327    // should now have the data328    expect(ds.data).toEqual(sampleData);329  });330  it('should not request data until the optional requestValidExpr is truthy', function(){331    scope.bValid = false;332    scope.loadOptions.request.url =  '/simple/2';333    scope.loadOptions.request.params = { foo: 'bar'};334    scope.loadOptions.requestValid = 'bValid';335    var ds = datasource.create(scope, scope.loadOptions);336    // load data337    $rootScope.$digest();338    expect($httpBackend.flush).toThrow();339    scope.loadOptions.request.params.foo = 'bar2';340    $rootScope.$digest();341    scope.loadOptions.request.url =  '/simple';342    delete scope.loadOptions.request.params;343    $rootScope.$digest();344    $timeout.flush();345    expect($httpBackend.flush).toThrow();346    ds.loadData();347    $timeout.flush();348    $rootScope.$digest();349    expect($httpBackend.flush).toThrow();350    scope.bValid = true;351    $rootScope.$digest();352    $timeout.flush();353    $httpBackend.flush();354    expect(ds.data).toEqual(sampleData);355  });356  it('should cancel the first request if another request is made before it completes', function(){357    scope.loadOptions.request.url =  '/simple/2';358    scope.loadOptions.request.params = {359      foo: 'bar'360    };361    scope.ds = datasource.create(scope, scope.loadOptions);362    var updateCount = 0;363    var data = [];364    scope.$watchCollection('ds.data', function(newData){365      if (!angular.equals(newData,data)) {366        updateCount++;367      }368    });369    // load data370    $rootScope.$digest();371    $timeout.flush();372    scope.loadOptions.request.url =  '/simple';373    delete scope.loadOptions.request.params;374    $rootScope.$digest();375    $timeout.flush();376    $httpBackend.flush();377    // check data is correct378    expect(scope.ds.data).toEqual(sampleData);379    // check two requests madce380    expect($http.calls.count()).toBe(2);381    // check data was only updated once382    expect(updateCount).toBe(1);383    // check nothing outstanding happens in afterEach()384  });385  it('should not start the second request if another identical request is made before it completes', function(){386    var updateCount = 0;387    var data = [];388    scope.$watchCollection('ds.data', function(newData){389      if (!angular.equals(newData,data)) {390        updateCount++;391      }392    });393    scope.ds = datasource.create(scope, scope.loadOptions);394    // load data395    $rootScope.$digest();396    $timeout.flush();397    scope.ds.loadData();398    $rootScope.$digest();399    $timeout.flush();400    $httpBackend.flush();401    // check data is correct402    expect(scope.ds.data).toEqual(sampleData);403    // check only one request was made404    expect($http.calls.count()).toBe(1);405    // check data was only updated once406    expect(updateCount).toBe(1);407    // check nothing outstanding happens in afterEach()408  });409  it('should be able to paginate the data', function(){410    scope.loadOptions.pagination = {411      perPage: 2412    };413    var ds = datasource.create(scope, scope.loadOptions);414    // load data415    $rootScope.$digest();416    $timeout.flush();417    $httpBackend.flush();418    $timeout.flush();419    expect(ds.data).toEqual(sampleData);420    // digest here to make sure filter/watcher is setup before data loaded421    ds.setPage(2);422    $rootScope.$digest();423    expect(ds.pageData).toEqual([424      { name: 'bob jones', someId: 9, otherField: 'a'},425      { name: 'elsbith maryface', someId: 5, otherField: 'b'}426    ]);427    expect(ds.pages).toBe(2);428    expect(ds.currentPage).toBe(2);429    // change the page430    ds.setPage(1);431    $rootScope.$digest();432    expect(ds.pageData).toEqual([433      { name: 'bob smith', someId: 7, otherField: 'x'},434      { name: 'dave ham', someId: 8, otherField: 'y'}435    ]);436  });437  it('should keep the current page within the bounds', function(){438    scope.loadOptions.pagination = {439      perPage: 2440    };441    var ds = datasource.create(scope, scope.loadOptions);442    // load data443    $rootScope.$digest();444    // should set current page to 0 initially as no data will be loaded445    expect(ds.currentPage).toBe(0);446    $timeout.flush(); // get data timeout447    $httpBackend.flush();448    $timeout.flush(); // apply filter timeout449    expect(ds.viewData).toEqual(sampleData);450    // set current page too high451    ds.setPage(4);452    $rootScope.$digest();453    expect(ds.currentPage).toBe(2);454    // set current page too low455    ds.setPage(-3);456    $rootScope.$digest();457    expect(ds.currentPage).toBe(1);458  });459  it('should sort the data if a sort function is provided', function(){460    var ds = datasource.create(scope, scope.loadOptions);461    ds.sortFunction = function(a) {462      return (a.name.toLowerCase());463    };464    // load data465    $rootScope.$digest();466    $timeout.flush();467    $httpBackend.flush();468    expect(ds.data).toEqual([469      { name: 'bob jones', someId: 9, otherField: 'a'},470      { name: 'bob smith', someId: 7, otherField: 'x'},471      { name: 'dave ham', someId: 8, otherField: 'y'},472      { name: 'elsbith maryface', someId: 5, otherField: 'b'}473    ]);474  });475  it('should reverse the order of the data if datasource.sortOrder is DESC', function(){476    var ds = datasource.create(scope, scope.loadOptions);477    ds.sortFunction = function(a) {478      return (a.name.toLowerCase());479    };480    // load data481    $rootScope.$digest();482    $timeout.flush();483    $httpBackend.flush();484    expect(ds.data).toEqual([485      { name: 'bob jones', someId: 9, otherField: 'a'},486      { name: 'bob smith', someId: 7, otherField: 'x'},487      { name: 'dave ham', someId: 8, otherField: 'y'},488      { name: 'elsbith maryface', someId: 5, otherField: 'b'}489    ]);490    ds.sortOrder = 'DESC';491    // load data492    $rootScope.$digest();493    expect(ds.data).toEqual([494      { name: 'elsbith maryface', someId: 5, otherField: 'b'},495      { name: 'dave ham', someId: 8, otherField: 'y'},496      { name: 'bob smith', someId: 7, otherField: 'x'},497      { name: 'bob jones', someId: 9, otherField: 'a'}498    ]);499  });500  it('should resort the data if the sort function changes', function(){501    var ds = datasource.create(scope, scope.loadOptions);502    ds.sortFunction = function(a) {503      return (a.name.toLowerCase());504    };505    ds.loadData();506    // load data507    $rootScope.$digest();508    $timeout.flush();509    $httpBackend.flush();510    expect(ds.data).toEqual([511      { name: 'bob jones', someId: 9, otherField: 'a'},512      { name: 'bob smith', someId: 7, otherField: 'x'},513      { name: 'dave ham', someId: 8, otherField: 'y'},514      { name: 'elsbith maryface', someId: 5, otherField: 'b'}515    ]);516    ds.sortFunction = function(a) {517      return (a.someId);518    };519    $rootScope.$digest();520    $timeout.flush();521    // this should not have caused a new request to the backend522    expect($httpBackend.flush).toThrow();523    expect(ds.data).toEqual([524      { name: 'elsbith maryface', someId: 5, otherField: 'b'},525      { name: 'bob smith', someId: 7, otherField: 'x'},526      { name: 'dave ham', someId: 8, otherField: 'y'},527      { name: 'bob jones', someId: 9, otherField: 'a'}528    ]);529  });530    // sampleData = [531    //   { name: 'bob smith', someId: 7, otherField: 'x'},532    //   { name: 'dave ham', someId: 8, otherField: 'y'},533    //   { name: 'bob jones', someId: 9, otherField: 'a'},534    //   { name: 'elsbith maryface', someId: 5, otherField: 'b'}535    // ];536  it('should be able to sort the data during async data loading', function () {537    scope.loadOptions = {538      request: { url: '/sampleAsyncData' }539    };540    var ds = datasource.create(scope, scope.loadOptions);541    ds.sortFunction = function(a) {542      return (a.name.toLowerCase());543    };544    // load data545    $rootScope.$digest();546    $timeout.flush();547    $httpBackend.flush();548    $rootScope.$digest();549    $timeout.flush();550    $httpBackend.flush();551    ds.sortOrder = 'DESC';552    $rootScope.$digest();553    $timeout.flush();554    $httpBackend.flush();555    // first two rows should be loaded + 3rd row pending556    $rootScope.$digest();557    $timeout.flush();558    ds.pause();559    expect(ds.viewData).toEqual( [ sampleData[1], sampleData[0] ] );560    ds.sortFunction = function(a) {561      return (a.someId);562    };563    $rootScope.$digest();564    expect(ds.viewData).toEqual( [ sampleData[1], sampleData[0] ] );565    ds.sortOrder = 'ASC';566    ds.sortFunction = function(a) {567      return (a.name.toLowerCase());568    };569    expect(ds.viewData).toEqual( [ sampleData[1], sampleData[0] ] );570    $httpBackend.flush();571    $rootScope.$digest();572    ds.resume();573    $timeout.flush();574    $httpBackend.flush();575    expect(ds.viewData).toEqual( [ sampleData[2], sampleData[0],  sampleData[1] ] );576    $rootScope.$digest();577    $timeout.flush();578    expect(ds.viewData).toEqual( [ sampleData[2], sampleData[0],  sampleData[1], sampleData[3] ] );579  });580  it('should be able to execute a function after data is loaded', function () {581    var complete = false;582    scope.loadOptions.onLoadComplete = function(){583      complete = true;584    };585    var ds = datasource.create(scope, scope.loadOptions);586    // load data587    $rootScope.$digest();588    $timeout.flush();589    $httpBackend.flush();590    // data isn't filtered/paged until next digest cycle, then function should be executed591    $timeout.flush();592    expect(ds.data).toEqual(sampleData);593    expect(complete).toEqual(true);594  });595  describe('trigger row reload function', function(){596    var ds;597    beforeEach(function(){598      scope.loadOptions.requestRowFunction = jasmine.createSpy('request row function');599      ds = datasource.create(scope, scope.loadOptions);600      // make the names sorted by alpha601      ds.sortFunction = function(a) {602        return (a.name.toLowerCase());603      };604      // load data605      $rootScope.$digest();606      $timeout.flush();607      $httpBackend.flush();608      $timeout.flush();609    });610    it('should be able to reload a single row and reapply sort/pagination', function () {611      scope.loadOptions.requestRowFunction.and.callFake(function(row){612        row.name = 'a ' + row.name + ' the first of his name';613        return row;614      });615      var match = angular.copy(sampleData[1]);616      ds.triggerRowReload(match);617      // digest + flush timeout to allow new sorting618      $rootScope.$digest();619      $timeout.flush();620      expect(scope.loadOptions.requestRowFunction).toHaveBeenCalledWith(match);621      expect(ds.viewData[0].name).toBe('a ' + sampleData[1].name + ' the first of his name');622      expect(ds.viewData[2].name).toBe('bob smith');623    });624    it('should be able to add a new row to the dataset if reload is triggered on an unknown row', function () {625      scope.loadOptions.requestRowFunction.and.callFake(_.identity);626      var match = { name: 'aardvarky albertson', someId: 11, otherField: 'f'};627      ds.triggerRowReload(match);628      // digest + flush timeout to allow new sorting629      $rootScope.$digest();630      $timeout.flush();631      expect(ds.viewData[0]).toBe(match);632    });633    it('should not add a new row to the dataset if reload is triggered on an unknown row but returns no data', function () {634      expect(ds.data.length).toBe(4);635      scope.loadOptions.requestRowFunction.and.callFake(angular.noop);636      var match = { name: 'aardvarky albertson', someId: 11, otherField: 'f'};637      ds.triggerRowReload(match);638      // digest + flush timeout to allow new sorting639      $rootScope.$digest();640      $timeout.flush();641      // should not be any new rowsz642      expect(ds.data.length).toBe(4);643    });644    it('should be able to reload a single row and reapply sort/pagination with new data provided to triggerReload', function () {645      var match = angular.copy(sampleData[1]);646      ds.triggerRowReload(match, {name: 'a ' + sampleData[1].name + ' the first of his name'});647      // digest + flush timeout to allow new sorting648      $rootScope.$digest();649      $timeout.flush();650      expect(ds.viewData[0].name).toBe('a ' + sampleData[1].name + ' the first of his name');651      expect(ds.viewData[2].name).toBe('bob smith');652    });653    it('should delete row if the reloaded data is null/undefined', function () {654      scope.loadOptions.requestRowFunction.and.callFake(function(){655        return null;656      });657      var match = angular.copy(sampleData[1]);658      expect(ds.data.length).toBe(4);659      expect(_.findWhere(ds.data, match)).toEqual(sampleData[1]);660      ds.triggerRowReload(match);661      // digest + flush timeout to allow new sorting662      $rootScope.$digest();663      $timeout.flush();664      expect(ds.data.length).toBe(3);665      expect(_.findWhere(ds.data, match)).toBe(undefined);666    });667    it('should delete row if the reloaded data is null/undefined with data provided to triggerReload', function () {668      var match = angular.copy(sampleData[1]);669      expect(ds.data.length).toBe(4);670      expect(_.findWhere(ds.data, match)).toEqual(sampleData[1]);671      ds.triggerRowReload(match, undefined);672      // digest + flush timeout to allow new sorting673      $rootScope.$digest();674      $timeout.flush();675      expect(ds.data.length).toBe(3);676      expect(_.findWhere(ds.data, match)).toBe(undefined);677    });678});...parse-chunked.js
Source:parse-chunked.js  
...126            }127        }128        return fragment;129    }130    flush(chunk, start, end) {131        let fragment = chunk.slice(start, end);132        // Save position correction an error in JSON.parse() if any133        this.jsonParseOffset = this.chunkOffset + start;134        // Prepend pending chunk if any135        if (this.pendingChunk !== null) {136            fragment = this.pendingChunk + fragment;137            this.jsonParseOffset -= this.pendingChunk.length;138            this.pendingChunk = null;139        }140        if (this.flushDepth === this.lastFlushDepth) {141            // Depth didn't changed, so it's a root value or entry/element set142            if (this.flushDepth > 0) {143                this.parseAndAppend(this.prepareAddition(fragment), true);144            } else {145                // That's an entire value on a top level146                this.value = JSON.parse(fragment);147                this.valueStack = {148                    value: this.value,149                    prev: null150                };151            }152        } else if (this.flushDepth > this.lastFlushDepth) {153            // Add missed closing brackets/parentheses154            for (let i = this.flushDepth - 1; i >= this.lastFlushDepth; i--) {155                fragment += this.stack[i] === STACK_OBJECT ? '}' : ']';156            }157            if (this.lastFlushDepth === 0) {158                // That's a root value159                this.value = JSON.parse(fragment);160                this.valueStack = {161                    value: this.value,162                    prev: null163                };164            } else {165                this.parseAndAppend(this.prepareAddition(fragment), true);166            }167            // Move down to the depths to the last object/array, which is current now168            for (let i = this.lastFlushDepth || 1; i < this.flushDepth; i++) {169                let value = this.valueStack.value;170                if (this.stack[i - 1] === STACK_OBJECT) {171                    // find last entry172                    let key;173                    // eslint-disable-next-line curly174                    for (key in value);175                    value = value[key];176                } else {177                    // last element178                    value = value[value.length - 1];179                }180                this.valueStack = {181                    value,182                    prev: this.valueStack183                };184            }185        } else /* this.flushDepth < this.lastFlushDepth */ {186            fragment = this.prepareAddition(fragment);187            // Add missed opening brackets/parentheses188            for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {189                this.jsonParseOffset--;190                fragment = (this.stack[i] === STACK_OBJECT ? '{' : '[') + fragment;191            }192            this.parseAndAppend(fragment, false);193            for (let i = this.lastFlushDepth - 1; i >= this.flushDepth; i--) {194                this.valueStack = this.valueStack.prev;195            }196        }197        this.lastFlushDepth = this.flushDepth;198    }199    push(chunk) {200        if (typeof chunk !== 'string') {201            // Suppose chunk is Buffer or Uint8Array202            // Prepend uncompleted byte sequence if any203            if (this.pendingByteSeq !== null) {204                const origRawChunk = chunk;205                chunk = new Uint8Array(this.pendingByteSeq.length + origRawChunk.length);206                chunk.set(this.pendingByteSeq);207                chunk.set(origRawChunk, this.pendingByteSeq.length);208                this.pendingByteSeq = null;209            }210            // In case Buffer/Uint8Array, an input is encoded in UTF8211            // Seek for parts of uncompleted UTF8 symbol on the ending212            // This makes sense only if we expect more chunks and last char is not multi-bytes213            if (chunk[chunk.length - 1] > 127) {214                for (let seqLength = 0; seqLength < chunk.length; seqLength++) {215                    const byte = chunk[chunk.length - 1 - seqLength];216                    // 10xxxxxx - 2nd, 3rd or 4th byte217                    // 110xxxxx â first byte of 2-byte sequence218                    // 1110xxxx - first byte of 3-byte sequence219                    // 11110xxx - first byte of 4-byte sequence220                    if (byte >> 6 === 3) {221                        seqLength++;222                        // If the sequence is really incomplete, then preserve it223                        // for the future chunk and cut off it from the current chunk224                        if ((seqLength !== 4 && byte >> 3 === 0b11110) ||225                            (seqLength !== 3 && byte >> 4 === 0b1110) ||226                            (seqLength !== 2 && byte >> 5 === 0b110)) {227                            this.pendingByteSeq = chunk.slice(chunk.length - seqLength);228                            chunk = chunk.slice(0, -seqLength);229                        }230                        break;231                    }232                }233            }234            // Convert chunk to a string, since single decode per chunk235            // is much effective than decode multiple small substrings236            chunk = decoder.decode(chunk);237        }238        const chunkLength = chunk.length;239        let lastFlushPoint = 0;240        let flushPoint = 0;241        // Main scan loop242        scan: for (let i = 0; i < chunkLength; i++) {243            if (this.stateString) {244                for (; i < chunkLength; i++) {245                    if (this.stateStringEscape) {246                        this.stateStringEscape = false;247                    } else {248                        switch (chunk.charCodeAt(i)) {249                            case 0x22: /* " */250                                this.stateString = false;251                                continue scan;252                            case 0x5C: /* \ */253                                this.stateStringEscape = true;254                        }255                    }256                }257                break;258            }259            switch (chunk.charCodeAt(i)) {260                case 0x22: /* " */261                    this.stateString = true;262                    this.stateStringEscape = false;263                    break;264                case 0x2C: /* , */265                    flushPoint = i;266                    break;267                case 0x7B: /* { */268                    // Open an object269                    flushPoint = i + 1;270                    this.stack[this.flushDepth++] = STACK_OBJECT;271                    break;272                case 0x5B: /* [ */273                    // Open an array274                    flushPoint = i + 1;275                    this.stack[this.flushDepth++] = STACK_ARRAY;276                    break;277                case 0x5D: /* ] */278                case 0x7D: /* } */279                    // Close an object or array280                    flushPoint = i + 1;281                    this.flushDepth--;282                    if (this.flushDepth < this.lastFlushDepth) {283                        this.flush(chunk, lastFlushPoint, flushPoint);284                        lastFlushPoint = flushPoint;285                    }286                    break;287                case 0x09: /* \t */288                case 0x0A: /* \n */289                case 0x0D: /* \r */290                case 0x20: /* space */291                    // Move points forward when they points on current position and it's a whitespace292                    if (lastFlushPoint === i) {293                        lastFlushPoint++;294                    }295                    if (flushPoint === i) {296                        flushPoint++;297                    }298                    break;299            }300        }301        if (flushPoint > lastFlushPoint) {302            this.flush(chunk, lastFlushPoint, flushPoint);303        }304        // Produce pendingChunk if something left305        if (flushPoint < chunkLength) {306            if (this.pendingChunk !== null) {307                // When there is already a pending chunk then no flush happened,308                // appending entire chunk to pending one309                this.pendingChunk += chunk;310            } else {311                // Create a pending chunk, it will start with non-whitespace since312                // flushPoint was moved forward away from whitespaces on scan313                this.pendingChunk = chunk.slice(flushPoint, chunkLength);314            }315        }316        this.chunkOffset += chunkLength;317    }318    finish() {319        if (this.pendingChunk !== null) {320            this.flush('', 0, 0);321            this.pendingChunk = null;322        }323        return this.value;324    }...collaboration.service_test.js
Source:collaboration.service_test.js  
...22				Bacon.interval(0, [{$id: 'id'}])23			)24	}25	function flushAll(){26		fb.ref.flush();27    try { 28    	$timeout.flush() 29    }30    // Catch all digest errors! Throw all others!31    catch (e) {32    	if(!/digest/ig.test(e.message) && !/deferred/ig.test(e.message)){33    		throw e34    	}35    }36	}37	beforeEach(function(){38		module('goodMood', function($provide){39			$provide.value('Auth', Auth)40			$provide.value('Iteration', Iteration)41			$provide.value('Thread', Thread)42			$provide.value('User', User)...index.js
Source:index.js  
...83  }84  end (chunk, encoding, cb) {85    if (chunk)86      this.write(chunk, encoding)87    this.flush(this[_finishFlushFlag])88    this[_ended] = true89    return super.end(null, null, cb)90  }91  get ended () {92    return this[_ended]93  }94  write (chunk, encoding, cb) {95    // process the chunk using the sync process96    // then super.write() all the outputted chunks97    if (typeof encoding === 'function')98      cb = encoding, encoding = 'utf8'99    if (typeof chunk === 'string')100      chunk = Buffer.from(chunk, encoding)101    if (this[_sawError])102      return103    assert(this[_handle], 'zlib binding closed')104    // _processChunk tries to .close() the native handle after it's done, so we105    // intercept that by temporarily making it a no-op.106    const nativeHandle = this[_handle]._handle107    const originalNativeClose = nativeHandle.close108    nativeHandle.close = () => {}109    const originalClose = this[_handle].close110    this[_handle].close = () => {}111    // It also calls `Buffer.concat()` at the end, which may be convenient112    // for some, but which we are not interested in as it slows us down.113    Buffer.concat = (args) => args114    let result115    try {116      const flushFlag = typeof chunk[_flushFlag] === 'number'117        ? chunk[_flushFlag] : this[_flushFlag]118      result = this[_handle]._processChunk(chunk, flushFlag)119      // if we don't throw, reset it back how it was120      Buffer.concat = OriginalBufferConcat121    } catch (err) {122      // or if we do, put Buffer.concat() back before we emit error123      // Error events call into user code, which may call Buffer.concat()124      Buffer.concat = OriginalBufferConcat125      this[_onError](new ZlibError(err))126    } finally {127      if (this[_handle]) {128        // Core zlib resets `_handle` to null after attempting to close the129        // native handle. Our no-op handler prevented actual closure, but we130        // need to restore the `._handle` property.131        this[_handle]._handle = nativeHandle132        nativeHandle.close = originalNativeClose133        this[_handle].close = originalClose134        // `_processChunk()` adds an 'error' listener. If we don't remove it135        // after each call, these handlers start piling up.136        this[_handle].removeAllListeners('error')137      }138    }139    let writeReturn140    if (result) {141      if (Array.isArray(result) && result.length > 0) {142        // The first buffer is always `handle._outBuffer`, which would be143        // re-used for later invocations; so, we always have to copy that one.144        writeReturn = super.write(Buffer.from(result[0]))145        for (let i = 1; i < result.length; i++) {146          writeReturn = super.write(result[i])147        }148      } else {149        writeReturn = super.write(Buffer.from(result))150      }151    }152    if (cb)153      cb()154    return writeReturn155  }156}157class Zlib extends ZlibBase {158  constructor (opts, mode) {159    opts = opts || {}160    opts.flush = opts.flush || constants.Z_NO_FLUSH161    opts.finishFlush = opts.finishFlush || constants.Z_FINISH162    super(opts, mode)163    this[_fullFlushFlag] = constants.Z_FULL_FLUSH164    this[_level] = opts.level165    this[_strategy] = opts.strategy166  }167  params (level, strategy) {168    if (this[_sawError])169      return170    if (!this[_handle])171      throw new Error('cannot switch params when binding is closed')172    // no way to test this without also not supporting params at all173    /* istanbul ignore if */174    if (!this[_handle].params)175      throw new Error('not supported in this implementation')176    if (this[_level] !== level || this[_strategy] !== strategy) {177      this.flush(constants.Z_SYNC_FLUSH)178      assert(this[_handle], 'zlib binding closed')179      // .params() calls .flush(), but the latter is always async in the180      // core zlib. We override .flush() temporarily to intercept that and181      // flush synchronously.182      const origFlush = this[_handle].flush183      this[_handle].flush = (flushFlag, cb) => {184        this.flush(flushFlag)185        cb()186      }187      try {188        this[_handle].params(level, strategy)189      } finally {190        this[_handle].flush = origFlush191      }192      /* istanbul ignore else */193      if (this[_handle]) {194        this[_level] = level195        this[_strategy] = strategy196      }197    }198  }...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
