Skip to content

Commit

Permalink
fix(dotnet): dotnet watch --project ... test should work (#426)
Browse files Browse the repository at this point in the history
Fixes #425
  • Loading branch information
AgentEnder authored Apr 25, 2022
1 parent 6e084ea commit 1575dda
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 194 deletions.
18 changes: 18 additions & 0 deletions e2e/core-e2e/tests/nx-dotnet.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
uniq,
updateFile,
} from '@nrwl/nx-plugin/testing';
import { runCommandUntil } from '../../utils';

import { readFileSync, unlinkSync, writeFileSync } from 'fs';
import { join } from 'path';
Expand Down Expand Up @@ -422,6 +423,23 @@ public class UnitTest1

expect(() => runNxCommand(`test ${testProject}`)).toThrow();
});

it('should work with watch', async () => {
const appProject = uniq('app');
const testProject = `${appProject}-test`;
runNxCommand(
`generate @nx-dotnet/core:app ${appProject} --language="C#" --template="webapi" --test-runner xunit`,
);
const p = runCommandUntil(
`test ${testProject} --watch`,
(output) =>
output.includes(
'Waiting for a file to change before restarting dotnet...',
),
{ kill: true },
);
await expect(p).resolves.not.toThrow();
});
});
});

Expand Down
185 changes: 6 additions & 179 deletions e2e/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { detectPackageManager } from '@nrwl/tao/src/shared/package-manager';

import { tmpProjPath } from '@nrwl/nx-plugin/testing';
import { ChildProcess, exec, execSync } from 'child_process';
import {
copySync,
Expand All @@ -17,155 +16,23 @@ import * as path from 'path';
import { dirSync } from 'tmp';

import isCI = require('is-ci');
import { workspaceConfigName } from 'nx/src/config/workspaces';
import { detectPackageManager } from '@nrwl/devkit';
interface RunCmdOpts {
silenceError?: boolean;
env?: Record<string, string> | NodeJS.ProcessEnv;
cwd?: string;
silent?: boolean;
}

export function currentCli() {
return process.env.SELECTED_CLI ?? 'nx';
}

export const e2eRoot = isCI ? dirSync({ prefix: 'nx-e2e-' }).name : `./tmp`;
export const e2eCwd = `${e2eRoot}/${currentCli()}`;
ensureDirSync(e2eCwd);

let projName: string;

export function uniq(prefix: string) {
return `${prefix}${Math.floor(Math.random() * 10000000)}`;
}

export function workspaceConfigName() {
return currentCli() === 'angular' ? 'angular.json' : 'workspace.json';
}

export function updateWorkspaceConfig(
callback: (json: { [key: string]: any }) => Object,
) {
const file = workspaceConfigName();
updateFile(file, JSON.stringify(callback(readJson(file)), null, 2));
}

export function runCreateWorkspace(
name: string,
{
preset,
appName,
style,
base,
packageManager,
cli,
extraArgs,
}: {
preset: string;
appName?: string;
style?: string;
base?: string;
packageManager?: 'npm' | 'yarn' | 'pnpm';
cli?: string;
extraArgs?: string;
},
) {
projName = name;

const pm = getPackageManagerCommand({ packageManager });

const linterArg =
preset === 'angular' || preset === 'angular-nest' ? ' --linter=tslint' : '';
let command = `${pm.createWorkspace} ${name} --cli=${
cli || currentCli()
} --preset=${preset} ${linterArg} --no-nxCloud --no-interactive`;
if (appName) {
command += ` --appName=${appName}`;
}
if (style) {
command += ` --style=${style}`;
}

if (base) {
command += ` --defaultBase="${base}"`;
}

if (packageManager) {
command += ` --package-manager=${packageManager}`;
}

if (extraArgs) {
command += ` ${extraArgs}`;
}

const create = execSync(command, {
cwd: e2eCwd,
stdio: [0, 1, 2],
env: process.env,
});
return create ? create.toString() : '';
}

export function packageInstall(pkg: string, projName?: string) {
const cwd = projName ? `${e2eCwd}/${projName}` : tmpProjPath();
const pm = getPackageManagerCommand({ path: cwd });
const install = execSync(`${pm.addDev} ${pkg}`, {
cwd,
// ...{ stdio: ['pipe', 'pipe', 'pipe'] },
...{ stdio: [0, 1, 2] },
env: process.env,
});
return install ? install.toString() : '';
}

export function runNgNew(): string {
return execSync(`../../node_modules/.bin/ng new proj --no-interactive`, {
cwd: e2eCwd,
env: process.env,
}).toString();
}

export function getSelectedPackageManager(): 'npm' | 'yarn' | 'pnpm' {
return process.env.SELECTED_PM as 'npm' | 'yarn' | 'pnpm';
}

/**
* Sets up a new project in the temporary project path
* for the currently selected CLI.
*/
export function newProject({ name = uniq('proj') } = {}): string {
const packageManager = getSelectedPackageManager();

try {
const useBackupProject = packageManager !== 'pnpm';
const projScope = useBackupProject ? 'proj' : name;

if (!useBackupProject || !directoryExists(tmpBackupProjPath())) {
runCreateWorkspace(projScope, { preset: 'empty', packageManager });

// Temporary hack to prevent installing with `--frozen-lockfile`
if (isCI && packageManager === 'pnpm') {
updateFile('.npmrc', 'prefer-frozen-lockfile=false');
}

const packages = [`@nx-dotnet/core`, `@nx-dotnet/typescript`];
packageInstall(packages.join(` `), projScope);

if (useBackupProject) {
moveSync(`${e2eCwd}/proj`, `${tmpBackupProjPath()}`);
}
}
projName = name;
if (useBackupProject) {
copySync(`${tmpBackupProjPath()}`, `${tmpProjPath()}`);
}
return projScope;
} catch (e: any) {
console.log(`Failed to set up project for e2e tests.`);
console.log(e.message);
throw e;
}
}

// Useful in order to cleanup space during CI to prevent `No space left on device` exceptions
export function removeProject({ onlyOnCI = false } = {}) {
if (onlyOnCI && !isCI) {
Expand Down Expand Up @@ -255,38 +122,6 @@ export function runCLIAsync(
);
}

export function runNgAdd(
command?: string,
opts: RunCmdOpts = {
silenceError: false,
env: process.env as Record<string, string>,
cwd: tmpProjPath(),
},
): string {
try {
packageInstall('@nrwl/workspace');
return execSync(
`./node_modules/.bin/ng g @nrwl/workspace:ng-add ${command}`,
{
cwd: tmpProjPath(),
env: opts.env as any,
},
)
.toString()
.replace(
/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,
'',
);
} catch (e: any) {
if (opts.silenceError) {
return e.stdout.toString();
} else {
console.log(e.stdout.toString(), e.stderr.toString());
throw e;
}
}
}

export function runCLI(
command?: string,
opts: RunCmdOpts = {
Expand Down Expand Up @@ -354,7 +189,7 @@ export function runCommand(command: string): string {
*/
function setMaxWorkers() {
if (isCI) {
const workspaceFile = workspaceConfigName();
const workspaceFile = workspaceConfigName(tmpProjPath());
const workspace = readJson(workspaceFile);

Object.keys(workspace.projects).forEach((appName) => {
Expand Down Expand Up @@ -466,17 +301,9 @@ export function getSize(filePath: string): number {
return statSync(filePath).size;
}

export function tmpProjPath(path?: string) {
return path ? `${e2eCwd}/${projName}/${path}` : `${e2eCwd}/${projName}`;
}

function tmpBackupProjPath(path?: string) {
return path ? `${e2eCwd}/proj-backup/${path}` : `${e2eCwd}/proj-backup`;
}

export function getPackageManagerCommand({
path = tmpProjPath(),
packageManager = detectPackageManager(path),
p = tmpProjPath() as string,
packageManager = detectPackageManager(p),
scriptsPrependNodePath = true,
} = {}): {
createWorkspace: string;
Expand Down
14 changes: 1 addition & 13 deletions packages/dotnet/src/lib/core/dotnet.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,7 @@ export class DotNetClient {
if (!watch) {
return this.logAndExecute(params);
} else {
const slicedParams = params.slice(1).filter((x) => x.length);
return this.logAndSpawn(slicedParams);
return this.logAndSpawn(params);
}
}

Expand Down Expand Up @@ -182,17 +181,6 @@ export class DotNetClient {
}
}

private execute(params: string[]): Buffer {
return spawnSync(this.cliCommand.command, params, {
cwd: this.cwd || process.cwd(),
})
.output.filter((buf) => buf !== null)
.reduce(
(acc, buf) => Buffer.concat([acc as Buffer, buf as Buffer]),
Buffer.from(''),
) as Buffer;
}

private logAndSpawn(params: string[]): ChildProcess {
console.log(
`Executing Command: ${this.cliCommand.command} "${params.join('" "')}"`,
Expand Down
4 changes: 2 additions & 2 deletions tools/scripts/e2e.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { execSync } from 'child_process';
import { copySync, removeSync } from 'fs-extra';

import { e2eRoot } from '../../e2e/utils';
import { tmpProjPath } from '@nrwl/nx-plugin/testing';
import { startCleanVerdaccioInstance } from './local-registry/setup';
import { publishAll } from './publish-all';

Expand Down Expand Up @@ -40,7 +40,7 @@ async function runTest() {

if (process.argv[5] != '--rerun') {
removeSync('./dist');
removeSync(e2eRoot);
removeSync(tmpProjPath());
}

try {
Expand Down

0 comments on commit 1575dda

Please sign in to comment.