1import spawnAsync from '@expo/spawn-async';
2import chalk from 'chalk';
3import path from 'path';
4
5import * as Directories from '../Directories';
6import * as Packages from '../Packages';
7import { filterAsync } from '../Utils';
8
9const ANDROID_DIR = Directories.getAndroidDir();
10
11const BARE_EXPO_DIR = path.join(Directories.getAppsDir(), 'bare-expo', 'android');
12
13const excludedInTests = [
14  'expo-module-template',
15  'expo-notifications',
16  'expo-in-app-purchases',
17  'expo-splash-screen',
18  'unimodules-test-core',
19  'expo-dev-client',
20];
21
22const packagesNeedToBeTestedUsingBareExpo = [
23  'expo-dev-menu',
24  'expo-dev-launcher',
25  'expo-dev-menu-interface',
26];
27
28type TestType = 'local' | 'instrumented';
29
30function consoleErrorOutput(output: string, label: string, colorifyLine: (string) => string): void {
31  const lines = output.trim().split(/\r\n?|\n/g);
32  console.error(lines.map((line) => `${chalk.gray(label)} ${colorifyLine(line)}`).join('\n'));
33}
34
35export async function androidNativeUnitTests({
36  type,
37  packages,
38}: {
39  type: TestType;
40  packages?: string;
41}) {
42  if (!type) {
43    throw new Error(
44      'Must specify which type of unit test to run with `--type local` or `--type instrumented`.'
45    );
46  }
47  if (type !== 'local' && type !== 'instrumented') {
48    throw new Error('Invalid type specified. Must use `--type local` or `--type instrumented`.');
49  }
50
51  const allPackages = await Packages.getListOfPackagesAsync();
52  const packageNamesFilter = packages ? packages.split(',') : [];
53
54  const androidPackages = await filterAsync(allPackages, async (pkg) => {
55    const pkgSlug = pkg.packageSlug;
56
57    if (packageNamesFilter.length > 0 && !packageNamesFilter.includes(pkg.packageName)) {
58      return false;
59    }
60
61    let includesTests;
62    if (type === 'instrumented') {
63      includesTests =
64        pkg.isSupportedOnPlatform('android') &&
65        (await pkg.hasNativeInstrumentationTestsAsync('android')) &&
66        !excludedInTests.includes(pkgSlug);
67    } else {
68      includesTests =
69        pkg.isSupportedOnPlatform('android') &&
70        (await pkg.hasNativeTestsAsync('android')) &&
71        !excludedInTests.includes(pkgSlug);
72    }
73
74    if (!includesTests && packageNamesFilter.includes(pkg.packageName)) {
75      throw new Error(
76        `The package ${pkg.packageName} does not include Android ${type} unit tests.`
77      );
78    }
79
80    return includesTests;
81  });
82
83  console.log(chalk.green('Packages to test: '));
84  androidPackages.forEach((pkg) => {
85    console.log(chalk.yellow(pkg.packageSlug));
86  });
87
88  const testCommand = type === 'instrumented' ? 'connectedAndroidTest' : 'test';
89
90  const partition = <T>(arr: T[], condition: (T) => boolean) => {
91    const trues = arr.filter((el) => condition(el));
92    const falses = arr.filter((el) => !condition(el));
93    return [trues, falses];
94  };
95
96  const [
97    androidPackagesTestedUsingBareProject,
98    androidPackagesTestedUsingExpoProject,
99  ] = partition(androidPackages, (element) =>
100    packagesNeedToBeTestedUsingBareExpo.includes(element.packageName)
101  );
102
103  await runGradlew(androidPackagesTestedUsingExpoProject, testCommand, ANDROID_DIR);
104  await runGradlew(androidPackagesTestedUsingBareProject, testCommand, BARE_EXPO_DIR);
105  console.log(chalk.green('Finished android unit tests successfully.'));
106}
107
108async function runGradlew(packages: Packages.Package[], testCommand: string, cwd: string) {
109  if (!packages.length) {
110    return;
111  }
112
113  try {
114    await spawnAsync(
115      './gradlew',
116      packages.map((pkg) => `:${pkg.packageSlug}:${testCommand}`),
117      {
118        cwd,
119        stdio: 'inherit',
120        env: { ...process.env },
121      }
122    );
123  } catch (error) {
124    console.error('Failed while executing android unit tests');
125    consoleErrorOutput(error.stdout, 'stdout >', chalk.reset);
126    consoleErrorOutput(error.stderr, 'stderr >', chalk.red);
127    throw error;
128  }
129}
130
131export default (program: any) => {
132  program
133    .command('android-native-unit-tests')
134    .option('-t, --type <string>', 'Type of unit test to run: local or instrumented')
135    .option(
136      '--packages <string>',
137      '[optional] Comma-separated list of package names to run unit tests for. Defaults to all packages with unit tests.'
138    )
139    .description('Runs Android native unit tests for each package that provides them.')
140    .asyncAction(androidNativeUnitTests);
141};
142