GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — nodejs-storage/test/resumable-upload.ts at main · googleapis/nodejs-storage
This repository was archived by the owner on Mar 3, 2026. It is now read-only.
Expand file tree/ Copy pathresumable-upload.tsMore file actions 3138 lines (2644 loc) · 94.6 KB / Copy pathresumable-upload.tsFile metadata and controls3138 lines (2644 loc) · 94.6 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 // Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import assert from 'assert'; import {describe, it, beforeEach, before, afterEach, after} from 'mocha'; import * as crypto from 'crypto'; import * as mockery from 'mockery'; import nock from 'nock'; import * as path from 'path'; import * as sinon from 'sinon'; import {Readable, Writable} from 'stream'; import { RETRY_DELAY_MULTIPLIER_DEFAULT, TOTAL_TIMEOUT_DEFAULT, MAX_RETRY_DELAY_DEFAULT, AUTO_RETRY_DEFAULT, MAX_RETRY_DEFAULT, RETRYABLE_ERR_FN_DEFAULT, } from '../src/storage.js'; import { ApiError, CreateUriCallback, PROTOCOL_REGEX, UploadConfig, } from '../src/resumable-upload.js'; import {GaxiosOptions, GaxiosError, GaxiosResponse} from 'gaxios'; import {GCCL_GCS_CMD_KEY} from '../src/nodejs-common/util.js'; import {getDirName} from '../src/util.js'; import {FileExceptionMessages} from '../src/file.js'; nock.disableNetConnect(); class AbortController { aborted = false; signal = this; abort() { this.aborted = true; } } const RESUMABLE_INCOMPLETE_STATUS_CODE = 308; /** 256 KiB */ const CHUNK_SIZE_MULTIPLE = 2 ** 18; const queryPath = '/?userProject=user-project-id'; const X_GOOG_API_HEADER_REGEX = /^gl-node\/(?<nodeVersion>[^W]+) gccl\/(?<gccl>[^W]+) gccl-invocation-id\/(?<gcclInvocationId>[^W]+) gccl-gcs-cmd\/(?<gcclGcsCmd>[^W]+)$/; const USER_AGENT_REGEX = /^gcloud-node-storage\/(?<libVersion>[^W]+)$/; const CORRECT_CLIENT_CRC32C = 'Q2hlY2tzdW0h'; const INCORRECT_SERVER_CRC32C = 'Q2hlY2tzdVUa'; const CORRECT_CLIENT_MD5 = 'CorrectMD5Hash'; const INCORRECT_SERVER_MD5 = 'IncorrectMD5Hash'; function mockAuthorizeRequest( code = 200, data: {} | string = { access_token: 'abc123', } ) { return nock('https://www.googleapis.com') .post('/oauth2/v4/token') .reply(code, data); } describe('resumable-upload', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let upload: any; // eslint-disable-next-line @typescript-eslint/no-explicit-any let up: any; const BUCKET = 'bucket-name'; const CUSTOM_REQUEST_OPTIONS = {headers: {'X-My-Header': 'My custom value'}}; const FILE = 'file-name'; const GENERATION = Date.now(); const METADATA = {contentLength: 1024, contentType: 'application/json'}; const ORIGIN = '*'; const PARAMS = {ifMetagenerationNotMatch: 3}; const PREDEFINED_ACL = 'authenticatedRead'; const USER_PROJECT = 'user-project-id'; const API_ENDPOINT = 'https://fake.googleapis.com'; const BASE_URI = `${API_ENDPOINT}/upload/storage/v1/b`; const RETRY_OPTIONS = { retryDelayMultiplier: RETRY_DELAY_MULTIPLIER_DEFAULT, totalTimeout: TOTAL_TIMEOUT_DEFAULT, maxRetryDelay: MAX_RETRY_DELAY_DEFAULT, autoRetry: AUTO_RETRY_DEFAULT, maxRetries: MAX_RETRY_DEFAULT, retryableErrorFn: RETRYABLE_ERR_FN_DEFAULT, }; let REQ_OPTS: GaxiosOptions; const keyFile = path.join(getDirName(), '../../../test/fixtures/keys.json'); before(() => { mockery.registerMock('abort-controller', AbortController); mockery.enable({useCleanCache: true, warnOnUnregistered: false}); upload = require('../src/resumable-upload').upload; }); beforeEach(() => { REQ_OPTS = {url: 'http://fake.local'}; up = upload({ bucket: BUCKET, file: FILE, customRequestOptions: CUSTOM_REQUEST_OPTIONS, generation: GENERATION, metadata: METADATA, origin: ORIGIN, params: PARAMS, predefinedAcl: PREDEFINED_ACL, userProject: USER_PROJECT, authConfig: {keyFile}, apiEndpoint: API_ENDPOINT, retryOptions: {...RETRY_OPTIONS}, [GCCL_GCS_CMD_KEY]: 'sample.command', clientCrc32c: CORRECT_CLIENT_CRC32C, clientMd5Hash: CORRECT_CLIENT_MD5, }); }); afterEach(() => { nock.cleanAll(); }); after(() => { mockery.deregisterAll(); mockery.disable(); }); describe('ctor', () => { it('should be a Writable', () => { assert(up instanceof Writable); }); it('should throw if a bucket or file is not given', () => { assert.throws(() => { upload(); }, /A bucket and file name are required/); }); it('should localize the bucket', () => { assert.strictEqual(up.bucket, BUCKET); }); it('should localize the cacheKey', () => { assert.strictEqual(up.cacheKey, [BUCKET, FILE, GENERATION].join('/')); }); it('should localize customRequestOptions', () => { assert.strictEqual(up.customRequestOptions, CUSTOM_REQUEST_OPTIONS); }); it('should default customRequestOptions to empty object', () => { const up = upload({ bucket: BUCKET, file: FILE, retryOptions: RETRY_OPTIONS, }); assert.deepStrictEqual(up.customRequestOptions, {}); }); it('should include ZERO generation value in the cacheKey', () => { const upWithZeroGeneration = upload({ bucket: BUCKET, file: FILE, generation: 0, metadata: METADATA, origin: ORIGIN, predefinedAcl: PREDEFINED_ACL, userProject: USER_PROJECT, authConfig: {keyFile}, apiEndpoint: API_ENDPOINT, retryOptions: RETRY_OPTIONS, }); assert.strictEqual( upWithZeroGeneration.cacheKey, [BUCKET, FILE, 0].join('/') ); }); it('should not include a generation in the cacheKey if it was not set', () => { const up = upload({ bucket: BUCKET, file: FILE, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.cacheKey, [BUCKET, FILE].join('/')); }); it('should localize the file', () => { assert.strictEqual(up.file, FILE); }); it('should localize the generation', () => { assert.strictEqual(up.generation, GENERATION); }); it('should localize the apiEndpoint', () => { assert.strictEqual(up.apiEndpoint, API_ENDPOINT); assert.strictEqual(up.baseURI, BASE_URI); }); it('should prepend https:// to apiEndpoint if not present', () => { const up = upload({ bucket: BUCKET, file: FILE, apiEndpoint: 'fake.googleapis.com', retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.apiEndpoint, API_ENDPOINT); assert.strictEqual(up.baseURI, BASE_URI); }); it('should localize the KMS key name', () => { const kmsKeyName = 'kms-key-name'; const up = upload({ bucket: 'BUCKET', file: FILE, kmsKeyName, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.kmsKeyName, kmsKeyName); }); it('should localize metadata or default to empty object', () => { assert.strictEqual(up.metadata, METADATA); const upWithoutMetadata = upload({ bucket: BUCKET, file: FILE, retryOptions: RETRY_OPTIONS, }); assert.deepStrictEqual(upWithoutMetadata.metadata, {}); }); it('should set the offset if it is provided', () => { const offset = 10; const up = upload({ bucket: BUCKET, file: FILE, offset, uri: 'https://example.com', retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.offset, offset); }); it('should localize the origin', () => { assert.strictEqual(up.origin, ORIGIN); }); it('should localize the params', () => { assert.strictEqual(up.params, PARAMS); }); it('should localize userProject', () => { assert.strictEqual(up.userProject, USER_PROJECT); }); it('should localize an encryption object from a key', () => { const key = crypto.randomBytes(32); const up = upload({ bucket: BUCKET, file: FILE, key, retryOptions: RETRY_OPTIONS, }); const expectedKey = key.toString('base64'); const expectedHash = crypto .createHash('sha256') .update(key) .digest('base64'); assert.deepStrictEqual(up.encryption, { key: expectedKey, hash: expectedHash, }); }); it('should localize the predefinedAcl', () => { assert.strictEqual(up.predefinedAcl, PREDEFINED_ACL); }); it('should set the predefinedAcl with public: true', () => { const up = upload({ bucket: BUCKET, file: FILE, public: true, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.predefinedAcl, 'publicRead'); }); it('should set the predefinedAcl with private: true', () => { const up = upload({ bucket: BUCKET, file: FILE, private: true, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.predefinedAcl, 'private'); }); it('should set numBytesWritten to 0', () => { assert.strictEqual(up.numBytesWritten, 0); }); it('should set numRetries to 0', () => { assert.strictEqual(up.numRetries, 0); }); it('should set the contentLength if provided', () => { const up = upload({ bucket: BUCKET, file: FILE, metadata: {contentLength: METADATA.contentLength}, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.contentLength, METADATA.contentLength); }); it('should default the contentLength to *', () => { const up = upload({ bucket: BUCKET, file: FILE, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.contentLength, '*'); }); it('should localize the uri', () => { const uri = 'http://www.blah.com/'; const upWithUri = upload({ bucket: BUCKET, file: FILE, uri, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(upWithUri.uriProvidedManually, true); assert.strictEqual(upWithUri.uri, uri); }); it('should not have `chunkSize` by default', () => { const up = upload({ bucket: BUCKET, file: FILE, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.chunkSize, undefined); }); it('should accept and set `chunkSize`', () => { const up = upload({ bucket: BUCKET, file: FILE, chunkSize: 123, retryOptions: RETRY_OPTIONS, }); assert.strictEqual(up.chunkSize, 123); }); it('should have a default `writableHighWaterMark`', () => { const up = upload({ bucket: BUCKET, file: FILE, retryOptions: RETRY_OPTIONS, }); assert(up.writableHighWaterMark); }); it('should accept a `highWaterMark` and set a `writableHighWaterMark`', () => { const up = upload({ bucket: BUCKET, file: FILE, retryOptions: RETRY_OPTIONS, highWaterMark: 123, }); assert.strictEqual(up.writableHighWaterMark, 123); }); describe('on write', () => { let uri = ''; beforeEach(() => { uri = 'uri'; }); it("should emit 'writing' when piped", done => { let read = false; const upstreamBuffer = new Readable({ read() { if (!read) { this.push(Buffer.alloc(1)); read = true; } }, }); up.createURI = () => {}; up.once('writing', () => { upstreamBuffer.push(null); done(); }); upstreamBuffer.pipe(up); }); it("should set `upstreamEnded` to `true` and emit 'upstreamFinished' on `#end()`", done => { const upstreamBuffer = new Readable({ read() { this.push(Buffer.alloc(1)); this.push(null); }, }); up.createURI = () => {}; up.once('writing', () => { up.on('upstreamFinished', () => { assert.equal(up.upstreamEnded, true); done(); }); assert.equal(up.upstreamEnded, false); up.once('wroteToChunkBuffer', () => up.emit('readFromChunkBuffer')); }); upstreamBuffer.pipe(up); }); it('should continue uploading', done => { up.uri = uri; up.continueUploading = done; up.emit('writing'); }); it('should create an upload', done => { up.startUploading = done; up.createURI = (callback: CreateUriCallback) => { callback(null); }; up.emit('writing'); }); it('should destroy the stream from an error', done => { const error: ApiError = { message: ':(', name: ':(', code: 123, }; up.destroy = (err: ApiError) => { assert(err.message.indexOf(error.message) > -1); assert(err.name.indexOf(error.name) > -1); assert.strictEqual(err.code, 123); done(); }; up.createURI = (callback: CreateUriCallback) => { callback(error); }; up.emit('writing'); }); }); }); describe('upstream', () => { beforeEach(() => { up.createURI = () => {}; }); it('should handle writes to class', done => { up.on('wroteToChunkBuffer', () => { assert.equal(up.writeBuffers[0].byteLength, 16); done(); }); up.write(Buffer.alloc(16)); }); it("should setup a 'uploadFinished' handler on 'upstreamFinished'", done => { assert.equal(up.eventNames().includes('uploadFinished'), false); up.on('upstreamFinished', () => { assert.equal(up.eventNames().includes('uploadFinished'), true); done(); }); up.end(); }); it("should finish only after 'uploadFinished' is emitted", done => { const upstreamBuffer = new Readable({ read() { this.push(Buffer.alloc(1)); this.push(null); }, }); // Readable has ended upstreamBuffer.on('end', () => { // The data has been written to the buffer up.on('wroteToChunkBuffer', () => { // Allow the writer's callback be called immediately up.emit('readFromChunkBuffer'); // setting up the listener now to prove it hasn't been fired before up.on('finish', done); process.nextTick(() => up.emit('uploadFinished')); }); }); upstreamBuffer.pipe(up); }); }); describe('#_write', () => { beforeEach(() => { up.createURI = () => {}; }); it('should append buffer to existing `writeBuffers`', () => { up.writeBuffers = [Buffer.from('abc')]; up.write(Buffer.from('def')); assert.equal( Buffer.compare(Buffer.concat(up.writeBuffers), Buffer.from('abcdef')), 0 ); }); it('should convert string with encoding to Buffer and append to existing `writeBuffers`', () => { const existing = 'a '; const sample = '🦃'; const concat = existing + sample; up.writeBuffers = [Buffer.from(existing)]; up.write(sample, 'utf-8', () => {}); for (const buf of up.writeBuffers) { assert(Buffer.isBuffer(buf)); } assert.equal(Buffer.concat(up.writeBuffers), concat); }); it("should callback on 'readFromChunkBuffer'", done => { // The 'done' here is a callback from 'readFromChunkBuffer' up.write('sample', 'utf-8', done); up.emit('readFromChunkBuffer'); }); it("should emit 'wroteToChunkBuffer' asynchronously", done => { up.write('sample', 'utf-8', () => {}); // setting this here proves it's async up.on('wroteToChunkBuffer', done); }); }); describe('#prependLocalBufferToUpstream', () => { it('should synchronously prepend to existing buffer', () => { up.localWriteCache = [Buffer.from('123')]; up.localWriteCacheByteLength = up.localWriteCache[0].byteLength; up.writeBuffers = [Buffer.from('456')]; up.prependLocalBufferToUpstream(); assert.equal(up.localWriteCache.length, 0); // shouldn't concat any buffers, thus writeBuffers.length = 2 assert.equal(up.writeBuffers.length, 2); assert.equal(Buffer.concat(up.writeBuffers).toString(), '123456'); assert.equal(up.localWriteCacheByteLength, 0); }); it('should keep the desired last few bytes', () => { up.localWriteCache = [Buffer.from('123'), Buffer.from('456')]; up.localWriteCacheByteLength = up.localWriteCache.reduce( (a: Buffer, b: number) => a.byteLength + b ); up.writeBuffers = [Buffer.from('789')]; up.prependLocalBufferToUpstream(2); assert.equal(up.localWriteCache.length, 0); // shouldn't concat any buffers, thus writeBuffers.length = 2 assert.equal(up.writeBuffers.length, 2); assert.equal(Buffer.concat(up.writeBuffers).toString(), '56789'); assert.equal(up.localWriteCacheByteLength, 0); }); }); describe('#pullFromChunkBuffer', () => { it('should retrieve from the beginning of the `writeBuffers`', () => { up.writeBuffers = [Buffer.from('ab')]; const [chunk] = [...up.pullFromChunkBuffer(1)]; assert.equal(chunk.toString(), 'a'); assert.equal(up.writeBuffers.length, 1); assert.equal(up.writeBuffers[0].toString(), 'b'); }); it('should retrieve no more than the limit provided', () => { up.writeBuffers = [Buffer.from('0123456789')]; const chunks = [...up.pullFromChunkBuffer(4)]; assert.equal(chunks.join('').toString(), '0123'); // length should be 1 assert.equal(up.writeBuffers.length, 1); assert.equal(up.writeBuffers[0].toString(), '456789'); }); it('should retrieve less than the limit if no more data is available (single write)', () => { up.writeBuffers = [Buffer.from('0123456789')]; const chunks = [...up.pullFromChunkBuffer(512)]; assert.equal(chunks.join('').toString(), '0123456789'); assert.equal(up.writeBuffers.length, 0); }); it('should retrieve less than the limit if no more data is available (multi write)', () => { // an array of 1-char buffers up.writeBuffers = '0123456789'.split('').map(c => Buffer.from(c)); const chunks = [...up.pullFromChunkBuffer(512)]; assert.equal(chunks.join('').toString(), '0123456789'); assert.equal(up.writeBuffers.length, 0); }); it('should retrieve a subset of part of a buffer and prepend the remainder', () => { up.writeBuffers = [ Buffer.from('0'), Buffer.from('123'), Buffer.from('456'), // this buffer should be split Buffer.from('789'), ]; const chunks = [...up.pullFromChunkBuffer(5)]; assert.equal(chunks.join('').toString(), '01234'); assert.equal(up.writeBuffers.length, 2); assert.equal(up.writeBuffers[0].toString(), '56'); assert.equal(up.writeBuffers[1].toString(), '789'); }); it('should return all data if `Infinity` is provided', () => { up.writeBuffers = [Buffer.from('012345'), Buffer.from('6789')]; const chunks = [...up.pullFromChunkBuffer(Infinity)]; assert.equal(chunks.join('').toString(), '0123456789'); assert.equal(up.writeBuffers.length, 0); }); it("should emit 'readFromChunkBuffer' synchronously on each iterator", () => { up.writeBuffers = [Buffer.from('012345'), Buffer.from('6789')]; const iter = up.pullFromChunkBuffer(Infinity); let count = 0; let loop = 0; up.on('readFromChunkBuffer', () => count++); while (!iter.next().done) { assert.equal(count, loop++); } }); }); describe('#waitForNextChunk', () => { it('should resolve `true` asynchronously if `writeBuffers.length` has data', async () => { up.writeBuffers = [Buffer.from('ab')]; assert(await up.waitForNextChunk()); }); it('should resolve `false` asynchronously if `upstreamEnded`', async () => { up.upstreamEnded = true; assert.equal(await up.waitForNextChunk(), false); }); it('should resolve `true` asynchronously if `writeBuffers.length` and `upstreamEnded`', async () => { up.writeBuffers = [Buffer.from('ab')]; up.upstreamEnded = true; assert(await up.waitForNextChunk()); }); it('should wait for `wroteToChunkBuffer` if !`writeBuffers.length` && !`upstreamEnded`', async () => { const result = await new Promise(resolve => { up.waitForNextChunk().then(resolve); up.emit('wroteToChunkBuffer'); }); assert(result); }); it("should wait for 'upstreamFinished' if !`writeBuffers.length` && !`upstreamEnded`", async () => { await new Promise(resolve => { up.waitForNextChunk().then(resolve); up.emit('upstreamFinished'); }); }); it("should wait for 'upstreamFinished' and resolve `false` if data is not available", async () => { const result = await new Promise(resolve => { up.waitForNextChunk().then(resolve); up.emit('upstreamFinished'); }); assert.equal(result, false); }); it("should wait for 'upstreamFinished' and resolve `true` if data is available", async () => { const result = await new Promise(resolve => { up.on('newListener', (event: string) => { if (event === 'upstreamFinished') { // Update the `writeBuffers` before emitting 'upstreamFinished' up.writeBuffers = [Buffer.from('abc')]; process.nextTick(() => up.emit('upstreamFinished')); } }); up.waitForNextChunk().then(resolve); }); assert.equal(result, true); }); it("should wait for 'upstreamFinished' if !`writeBuffers.length` && !`upstreamEnded`", async () => { await new Promise(resolve => { up.waitForNextChunk().then(resolve); up.emit('upstreamFinished'); }); }); it("should wait for 'upstreamFinished' and resolve `false` if data is not available", async () => { const result = await new Promise(resolve => { up.waitForNextChunk().then(resolve); up.emit('upstreamFinished'); }); assert.equal(result, false); }); it("should wait for 'upstreamFinished' and resolve `true` if data is available", async () => { const result = await new Promise(resolve => { up.on('newListener', (event: string) => { if (event === 'upstreamFinished') { // Update the `writeBuffers` before emitting 'upstreamFinished' up.writeBuffers = [Buffer.from('abc')]; process.nextTick(() => up.emit('upstreamFinished')); } }); up.waitForNextChunk().then(resolve); }); assert.equal(result, true); }); it('should remove listeners after calling back from `wroteToChunkBuffer`', async () => { assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); assert.equal(up.listenerCount('upstreamFinished'), 0); await new Promise(resolve => { up.on('newListener', (event: string) => { if (event === 'wroteToChunkBuffer') { process.nextTick(() => up.emit('wroteToChunkBuffer')); } }); up.waitForNextChunk().then(resolve); }); assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); assert.equal(up.listenerCount('upstreamFinished'), 0); }); it("should remove listeners after calling back from 'upstreamFinished'", async () => { assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); assert.equal(up.listenerCount('upstreamFinished'), 0); await new Promise(resolve => { up.on('newListener', (event: string) => { if (event === 'upstreamFinished') { process.nextTick(() => up.emit('upstreamFinished')); } }); up.waitForNextChunk().then(resolve); }); assert.equal(up.listenerCount('wroteToChunkBuffer'), 0); assert.equal(up.listenerCount('upstreamFinished'), 0); }); }); describe('#upstreamIterator', () => { it('should yield all data from upstream by default', done => { up.writeBuffers = [Buffer.alloc(1)]; assert(up.writableHighWaterMark); up.pullFromChunkBuffer = (limit: number) => { assert.equal(limit, Infinity); done(); }; const iterator = up.upstreamIterator(); iterator.next(); }); it('should yield up to limit if provided', async () => { up.writeBuffers = [Buffer.alloc(16)]; let data = Buffer.alloc(0); for await (const chunk of up.upstreamIterator(8)) { data = Buffer.concat([data, chunk]); } assert.equal(data.byteLength, 8); }); it("should yield less than the limit if that's all that's available", async () => { up.writeBuffers = [Buffer.alloc(8)]; up.upstreamEnded = true; let data = Buffer.alloc(0); for await (const chunk of up.upstreamIterator(16)) { data = Buffer.concat([data, chunk]); } assert.equal(data.byteLength, 8); }); it('should yield many, arbitrarily sized chunks', async () => { up.waitForNextChunk = () => true; up.pullFromChunkBuffer = () => [Buffer.from('a')]; let data = Buffer.alloc(0); let count = 0; for await (const chunk of up.upstreamIterator(16)) { data = Buffer.concat([data, chunk]); count++; } assert.equal(data.toString(), 'a'.repeat(16)); assert.equal(count, 16); }); }); describe('#createURI', () => { it('should make the correct request', done => { up.makeRequest = async (reqOpts: GaxiosOptions) => { assert.strictEqual(reqOpts.method, 'POST'); assert.strictEqual(reqOpts.url, `${BASE_URI}/${BUCKET}/o`); assert.deepStrictEqual(reqOpts.params, { predefinedAcl: up.predefinedAcl, name: FILE, uploadType: 'resumable', ifGenerationMatch: GENERATION, ifMetagenerationNotMatch: PARAMS.ifMetagenerationNotMatch, }); const metadataNoHeaders = {...up.metadata}; delete metadataNoHeaders.contentLength; delete metadataNoHeaders.contentType; assert.deepStrictEqual(reqOpts.data, metadataNoHeaders); done(); return {headers: {location: '/foo'}}; }; up.createURI(); }); it('should pass through the KMS key name', done => { const kmsKeyName = 'kms-key-name'; const up = upload({ bucket: BUCKET, file: FILE, kmsKeyName, retryOptions: RETRY_OPTIONS, }); up.makeRequest = async (reqOpts: GaxiosOptions) => { assert.strictEqual(reqOpts.params.kmsKeyName, kmsKeyName); done(); return {headers: {location: '/foo'}}; }; up.createURI(); }); it('should respect 0 as a generation', done => { up.makeRequest = async (reqOpts: GaxiosOptions) => { assert.strictEqual(reqOpts.params.ifGenerationMatch, 0); done(); return {headers: {location: '/foo'}}; }; up.generation = 0; up.createURI(); }); describe('error', () => { const error = new Error(':('); beforeEach(() => { up.makeRequest = async () => { throw error; }; }); it('should exec callback with error', done => { up.createURI((err: Error) => { assert.strictEqual(err, error); done(); }); }); it('currentInvocationId.uri should remain the same on error', done => { const beforeCallInvocationId = up.currentInvocationId.uri; up.createURI((err: Error) => { assert(err); assert.equal(beforeCallInvocationId, up.currentInvocationId.uri); done(); }); }); }); describe('success', () => { const URI = 'uri'; const RESP = {headers: {location: URI}}; beforeEach(() => { up.makeRequest = async () => { return RESP; }; }); it('should localize the uri', done => { up.createURI((err: Error) => { assert.ifError(err); assert.strictEqual(up.uri, URI); assert.strictEqual(up.offset, 0); done(); }); }); it('should default the offset to 0', done => { up.createURI((err: Error) => { assert.ifError(err); assert.strictEqual(up.offset, 0); done(); }); }); it('should exec callback with URI', done => { up.createURI((err: Error, uri: string) => { assert.ifError(err); assert.strictEqual(uri, URI); done(); }); }); it('currentInvocationId.uri should be different after success', done => { const beforeCallInvocationId = up.currentInvocationId.uri; up.createURI(() => { assert.notEqual(beforeCallInvocationId, up.currentInvocationId.uri); done(); }); }); }); }); describe('#continueUploading', () => { it('should start uploading if an offset was set', done => { up.offset = 0; up.startUploading = async () => { done(); }; up.continueUploading(); }); it('should get and set offset if no offset was set', done => { up.getAndSetOffset = async () => { done(); }; up.startUploading = () => Promise.resolve(); up.continueUploading(); }); |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |