Skip to content

fix: validate test init before executing the test command #4381

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 68 additions & 23 deletions lib/commands/test.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,75 @@
import * as helpers from "../common/helpers";

function RunKarmaTestCommandFactory(platform: string) {
return function RunKarmaTestCommand($options: IOptions, $testExecutionService: ITestExecutionService, $projectData: IProjectData, $analyticsService: IAnalyticsService, $platformEnvironmentRequirements: IPlatformEnvironmentRequirements) {
$projectData.initializeProjectData();
$analyticsService.setShouldDispose($options.justlaunch || !$options.watch);
const projectFilesConfig = helpers.getProjectFilesConfig({ isReleaseBuild: $options.release });
this.execute = (args: string[]): Promise<void> => $testExecutionService.startKarmaServer(platform, $projectData, projectFilesConfig);
this.canExecute = (args: string[]): Promise<boolean> => canExecute({ $platformEnvironmentRequirements, $projectData, $options, platform });
this.allowedParameters = [];
};
}
abstract class TestCommandBase {
public allowedParameters: ICommandParameter[] = [];
private projectFilesConfig: IProjectFilesConfig;
protected abstract platform: string;
protected abstract $projectData: IProjectData;
protected abstract $testExecutionService: ITestExecutionService;
protected abstract $analyticsService: IAnalyticsService;
protected abstract $options: IOptions;
protected abstract $platformEnvironmentRequirements: IPlatformEnvironmentRequirements;
protected abstract $errors: IErrors;

async execute(args: string[]): Promise<void> {
await this.$testExecutionService.startKarmaServer(this.platform, this.$projectData, this.projectFilesConfig);
}

async canExecute(args: string[]): Promise<boolean | ICanExecuteCommandOutput> {
this.$projectData.initializeProjectData();
this.$analyticsService.setShouldDispose(this.$options.justlaunch || !this.$options.watch);
this.projectFilesConfig = helpers.getProjectFilesConfig({ isReleaseBuild: this.$options.release });

async function canExecute(input: { $platformEnvironmentRequirements: IPlatformEnvironmentRequirements, $projectData: IProjectData, $options: IOptions, platform: string }): Promise<boolean> {
const { $platformEnvironmentRequirements, $projectData, $options, platform } = input;
const output = await $platformEnvironmentRequirements.checkEnvironmentRequirements({
platform,
projectDir: $projectData.projectDir,
options: $options,
notConfiguredEnvOptions: {
hideSyncToPreviewAppOption: true,
hideCloudBuildOption: true
const output = await this.$platformEnvironmentRequirements.checkEnvironmentRequirements({
platform: this.platform,
projectDir: this.$projectData.projectDir,
options: this.$options,
notConfiguredEnvOptions: {
hideSyncToPreviewAppOption: true,
hideCloudBuildOption: true
}
});

const canStartKarmaServer = await this.$testExecutionService.canStartKarmaServer(this.$projectData);
if (!canStartKarmaServer) {
this.$errors.fail({
formatStr: "Error: In order to run unit tests, your project must already be configured by running $ tns test init.",
suppressCommandHelp: true,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we can create better user experience by prompt the user to automatically execute tns test init command.
This is not a merge stopper and can be done in another PR if we decide it is appropriate.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

errorCode: ErrorCodes.TESTS_INIT_REQUIRED
});
}
});

return output.canExecute;
return output.canExecute && canStartKarmaServer;
}
}

class TestAndroidCommand extends TestCommandBase implements ICommand {
protected platform = "android";

constructor(protected $projectData: IProjectData,
protected $testExecutionService: ITestExecutionService,
protected $analyticsService: IAnalyticsService,
protected $options: IOptions,
protected $platformEnvironmentRequirements: IPlatformEnvironmentRequirements,
protected $errors: IErrors) {
super();
}

}

class TestIosCommand extends TestCommandBase implements ICommand {
protected platform = "iOS";

constructor(protected $projectData: IProjectData,
protected $testExecutionService: ITestExecutionService,
protected $analyticsService: IAnalyticsService,
protected $options: IOptions,
protected $platformEnvironmentRequirements: IPlatformEnvironmentRequirements,
protected $errors: IErrors) {
super();
}

}

$injector.registerCommand("test|android", RunKarmaTestCommandFactory('android'));
$injector.registerCommand("test|ios", RunKarmaTestCommandFactory('iOS'));
$injector.registerCommand("test|android", TestAndroidCommand);
$injector.registerCommand("test|ios", TestIosCommand);
1 change: 1 addition & 0 deletions lib/common/declarations.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,7 @@ declare const enum ErrorCodes {
KARMA_FAIL = 130,
UNHANDLED_REJECTION_FAILURE = 131,
DELETED_KILL_FILE = 132,
TESTS_INIT_REQUIRED = 133
}

interface IFutureDispatcher {
Expand Down
3 changes: 2 additions & 1 deletion lib/common/errors.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as util from "util";
import * as path from "path";
import { SourceMapConsumer } from "source-map";
import { isInteractive } from "./helpers";

// we need this to overwrite .stack property (read-only in Error)
function Exception() {
Expand Down Expand Up @@ -159,7 +160,7 @@ export class Errors implements IErrors {
} catch (ex) {
const loggerLevel: string = $injector.resolve("logger").getLevel().toUpperCase();
const printCallStack = this.printCallStack || loggerLevel === "TRACE" || loggerLevel === "DEBUG";
const message = printCallStack ? resolveCallStack(ex) : `\x1B[31;1m${ex.message}\x1B[0m`;
const message = printCallStack ? resolveCallStack(ex) : isInteractive() ? `\x1B[31;1m${ex.message}\x1B[0m` : ex.message;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems this probably will affect Sidekick/KinveyStudio but I'm not sure what exactly will be the impact.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be better to split the conditions in two separate lines for readability of the code.


if (ex.printOnStdout) {
this.$injector.resolve("logger").out(message);
Expand Down
1 change: 1 addition & 0 deletions lib/definitions/project.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ interface IValidatePlatformOutput {

interface ITestExecutionService {
startKarmaServer(platform: string, projectData: IProjectData, projectFilesConfig: IProjectFilesConfig): Promise<void>;
canStartKarmaServer(projectData: IProjectData): Promise<boolean>;
}

/**
Expand Down
15 changes: 14 additions & 1 deletion lib/services/test-execution-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ interface IKarmaConfigOptions {
debugTransport: boolean;
}

class TestExecutionService implements ITestExecutionService {
export class TestExecutionService implements ITestExecutionService {
private static CONFIG_FILE_NAME = `node_modules/${constants.TEST_RUNNER_NAME}/config.js`;
private static SOCKETIO_JS_FILE_NAME = `node_modules/${constants.TEST_RUNNER_NAME}/socket.io.js`;

Expand Down Expand Up @@ -163,6 +163,19 @@ class TestExecutionService implements ITestExecutionService {
});
}

public async canStartKarmaServer(projectData: IProjectData): Promise<boolean> {
let canStartKarmaServer = true;
const requiredDependencies = ["karma", "nativescript-unit-test-runner"];
_.each(requiredDependencies, (dep) => {
if (!projectData.dependencies[dep] && !projectData.devDependencies[dep]) {
canStartKarmaServer = false;
return;
}
});

return canStartKarmaServer;
}

allowedParameters: ICommandParameter[] = [];

private generateConfig(port: string, options: any): string {
Expand Down
67 changes: 67 additions & 0 deletions test/services/test-execution-serice.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { InjectorStub } from "../stubs";
import { TestExecutionService } from "../../lib/services/test-execution-service";
import { assert } from "chai";

const karmaPluginName = "karma";
const unitTestsPluginName = "nativescript-unit-test-runner";

function getTestExecutionService(): ITestExecutionService {
const injector = new InjectorStub();
injector.register("testExecutionService", TestExecutionService);

return injector.resolve("testExecutionService");
}

function getDependenciesObj(deps: string[]): IDictionary<string> {
const depsObj: IDictionary<string> = {};
deps.forEach(dep => {
depsObj[dep] = "1.0.0";
});

return depsObj;
}

describe("testExecutionService", () => {
const testCases = [
{
name: "should return false when the project has no dependencies and dev dependencies",
expectedCanStartKarmaServer: false,
projectData: { dependencies: {}, devDependencies: {} }
},
{
name: "should return false when the project has no karma",
expectedCanStartKarmaServer: false,
projectData: { dependencies: getDependenciesObj([unitTestsPluginName]), devDependencies: {} }
},
{
name: "should return false when the project has no unit test runner",
expectedCanStartKarmaServer: false,
projectData: { dependencies: getDependenciesObj([karmaPluginName]), devDependencies: {} }
},
{
name: "should return true when the project has the required plugins as dependencies",
expectedCanStartKarmaServer: true,
projectData: { dependencies: getDependenciesObj([karmaPluginName, unitTestsPluginName]), devDependencies: {} }
},
{
name: "should return true when the project has the required plugins as dev dependencies",
expectedCanStartKarmaServer: true,
projectData: { dependencies: {}, devDependencies: getDependenciesObj([karmaPluginName, unitTestsPluginName]) }
},
{
name: "should return true when the project has the required plugins as dev and normal dependencies",
expectedCanStartKarmaServer: true,
projectData: { dependencies: getDependenciesObj([karmaPluginName]), devDependencies: getDependenciesObj([unitTestsPluginName]) }
}
];

describe("canStartKarmaServer", () => {
_.each(testCases, (testCase: any) => {
it(`${testCase.name}`, async () => {
const testExecutionService = getTestExecutionService();
const canStartKarmaServer = await testExecutionService.canStartKarmaServer(testCase.projectData);
assert.equal(canStartKarmaServer, testCase.expectedCanStartKarmaServer);
});
});
});
});
14 changes: 13 additions & 1 deletion test/stubs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,7 @@ export class AndroidBundleValidatorHelper implements IAndroidBundleValidatorHelp

export class PerformanceService implements IPerformanceService {
now(): number { return 10; }
processExecutionData() {}
processExecutionData() { }
}

export class InjectorStub extends Yok implements IInjector {
Expand Down Expand Up @@ -942,5 +942,17 @@ export class InjectorStub extends Yok implements IInjector {
this.register('projectData', ProjectDataStub);
this.register('packageInstallationManager', PackageInstallationManagerStub);
this.register('packageInstallationManager', PackageInstallationManagerStub);
this.register("httpClient", {
httpRequest: async (options: any, proxySettings?: IProxySettings): Promise<Server.IResponse> => undefined
});
this.register("pluginsService", {
add: async (): Promise<void> => undefined,
remove: async (): Promise<void> => undefined,
ensureAllDependenciesAreInstalled: () => { return Promise.resolve(); },
});
this.register("devicesService", {
getDevice: (): Mobile.IDevice => undefined,
getDeviceByIdentifier: (): Mobile.IDevice => undefined
});
}
}