microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
0.4.1

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/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 "../../common/node/promise";
9
10import * as reactNative from "../../common/reactNative";
11import {ISpawnResult} from "../../common/node/childProcess";
12import {FileSystem} from "../../common/node/fileSystem";
13import {Package} from "../../common/node/package";
14import {Recording, Simulator} from "./processExecution/simulator";
15import {AdbSimulator} from "./simulators/adbSimulator";
16import {APKSerializer} from "./simulators/apkSerializer";
17
18const resourcesPath = path.join(__dirname, "../../../src/test/resources/");
19const sampleRNProjectPath = path.join(resourcesPath, "sampleReactNative022Project");
20const processExecutionsRecordingsPath = path.join(resourcesPath, "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(projectRoot: string): ISpawnResult {
106 this.projectRoot = 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 if (!isPresent) {
128 return Q.reject<void>(new Error("The recording expects the Android project to be present, but it's not"));
129 }
130 }).then(() => {
131 this.androidAPKPath = path.join(this.projectRoot, ReactNative022.ANDROID_APK_RELATIVE_PATH);
132 return new APKSerializer(this.fileSystem).writeApk(this.androidAPKPath, { packageName: this.androidPackageName });
133 });
134 }
135
136 private isAndroidProjectPresent(): Q.Promise<boolean> {
137 // TODO: Make more checks as neccesary for the tests
138 return this.fileSystem.directoryExists(this.getAndroidProjectPath());
139 }
140
141 private installAppInAllDevices(): Q.Promise<void> {
142 return new PromiseUtil().reduce(this.adb.getConnectedDevices(), device => this.installAppInDevice(device.id));
143 }
144
145 private installAppInDevice(deviceId: string): Q.Promise<void> {
146 return this.adb.isDeviceOnline(deviceId).then(isOnline => {
147 if (isOnline) {
148 return this.adb.installApp(this.androidAPKPath, deviceId);
149 } else {
150 // TODO: Figure out what's the right thing to do here, if we ever need this for the tests
151 }
152 });
153 }
154
155 private launchApp(stdout: string, stderr: string): Q.Promise<void> {
156 /*
157 Sample output we want to accept:
158 BUILD SUCCESSFUL
159
160 Total time: 9.052 secs
161 Starting the app (C:\Program Files (x86)\Android\android-sdk/platform-tools/adb shell am start -n com.sampleapplication/.MainActivity)...
162 Starting: Intent { cmp=com.sampleapplication/.MainActivity }
163
164
165 Sample output we don't to accept:
166 BUILD SUCCESSFUL
167
168 Total time: 9.052 secs
169 Starting the app (C:\Program Files (x86)\Android\android-sdk/platform-tools/adb shell am start -n com.sampleapplication/.MainActivity)...
170 Starting: Intent { cmp=com.sampleapplication/.MainActivity }
171 Error: some error happened
172 **/
173 const succesfulOutputEnd = `Starting the app \\(.*adb shell am start -n ([^ /]+)\/\\.MainActivity\\)\\.\\.\\.\\s+`
174 + `Starting: Intent { cmp=([^ /]+)\/\\.MainActivity }\\s+$`;
175 const matches = stdout.match(new RegExp(succesfulOutputEnd));
176 if (matches) {
177 if (matches.length === 3 && matches[1] === this.androidPackageName && matches[2] === this.androidPackageName) {
178 return this.adb.launchApp(this.projectRoot, this.androidPackageName);
179 } else {
180 return Q.reject<void>(new Error("There was an error while trying to match the Starting the app messages."
181 + "Expected to match the pattern and recognize the expected android package name, but it failed."
182 + `Expected android package name: ${this.androidPackageName}. Actual matches: ${JSON.stringify(matches)}`));
183 }
184 } else {
185 // The record doesn't indicate that the app was launched, so we don't do anything
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