test: remove view-engine-only tests (#43884)

This commit removes most tests that were designated as only covering View
Engine code. It also removes tag filters from CI and local commands to run
tests.

In a few cases (such as with the packages/compiler tests), this tag was
improperly applied, and certain test cases have been added back running in
Ivy mode.

This commit also empties `@angular/compiler/testing` as it is no longer
necessary (this is safe since compiler packages are not public API). It can
be deleted in the future.

PR Close #43884
This commit is contained in:
Alex Rickabaugh
2021-11-23 21:10:06 +00:00
committed by Jessica Janiuk
parent f44cb57c12
commit bb9ff6003c
114 changed files with 184 additions and 20756 deletions
+3 -3
View File
@@ -344,7 +344,7 @@ jobs:
# See /tools/saucelabs/README.md for more info # See /tools/saucelabs/README.md for more info
command: | command: |
yarn bazel run //tools/saucelabs:sauce_service_setup yarn bazel run //tools/saucelabs:sauce_service_setup
TESTS=$(./node_modules/.bin/bazelisk query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "view-engine-only", ...) except attr("tags", "fixme-saucelabs", ...)') TESTS=$(./node_modules/.bin/bazelisk query --output label '(kind(karma_web_test, ...) intersect attr("tags", "saucelabs", ...)) except attr("tags", "fixme-saucelabs", ...)')
yarn bazel test --config=saucelabs ${TESTS} yarn bazel test --config=saucelabs ${TESTS}
yarn bazel run //tools/saucelabs:sauce_service_stop yarn bazel run //tools/saucelabs:sauce_service_stop
no_output_timeout: 40m no_output_timeout: 40m
@@ -723,11 +723,11 @@ jobs:
- setup_win - setup_win
- run: - run:
name: Build all windows CI targets name: Build all windows CI targets
command: bazel build --build_tag_filters=-view-engine-only //packages/compiler-cli/... command: bazel build //packages/compiler-cli/...
no_output_timeout: 15m no_output_timeout: 15m
- run: - run:
name: Test all windows CI targets name: Test all windows CI targets
command: bazel test --test_tag_filters="-view-engine-only,-browser:chromium-local" //packages/compiler-cli/... command: bazel test --test_tag_filters="-browser:chromium-local" //packages/compiler-cli/...
no_output_timeout: 15m no_output_timeout: 15m
workflows: workflows:
@@ -1,48 +0,0 @@
load("//tools:defaults.bzl", "ts_devserver", "ts_library")
load("@npm//@angular/dev-infra-private/bazel/benchmark/component_benchmark:benchmark_test.bzl", "benchmark_test")
load("//modules/benchmarks:e2e_test.bzl", "e2e_test")
package(default_visibility = ["//modules/benchmarks:__subpackages__"])
ts_library(
name = "ng2_next",
srcs = glob(["*.ts"]),
tsconfig = "//modules/benchmarks:tsconfig-build.json",
deps = [
"//modules/benchmarks/src:util_lib",
"//modules/benchmarks/src/tree:util_lib",
"//packages/common",
"//packages/core",
"//packages/platform-browser",
],
)
ts_devserver(
name = "devserver",
entry_module = "angular/modules/benchmarks/src/tree/ng2_next/index",
port = 4200,
scripts = [
"@npm//:node_modules/tslib/tslib.js",
"//tools/rxjs:rxjs_umd_modules",
],
static_files = ["index.html"],
deps = [":ng2_next"],
)
benchmark_test(
name = "perf",
server = ":devserver",
deps = [
"//modules/benchmarks/src/tree:detect_changes_perf_tests_lib",
"//modules/benchmarks/src/tree:perf_tests_lib",
],
)
e2e_test(
name = "e2e",
server = ":devserver",
deps = [
"//modules/benchmarks/src/tree:detect_changes_e2e_tests_lib",
"//modules/benchmarks/src/tree:e2e_tests_lib",
],
)
@@ -1,46 +0,0 @@
# Ng2 Next Benchmark
This benchmark uses the upcoming view engine for Angular, which moves
more functionality from codegen into runtime to reduce generated code size.
As we introduce more runtime code, we need to be very careful to not
regress in performance, compared to the pure codegen solution.
## Initial results: size of Deep Tree Benchmark
File size for Tree benchmark template,
view class of the component + the 2 embedded view classes (without imports nor host view factory):
| bytes | ratio | bytes (gzip) | ratio (gzip)
------------------------------ | ----- | ----- | ------------ | ------------
Source template + annotation | 245 | 1x | 159 | 1x
Gen code (Closure minified) | 2693 | 11.9x | 746 | 4.7x
New View Engine (minified) | 868 | 3.5x | 436 | 2.7x
## Initial results: performance of Deep Tree Benchmark
Measured locally on a MacBook Pro.
BENCHMARK deepTree....
Description:
- bundles: false
- depth: 11
- forceGc: false
- regressionSlopeMetric: scriptTime
- sampleSize: 20
- userAgent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36
...createOnly | gcAmount | gcTime | majorGcTime | pureScriptTime | renderTime | scriptTime
--------------- | ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | ------------------
ng2 | 11461.24+-21% | 12.35+-42% | 1.15+-429% | 72.49+-4% | 49.61+-4% | 82.69+-6%
ng2 next | 6207.77+-93% | 9.84+-84% | 3.35+-238% | 73.95+-4% | 49.86+-4% | 77.53+-10%
...update | gcAmount | gcTime | majorGcTime | pureScriptTime | renderTime | scriptTime
--------------- | ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | ------------------
ng2 | 0.00 | 0.00+-435% | 0.00+-435% | 13.34+-8% | 28.55+-8% | 13.34+-8%
ng2 next | 175.02+-435% | 0.74+-435% | 0.00+-302% | 20.55+-12% | 28.00+-6% | 20.55+-12%
...pure cd (10x) | gcAmount | gcTime | majorGcTime | pureScriptTime | renderTime | scriptTime
--------------- | ------------------ | ------------------ | ------------------ | ------------------ | ------------------ | ------------------
ng2 | 2155.57+-238% | 0.24+-238% | 0.00+-238% | 19.32+-9% | 2.54+-6% | 19.32+-9%
ng2 next | 908.12+-366% | 1.62+-325% | 0.49+-435% | 30.66+-6% | 2.62+-19% | 30.66+-6%
@@ -1,37 +0,0 @@
<!doctype html>
<html>
<head>
<!-- Prevent the browser from requesting any favicon. -->
<link rel="icon" href="data:,">
</head>
<body>
<h2>Params</h2>
<form>
Depth:
<input type="number" name="depth" placeholder="depth" value="10">
<br>
<button>Apply</button>
</form>
<h2>Ng2 Next Tree Benchmark</h2>
<p>
<button id="destroyDom">destroyDom</button>
<button id="createDom">createDom</button>
<button id="detectChanges">detectChanges</button>
<button id="updateDomProfile">profile updateDom</button>
<button id="createDomProfile">profile createDom</button>
<button id="detectChangesProfile">profile detectChanges</button>
</p>
<div>
Change detection runs:<span id="numberOfChecks"></span>
</div>
<div>
<tree id="root">Loading...</tree>
</div>
<!--load location for ts_devserver-->
<script src="/app_bundle.js"></script>
</body>
</html>
@@ -1,52 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {enableProdMode} from '@angular/core';
import {bindAction, profile} from '../../util';
import {buildTree, emptyTree} from '../util';
import {AppModule, TreeComponent} from './tree';
let tree: TreeComponent;
let appMod: AppModule;
let detectChangesRuns = 0;
function destroyDom() {
tree.data = emptyTree;
appMod.tick();
}
function createDom() {
tree.data = buildTree();
appMod.tick();
}
function detectChanges() {
for (let i = 0; i < 10; i++) {
appMod.tick();
}
detectChangesRuns += 10;
numberOfChecksEl.textContent = `${detectChangesRuns}`;
}
function noop() {}
const numberOfChecksEl = document.getElementById('numberOfChecks');
enableProdMode();
appMod = new AppModule();
appMod.bootstrap();
tree = appMod.componentRef.instance;
bindAction('#destroyDom', destroyDom);
bindAction('#createDom', createDom);
bindAction('#detectChanges', detectChanges);
bindAction('#detectChangesProfile', profile(detectChanges, noop, 'detectChanges'));
bindAction('#updateDomProfile', profile(createDom, noop, 'update'));
bindAction('#createDomProfile', profile(createDom, destroyDom, 'create'));
@@ -1,140 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgIf} from '@angular/common';
import {ComponentFactory, ComponentFactoryResolver, ComponentRef, ErrorHandler, Injector, NgModuleRef, RendererFactory2, Sanitizer, TemplateRef, ViewContainerRef, ɵand as anchorDef, ɵArgumentType as ArgumentType, ɵBindingFlags as BindingFlags, ɵccf as createComponentFactory, ɵdid as directiveDef, ɵeld as elementDef, ɵinitServicesIfNeeded as initServicesIfNeeded, ɵNodeFlags as NodeFlags, ɵted as textDef, ɵvid as viewDef, ɵViewDefinition as ViewDefinition, ɵViewFlags as ViewFlags} from '@angular/core';
import {SafeStyle, ɵDomRendererFactory2 as DomRendererFactory2, ɵDomSanitizerImpl as DomSanitizerImpl} from '@angular/platform-browser';
import {emptyTree, TreeNode} from '../util';
let trustedEmptyColor: SafeStyle;
let trustedGreyColor: SafeStyle;
export class TreeComponent {
data: TreeNode = emptyTree;
get bgColor() {
return this.data.depth % 2 ? trustedEmptyColor : trustedGreyColor;
}
}
let viewFlags = ViewFlags.None;
function TreeComponent_Host(): ViewDefinition {
return viewDef(viewFlags, [
elementDef(0, NodeFlags.None, null, null, 1, 'tree', null, null, null, null, TreeComponent_0),
directiveDef(1, NodeFlags.Component, null, 0, TreeComponent, []),
]);
}
function TreeComponent_1() {
return viewDef(
viewFlags,
[
elementDef(
0, NodeFlags.None, null, null, 1, 'tree', null, null, null, null, TreeComponent_0),
directiveDef(1, NodeFlags.Component, null, 0, TreeComponent, [], {data: [0, 'data']}),
],
(check, view) => {
const cmp = view.component;
check(view, 1, ArgumentType.Inline, cmp.data.left);
});
}
function TreeComponent_2() {
return viewDef(
viewFlags,
[
elementDef(
0, NodeFlags.None, null, null, 1, 'tree', null, null, null, null, TreeComponent_0),
directiveDef(1, NodeFlags.Component, null, 0, TreeComponent, [], {data: [0, 'data']}),
],
(check, view) => {
const cmp = view.component;
check(view, 1, ArgumentType.Inline, cmp.data.left);
});
}
function TreeComponent_0(): ViewDefinition {
return viewDef(
viewFlags,
[
elementDef(
0, NodeFlags.None, null, null, 1, 'span', null,
[[BindingFlags.TypeElementStyle, 'backgroundColor', null]]),
textDef(1, null, [' ', ' ']),
anchorDef(NodeFlags.EmbeddedViews, null, null, 1, null, TreeComponent_1),
directiveDef(
3, NodeFlags.None, null, 0, NgIf, [ViewContainerRef, TemplateRef], {ngIf: [0, 'ngIf']}),
anchorDef(NodeFlags.EmbeddedViews, null, null, 1, null, TreeComponent_2),
directiveDef(
5, NodeFlags.None, null, 0, NgIf, [ViewContainerRef, TemplateRef], {ngIf: [0, 'ngIf']}),
],
(check, view) => {
const cmp = view.component;
check(view, 3, ArgumentType.Inline, cmp.data.left != null);
check(view, 5, ArgumentType.Inline, cmp.data.right != null);
},
(check, view) => {
const cmp = view.component;
check(view, 0, ArgumentType.Inline, cmp.bgColor);
check(view, 1, ArgumentType.Inline, cmp.data.value);
});
}
export class AppModule implements Injector, NgModuleRef<any> {
private sanitizer: DomSanitizerImpl;
private componentFactory: ComponentFactory<TreeComponent>;
private renderer2: RendererFactory2;
componentRef: ComponentRef<TreeComponent>;
constructor() {
initServicesIfNeeded();
this.sanitizer = new DomSanitizerImpl(document);
this.renderer2 = new DomRendererFactory2(null, null, null);
trustedEmptyColor = this.sanitizer.bypassSecurityTrustStyle('');
trustedGreyColor = this.sanitizer.bypassSecurityTrustStyle('grey');
this.componentFactory =
createComponentFactory('#root', TreeComponent, TreeComponent_Host, {}, {}, []);
}
get(token: any, notFoundValue: any = Injector.THROW_IF_NOT_FOUND): any {
switch (token) {
case RendererFactory2:
return this.renderer2;
case Sanitizer:
return this.sanitizer;
case ErrorHandler:
return null;
case NgModuleRef:
return this;
}
return Injector.NULL.get(token, notFoundValue);
}
bootstrap() {
this.componentRef =
this.componentFactory.create(Injector.NULL, [], this.componentFactory.selector, this);
}
tick() {
this.componentRef.changeDetectorRef.detectChanges();
}
get injector() {
return this;
}
get componentFactoryResolver(): ComponentFactoryResolver {
return null;
}
get instance() {
return this;
}
destroy() {}
onDestroy(callback: () => void) {}
}
+1 -4
View File
@@ -24,10 +24,7 @@
"/ ": "", "/ ": "",
"postinstall": "node scripts/webdriver-manager-update.js && node --preserve-symlinks --preserve-symlinks-main ./tools/postinstall-patches.js", "postinstall": "node scripts/webdriver-manager-update.js && node --preserve-symlinks --preserve-symlinks-main ./tools/postinstall-patches.js",
"prepare": "husky install", "prepare": "husky install",
"test": "bazelisk test --build_tag_filters=-view-engine-only --test_tag_filters=-view-engine-only", "test": "bazelisk test",
"test-view-engine-only": "bazelisk test --config=view-engine --build_tag_filters=view-engine-only --test_tag_filters=view-engine-only",
"test-ivy-aot": "echo \\`test-ivy-aot\\` no longer valid, use \\`yarn test\\` instead",
"test-non-ivy": "echo \\`test-ivy-aot\\` no longer valid, use \\`yarn test-view-engine-only\\` instead",
"test-tsec": "bazelisk test //... --build_tag_filters=tsec --test_tag_filters=tsec", "test-tsec": "bazelisk test //... --build_tag_filters=tsec --test_tag_filters=tsec",
"lint": "yarn -s tslint && yarn -s ng-dev format changed --check", "lint": "yarn -s tslint && yarn -s ng-dev format changed --check",
"tslint": "tslint -c tslint.json --project tsconfig-tslint.json", "tslint": "tslint -c tslint.json --project tsconfig-tslint.json",
@@ -82,7 +82,6 @@ jasmine_node_test(
# file is based on non-ivy output and therefore won't work for ngc and Ivy at the same time. # file is based on non-ivy output and therefore won't work for ngc and Ivy at the same time.
# TODO: Update test to rely on Ivy partial compilation after View Engine's removal, update the # TODO: Update test to rely on Ivy partial compilation after View Engine's removal, update the
# golden files as appropriate for the change in compilation. # golden files as appropriate for the change in compilation.
tags = ["view-engine-only"],
deps = ["@npm//diff"], deps = ["@npm//diff"],
) )
@@ -1,4 +1,3 @@
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_test")
load("//tools:defaults.bzl", "nodejs_binary") load("//tools:defaults.bzl", "nodejs_binary")
package(default_visibility = ["//visibility:public"]) package(default_visibility = ["//visibility:public"])
@@ -22,49 +21,3 @@ nodejs_binary(
], ],
entry_point = "//packages/compiler-cli:src/extract_i18n.ts", entry_point = "//packages/compiler-cli:src/extract_i18n.ts",
) )
nodejs_test(
name = "integrationtest",
data = [
":ngc_bin",
":ng_xi18n",
"@nodejs//:node",
"@npm//domino",
"@npm//chokidar",
"@npm//source-map-support",
"@npm//shelljs",
"@npm//typescript",
"@npm//reflect-metadata",
"@npm//rxjs",
"@npm//tslib",
"@npm//jasmine/bin:jasmine",
"@npm//xhr2",
"@npm//@types/node",
"@npm//@types/jasmine",
# we need to reference zone.d.ts typing file from zone.js build target
# instead of npm because angular repo will not depends on npm zone.js
# any longer.
"//packages/zone.js/lib:zone_d_ts",
# we need to reference zone.js npm_package build target
# instead of npm because angular repo will not depends on npm zone.js
# any longer, so we need to build a zone.js npm release first.
"//packages/zone.js:npm_package",
"//packages/animations:npm_package",
"//packages/common:npm_package",
"//packages/compiler:npm_package",
"//packages/compiler-cli:npm_package",
"//packages/core:npm_package",
"//packages/forms:npm_package",
"//packages/platform-browser:npm_package",
"//packages/platform-browser-dynamic:npm_package",
"//packages/platform-server:npm_package",
"//packages/router:npm_package",
] + glob(["**/*"]),
entry_point = "test.js",
tags = [
# TODO(josephperrott): reenable or remove test after investigating the cause of failures
# on windows CI runs.
"manual",
"view-engine-only",
],
)
@@ -1,42 +0,0 @@
load("//packages/bazel:index.bzl", "ng_module")
load("//tools:defaults.bzl", "jasmine_node_test")
load(":extract_flat_module_index.bzl", "extract_flat_module_index")
ng_module(
name = "test_module",
testonly = True,
srcs = glob(["*.ts"]),
api_extractor = "//packages/bazel/src/api-extractor:api_extractor",
compiler = "//packages/bazel/src/ngc-wrapped",
entry_point = "index.ts",
flat_module_out_file = "flat_module_filename",
module_name = "some_npm_module",
ng_xi18n = "//packages/bazel/src/ngc-wrapped:xi18n",
node_modules = "@npm//typescript:typescript__typings",
tags = [
# Disabled as this test is specific to the flat module indexing of metadata.json files that
# the old ngc compiler does. Ivy has no metadata.json files so this test does not apply.
"view-engine-only",
],
deps = [
"//packages/core",
"@npm//tslib",
],
)
extract_flat_module_index(
name = "flat_module_index",
testonly = True,
deps = [":test_module"],
)
jasmine_node_test(
name = "test",
srcs = ["spec.js"],
data = [":flat_module_index"],
tags = [
# Disabled as this test is specific to the flat module indexing of metadata.json files that
# the old ngc compiler does. Ivy has no metadata.json files so this test does not apply.
"view-engine-only",
],
)
@@ -1,14 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
import {Parent} from './parent';
@NgModule({imports: [Parent]})
export class Child {
}
@@ -1,26 +0,0 @@
# Copyright Google LLC All Rights Reserved.
#
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file at https://angular.io/license
"""Test utility to extract the "flat_module_metadata" from transitive Angular deps.
"""
def _extract_flat_module_index(ctx):
files = []
for dep in ctx.attr.deps:
if hasattr(dep, "angular") and hasattr(dep.angular, "flat_module_metadata"):
flat_module = dep.angular.flat_module_metadata
files.append(flat_module.typings_file)
# The flat module metadata file could be `None` for targets
# built with Ivy. No metadata files are generated in ngtsc.
if flat_module.metadata_file != None:
files.append(flat_module.metadata_file)
return [DefaultInfo(files = depset(files))]
extract_flat_module_index = rule(
implementation = _extract_flat_module_index,
attrs = {
"deps": attr.label_list(),
},
)
@@ -1,9 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export * from './child';
@@ -1,13 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
@NgModule({})
export class Parent {
}
@@ -1,33 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const fs = require('fs');
const PKG = 'angular/packages/compiler-cli/integrationtest/bazel/ng_module';
describe('flat module index', () => {
describe('child metadata', () => {
it('should have contents', () => {
const metadata = fs.readFileSync(
require.resolve(`${PKG}/flat_module_filename.metadata.json`), {encoding: 'utf-8'});
expect(metadata).toContain('"__symbolic":"module"');
expect(metadata).toContain('"__symbolic":"reference","module":"@angular/core"');
expect(metadata).toContain(
'"origins":{"Child":"./child","ɵangular_packages_compiler_cli_integrationtest_bazel_ng_module_test_module_a":"./parent"}');
expect(metadata).toContain('"importAs":"some_npm_module"');
});
});
describe('child typings', () => {
it('should have contents', () => {
const dts =
fs.readFileSync(require.resolve(`${PKG}/flat_module_filename.d.ts`), {encoding: 'utf-8'});
expect(dts).toContain('export * from \'./index\';');
expect(dts).toContain(
'export { Parent as ɵangular_packages_compiler_cli_integrationtest_bazel_ng_module_test_module_a } from \'./parent\';');
});
});
});
-39
View File
@@ -52,45 +52,6 @@ jasmine_node_test(
], ],
) )
# ngc_spec
ts_library(
name = "ngc_lib",
testonly = True,
srcs = [
"ngc_spec.ts",
],
deps = [
":test_utils",
"//packages/compiler",
"//packages/compiler-cli",
"@npm//tsickle",
"@npm//typescript",
],
)
jasmine_node_test(
name = "ngc",
timeout = "long", # 900 seconds
bootstrap = ["//tools/testing:node_es5"],
data = [
"@npm//@angular/common-12",
"@npm//@angular/core-12",
"@npm//@angular/platform-browser-12",
"@npm//@angular/router-12",
],
tags = [
# Disabled as these tests are specific to the old ngc compiler, and not ngtsc which has its
# own tests under //packages/compiler-cli/test/ngtsc.
"view-engine-only",
],
deps = [
":ngc_lib",
"//packages/core",
"@npm//rxjs",
"@npm//yargs",
],
)
# perform_watch_spec # perform_watch_spec
ts_library( ts_library(
name = "perform_watch_lib", name = "perform_watch_lib",
@@ -1,36 +1,5 @@
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library") load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
# check_types_spec
ts_library(
name = "check_types_lib",
testonly = True,
srcs = ["check_types_spec.ts"],
deps = [
"//packages/compiler-cli",
"//packages/compiler-cli/test:test_utils",
"@npm//typescript",
],
)
jasmine_node_test(
name = "check_types",
timeout = "long", # 900 seconds
bootstrap = ["//tools/testing:node_es5"],
data = [
"@npm//@angular/common-12",
"@npm//@angular/core-12",
],
tags = [
# Disabled as these tests pertain to typechecking in the old ngc compiler. The Ivy ngtsc
# compiler has its own typechecking implementation and tests.
"view-engine-only",
],
deps = [
":check_types_lib",
"//packages/core",
],
)
# typescript_version_spec # typescript_version_spec
ts_library( ts_library(
name = "typescript_version_lib", name = "typescript_version_lib",
@@ -1,40 +0,0 @@
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/transformers/downlevel_decorators_transform",
"//packages/compiler-cli/test:test_utils",
"//packages/compiler/test:test_utils",
"//packages/core",
"//packages/platform-browser",
"@npm//typescript",
],
)
jasmine_node_test(
name = "test",
timeout = "long", # 900 seconds
bootstrap = ["//tools/testing:node_es5"],
data = [
"@npm//@angular/common-12",
"@npm//@angular/core-12",
"@npm//@angular/router-12",
],
tags = [
# Disabled as these tests pertain to the old compiler and not ngtsc, which doesn't use any
# of these transformer utilities.
"view-engine-only",
],
deps = [
":test_lib",
"//packages/core",
"@npm//source-map",
],
)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,194 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import ts from 'typescript';
import {isClassMetadata, MetadataCollector} from '../../src/metadata/index';
import {getInlineResourcesTransformFactory, InlineResourcesMetadataTransformer} from '../../src/transformers/inline_resources';
import {MetadataCache} from '../../src/transformers/metadata_cache';
import {MockAotContext, MockCompilerHost} from '../mocks';
describe('inline resources transformer', () => {
describe('decorator input', () => {
describe('should not touch unrecognized decorators', () => {
it('Not from @angular/core', () => {
expect(convert(`declare const Component: Function;
@Component({templateUrl: './thing.html'}) class Foo {}`))
.toContain('templateUrl');
});
it('missing @ sign', () => {
expect(convert(`import {Component} from '@angular/core';
Component({templateUrl: './thing.html'}) class Foo {}`))
.toContain('templateUrl');
});
it('too many arguments to @Component', () => {
expect(convert(`import {Component} from '@angular/core';
@Component(1, {templateUrl: './thing.html'}) class Foo {}`))
.toContain('templateUrl');
});
it('wrong argument type to @Component', () => {
expect(convert(`import {Component} from '@angular/core';
@Component([{templateUrl: './thing.html'}]) class Foo {}`))
.toContain('templateUrl');
});
});
it('should replace templateUrl', () => {
const actual = convert(`import {Component} from '@angular/core';
@Component({
templateUrl: './thing.html',
otherProp: 3,
}) export class Foo {}`);
expect(actual).not.toContain('templateUrl:');
expect(actual.replace(/\s+/g, ' '))
.toContain(
'Foo = __decorate([ (0, core_1.Component)({ template: "Some template", otherProp: 3 }) ], Foo)');
});
it('should allow different quotes', () => {
const actual = convert(`import {Component} from '@angular/core';
@Component({"templateUrl": \`./thing.html\`}) export class Foo {}`);
expect(actual).not.toContain('templateUrl:');
expect(actual).toContain('{ template: "Some template" }');
});
it('should replace styleUrls', () => {
const actual = convert(`import {Component} from '@angular/core';
@Component({
styleUrls: ['./thing1.css', './thing2.css'],
})
export class Foo {}`);
expect(actual).not.toContain('styleUrls:');
expect(actual).toContain('styles: [".some_style {}", ".some_other_style {}"]');
});
it('should preserve existing styles', () => {
const actual = convert(`import {Component} from '@angular/core';
@Component({
styles: ['h1 { color: blue }'],
styleUrls: ['./thing1.css'],
})
export class Foo {}`);
expect(actual).not.toContain('styleUrls:');
expect(actual).toContain(`styles: ['h1 { color: blue }', ".some_style {}"]`);
});
it('should handle empty styleUrls', () => {
const actual = convert(`import {Component} from '@angular/core';
@Component({styleUrls: [], styles: []}) export class Foo {}`);
expect(actual).not.toContain('styleUrls:');
expect(actual).not.toContain('styles:');
});
});
describe('annotation input', () => {
it('should replace templateUrl', () => {
const actual = convert(`import {Component} from '@angular/core';
declare const NotComponent: Function;
export class Foo {
static decorators: {type: Function, args?: any[]}[] = [
{
type: NotComponent,
args: [],
},{
type: Component,
args: [{
templateUrl: './thing.html'
}],
}];
}
`);
expect(actual).not.toContain('templateUrl:');
expect(actual.replace(/\s+/g, ' '))
.toMatch(
/Foo\.decorators = [{ .*type: core_1\.Component, args: [{ template: "Some template" }]/);
});
it('should replace styleUrls', () => {
const actual = convert(`import {Component} from '@angular/core';
declare const NotComponent: Function;
export class Foo {
static decorators: {type: Function, args?: any[]}[] = [{
type: Component,
args: [{
styleUrls: ['./thing1.css', './thing2.css'],
}],
}];
}
`);
expect(actual).not.toContain('styleUrls:');
expect(actual.replace(/\s+/g, ' '))
.toMatch(
/Foo\.decorators = [{ .*type: core_1\.Component, args: [{ style: "Some template" }]/);
});
});
});
describe('metadata transformer', () => {
it('should transform decorators', () => {
const source = `import {Component} from '@angular/core';
@Component({
templateUrl: './thing.html',
styleUrls: ['./thing1.css', './thing2.css'],
styles: ['h1 { color: red }'],
})
export class Foo {}
`;
const sourceFile = ts.createSourceFile(
'someFile.ts', source, ts.ScriptTarget.Latest, /* setParentNodes */ true);
const cache = new MetadataCache(
new MetadataCollector(), /* strict */ true,
[new InlineResourcesMetadataTransformer(
{loadResource, resourceNameToFileName: (u: string) => u})]);
const metadata = cache.getMetadata(sourceFile);
expect(metadata).toBeDefined('Expected metadata from test source file');
if (metadata) {
const classData = metadata.metadata['Foo'];
expect(classData && isClassMetadata(classData))
.toBeDefined(`Expected metadata to contain data for Foo`);
if (classData && isClassMetadata(classData)) {
expect(JSON.stringify(classData)).not.toContain('templateUrl');
expect(JSON.stringify(classData)).toContain('"template":"Some template"');
expect(JSON.stringify(classData)).not.toContain('styleUrls');
expect(JSON.stringify(classData))
.toContain('"styles":["h1 { color: red }",".some_style {}",".some_other_style {}"]');
}
}
});
});
function loadResource(path: string): Promise<string>|string {
if (path === './thing.html') return 'Some template';
if (path === './thing1.css') return '.some_style {}';
if (path === './thing2.css') return '.some_other_style {}';
throw new Error('No fake data for path ' + path);
}
function convert(source: string) {
const baseFileName = 'someFile';
const moduleName = '/' + baseFileName;
const fileName = moduleName + '.ts';
const context = new MockAotContext('/', {[baseFileName + '.ts']: source});
const host = new MockCompilerHost(context);
const program = ts.createProgram(
[fileName], {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2017,
},
host);
const moduleSourceFile = program.getSourceFile(fileName);
const transformers: ts.CustomTransformers = {
before: [getInlineResourcesTransformFactory(
program, {loadResource, resourceNameToFileName: (u: string) => u})]
};
let result = '';
program.emit(
moduleSourceFile, (emittedFileName, data, writeByteOrderMark, onError, sourceFiles) => {
if (fileName.startsWith(moduleName)) {
result = data;
}
}, undefined, undefined, transformers);
return result;
}
@@ -1,262 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import ts from 'typescript';
import {MetadataCollector, ModuleMetadata} from '../../src/metadata/index';
import {getExpressionLoweringTransformFactory, LoweringRequest, LowerMetadataTransform, RequestLocationMap} from '../../src/transformers/lower_expressions';
import {MetadataCache} from '../../src/transformers/metadata_cache';
import {Directory, MockAotContext, MockCompilerHost} from '../mocks';
const DEFAULT_FIELDS_TO_LOWER = ['useFactory', 'useValue', 'data'];
describe('Expression lowering', () => {
describe('transform', () => {
it('should be able to lower a simple expression', () => {
expect(convert('const a = 1 +◊b: 2◊;')).toBe('const b = 2; const a = 1 + b; export { b };');
});
it('should be able to lower an expression in a decorator', () => {
expect(convert(`
import {Component} from '@angular/core';
@Component({
provider: [{provide: 'someToken', useFactory:◊l: () => null◊}]
})
class MyClass {}
`)).toContain('const l = () => null; exports.l = l;');
});
it('should be able to export a variable if the whole value is lowered', () => {
expect(convert('/*a*/ const a =◊b: () => null◊;'))
.toBe('/*a*/ const a = () => null; const b = a; export { b };');
});
});
describe('collector', () => {
it('should request a lowering for useValue', () => {
const collected = collect(`
import {Component} from '@angular/core';
enum SomeEnum {
OK,
NotOK
}
@Component({
provider: [{provide: 'someToken', useValue:◊enum: SomeEnum.OK◊}]
})
export class MyClass {}
`);
expect(collected.requests.has(collected.annotations[0].start))
.toBeTruthy('did not find the useValue');
});
it('should not request a lowering for useValue with a reference to a static property', () => {
const collected = collect(`
import {Component} from '@angular/core';
@Component({
provider: [{provide: 'someToken', useValue:◊value: MyClass.someMethod◊}]
})
export class MyClass {
static someMethod() {}
}
`);
expect(collected.requests.size).toBe(0);
});
it('should request a lowering for useFactory', () => {
const collected = collect(`
import {Component} from '@angular/core';
@Component({
provider: [{provide: 'someToken', useFactory:◊lambda: () => null◊}]
})
export class MyClass {}
`);
expect(collected.requests.has(collected.annotations[0].start))
.toBeTruthy('did not find the useFactory');
});
it('should request a lowering for data', () => {
const collected = collect(`
import {Component} from '@angular/core';
enum SomeEnum {
OK,
NotOK
}
@Component({
provider: [{provide: 'someToken', data:◊enum: SomeEnum.OK◊}]
})
export class MyClass {}
`);
expect(collected.requests.has(collected.annotations[0].start))
.toBeTruthy('did not find the data field');
});
it('should not lower a non-module', () => {
const collected = collect(`
declare const global: any;
const ngDevMode: boolean = (function(global: any) {
return global.ngDevMode = true;
})(typeof window != 'undefined' && window || typeof self != 'undefined' && self || typeof global != 'undefined' && global);
`);
expect(collected.requests.size).toBe(0, 'unexpected rewriting');
});
it('should throw a validation exception for invalid files', () => {
const cache = new MetadataCache(
new MetadataCollector({}), /* strict */ true,
[new LowerMetadataTransform(DEFAULT_FIELDS_TO_LOWER)]);
const sourceFile = ts.createSourceFile(
'foo.ts', `
import {Injectable} from '@angular/core';
class SomeLocalClass {}
@Injectable()
export class SomeClass {
constructor(a: SomeLocalClass) {}
}
`,
ts.ScriptTarget.Latest, true);
expect(() => cache.getMetadata(sourceFile)).toThrow();
});
it('should not report validation errors on a .d.ts file', () => {
const cache = new MetadataCache(
new MetadataCollector({}), /* strict */ true,
[new LowerMetadataTransform(DEFAULT_FIELDS_TO_LOWER)]);
const dtsFile = ts.createSourceFile(
'foo.d.ts', `
import {Injectable} from '@angular/core';
class SomeLocalClass {}
@Injectable()
export class SomeClass {
constructor(a: SomeLocalClass) {}
}
`,
ts.ScriptTarget.Latest, true);
expect(() => cache.getMetadata(dtsFile)).not.toThrow();
});
});
});
// Helpers
interface Annotation {
start: number;
length: number;
name: string;
}
function getAnnotations(annotatedSource: string):
{unannotatedSource: string, annotations: Annotation[]} {
const annotations: {start: number, length: number, name: string}[] = [];
let adjustment = 0;
const unannotatedSource = annotatedSource.replace(
/◊([a-zA-Z]+):(.*)◊/g,
(text: string, name: string, source: string, index: number): string => {
annotations.push({start: index + adjustment, length: source.length, name});
adjustment -= text.length - source.length;
return source;
});
return {unannotatedSource, annotations};
}
// Transform helpers
function convert(annotatedSource: string) {
const {annotations, unannotatedSource} = getAnnotations(annotatedSource);
const baseFileName = 'someFile';
const moduleName = '/' + baseFileName;
const fileName = moduleName + '.ts';
const context = new MockAotContext('/', {[baseFileName + '.ts']: unannotatedSource});
const host = new MockCompilerHost(context);
const sourceFile = ts.createSourceFile(
fileName, unannotatedSource, ts.ScriptTarget.Latest, /* setParentNodes */ true);
const requests = new Map<number, LoweringRequest>();
for (const annotation of annotations) {
const node = findNode(sourceFile, annotation.start, annotation.length);
if (!node) throw new Error('Invalid test specification. Could not find the node to substitute');
const location = node.pos;
requests.set(location, {name: annotation.name, kind: node.kind, location, end: node.end});
}
const program = ts.createProgram(
[fileName], {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2017}, host);
const moduleSourceFile = program.getSourceFile(fileName)!;
const transformers: ts.CustomTransformers = {
before: [getExpressionLoweringTransformFactory(
{
getRequests(sourceFile: ts.SourceFile): RequestLocationMap {
if (sourceFile.fileName == moduleSourceFile.fileName) {
return requests;
} else {
return new Map();
}
}
},
program)]
};
let result: string = '';
const emitResult = program.emit(
moduleSourceFile, (emittedFileName, data, writeByteOrderMark, onError, sourceFiles) => {
if (fileName.startsWith(moduleName)) {
result = data;
}
}, undefined, undefined, transformers);
return normalizeResult(result);
}
function findNode(node: ts.Node, start: number, length: number): ts.Node|undefined {
function find(node: ts.Node): ts.Node|undefined {
if (node.getFullStart() == start && node.getEnd() == start + length) {
return node;
}
if (node.getFullStart() <= start && node.getEnd() >= start + length) {
return ts.forEachChild(node, find);
}
}
return ts.forEachChild(node, find);
}
function normalizeResult(result: string): string {
// Remove TypeScript prefixes
// Remove new lines
// Squish adjacent spaces
// Remove prefix and postfix spaces
return result.replace('"use strict";', ' ')
.replace('exports.__esModule = true;', ' ')
.replace('Object.defineProperty(exports, "__esModule", { value: true });', ' ')
.replace(/\n/g, ' ')
.replace(/ +/g, ' ')
.replace(/^ /g, '')
.replace(/ $/g, '');
}
// Collector helpers
function collect(annotatedSource: string) {
const {annotations, unannotatedSource} = getAnnotations(annotatedSource);
const transformer = new LowerMetadataTransform(DEFAULT_FIELDS_TO_LOWER);
const cache = new MetadataCache(new MetadataCollector({}), false, [transformer]);
const sourceFile = ts.createSourceFile(
'someName.ts', unannotatedSource, ts.ScriptTarget.Latest, /* setParentNodes */ true);
return {
metadata: cache.getMetadata(sourceFile),
requests: transformer.getRequests(sourceFile),
annotations
};
}
@@ -1,178 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import ts from 'typescript';
import {METADATA_VERSION, MetadataCollector, ModuleMetadata} from '../../src/metadata';
import {MetadataReaderHost, readMetadata} from '../../src/transformers/metadata_reader';
import {Directory, Entry, MockAotContext} from '../mocks';
describe('metadata reader', () => {
let host: MetadataReaderHost;
beforeEach(() => {
const context = new MockAotContext('/tmp/src', clone(FILES));
const metadataCollector = new MetadataCollector();
host = {
fileExists: (fileName) => context.fileExists(fileName),
readFile: (fileName) => context.readFile(fileName),
getSourceFileMetadata: (fileName) => {
const sourceText = context.readFile(fileName);
return sourceText != null ? metadataCollector.getMetadata(ts.createSourceFile(
fileName, sourceText, ts.ScriptTarget.Latest)) :
undefined;
},
};
});
it('should be able to read a metadata file', () => {
expect(readMetadata('node_modules/@angular/core.d.ts', host)).toEqual([
{__symbolic: 'module', version: METADATA_VERSION, metadata: {foo: {__symbolic: 'class'}}}
]);
});
it('should be able to read metadata from an otherwise unused .d.ts file ', () => {
expect(readMetadata('node_modules/@angular/unused.d.ts', host)).toEqual([dummyMetadata]);
});
it('should be able to read empty metadata ', () => {
expect(readMetadata('node_modules/@angular/empty.d.ts', host)).toEqual([]);
});
it('should return undefined for missing modules', () => {
expect(readMetadata('node_modules/@angular/missing.d.ts', host)).toBeUndefined();
});
it(`should add missing v${METADATA_VERSION} metadata from v1 metadata and .d.ts files`, () => {
expect(readMetadata('metadata_versions/v1.d.ts', host)).toEqual([
{__symbolic: 'module', version: 1, metadata: {foo: {__symbolic: 'class'}}}, {
__symbolic: 'module',
version: METADATA_VERSION,
metadata: {
foo: {__symbolic: 'class'},
aType: {__symbolic: 'interface'},
Bar: {__symbolic: 'class', members: {ngOnInit: [{__symbolic: 'method'}]}},
BarChild: {__symbolic: 'class', extends: {__symbolic: 'reference', name: 'Bar'}},
ReExport: {__symbolic: 'reference', module: './lib/utils2', name: 'ReExport'},
},
exports: [{from: './lib/utils2', export: ['Export']}],
}
]);
});
it(`should upgrade a missing metadata file into v${METADATA_VERSION}`, () => {
expect(readMetadata('metadata_versions/v1_empty.d.ts', host)).toEqual([{
__symbolic: 'module',
version: METADATA_VERSION,
metadata: {},
exports: [{from: './lib/utils'}]
}]);
});
it(`should upgrade v3 metadata into v${METADATA_VERSION}`, () => {
expect(readMetadata('metadata_versions/v3.d.ts', host)).toEqual([
{__symbolic: 'module', version: 3, metadata: {foo: {__symbolic: 'class'}}}, {
__symbolic: 'module',
version: METADATA_VERSION,
metadata: {
foo: {__symbolic: 'class'},
aType: {__symbolic: 'interface'},
Bar: {__symbolic: 'class', members: {ngOnInit: [{__symbolic: 'method'}]}},
BarChild: {__symbolic: 'class', extends: {__symbolic: 'reference', name: 'Bar'}},
ReExport: {__symbolic: 'reference', module: './lib/utils2', name: 'ReExport'},
}
// Note: exports is missing because it was elided in the original.
}
]);
});
});
const dummyModule = 'export let foo: any[];';
const dummyMetadata: ModuleMetadata = {
__symbolic: 'module',
version: METADATA_VERSION,
metadata:
{foo: {__symbolic: 'error', message: 'Variable not initialized', line: 0, character: 11}}
};
const FILES: Entry = {
'tmp': {
'src': {
'main.ts': `
import * as c from '@angular/core';
import * as r from '@angular/router';
import * as u from './lib/utils';
import * as cs from './lib/collections';
import * as u2 from './lib2/utils2';
`,
'lib': {
'utils.ts': dummyModule,
'collections.ts': dummyModule,
},
'lib2': {'utils2.ts': dummyModule},
'node_modules': {
'@angular': {
'core.d.ts': dummyModule,
'core.metadata.json': `{"__symbolic":"module", "version": ${
METADATA_VERSION}, "metadata": {"foo": {"__symbolic": "class"}}}`,
'router': {'index.d.ts': dummyModule, 'src': {'providers.d.ts': dummyModule}},
'unused.d.ts': dummyModule,
'empty.d.ts': 'export declare var a: string;',
'empty.metadata.json': '[]',
}
},
'metadata_versions': {
'v1.d.ts': `
import {ReExport} from './lib/utils2';
export {ReExport};
export {Export} from './lib/utils2';
export type aType = number;
export declare class Bar {
ngOnInit() {}
}
export declare class BarChild extends Bar {}
`,
'v1.metadata.json':
`{"__symbolic":"module", "version": 1, "metadata": {"foo": {"__symbolic": "class"}}}`,
'v1_empty.d.ts': `
export * from './lib/utils';
`,
'v3.d.ts': `
import {ReExport} from './lib/utils2';
export {ReExport};
export {Export} from './lib/utils2';
export type aType = number;
export declare class Bar {
ngOnInit() {}
}
export declare class BarChild extends Bar {}
`,
'v3.metadata.json':
`{"__symbolic":"module", "version": 3, "metadata": {"foo": {"__symbolic": "class"}}}`,
}
}
}
};
function clone(entry: Entry): Entry {
if (typeof entry === 'string') {
return entry;
} else {
const result: Directory = {};
for (const name in entry) {
result[name] = clone(entry[name]);
}
return result;
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,57 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ClassField, ClassMethod, ClassStmt, PartialModule, Statement, StmtModifier} from '@angular/compiler';
import ts from 'typescript';
import {isClassMetadata, MetadataCollector} from '../../src/metadata/index';
import {MetadataCache} from '../../src/transformers/metadata_cache';
import {PartialModuleMetadataTransformer} from '../../src/transformers/r3_metadata_transform';
describe('r3_transform_spec', () => {
it('should add a static method to collected metadata', () => {
const fileName = '/some/directory/someFileName.ts';
const className = 'SomeClass';
const newFieldName = 'newStaticField';
const source = `
export class ${className} {
myMethod(): void {}
}
`;
const sourceFile =
ts.createSourceFile(fileName, source, ts.ScriptTarget.Latest, /* setParentNodes */ true);
const partialModule: PartialModule = {
fileName,
statements: [new ClassStmt(
className, /* parent */ null, /* fields */[new ClassField(
/* name */ newFieldName, /* type */ null, /* modifiers */[StmtModifier.Static])],
/* getters */[],
/* constructorMethod */ new ClassMethod(/* name */ null, /* params */[], /* body */[]),
/* methods */[])]
};
const cache = new MetadataCache(
new MetadataCollector(), /* strict */ true,
[new PartialModuleMetadataTransformer([partialModule])]);
const metadata = cache.getMetadata(sourceFile);
expect(metadata).toBeDefined('Expected metadata from test source file');
if (metadata) {
const classData = metadata.metadata[className];
expect(classData && isClassMetadata(classData))
.toBeDefined(`Expected metadata to contain data for "${className}"`);
if (classData && isClassMetadata(classData)) {
const statics = classData.statics;
expect(statics).toBeDefined(`Expected "${className}" metadata to contain statics`);
if (statics) {
expect(statics[newFieldName]).toEqual({}, 'Expected new field to recorded as a function');
}
}
}
});
});
@@ -1,164 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PartialModule} from '@angular/compiler';
import * as o from '@angular/compiler/src/output/output_ast';
import ts from 'typescript';
import {getAngularClassTransformerFactory} from '../../src/transformers/r3_transform';
import {Directory, MockAotContext, MockCompilerHost} from '../mocks';
const someGenFilePath = '/somePackage/someGenFile';
const someGenFileName = someGenFilePath + '.ts';
describe('r3_transform_spec', () => {
let context: MockAotContext;
let host: MockCompilerHost;
beforeEach(() => {
context = new MockAotContext('/', FILES);
host = new MockCompilerHost(context);
});
it('should be able to generate a simple identity function', () => {
expect(emitStaticMethod(new o.ReturnStatement(o.variable('v')), ['v']))
.toContain('static someMethod(v) { return v; }');
});
it('should be able to generate a static field declaration', () => {
expect(emitStaticField(o.literal(10))).toContain('SomeClass.someField = 10');
});
it('should be able to import a symbol', () => {
expect(emitStaticMethod(new o.ReturnStatement(
o.importExpr(new o.ExternalReference('@angular/core', 'Component')))))
.toContain('static someMethod() { return i0.Component; } }');
});
it('should be able to modify multiple classes in the same module', () => {
const result = emit(getAngularClassTransformerFactory(
[{
fileName: someGenFileName,
statements: [
classMethod(new o.ReturnStatement(o.variable('v')), ['v'], 'someMethod', 'SomeClass'),
classMethod(
new o.ReturnStatement(o.variable('v')), ['v'], 'someOtherMethod', 'SomeOtherClass')
]
}],
false));
expect(result).toContain('static someMethod(v) { return v; }');
expect(result).toContain('static someOtherMethod(v) { return v; }');
});
it('should insert imports after existing imports', () => {
context = context.override({
somePackage: {
'someGenFile.ts': `
import {Component} from '@angular/core';
@Component({selector: 'some-class', template: 'hello!'})
export class SomeClass {}
export class SomeOtherClass {}
`
}
});
host = new MockCompilerHost(context);
expect(emitStaticMethod(new o.ReturnStatement(
o.importExpr(new o.ExternalReference('@angular/core', 'Component')))))
.toContain('const core_1 = require("@angular/core"); const i0 = require("@angular/core");');
});
function emit(factory: ts.TransformerFactory<ts.SourceFile>): string {
let result: string = '';
const program = ts.createProgram(
[someGenFileName], {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2017}, host);
const moduleSourceFile = program.getSourceFile(someGenFileName);
const transformers: ts.CustomTransformers = {before: [factory]};
const emitResult = program.emit(
moduleSourceFile, (fileName, data, writeByteOrderMark, onError, sourceFiles) => {
if (fileName.startsWith(someGenFilePath)) {
result = data;
}
}, undefined, undefined, transformers);
return normalizeResult(result);
}
function emitStaticMethod(
stmt: o.Statement|o.Statement[], parameters: string[] = [], methodName: string = 'someMethod',
className: string = 'SomeClass'): string {
const module: PartialModule = {
fileName: someGenFileName,
statements: [classMethod(stmt, parameters, methodName, className)]
};
return emit(getAngularClassTransformerFactory([module], false));
}
function emitStaticField(
initializer: o.Expression, fieldName: string = 'someField',
className: string = 'SomeClass'): string {
const module: PartialModule = {
fileName: someGenFileName,
statements: [classField(initializer, fieldName, className)]
};
return emit(getAngularClassTransformerFactory([module], false));
}
});
const FILES: Directory = {
somePackage: {
'someGenFile.ts': `
export class SomeClass {}
export class SomeOtherClass {}
`
}
};
function classMethod(
stmt: o.Statement|o.Statement[], parameters: string[] = [], methodName: string = 'someMethod',
className: string = 'SomeClass'): o.ClassStmt {
const statements = Array.isArray(stmt) ? stmt : [stmt];
return new o.ClassStmt(
/* name */ className,
/* parent */ null,
/* fields */[],
/* getters */[],
/* constructorMethod */ new o.ClassMethod(null, [], []),
/* methods */[new o.ClassMethod(
methodName, parameters.map(name => new o.FnParam(name)), statements, null,
[o.StmtModifier.Static])]);
}
function classField(
initializer: o.Expression, fieldName: string = 'someField',
className: string = 'SomeClass'): o.ClassStmt {
return new o.ClassStmt(
/* name */ className,
/* parent */ null,
/* fields */[new o.ClassField(fieldName, null, [o.StmtModifier.Static], initializer)],
/* getters */[],
/* constructorMethod */ new o.ClassMethod(null, [], []),
/* methods */[]);
}
function normalizeResult(result: string): string {
// Remove TypeScript prefixes
// Remove new lines
// Squish adjacent spaces
// Remove prefix and postfix spaces
return result.replace('"use strict";', ' ')
.replace('exports.__esModule = true;', ' ')
.replace('Object.defineProperty(exports, "__esModule", { value: true });', ' ')
.replace(/\n/g, ' ')
.replace(/ +/g, ' ')
.replace(/^ /g, '')
.replace(/ $/g, '');
}
+3 -39
View File
@@ -7,39 +7,18 @@ NODE_ONLY = [
"aot/**/*.ts", "aot/**/*.ts",
] ]
UTILS = [
"aot/test_util.ts",
]
circular_dependency_test( circular_dependency_test(
name = "circular_deps_test", name = "circular_deps_test",
entry_point = "angular/packages/compiler/index.js", entry_point = "angular/packages/compiler/index.js",
deps = ["//packages/compiler"], deps = ["//packages/compiler"],
) )
ts_library(
name = "test_utils",
testonly = True,
srcs = UTILS,
visibility = [
"//packages/compiler-cli/test:__subpackages__",
"//packages/compiler/test:__subpackages__",
],
deps = [
"//packages:types",
"//packages/compiler",
"//packages/compiler-cli",
"//packages/compiler-cli/src/ngtsc/testing",
"@npm//typescript",
],
)
ts_library( ts_library(
name = "test_lib", name = "test_lib",
testonly = True, testonly = True,
srcs = glob( srcs = glob(
["**/*.ts"], ["**/*.ts"],
exclude = NODE_ONLY + UTILS, exclude = NODE_ONLY,
), ),
deps = [ deps = [
"//packages:types", "//packages:types",
@@ -47,13 +26,14 @@ ts_library(
"//packages/compiler", "//packages/compiler",
"//packages/compiler/test/expression_parser/utils", "//packages/compiler/test/expression_parser/utils",
"//packages/compiler/test/ml_parser/util", "//packages/compiler/test/ml_parser/util",
"//packages/compiler/testing",
"//packages/core", "//packages/core",
"//packages/core/src/compiler", "//packages/core/src/compiler",
"//packages/core/testing", "//packages/core/testing",
"//packages/platform-browser", "//packages/platform-browser",
"//packages/platform-browser-dynamic", "//packages/platform-browser-dynamic",
"//packages/platform-browser/testing", "//packages/platform-browser/testing",
"@npm//base64-js",
"@npm//source-map",
], ],
) )
@@ -62,15 +42,11 @@ ts_library(
testonly = True, testonly = True,
srcs = glob( srcs = glob(
NODE_ONLY, NODE_ONLY,
exclude = UTILS,
), ),
deps = [ deps = [
":test_lib", ":test_lib",
":test_utils",
"//packages/compiler", "//packages/compiler",
"//packages/compiler-cli",
"//packages/compiler/test/expression_parser/utils", "//packages/compiler/test/expression_parser/utils",
"//packages/compiler/testing",
"//packages/core", "//packages/core",
"@npm//typescript", "@npm//typescript",
], ],
@@ -79,14 +55,6 @@ ts_library(
jasmine_node_test( jasmine_node_test(
name = "test", name = "test",
bootstrap = ["//tools/testing:node_es5"], bootstrap = ["//tools/testing:node_es5"],
data = [
"@npm//@angular/animations-12",
"@npm//@angular/core-12",
],
tags = [
# Disabled as these tests pertain to the old ngc compilation and are not relevant in Ivy.
"view-engine-only",
],
deps = [ deps = [
":test_lib", ":test_lib",
":test_node_only_lib", ":test_node_only_lib",
@@ -97,10 +65,6 @@ jasmine_node_test(
karma_web_test_suite( karma_web_test_suite(
name = "test_web", name = "test_web",
tags = [
# Disabled as these tests pertain to the old ngc compilation and are not relevant in Ivy.
"view-engine-only",
],
deps = [ deps = [
":test_lib", ":test_lib",
], ],
-1
View File
@@ -1 +0,0 @@
Tests in this directory are excluded from running in the browser and only run in node.
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More