-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathplatform-service.ts
1210 lines (1052 loc) · 48.5 KB
/
platform-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
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
import * as yok from "../lib/common/yok";
import * as stubs from "./stubs";
import * as PlatformServiceLib from "../lib/services/platform-service";
import * as StaticConfigLib from "../lib/config";
import { VERSION_STRING, PACKAGE_JSON_FILE_NAME, AddPlaformErrors } from "../lib/constants";
import * as fsLib from "../lib/common/file-system";
import * as optionsLib from "../lib/options";
import * as hostInfoLib from "../lib/common/host-info";
import * as ProjectFilesManagerLib from "../lib/common/services/project-files-manager";
import * as path from "path";
import { format } from "util";
import { assert } from "chai";
import { LocalToDevicePathDataFactory } from "../lib/common/mobile/local-to-device-path-data-factory";
import { MobileHelper } from "../lib/common/mobile/mobile-helper";
import { ProjectFilesProvider } from "../lib/providers/project-files-provider";
import { DevicePlatformsConstants } from "../lib/common/mobile/device-platforms-constants";
import { XmlValidator } from "../lib/xml-validator";
import { PreparePlatformNativeService } from "../lib/services/prepare-platform-native-service";
import { PreparePlatformJSService } from "../lib/services/prepare-platform-js-service";
import * as ChildProcessLib from "../lib/common/child-process";
import ProjectChangesLib = require("../lib/services/project-changes-service");
import { Messages } from "../lib/common/messages/messages";
import { SettingsService } from "../lib/common/test/unit-tests/stubs";
import { INFO_PLIST_FILE_NAME, MANIFEST_FILE_NAME } from "../lib/constants";
import { mkdir } from "shelljs";
import * as constants from "../lib/constants";
require("should");
const temp = require("temp");
temp.track();
function createTestInjector() {
const testInjector = new yok.Yok();
testInjector.register("workflowService", stubs.WorkflowServiceStub);
testInjector.register('platformService', PlatformServiceLib.PlatformService);
testInjector.register('errors', stubs.ErrorsStub);
testInjector.register('logger', stubs.LoggerStub);
testInjector.register("nodeModulesDependenciesBuilder", {});
testInjector.register('packageInstallationManager', stubs.PackageInstallationManagerStub);
// TODO: Remove the projectData - it shouldn't be required in the service itself.
testInjector.register('projectData', stubs.ProjectDataStub);
testInjector.register('platformsData', stubs.PlatformsDataStub);
testInjector.register('devicesService', {});
testInjector.register('androidEmulatorServices', {});
testInjector.register('projectDataService', stubs.ProjectDataService);
testInjector.register('prompter', {});
testInjector.register('sysInfo', {});
testInjector.register("commandsService", {
tryExecuteCommand: () => { /* intentionally left blank */ }
});
testInjector.register("options", optionsLib.Options);
testInjector.register("hostInfo", hostInfoLib.HostInfo);
testInjector.register("staticConfig", StaticConfigLib.StaticConfig);
testInjector.register("nodeModulesBuilder", {
prepareNodeModules: () => {
return Promise.resolve();
},
prepareJSNodeModules: () => {
return Promise.resolve();
}
});
testInjector.register("pluginsService", {
getAllInstalledPlugins: () => {
return <any>[];
},
ensureAllDependenciesAreInstalled: () => {
return Promise.resolve();
},
validate: (platformData: IPlatformData, projectData: IProjectData) => {
return Promise.resolve();
}
});
testInjector.register("projectFilesManager", ProjectFilesManagerLib.ProjectFilesManager);
testInjector.register("hooksService", stubs.HooksServiceStub);
testInjector.register("localToDevicePathDataFactory", LocalToDevicePathDataFactory);
testInjector.register("mobileHelper", MobileHelper);
testInjector.register("projectFilesProvider", ProjectFilesProvider);
testInjector.register("devicePlatformsConstants", DevicePlatformsConstants);
testInjector.register("xmlValidator", XmlValidator);
testInjector.register("preparePlatformNativeService", PreparePlatformNativeService);
testInjector.register("preparePlatformJSService", PreparePlatformJSService);
testInjector.register("packageManager", {
uninstall: async () => {
return true;
}
});
testInjector.register("childProcess", ChildProcessLib.ChildProcess);
testInjector.register("projectChangesService", ProjectChangesLib.ProjectChangesService);
testInjector.register("analyticsService", {
track: async (): Promise<any[]> => undefined,
trackEventActionInGoogleAnalytics: () => Promise.resolve()
});
testInjector.register("messages", Messages);
testInjector.register("devicePathProvider", {});
testInjector.register("helpService", {
showCommandLineHelp: async (): Promise<void> => (undefined)
});
testInjector.register("settingsService", SettingsService);
testInjector.register("terminalSpinnerService", {
createSpinner: (msg: string) => ({
start: (): void => undefined,
stop: (): void => undefined,
message: (): void => undefined
})
});
testInjector.register("androidResourcesMigrationService", stubs.AndroidResourcesMigrationServiceStub);
testInjector.register("filesHashService", {
generateHashes: () => Promise.resolve(),
getChanges: () => Promise.resolve({ test: "testHash" })
});
testInjector.register("pacoteService", {
extractPackage: async (packageName: string, destinationDirectory: string, options?: IPacoteExtractOptions): Promise<void> => {
mkdir(path.join(destinationDirectory, "framework"));
(new fsLib.FileSystem(testInjector)).writeFile(path.join(destinationDirectory, PACKAGE_JSON_FILE_NAME), JSON.stringify({
name: "package-name",
version: "1.0.0"
}));
}
});
testInjector.register("usbLiveSyncService", () => ({}));
testInjector.register("doctorService", {
checkForDeprecatedShortImportsInAppDir: (projectDir: string): void => undefined
});
testInjector.register("cleanupService", {
setShouldDispose: (shouldDispose: boolean): void => undefined
});
return testInjector;
}
class CreatedTestData {
files: string[];
resources: {
ios: string[],
android: string[]
};
testDirData: {
tempFolder: string,
appFolderPath: string,
app1FolderPath: string,
appDestFolderPath: string,
appResourcesFolderPath: string
};
constructor() {
this.files = [];
this.resources = {
ios: [],
android: []
};
this.testDirData = {
tempFolder: "",
appFolderPath: "",
app1FolderPath: "",
appDestFolderPath: "",
appResourcesFolderPath: ""
};
}
}
class DestinationFolderVerifier {
static verify(data: any, fs: IFileSystem) {
_.forOwn(data, (folder, folderRoot) => {
_.each(folder.filesWithContent || [], (file) => {
const filePath = path.join(folderRoot, file.name);
assert.isTrue(fs.exists(filePath), `Expected file ${filePath} to be present.`);
assert.equal(fs.readFile(filePath).toString(), file.content, `File content for ${filePath} doesn't match.`);
});
_.each(folder.missingFiles || [], (file) => {
assert.isFalse(fs.exists(path.join(folderRoot, file)), `Expected file ${file} to be missing.`);
});
_.each(folder.presentFiles || [], (file) => {
assert.isTrue(fs.exists(path.join(folderRoot, file)), `Expected file ${file} to be present.`);
});
});
}
}
describe('Platform Service Tests', () => {
let platformService: IPlatformService, testInjector: IInjector;
const config: IPlatformOptions = {
ignoreScripts: false,
provision: null,
teamId: null,
sdk: null,
frameworkPath: null
};
beforeEach(() => {
testInjector = createTestInjector();
testInjector.register("fs", stubs.FileSystemStub);
testInjector.resolve("projectData").initializeProjectData();
platformService = testInjector.resolve("platformService");
});
describe("add platform unit tests", () => {
describe("#add platform()", () => {
it("should not fail if platform is not normalized", async () => {
const fs = testInjector.resolve("fs");
fs.exists = () => false;
const projectData: IProjectData = testInjector.resolve("projectData");
await platformService.addPlatforms(["Android"], "", projectData, config);
await platformService.addPlatforms(["ANDROID"], "", projectData, config);
await platformService.addPlatforms(["AnDrOiD"], "", projectData, config);
await platformService.addPlatforms(["androiD"], "", projectData, config);
await platformService.addPlatforms(["iOS"], "", projectData, config);
await platformService.addPlatforms(["IOS"], "", projectData, config);
await platformService.addPlatforms(["IoS"], "", projectData, config);
await platformService.addPlatforms(["iOs"], "", projectData, config);
});
it("should fail if platform is already installed", async () => {
const projectData: IProjectData = testInjector.resolve("projectData");
// By default fs.exists returns true, so the platforms directory should exists
await assert.isRejected(platformService.addPlatforms(["android"], "", projectData, config), "Platform android already added");
await assert.isRejected(platformService.addPlatforms(["ios"], "", projectData, config), "Platform ios already added");
});
it("should fail if unable to extract runtime package", async () => {
const fs = testInjector.resolve("fs");
fs.exists = () => false;
const pacoteService = testInjector.resolve<IPacoteService>("pacoteService");
const errorMessage = "Pacote service unable to extract package";
pacoteService.extractPackage = async (packageName: string, destinationDirectory: string, options?: IPacoteExtractOptions): Promise<void> => {
throw new Error(errorMessage);
};
const projectData: IProjectData = testInjector.resolve("projectData");
await assert.isRejected(platformService.addPlatforms(["android"], "", projectData, config), errorMessage);
});
it("fails when path passed to frameworkPath does not exist", async () => {
const fs = testInjector.resolve("fs");
fs.exists = () => false;
const projectData: IProjectData = testInjector.resolve("projectData");
const frameworkPath = "invalidPath";
const errorMessage = format(AddPlaformErrors.InvalidFrameworkPathStringFormat, frameworkPath);
await assert.isRejected(platformService.addPlatforms(["android"], "", projectData, config, frameworkPath), errorMessage);
});
const assertCorrectDataIsPassedToPacoteService = async (versionString: string): Promise<void> => {
const fs = testInjector.resolve("fs");
fs.exists = () => false;
const pacoteService = testInjector.resolve<IPacoteService>("pacoteService");
let packageNamePassedToPacoteService = "";
pacoteService.extractPackage = async (name: string, destinationDirectory: string, options?: IPacoteExtractOptions): Promise<void> => {
packageNamePassedToPacoteService = name;
};
const platformsData = testInjector.resolve<IPlatformsData>("platformsData");
const packageName = "packageName";
platformsData.getPlatformData = (platform: string, pData: IProjectData): IPlatformData => {
return {
frameworkPackageName: packageName,
platformProjectService: new stubs.PlatformProjectServiceStub(),
projectRoot: "",
normalizedPlatformName: "",
appDestinationDirectoryPath: "",
getBuildOutputPath: () => "",
getValidBuildOutputData: (buildOptions: IBuildOutputOptions) => ({ packageNames: [] }),
frameworkFilesExtensions: [],
relativeToFrameworkConfigurationFilePath: "",
fastLivesyncFileExtensions: []
};
};
const projectData: IProjectData = testInjector.resolve("projectData");
await platformService.addPlatforms(["android"], "", projectData, config);
assert.equal(packageNamePassedToPacoteService, `${packageName}@${versionString}`);
await platformService.addPlatforms(["ios"], "", projectData, config);
assert.equal(packageNamePassedToPacoteService, `${packageName}@${versionString}`);
};
it("should respect platform version in package.json's nativescript key", async () => {
const versionString = "2.5.0";
const nsValueObject: any = {
[VERSION_STRING]: versionString
};
const projectDataService = testInjector.resolve("projectDataService");
projectDataService.getNSValue = () => nsValueObject;
await assertCorrectDataIsPassedToPacoteService(versionString);
});
it("should install latest platform if no information found in package.json's nativescript key", async () => {
const projectDataService = testInjector.resolve("projectDataService");
projectDataService.getNSValue = (): any => null;
const latestCompatibleVersion = "1.0.0";
const packageInstallationManager = testInjector.resolve<IPackageInstallationManager>("packageInstallationManager");
packageInstallationManager.getLatestCompatibleVersion = async (packageName: string, referenceVersion?: string): Promise<string> => {
return latestCompatibleVersion;
};
await assertCorrectDataIsPassedToPacoteService(latestCompatibleVersion);
});
// Workflow: tns preview; tns platform add
it(`should add platform when only .js part of the platform has already been added (nativePlatformStatus is ${constants.NativePlatformStatus.requiresPlatformAdd})`, async () => {
const fs = testInjector.resolve("fs");
fs.exists = () => true;
const projectChangesService = testInjector.resolve("projectChangesService");
projectChangesService.getPrepareInfo = () => ({ nativePlatformStatus: constants.NativePlatformStatus.requiresPlatformAdd });
const projectData = testInjector.resolve("projectData");
let isJsPlatformAdded = false;
const preparePlatformJSService = testInjector.resolve("preparePlatformJSService");
preparePlatformJSService.addPlatform = async () => isJsPlatformAdded = true;
let isNativePlatformAdded = false;
const preparePlatformNativeService = testInjector.resolve("preparePlatformNativeService");
preparePlatformNativeService.addPlatform = async () => isNativePlatformAdded = true;
await platformService.addPlatforms(["android"], "", projectData, config);
assert.isTrue(isJsPlatformAdded);
assert.isTrue(isNativePlatformAdded);
});
// Workflow: tns platform add; tns platform add
it("shouldn't add platform when platforms folder exist and no .nsprepare file", async () => {
const fs = testInjector.resolve("fs");
fs.exists = () => true;
const projectChangesService = testInjector.resolve("projectChangesService");
projectChangesService.getPrepareInfo = () => <any>null;
const projectData = testInjector.resolve("projectData");
await assert.isRejected(platformService.addPlatforms(["android"], "", projectData, config), "Platform android already added");
});
// Workflow: tns run; tns platform add
it(`shouldn't add platform when both native and .js parts of the platform have already been added (nativePlatformStatus is ${constants.NativePlatformStatus.alreadyPrepared})`, async () => {
const fs = testInjector.resolve("fs");
fs.exists = () => true;
const projectChangesService = testInjector.resolve("projectChangesService");
projectChangesService.getPrepareInfo = () => ({ nativePlatformStatus: constants.NativePlatformStatus.alreadyPrepared });
const projectData = testInjector.resolve("projectData");
await assert.isRejected(platformService.addPlatforms(["android"], "", projectData, config), "Platform android already added");
});
});
});
describe("remove platform unit tests", () => {
it("should fail when platforms are not added", async () => {
const ExpectedErrorsCaught = 2;
let errorsCaught = 0;
const projectData: IProjectData = testInjector.resolve("projectData");
testInjector.resolve("fs").exists = () => false;
try {
await platformService.removePlatforms(["android"], projectData);
} catch (e) {
errorsCaught++;
}
try {
await platformService.removePlatforms(["ios"], projectData);
} catch (e) {
errorsCaught++;
}
assert.isTrue(errorsCaught === ExpectedErrorsCaught);
});
it("shouldn't fail when platforms are added", async () => {
const projectData: IProjectData = testInjector.resolve("projectData");
testInjector.resolve("fs").exists = () => false;
await platformService.addPlatforms(["android"], "", projectData, config);
testInjector.resolve("fs").exists = () => true;
await platformService.removePlatforms(["android"], projectData);
});
});
describe("clean platform unit tests", () => {
it("should preserve the specified in the project nativescript version", async () => {
const versionString = "2.4.1";
const fs = testInjector.resolve("fs");
fs.exists = () => false;
const nsValueObject: any = {};
nsValueObject[VERSION_STRING] = versionString;
const projectDataService = testInjector.resolve("projectDataService");
projectDataService.getNSValue = () => nsValueObject;
const packageInstallationManager = testInjector.resolve("packageInstallationManager");
packageInstallationManager.install = (packageName: string, packageDir: string, options: INpmInstallOptions) => {
assert.deepEqual(options.version, versionString);
return "";
};
const projectData: IProjectData = testInjector.resolve("projectData");
platformService.removePlatforms = (platforms: string[], prjctData: IProjectData): Promise<void> => {
nsValueObject[VERSION_STRING] = undefined;
return Promise.resolve();
};
await platformService.cleanPlatforms(["android"], "", projectData, config);
nsValueObject[VERSION_STRING] = versionString;
await platformService.cleanPlatforms(["ios"], "", projectData, config);
});
});
// TODO: Commented as it doesn't seem correct. Check what's the case and why it's been expected to fail.
// describe("list platform unit tests", () => {
// it("fails when platforms are not added", () => {
// assert.throws(async () => await platformService.getAvailablePlatforms());
// });
// });
describe("update Platform", () => {
describe("#updatePlatform(platform)", () => {
it("should fail when the versions are the same", async () => {
const packageInstallationManager: IPackageInstallationManager = testInjector.resolve("packageInstallationManager");
packageInstallationManager.getLatestVersion = async () => "0.2.0";
const projectData: IProjectData = testInjector.resolve("projectData");
await assert.isRejected(platformService.updatePlatforms(["android"], "", projectData, null));
});
});
});
describe("prepare platform unit tests", () => {
let fs: IFileSystem;
beforeEach(() => {
testInjector = createTestInjector();
testInjector.register("fs", fsLib.FileSystem);
fs = testInjector.resolve("fs");
testInjector.resolve("projectData").initializeProjectData();
});
function prepareDirStructure() {
const tempFolder = temp.mkdirSync("prepare_platform");
const appFolderPath = path.join(tempFolder, "app");
fs.createDirectory(appFolderPath);
const nodeModulesPath = path.join(tempFolder, "node_modules");
fs.createDirectory(nodeModulesPath);
const testsFolderPath = path.join(appFolderPath, "tests");
fs.createDirectory(testsFolderPath);
const app1FolderPath = path.join(tempFolder, "app1");
fs.createDirectory(app1FolderPath);
const appDestFolderPath = path.join(tempFolder, "appDest");
const appResourcesFolderPath = path.join(appDestFolderPath, "App_Resources");
const appResourcesPath = path.join(appFolderPath, "App_Resources/Android");
fs.createDirectory(appResourcesPath);
fs.writeFile(path.join(appResourcesPath, "test.txt"), "test");
fs.writeJson(path.join(tempFolder, "package.json"), {
name: "testname",
nativescript: {
id: "org.nativescript.testname"
}
});
return { tempFolder, appFolderPath, app1FolderPath, appDestFolderPath, appResourcesFolderPath };
}
async function execPreparePlatform(platformToTest: string, testDirData: any,
release?: boolean) {
const platformsData = testInjector.resolve("platformsData");
platformsData.platformsNames = ["ios", "android"];
platformsData.getPlatformData = (platform: string) => {
return {
appDestinationDirectoryPath: testDirData.appDestFolderPath,
appResourcesDestinationDirectoryPath: testDirData.appResourcesFolderPath,
normalizedPlatformName: platformToTest,
configurationFileName: platformToTest === "ios" ? INFO_PLIST_FILE_NAME : MANIFEST_FILE_NAME,
projectRoot: testDirData.tempFolder,
platformProjectService: {
prepareProject: (): any => null,
validate: () => Promise.resolve(),
createProject: (projectRoot: string, frameworkDir: string) => Promise.resolve(),
interpolateData: (projectRoot: string) => Promise.resolve(),
afterCreateProject: (projectRoot: string): any => null,
getAppResourcesDestinationDirectoryPath: (pData: IProjectData, frameworkVersion?: string): string => {
if (platform.toLowerCase() === "ios") {
const dirPath = path.join(testDirData.appDestFolderPath, "Resources");
fs.ensureDirectoryExists(dirPath);
return dirPath;
} else {
const dirPath = path.join(testDirData.appDestFolderPath, "src", "main", "res");
fs.ensureDirectoryExists(dirPath);
return dirPath;
}
},
processConfigurationFilesFromAppResources: () => Promise.resolve(),
handleNativeDependenciesChange: () => Promise.resolve(),
ensureConfigurationFileInAppResources: (): any => null,
interpolateConfigurationFile: (): void => undefined,
isPlatformPrepared: (projectRoot: string) => false,
prepareAppResources: (appResourcesDirectoryPath: string, pData: IProjectData): void => undefined,
checkForChanges: () => { /* */ }
}
};
};
const projectData = testInjector.resolve("projectData");
projectData.projectDir = testDirData.tempFolder;
projectData.projectName = "app";
projectData.appDirectoryPath = testDirData.appFolderPath;
projectData.appResourcesDirectoryPath = path.join(testDirData.appFolderPath, "App_Resources");
platformService = testInjector.resolve("platformService");
const appFilesUpdaterOptions: IAppFilesUpdaterOptions = { bundle: false, release: release, useHotModuleReload: false };
platformService.getCurrentPlatformVersion = () => "5.1.1";
await platformService.preparePlatform({
platform: platformToTest,
appFilesUpdaterOptions,
platformTemplate: "",
projectData,
config: { provision: null, teamId: null, sdk: null, frameworkPath: null, ignoreScripts: false },
env: {}
});
}
async function testPreparePlatform(platformToTest: string, release?: boolean): Promise<CreatedTestData> {
const testDirData = prepareDirStructure();
const created: CreatedTestData = new CreatedTestData();
created.testDirData = testDirData;
// Add platform specific files to app and app1 folders
const platformSpecificFiles = [
"test1.ios.js", "test1-ios-js", "test2.android.js", "test2-android-js",
"main.js"
];
const destinationDirectories = [testDirData.appFolderPath, testDirData.app1FolderPath];
_.each(destinationDirectories, directoryPath => {
_.each(platformSpecificFiles, filePath => {
const fileFullPath = path.join(directoryPath, filePath);
fs.writeFile(fileFullPath, "testData");
created.files.push(fileFullPath);
});
});
// Add App_Resources file to app and app1 folders
_.each(destinationDirectories, directoryPath => {
const iosIconFullPath = path.join(directoryPath, "App_Resources/iOS/icon.png");
fs.writeFile(iosIconFullPath, "test-image");
created.resources.ios.push(iosIconFullPath);
const androidFullPath = path.join(directoryPath, "App_Resources/Android/icon.png");
fs.writeFile(androidFullPath, "test-image");
created.resources.android.push(androidFullPath);
});
await execPreparePlatform(platformToTest, testDirData, release);
const test1FileName = platformToTest.toLowerCase() === "ios" ? "test1.js" : "test2.js";
const test2FileName = platformToTest.toLowerCase() === "ios" ? "test2.js" : "test1.js";
// Asserts that the files in app folder are process as platform specific
assert.isTrue(fs.exists(path.join(testDirData.appDestFolderPath, "app", test1FileName)));
assert.isFalse(fs.exists(path.join(testDirData.appDestFolderPath, "app", "test1-js")));
assert.isFalse(fs.exists(path.join(testDirData.appDestFolderPath, "app", test2FileName)));
assert.isFalse(fs.exists(path.join(testDirData.appDestFolderPath, "app", "test2-js")));
// Asserts that the files in app1 folder aren't process as platform specific
assert.isFalse(fs.exists(path.join(testDirData.appDestFolderPath, "app1")), "Asserts that the files in app1 folder aren't process as platform specific");
if (release) {
// Asserts that the files in tests folder aren't copied
assert.isFalse(fs.exists(path.join(testDirData.appDestFolderPath, "tests")), "Asserts that the files in tests folder aren't copied");
}
return created;
}
function updateFile(files: string[], fileName: string, content: string) {
const fileToUpdate = _.find(files, (f) => f.indexOf(fileName) !== -1);
fs.writeFile(fileToUpdate, content);
}
it("should process only files in app folder when preparing for iOS platform", async () => {
await testPreparePlatform("iOS");
});
it("should process only files in app folder when preparing for Android platform", async () => {
await testPreparePlatform("Android");
});
it("should process only files in app folder when preparing for iOS platform", async () => {
await testPreparePlatform("iOS", true);
});
it("should process only files in app folder when preparing for Android platform", async () => {
await testPreparePlatform("Android", true);
});
function getDefaultFolderVerificationData(platform: string, appDestFolderPath: string) {
const data: any = {};
if (platform.toLowerCase() === "ios") {
data[path.join(appDestFolderPath, "app")] = {
missingFiles: ["test1.ios.js", "test2.android.js", "test2.js"],
presentFiles: ["test1.js", "test2-android-js", "test1-ios-js", "main.js"]
};
data[appDestFolderPath] = {
filesWithContent: [
{
name: "Resources/icon.png",
content: "test-image"
}
]
};
} else {
data[path.join(appDestFolderPath, "app")] = {
missingFiles: ["test1.android.js", "test2.ios.js", "test1.js"],
presentFiles: ["test2.js", "test2-android-js", "test1-ios-js"]
};
data[appDestFolderPath] = {
filesWithContent: [
{
name: "src/main/res/icon.png",
content: "test-image"
}
]
};
}
return data;
}
function mergeModifications(def: any, mod: any) {
// custom merge to reflect changes
const merged: any = _.cloneDeep(def);
_.forOwn(mod, (modFolder, folderRoot) => {
// whole folder not present in Default
if (!def.hasOwnProperty(folderRoot)) {
merged[folderRoot] = _.cloneDeep(modFolder[folderRoot]);
} else {
const defFolder = def[folderRoot];
merged[folderRoot].filesWithContent = _.merge(defFolder.filesWithContent || [], modFolder.filesWithContent || []);
merged[folderRoot].missingFiles = (defFolder.missingFiles || []).concat(modFolder.missingFiles || []);
merged[folderRoot].presentFiles = (defFolder.presentFiles || []).concat(modFolder.presentFiles || []);
// remove the missingFiles from the presentFiles if they were initially there
if (modFolder.missingFiles) {
merged[folderRoot].presentFiles = _.difference(defFolder.presentFiles, modFolder.missingFiles);
}
// remove the presentFiles from the missingFiles if they were initially there.
if (modFolder.presentFiles) {
merged[folderRoot].missingFiles = _.difference(defFolder.presentFiles, modFolder.presentFiles);
}
}
});
return merged;
}
// Executes a changes test case:
// 1. Executes Prepare Platform for the Platform
// 2. Applies some changes to the App. Persists the expected Modifications
// 3. Executes again Prepare Platform for the Platform
// 4. Gets the Default Destination App Structure and merges it with the Modifications
// 5. Asserts the Destination App matches our expectations
async function testChangesApplied(platform: string, applyChangesFn: (createdTestData: CreatedTestData) => any) {
const createdTestData = await testPreparePlatform(platform);
const modifications = applyChangesFn(createdTestData);
await execPreparePlatform(platform, createdTestData.testDirData);
const defaultStructure = getDefaultFolderVerificationData(platform, createdTestData.testDirData.appDestFolderPath);
const merged = mergeModifications(defaultStructure, modifications);
DestinationFolderVerifier.verify(merged, fs);
}
it("should sync only changed files, without special folders (iOS)", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "updated-content-ios";
updateFile(createdTestData.files, "test1.ios.js", expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = {
filesWithContent: [
{
name: "test1.js",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("iOS", applyChangesFn);
});
it("should sync only changed files, without special folders (Android) #2697", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "updated-content-android";
updateFile(createdTestData.files, "test2.android.js", expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = {
filesWithContent: [
{
name: "test2.js",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("Android", applyChangesFn);
});
it("Ensure App_Resources get reloaded after change in the app folder (iOS) #2560", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "updated-icon-content";
const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/iOS/icon.png");
fs.writeFile(iconPngPath, expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[createdTestData.testDirData.appDestFolderPath] = {
filesWithContent: [
{
name: "Resources/icon.png",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("iOS", applyChangesFn);
});
it("Ensure App_Resources get reloaded after change in the app folder (Android) #2560", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "updated-icon-content";
const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/Android/icon.png");
fs.writeFile(iconPngPath, expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[createdTestData.testDirData.appDestFolderPath] = {
filesWithContent: [
{
name: "src/main/res/icon.png",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("Android", applyChangesFn);
});
it("Ensure App_Resources get reloaded after a new file appears in the app folder (iOS) #2560", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "new-file-content";
const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/iOS/new-file.png");
fs.writeFile(iconPngPath, expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[createdTestData.testDirData.appDestFolderPath] = {
filesWithContent: [
{
name: "Resources/new-file.png",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("iOS", applyChangesFn);
});
it("Ensure App_Resources get reloaded after a new file appears in the app folder (Android) #2560", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "new-file-content";
const iconPngPath = path.join(createdTestData.testDirData.appFolderPath, "App_Resources/Android/new-file.png");
fs.writeFile(iconPngPath, expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[createdTestData.testDirData.appDestFolderPath] = {
filesWithContent: [
{
name: "src/main/res/new-file.png",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("Android", applyChangesFn);
});
it("should sync new platform specific files (iOS)", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "new-content-ios";
fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.ios.js"), expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = {
filesWithContent: [
{
name: "test3.js",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("iOS", applyChangesFn);
});
it("should sync new platform specific files (Android)", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "new-content-android";
fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.android.js"), expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = {
filesWithContent: [
{
name: "test3.js",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("Android", applyChangesFn);
});
it("should sync new common files (iOS)", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "new-content-ios";
fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.js"), expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = {
filesWithContent: [
{
name: "test3.js",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("iOS", applyChangesFn);
});
it("should sync new common file (Android)", async () => {
const applyChangesFn = (createdTestData: CreatedTestData) => {
// apply changes
const expectedFileContent = "new-content-android";
fs.writeFile(path.join(createdTestData.testDirData.appFolderPath, "test3.js"), expectedFileContent);
// construct the folder modifications data
const modifications: any = {};
modifications[path.join(createdTestData.testDirData.appDestFolderPath, "app")] = {
filesWithContent: [
{
name: "test3.js",
content: expectedFileContent
}
]
};
return modifications;
};
await testChangesApplied("Android", applyChangesFn);
});
it("invalid xml is caught", async () => {
require("colors");
const testDirData = prepareDirStructure();
// generate invalid xml
const fileFullPath = path.join(testDirData.appFolderPath, "file.xml");
fs.writeFile(fileFullPath, "<xml><unclosedTag></xml>");
const platformsData = testInjector.resolve("platformsData");
platformsData.platformsNames = ["android"];
platformsData.getPlatformData = (platform: string) => {
return {
appDestinationDirectoryPath: testDirData.appDestFolderPath,
appResourcesDestinationDirectoryPath: testDirData.appResourcesFolderPath,
normalizedPlatformName: "Android",
projectRoot: testDirData.tempFolder,
configurationFileName: "configFileName",
platformProjectService: {
prepareProject: (): any => null,
prepareAppResources: (): any => null,
validate: () => Promise.resolve(),
createProject: (projectRoot: string, frameworkDir: string) => Promise.resolve(),
interpolateData: (projectRoot: string) => Promise.resolve(),
afterCreateProject: (projectRoot: string): any => null,
getAppResourcesDestinationDirectoryPath: () => testDirData.appResourcesFolderPath,
processConfigurationFilesFromAppResources: () => Promise.resolve(),
handleNativeDependenciesChange: () => Promise.resolve(),
ensureConfigurationFileInAppResources: (): any => null,
interpolateConfigurationFile: (): void => undefined,
isPlatformPrepared: (projectRoot: string) => false,
checkForChanges: () => { /* */ }
},
frameworkPackageName: "tns-ios"
};
};
const projectData = testInjector.resolve("projectData");
projectData.projectDir = testDirData.tempFolder;
projectData.appDirectoryPath = projectData.getAppDirectoryPath();
projectData.appResourcesDirectoryPath = projectData.getAppResourcesDirectoryPath();
platformService = testInjector.resolve("platformService");
platformService.getCurrentPlatformVersion = () => "5.1.1";
const oldLoggerWarner = testInjector.resolve("$logger").warn;
let warnings: string = "";
try {
testInjector.resolve("$logger").warn = (text: string) => warnings += text;
const appFilesUpdaterOptions: IAppFilesUpdaterOptions = { bundle: false, release: false, useHotModuleReload: false };
await platformService.preparePlatform({
platform: "android",
appFilesUpdaterOptions,
platformTemplate: "",
projectData,
config: { provision: null, teamId: null, sdk: null, frameworkPath: null, ignoreScripts: false },
env: {}
});
} finally {
testInjector.resolve("$logger").warn = oldLoggerWarner;
}
// Asserts that prepare has caught invalid xml
assert.isFalse(warnings.indexOf("has errors") !== -1);
});
});
describe("build", () => {
function mockData(buildOutput: string[], projectName: string): void {
mockPlatformsData(projectName);
mockFileSystem(buildOutput);
platformService.saveBuildInfoFile = () => undefined;
}
function mockPlatformsData(projectName: string): void {
const platformsData = testInjector.resolve("platformsData");
platformsData.getPlatformData = (platform: string) => {
return {
deviceBuildOutputPath: "",
normalizedPlatformName: "",
getBuildOutputPath: () => "",
platformProjectService: {
buildProject: () => Promise.resolve(),
on: () => ({}),
removeListener: () => ({})
},
getValidBuildOutputData: () => ({
packageNames: ["app-debug.apk", "app-release.apk", `${projectName}-debug.apk`, `${projectName}-release.apk`],
regexes: [/app-.*-(debug|release).apk/, new RegExp(`${projectName}-.*-(debug|release).apk`)]
})
};