microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
678db279088f7b3fd6c7888d37be778e758ff688

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

test/resources/reactNative022.ts

193lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as Q from "q";
5import * as path from "path";
6import * as assert from "assert";
7
8import {PromiseUtil} from "../../src/common/node/promise";
9
10import * as reactNative from "../../src/common/reactNative";
11import {IAndroidRunOptions} from "../../src/common/launchArgs";
12import {ISpawnResult} from "../../src/common/node/childProcess";
13import {FileSystem} from "../../src/common/node/fileSystem";
14import {Package} from "../../src/common/node/package";
15import {Recording, Simulator} from "./processExecution/simulator";
16import {AdbSimulator} from "./simulators/adbSimulator";
17import {APKSerializer} from "./simulators/apkSerializer";
18
19const sampleRNProjectPath = path.join(__dirname, "sampleReactNative022Project");
20const processExecutionsRecordingsPath = path.join(__dirname, "processExecutionsRecordings");
21
22export type IReactNative = reactNative.IReactNative;
23
24/* This class simulates calling the React-Native CLI v0.22. It currently supports react-native init
25 and react-native run-android. */
26export class ReactNative022 implements IReactNative {
27
28 public static DEFAULT_PROJECT_FILE = path.join(sampleRNProjectPath, "package.json");
29
30 private static ANDROID_APK_RELATIVE_PATH = "android/app/build/outputs/apk/app-debug.apk";
31
32 private projectFileContent: string;
33
34 private simulator: Simulator = new Simulator({
35 beforeStart: () => this.readAndroidPackageName(), // 1. We read the package.json to verify this is a RN project
36 outputBased: [
37 {
38 eventPattern: /:app:assembleDebug/,
39 action: () => this.createAPK(), // 2. We compile the application.
40 },
41 {
42 eventPattern: /Installed on [0-9]+ devices*\./,
43 action: () => this.installAppInAllDevices(), // 3. We install it on all available devices.
44 },
45 ],
46 beforeSuccess: (stdout: string, stderr: string) => // 4. If we didn't had any errors after starting to launch the app,
47 this.launchApp(stdout, stderr), // it means we were succesful
48 });
49
50 private recording: Recording;
51
52 private androidPackageName: string;
53 private projectRoot: string;
54 private androidAPKPath: string;
55
56 constructor(private adb: AdbSimulator, private fileSystem: FileSystem) {
57 assert(this.adb, "adb shouldn't be null");
58 assert(this.fileSystem, "fileSystem shouldn't be null");
59 }
60
61 public fromProjectFileContent(content: string): this {
62 this.projectFileContent = content;
63 return this;
64 }
65
66 public loadRecordingFromName(recordingName: string): Q.Promise<void> {
67 return this.loadRecordingFromFile(path.join(processExecutionsRecordingsPath, `${recordingName}.json`));
68 }
69
70 public loadRecordingFromString(recordingContent: string): Q.Promise<void> {
71 return Q.when(this.loadRecording(JSON.parse(recordingContent)));
72 }
73
74 public loadRecordingFromFile(recordingPath: string): Q.Promise<void> {
75 return Q({})
76 .then(() => {
77 return new FileSystem().readFile(recordingPath);
78 }).then(fileContents => {
79 this.loadRecording(JSON.parse(fileContents));
80 });
81 }
82
83 public loadRecording(recording: Recording): void {
84 assert(recording, "recording shouldn't be null");
85 this.recording = recording;
86 }
87
88 public createProject(projectRoot: string, projectName: string): Q.Promise<void> {
89 return Q({})
90 .then(() => {
91 this.fileSystem.makeDirectoryRecursiveSync(projectRoot);
92 return this.projectFileContent !== undefined ?
93 this.projectFileContent :
94 this.readDefaultProjectFile();
95 }).then(defaultContents => {
96 const reactNativeConfiguration = JSON.parse(defaultContents);
97 reactNativeConfiguration.name = projectName;
98 const reactNativeConfigurationFormatted = JSON.stringify(reactNativeConfiguration);
99 return this.fileSystem.writeFile(this.getPackageJsonPath(projectRoot), reactNativeConfigurationFormatted);
100 }).then(() => {
101 return this.fileSystem.mkDir(this.getAndroidProjectPath(projectRoot));
102 });
103 }
104
105 public runAndroid(runOptions: IAndroidRunOptions): ISpawnResult {
106 this.projectRoot = runOptions.projectRoot;
107 this.simulator.simulate(this.recording).done();
108 return this.simulator.spawn();
109 }
110
111 private getAndroidProjectPath(projectRoot = this.projectRoot): string {
112 return path.join(projectRoot, "android");
113 }
114
115 private getPackageJsonPath(projectRoot: string): string {
116 return new Package(projectRoot, { fileSystem: this.fileSystem }).informationJsonFilePath();
117 }
118
119 private readAndroidPackageName(): Q.Promise<void> {
120 return new Package(this.projectRoot, { fileSystem: this.fileSystem }).name().then(name => {
121 this.androidPackageName = `com.${name.toLowerCase()}`;
122 });
123 }
124
125 private createAPK(): Q.Promise<void> {
126 return this.isAndroidProjectPresent().then(isPresent => {
127 return isPresent ? void 0 : Q.reject<void>(new Error("The recording expects the Android project to be present, but it's not"));
128 }).then(() => {
129 this.androidAPKPath = path.join(this.projectRoot, ReactNative022.ANDROID_APK_RELATIVE_PATH);
130 return new APKSerializer(this.fileSystem).writeApk(this.androidAPKPath, { packageName: this.androidPackageName });
131 });
132 }
133
134 private isAndroidProjectPresent(): Q.Promise<boolean> {
135 // TODO: Make more checks as neccesary for the tests
136 return this.fileSystem.directoryExists(this.getAndroidProjectPath());
137 }
138
139 private installAppInAllDevices(): Q.Promise<void> {
140 return new PromiseUtil().reduce(this.adb.getConnectedDevices(), device => this.installAppInDevice(device.id));
141 }
142
143 private installAppInDevice(deviceId: string): Q.Promise<void> {
144 return this.adb.isDeviceOnline(deviceId).then(isOnline => {
145 if (isOnline) {
146 return this.adb.installApp(this.androidAPKPath, deviceId);
147 } else {
148 // TODO: Figure out what's the right thing to do here, if we ever need this for the tests
149 return void 0;
150 }
151 });
152 }
153
154 private launchApp(stdout: string, stderr: string): Q.Promise<void> {
155 /*
156 Sample output we want to accept:
157 BUILD SUCCESSFUL
158
159 Total time: 9.052 secs
160 Starting the app (C:\Program Files (x86)\Android\android-sdk/platform-tools/adb shell am start -n com.sampleapplication/.MainActivity)...
161 Starting: Intent { cmp=com.sampleapplication/.MainActivity }
162
163
164 Sample output we don't to accept:
165 BUILD SUCCESSFUL
166
167 Total time: 9.052 secs
168 Starting the app (C:\Program Files (x86)\Android\android-sdk/platform-tools/adb shell am start -n com.sampleapplication/.MainActivity)...
169 Starting: Intent { cmp=com.sampleapplication/.MainActivity }
170 Error: some error happened
171 **/
172 const succesfulOutputEnd = `Starting the app \\(.*adb shell am start -n ([^ /]+)\/\\.MainActivity\\)\\.\\.\\.\\s+`
173 + `Starting: Intent { cmp=([^ /]+)\/\\.MainActivity }\\s+$`;
174 const matches = stdout.match(new RegExp(succesfulOutputEnd));
175 if (matches) {
176 if (matches.length === 3 && matches[1] === this.androidPackageName && matches[2] === this.androidPackageName) {
177 return this.adb.launchApp(this.projectRoot, this.androidPackageName);
178 } else {
179 return Q.reject<void>(new Error("There was an error while trying to match the Starting the app messages."
180 + "Expected to match the pattern and recognize the expected android package name, but it failed."
181 + `Expected android package name: ${this.androidPackageName}. Actual matches: ${JSON.stringify(matches)}`));
182 }
183 } else {
184 // The record doesn't indicate that the app was launched, so we don't do anything
185 return Q.resolve(void 0);
186 }
187 }
188
189 private readDefaultProjectFile(): Q.Promise<string> {
190 const realFileSystem = new FileSystem(); // We always use the real file system (not the mock one) to read the sample project
191 return realFileSystem.readFile(ReactNative022.DEFAULT_PROJECT_FILE);
192 }
193}
194