forked from NativeScript/nativescript-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextensibility-service.ts
911 lines (785 loc) · 37.5 KB
/
extensibility-service.ts
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
import { ExtensibilityService } from '../../lib/services/extensibility-service';
import { Yok } from "../../lib/common/yok";
import * as stubs from "../stubs";
import { assert } from "chai";
import { NodePackageManager } from "../../lib/node-package-manager";
import { PackageManager } from "../../lib/package-manager";
import { YarnPackageManager } from "../../lib/yarn-package-manager";
import { PnpmPackageManager } from "../../lib/pnpm-package-manager";
import * as constants from "../../lib/constants";
import { ChildProcess } from "../../lib/common/child-process";
import { CommandsDelimiters } from "../../lib/common/constants";
import { Errors } from "../../lib/common/errors";
import { HostInfo } from "../../lib/common/host-info";
import { SettingsService } from "../../lib/common/test/unit-tests/stubs";
const path = require("path");
const originalResolve = path.resolve;
interface ITestData {
name: string;
extensionsDefinitions: ITestExtensionDefinition[];
inputStrings: string[];
expectedResult: IExtensionCommandInfo;
}
interface ITestExtensionDefinition {
extensionName: string;
commands?: string[];
failRequestToRegistryNpm?: boolean;
}
describe("extensibilityService", () => {
before(() => {
path.resolve = (p: string) => p;
});
after(() => {
path.resolve = originalResolve;
});
const getTestInjector = (): IInjector => {
const testInjector = new Yok();
testInjector.register("fs", {
readJson: (pathToFile: string): any => ({})
});
testInjector.register("logger", stubs.LoggerStub);
testInjector.register("childProcess", ChildProcess);
testInjector.register("errors", Errors);
testInjector.register("hostInfo", HostInfo);
testInjector.register("httpClient", {});
testInjector.register("packageManager", PackageManager);
testInjector.register("options", {});
testInjector.register("pacoteService", {
manifest: async (packageName: string, options?: IPacoteManifestOptions): Promise<any> => {
return {};
}
});
testInjector.register("userSettingsService", {
getSettingValue: async (settingName: string): Promise<void> => undefined
});
testInjector.register("npm", NodePackageManager);
testInjector.register("yarn", YarnPackageManager);
testInjector.register("pnpm", PnpmPackageManager);
testInjector.register("settingsService", SettingsService);
testInjector.register("requireService", {
require: (pathToRequire: string): any => undefined
});
return testInjector;
};
const getExpectedInstallationPathForExtension = (testInjector: IInjector, extensionName: string): string => {
const settingsService = testInjector.resolve<ISettingsService>("settingsService");
const profileDir = settingsService.getProfileDir();
return path.join(profileDir, "extensions", "node_modules", extensionName);
};
const mockFsReadJson = (testInjector: IInjector, extensionNames: string[]): void => {
const fs = testInjector.resolve<IFileSystem>("fs");
fs.readJson = (filename: string, encoding?: string): any => {
const extensionName = _.find(extensionNames, extName => filename.indexOf(extName) !== -1);
if (extensionName) {
return {
name: extensionName,
version: "1.0.0"
};
}
const dependencies: any = {};
_.each(extensionNames, name => {
dependencies[name] = "1.0.0";
});
return { dependencies };
};
};
describe("installExtension", () => {
describe("fails", () => {
it("when extensions dir does not exist and trying to create it fails", async () => {
const expectedErrorMessage = "Unable to create dir";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => false;
fs.createDirectory = (dirToCreate: string): void => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await assert.isRejected(extensibilityService.installExtension("extensionToInstall"), expectedErrorMessage);
});
it("when extensions dir exists, but default package.json is missing and trying to create it fails", async () => {
const expectedErrorMessage = "Unable to write json";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) !== constants.PACKAGE_JSON_FILE_NAME;
fs.writeJson = (pathToFile: string, content: any) => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await assert.isRejected(extensibilityService.installExtension("extensionToInstall"), expectedErrorMessage);
});
it("when npm install fails", async () => {
const expectedErrorMessage = "Unable to install package";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => true;
const npm: INodePackageManager = testInjector.resolve("npm");
npm.install = async (packageName: string, pathToSave: string, config?: any): Promise<any> => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await assert.isRejected(extensibilityService.installExtension("extensionToInstall"), expectedErrorMessage);
});
});
describe("passes correct arguments to npm install", () => {
const getArgsPassedToNpmInstallDuringInstallExtensionCall = async (userSpecifiedValue: string, testInjector?: IInjector): Promise<any> => {
testInjector = testInjector || getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => true;
fs.readDirectory = (dir: string): string[] => [userSpecifiedValue];
const npm: INodePackageManager = testInjector.resolve("npm");
const argsPassedToNpmInstall: any = {};
npm.install = async (packageName: string, pathToSave: string, config?: any): Promise<any> => {
argsPassedToNpmInstall.packageName = packageName;
argsPassedToNpmInstall.pathToSave = pathToSave;
argsPassedToNpmInstall.config = config;
return { name: userSpecifiedValue };
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await extensibilityService.installExtension(userSpecifiedValue);
return argsPassedToNpmInstall;
};
const assertPackageNamePassedToNpmInstall = async (userSpecifiedValue: string, expectedValue: string): Promise<void> => {
const argsPassedToNpmInstall = await getArgsPassedToNpmInstallDuringInstallExtensionCall(userSpecifiedValue);
assert.deepEqual(argsPassedToNpmInstall.packageName, expectedValue);
};
it("passes full path for installation, when trying to install local package (user specifies relative path)", async () => {
const extensionName = "../extension1";
await assertPackageNamePassedToNpmInstall(extensionName, path.resolve(extensionName));
});
it("passes the value specified by user for installation, when the local path does not exist", async () => {
const extensionName = "extension1";
await assertPackageNamePassedToNpmInstall(extensionName, path.resolve(extensionName));
});
it("passes save and save-exact options to npm install", async () => {
const extensionName = "extension1";
const argsPassedToNpmInstall = await getArgsPassedToNpmInstallDuringInstallExtensionCall(extensionName);
const expectedNpmConfg: any = { save: true };
expectedNpmConfg["save-exact"] = true;
assert.deepEqual(argsPassedToNpmInstall.config, expectedNpmConfg);
});
it("passes full path to extensions dir for installation", async () => {
const extensionName = "extension1";
const testInjector = getTestInjector();
const settingsService: ISettingsService = testInjector.resolve("settingsService");
const profileDir = "my-profile-dir";
settingsService.getProfileDir = () => profileDir;
const expectedDirForInstallation = path.join(profileDir, "extensions");
const argsPassedToNpmInstall = await getArgsPassedToNpmInstallDuringInstallExtensionCall(extensionName, testInjector);
assert.deepEqual(argsPassedToNpmInstall.pathToSave, expectedDirForInstallation);
});
});
it("returns the name of the installed extension", async () => {
const extensionName = "extension1";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) !== extensionName;
fs.readDirectory = (dir: string): string[] => [extensionName];
fs.readJson = () => ({ name: extensionName, version: "1.0.0" });
const npm: INodePackageManager = testInjector.resolve("npm");
npm.install = async (packageName: string, pathToSave: string, config?: any): Promise<any> => ({ name: extensionName, version: "1.0.0" });
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const actualResult = await extensibilityService.installExtension(extensionName);
assert.deepEqual(actualResult, { extensionName, version: "1.0.0", docs: undefined, pathToExtension: getExpectedInstallationPathForExtension(testInjector, extensionName) });
});
});
describe("loadExtensions", () => {
describe("returns correct results for each extension", () => {
it("resolves all Promises with correct values when all extensions can be loaded", async () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
const extensionNames = ["extension1", "extension2", "extension3"];
fs.exists = (pathToCheck: string): boolean => true;
fs.readDirectory = (dir: string): string[] => {
assert.deepEqual(path.basename(dir), constants.NODE_MODULES_FOLDER_NAME);
// Simulates extensions are installed in node_modules
return extensionNames;
};
mockFsReadJson(testInjector, extensionNames);
const expectedResults: IExtensionData[] = _.map(extensionNames, extensionName => (
{
extensionName,
version: "1.0.0",
pathToExtension: getExpectedInstallationPathForExtension(testInjector, extensionName),
docs: undefined
}
));
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const actualResult = await Promise.all(extensibilityService.loadExtensions());
assert.deepEqual(actualResult, expectedResults);
});
it("installs extensions that are available in package.json, but are not available in node_modules", async () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
const extensionNames = ["extension1", "extension2", "extension3"];
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) !== extensionNames[0];
let isFirstReadDirExecution = true;
fs.readDirectory = (dir: string): string[] => {
assert.deepEqual(path.basename(dir), constants.NODE_MODULES_FOLDER_NAME);
// Simulates extensions are installed in node_modules
if (isFirstReadDirExecution) {
isFirstReadDirExecution = false;
return extensionNames.filter(ext => ext !== "extension1");
} else {
return extensionNames;
}
};
mockFsReadJson(testInjector, extensionNames);
let isNpmInstallCalled = false;
const npm: INodePackageManager = testInjector.resolve("npm");
npm.install = async (packageName: string, pathToSave: string, config?: any): Promise<any> => {
assert.deepEqual(packageName, extensionNames[0]);
isNpmInstallCalled = true;
return { name: packageName };
};
const expectedResults: IExtensionData[] = _.map(extensionNames, extensionName => ({ extensionName, version: "1.0.0", pathToExtension: getExpectedInstallationPathForExtension(testInjector, extensionName), docs: undefined }));
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const actualResult = await Promise.all(extensibilityService.loadExtensions());
assert.deepEqual(actualResult, expectedResults);
assert.isTrue(isNpmInstallCalled);
});
it("rejects only promises for extensions that cannot be loaded", async () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
const extensionNames = ["extension1", "extension2", "extension3"];
fs.exists = (pathToCheck: string): boolean => true;
fs.readDirectory = (dir: string): string[] => {
assert.deepEqual(path.basename(dir), constants.NODE_MODULES_FOLDER_NAME);
// Simulates extensions are installed in node_modules
return extensionNames;
};
mockFsReadJson(testInjector, extensionNames);
const requireService: IRequireService = testInjector.resolve("requireService");
requireService.require = (module: string) => {
if (path.basename(module) === extensionNames[0]) {
throw new Error("Unable to load module.");
}
};
const expectedResults: any[] = _.map(extensionNames, extensionName => ({ extensionName, version: "1.0.0", pathToExtension: getExpectedInstallationPathForExtension(testInjector, extensionName), docs: undefined }));
expectedResults[0] = new Error("Unable to load extension extension1. You will not be able to use the functionality that it adds. Error: Unable to load module.");
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const promises = extensibilityService.loadExtensions();
assert.deepEqual(promises.length, extensionNames.length);
for (let index = 0; index < promises.length; index++) {
const loadExtensionPromise = promises[index];
await loadExtensionPromise
.then(result => assert.deepEqual(result, expectedResults[index]),
err => {
assert.deepEqual(err.message, expectedResults[index].message);
assert.deepEqual(err.extensionName, extensionNames[index]);
});
}
});
it("rejects all promises when unable to read node_modules dir (simulate EPERM error)", async () => {
const testInjector = getTestInjector();
const extensionNames = ["extension1", "extension2", "extension3"];
const fs: IFileSystem = testInjector.resolve("fs");
const expectedErrorMessage = `Unable to read ${constants.NODE_MODULES_FOLDER_NAME} dir.`;
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) === "extensions" || path.basename(pathToCheck) === constants.PACKAGE_JSON_FILE_NAME;
mockFsReadJson(testInjector, extensionNames);
let isReadDirCalled = false;
fs.readDirectory = (dir: string): string[] => {
isReadDirCalled = true;
assert.deepEqual(path.basename(dir), constants.NODE_MODULES_FOLDER_NAME);
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const promises = extensibilityService.loadExtensions();
for (let index = 0; index < promises.length; index++) {
const loadExtensionPromise = promises[index];
await loadExtensionPromise.then(res => { throw new Error("Shouldn't get here!"); },
err => {
const extensionName = extensionNames[index];
assert.deepEqual(err.message, `Unable to load extension ${extensionName}. You will not be able to use the functionality that it adds. Error: ${expectedErrorMessage}`);
assert.deepEqual(err.extensionName, extensionName);
});
}
assert.deepEqual(promises.length, extensionNames.length);
assert.isTrue(isReadDirCalled, "readDirectory should have been called for the extensions.");
});
it("rejects all promises when unable to install extensions to extension dir (simulate EPERM error)", async () => {
const testInjector = getTestInjector();
const extensionNames = ["extension1", "extension2", "extension3"];
const expectedErrorMessages = ["Unable to install to node_modules dir.",
"expected 'extension2' to deeply equal 'extension1'",
"expected 'extension3' to deeply equal 'extension1'"];
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) === "extensions" || path.basename(pathToCheck) === constants.PACKAGE_JSON_FILE_NAME;
mockFsReadJson(testInjector, extensionNames);
let isReadDirCalled = false;
fs.readDirectory = (dir: string): string[] => {
isReadDirCalled = true;
assert.deepEqual(path.basename(dir), constants.NODE_MODULES_FOLDER_NAME);
return [];
};
let isNpmInstallCalled = false;
const npm: INodePackageManager = testInjector.resolve("npm");
const expectedErrorMessage = `Unable to install to ${constants.NODE_MODULES_FOLDER_NAME} dir.`;
npm.install = async (packageName: string, pathToSave: string, config?: any): Promise<any> => {
assert.deepEqual(packageName, extensionNames[0]);
isNpmInstallCalled = true;
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const promises = extensibilityService.loadExtensions();
for (let index = 0; index < promises.length; index++) {
const loadExtensionPromise = promises[index];
await loadExtensionPromise.then(res => {
throw new Error("Shouldn't get here!");
},
err => {
const extensionName = extensionNames[index];
assert.deepEqual(err.message, `Unable to load extension ${extensionName}. You will not be able to use the functionality that it adds. Error: ${expectedErrorMessages[index]}`);
assert.deepEqual(err.extensionName, extensionName);
});
}
assert.deepEqual(promises.length, extensionNames.length);
assert.isTrue(isNpmInstallCalled, "Npm install should have been called for the extensions.");
assert.isTrue(isReadDirCalled, "readDirectory should have been called for the extensions.");
});
it("does not return any promises when its unable to create extensions dir", () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => false;
const expectedErrorMessage = "Unable to create dir";
fs.createDirectory = (dirToCreate: string): void => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const promises = extensibilityService.loadExtensions();
assert.deepEqual(promises.length, 0);
});
it("does not return any promises when its unable to read extensions package.json", () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => true;
const expectedErrorMessage = "Unable to read json";
fs.readJson = (filename: string, encoding?: string): any => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const promises = extensibilityService.loadExtensions();
assert.deepEqual(promises.length, 0);
});
it("does not fail when package.json in extension dir does not exist", async () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => {
// Add the assert here, so we are sure the only call to fs.exists is for package.json of the extensions dir.
assert.deepEqual(path.basename(pathToCheck), constants.PACKAGE_JSON_FILE_NAME);
return false;
};
const expectedResults: IExtensionData[] = [];
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const actualResult = await Promise.all(extensibilityService.loadExtensions());
assert.deepEqual(actualResult, expectedResults, "When there's no package.json in extensions dir, there's nothing for loading.");
});
it("does not fail when unable to read extensions dir package.json", async () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => {
// Add the assert here, so we are sure the only call to fs.exists is for package.json of the extensions dir.
assert.deepEqual(path.basename(pathToCheck), constants.PACKAGE_JSON_FILE_NAME);
return true;
};
fs.readJson = (filename: string, encoding?: string): any => {
throw new Error("Unable to read JSON");
};
const expectedResults: IExtensionData[] = [];
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
const actualResult = await Promise.all(extensibilityService.loadExtensions());
assert.deepEqual(actualResult, expectedResults, "When unable to read package.json in extensions dir, there's nothing for loading.");
});
});
});
describe("uninstallExtension", () => {
describe("fails", () => {
it("when extensions dir does not exist and trying to create it fails", async () => {
const expectedErrorMessage = "Unable to create dir";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => false;
fs.createDirectory = (dirToCreate: string): void => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await assert.isRejected(extensibilityService.uninstallExtension("extensionToInstall"), expectedErrorMessage);
});
it("when extensions dir exists, but default package.json is missing and trying to create it fails", async () => {
const expectedErrorMessage = "Unable to write json";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) !== constants.PACKAGE_JSON_FILE_NAME;
fs.writeJson = (pathToFile: string, content: any) => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await assert.isRejected(extensibilityService.uninstallExtension("extensionToInstall"), expectedErrorMessage);
});
it("when npm uninstall fails", async () => {
const expectedErrorMessage = "Unable to install package";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => true;
const npm: INodePackageManager = testInjector.resolve("npm");
npm.uninstall = async (packageName: string, config?: any, p?: string): Promise<any> => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await assert.isRejected(extensibilityService.uninstallExtension("extensionToInstall"), expectedErrorMessage);
});
});
describe("passes correct arguments to npm uninstall", () => {
const getArgsPassedToNpmUninstallDuringUninstallExtensionCall = async (userSpecifiedValue: string, testInjector?: IInjector): Promise<any> => {
testInjector = testInjector || getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => true;
fs.readDirectory = (dir: string): string[] => [userSpecifiedValue];
const npm: INodePackageManager = testInjector.resolve("npm");
const argsPassedToNpmInstall: any = {};
npm.uninstall = async (packageName: string, config?: any, p?: string): Promise<any> => {
argsPassedToNpmInstall.packageName = packageName;
argsPassedToNpmInstall.pathToSave = p;
argsPassedToNpmInstall.config = config;
return [userSpecifiedValue];
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await extensibilityService.uninstallExtension(userSpecifiedValue);
return argsPassedToNpmInstall;
};
const assertPackageNamePassedToNpmUninstall = async (userSpecifiedValue: string, expectedValue: string): Promise<void> => {
const argsPassedToNpmInstall = await getArgsPassedToNpmUninstallDuringUninstallExtensionCall(userSpecifiedValue);
assert.deepEqual(argsPassedToNpmInstall.packageName, expectedValue);
};
it("passes the value specified by user for installation", async () => {
const extensionName = "extension1";
await assertPackageNamePassedToNpmUninstall(extensionName, extensionName);
const relativePathToExtension = "../extension1";
await assertPackageNamePassedToNpmUninstall(relativePathToExtension, relativePathToExtension);
});
it("passes save option to npm uninstall", async () => {
const extensionName = "extension1";
const argsPassedToNpmUninstall = await getArgsPassedToNpmUninstallDuringUninstallExtensionCall(extensionName);
const expectedNpmConfg: any = { save: true };
assert.deepEqual(argsPassedToNpmUninstall.config, expectedNpmConfg);
});
it("passes full path to extensions dir for uninstallation", async () => {
const extensionName = "extension1";
const testInjector = getTestInjector();
const settingsService: ISettingsService = testInjector.resolve("settingsService");
const profileDir = "my-profile-dir";
settingsService.getProfileDir = () => profileDir;
const expectedDirForUninstall = path.join(profileDir, "extensions");
const argsPassedToNpmUninstall = await getArgsPassedToNpmUninstallDuringUninstallExtensionCall(extensionName, testInjector);
assert.deepEqual(argsPassedToNpmUninstall.pathToSave, expectedDirForUninstall);
});
});
it("executes successfully uninstall operation", async () => {
const extensionName = "extension1";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) !== extensionName;
fs.readDirectory = (dir: string): string[] => [extensionName];
const npm: INodePackageManager = testInjector.resolve("npm");
npm.uninstall = async (packageName: string, config?: any, p?: string): Promise<any> => [extensionName];
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
await extensibilityService.uninstallExtension(extensionName);
});
});
describe("getInstalledExtensions", () => {
it("fails when unable to read package.json from extensions dir", () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string) => true;
const expectedErrorMessage = "Failed to read package.json";
fs.readJson = (filename: string, encoding?: string): any => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
assert.throws(() => extensibilityService.getInstalledExtensions(), expectedErrorMessage);
});
it("returns null when there's no package.json dir", () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string) => false;
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
assert.isNull(extensibilityService.getInstalledExtensions());
});
it("returns undefined when package.json does not have dependencies section", () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string) => true;
fs.readJson = (filename: string, encoding?: string): any => {
return {};
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
assert.isUndefined(extensibilityService.getInstalledExtensions());
});
it("returns dependencies section of package.json", () => {
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string) => true;
const dependencies = {
"dep1": "1.0.0",
"dep2": "~1.0.0",
"dep3": "^1.0.0"
};
fs.readJson = (filename: string, encoding?: string): any => {
return { dependencies };
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
assert.deepEqual(extensibilityService.getInstalledExtensions(), dependencies);
});
});
describe("loadExtension", () => {
it("throws error that has extensionName property when unable to load extension", async () => {
const expectedErrorMessage = "Require failed";
const extensionName = "extension1";
const testInjector = getTestInjector();
const fs: IFileSystem = testInjector.resolve("fs");
fs.exists = (pathToCheck: string): boolean => path.basename(pathToCheck) !== extensionName;
fs.readDirectory = (dir: string): string[] => [extensionName];
const npm: INodePackageManager = testInjector.resolve("npm");
npm.install = async (packageName: string, pathToSave: string, config?: any): Promise<any> => ({ name: extensionName });
const requireService: IRequireService = testInjector.resolve("requireService");
requireService.require = (pathToRequire: string) => {
throw new Error(expectedErrorMessage);
};
const extensibilityService: IExtensibilityService = testInjector.resolve(ExtensibilityService);
let isErrorRaised = false;
try {
await extensibilityService.loadExtension(extensionName);
} catch (err) {
isErrorRaised = true;
assert.deepEqual(err.message, `Unable to load extension ${extensionName}. You will not be able to use the functionality that it adds. Error: ${expectedErrorMessage}`);
assert.deepEqual(err.extensionName, extensionName);
}
assert.isTrue(isErrorRaised);
});
});
describe("getExtensionNameWhereCommandIsRegistered", () => {
const getInstallationMessage = (extensionName: string, commandName: string): string => {
return `The command ${commandName.replace(/\|\*/g, " ").replace(/\|/g, " ")} is registered in extension ${extensionName}. You can install it by executing 'tns extension install ${extensionName}'`;
};
const testData: ITestData[] = [
{
name: "returns correct data when user enters exact command name",
inputStrings: ["command1"],
extensionsDefinitions: [
{
extensionName: "extension1",
commands: ["command1", "hierarchical|command", "deep|hierarchical|command|for|tests"]
},
{
extensionName: "extension2"
}
],
expectedResult: {
extensionName: "extension1",
registeredCommandName: "command1",
installationMessage: getInstallationMessage("extension1", "command1")
}
},
{
name: "returns correct data when user enters exact hierarchical command name",
inputStrings: ["hierarchical", "command"],
extensionsDefinitions: [
{
extensionName: "extension1",
commands: ["command1", "hierarchical|command", "deep|hierarchical|command|for|tests"]
},
{
extensionName: "extension2"
}
],
expectedResult: {
extensionName: "extension1",
registeredCommandName: "hierarchical|command",
installationMessage: getInstallationMessage("extension1", "hierarchical|command")
}
},
{
name: "returns null when user enters invalid command name",
inputStrings: ["invalid", "command"],
extensionsDefinitions: [
{
extensionName: "extension1",
commands: ["command1", "hierarchical|command", "deep|hierarchical|command|for|tests"]
},
{
extensionName: "extension2"
}
],
expectedResult: null
},
{
name: "returns correct data when user enters hierarchical command and args for this command",
inputStrings: ["valid", "command", "with", "lots", "of", "params"],
extensionsDefinitions: [
{
extensionName: "extension1",
commands: ["command1", "hierarchical|command", "deep|hierarchical|command|for|tests"]
},
{
extensionName: "extension2"
},
{
extensionName: "extension3",
commands: ["valid", "valid|command", "valid|command|with"]
},
],
expectedResult: {
extensionName: "extension3",
registeredCommandName: "valid|command|with",
installationMessage: getInstallationMessage("extension3", "valid|command|with")
}
},
{
name: "returns correct data when user enters the default value of hierarchical command",
inputStrings: ["valid", "and", "lots", "of", "params"],
extensionsDefinitions: [
{
extensionName: "extension3",
commands: ["valid|*command", "valid|command|with"]
},
],
expectedResult: {
extensionName: "extension3",
registeredCommandName: "valid",
installationMessage: getInstallationMessage("extension3", "valid")
}
},
{
name: "returns correct data when user enters the full default value of hierarchical command",
inputStrings: ["valid", "command", "and", "lots", "of", "params"],
extensionsDefinitions: [
{
extensionName: "extension3",
commands: ["valid|*command", "valid|command|with"]
},
],
expectedResult: {
extensionName: "extension3",
registeredCommandName: "valid",
installationMessage: getInstallationMessage("extension3", "valid")
}
},
{
name: "returns correct data when user enters the default value of multilevel hierarchical command",
inputStrings: ["valid", "multilevel", "command", "and", "lots", "of", "params"],
extensionsDefinitions: [
{
extensionName: "extension3",
commands: ["valid|multilevel|command|*default", "valid|command|with"]
},
],
expectedResult: {
extensionName: "extension3",
registeredCommandName: "valid|multilevel|command",
installationMessage: getInstallationMessage("extension3", "valid|multilevel|command")
}
},
{
name: "returns correct data when user enters the full default value of multilevel hierarchical command",
inputStrings: ["valid", "multilevel", "command", "and", "lots", "of", "params"],
extensionsDefinitions: [
{
extensionName: "extension3",
commands: ["valid|multilevel|command|*default", "valid|command|with"]
},
],
expectedResult: {
extensionName: "extension3",
registeredCommandName: "valid|multilevel|command",
installationMessage: getInstallationMessage("extension3", "valid|multilevel|command")
}
},
{
name: "does not fail when request to one of the extension fails",
inputStrings: ["command1"],
extensionsDefinitions: [
{
extensionName: "extension2",
failRequestToRegistryNpm: true
},
{
extensionName: "extension1",
commands: ["command1", "hierarchical|command", "deep|hierarchical|command|for|tests"]
}
],
expectedResult: {
extensionName: "extension1",
registeredCommandName: "command1",
installationMessage: getInstallationMessage("extension1", "command1")
}
}
];
_.each(testData, testCase => {
it(testCase.name, async () => {
const testInjector = getTestInjector();
const expectedKeyword = "nativescript:extension";
const npm = testInjector.resolve<INodePackageManager>("npm");
npm.searchNpms = async (keyword: string): Promise<INpmsResult> => {
assert.equal(keyword, expectedKeyword);
const result = <any>{
total: testCase.extensionsDefinitions.length,
results: []
};
_.each(testCase.extensionsDefinitions, extensionData => {
result.results.push({
package: {
name: extensionData.extensionName
}
});
});
return result;
};
const version = "1.0.0";
npm.getRegistryPackageData = async (packageName: string): Promise<any> => {
const extensionData = _.find(testCase.extensionsDefinitions, extData => extData.extensionName === packageName);
if (extensionData && extensionData.failRequestToRegistryNpm) {
throw new Error(`Request to registry.npmjs.org for package ${packageName} failed.`);
}
const result = {
["dist-tags"]: {
latest: version
},
versions: {
[version]: <any>{}
}
};
if (extensionData && extensionData.commands) {
result.versions[version].nativescript = {
commands: extensionData.commands
};
}
return result;
};
const extensibilityService = testInjector.resolve<IExtensibilityService>(ExtensibilityService);
const inputData = {
inputStrings: testCase.inputStrings,
commandDelimiter: CommandsDelimiters.HierarchicalCommand,
defaultCommandDelimiter: CommandsDelimiters.DefaultHierarchicalCommand
};
const actualExtensionName = await extensibilityService.getExtensionNameWhereCommandIsRegistered(inputData);
assert.deepEqual(actualExtensionName, testCase.expectedResult);
});
});
it("does not fail when request to npms fails", async () => {
const testInjector = getTestInjector();
const expectedKeyword = "nativescript:extension";
const npm = testInjector.resolve<INodePackageManager>("npm");
npm.searchNpms = async (keyword: string): Promise<INpmsResult> => {
assert.equal(keyword, expectedKeyword);
throw new Error("Error");
};
let isGetRegistryPackageDataCalled = false;
npm.getRegistryPackageData = async (packageName: string): Promise<any> => {
isGetRegistryPackageDataCalled = true;
};
const extensibilityService = testInjector.resolve<IExtensibilityService>(ExtensibilityService);
const actualExtensionName = await extensibilityService.getExtensionNameWhereCommandIsRegistered(null);
assert.deepEqual(actualExtensionName, null);
assert.isFalse(isGetRegistryPackageDataCalled, "The method npm.getRegistryPackageData should not be called when npm.searchNpms fails.");
});
});
});