// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Verifies that VM is able to handle certain cases of unreachable code.

// VMOptions=--no_background_compilation --optimization_counter_threshold=10

import "package:expect/expect.dart";

class A {
  dynamic next;
}

test1(A arg1, bool arg2, bool arg3) {
  assert(arg1.next == (arg2 ?? arg3));
}

test2(A arg1, bool arg2, bool arg3) {
  print(((throw 'Error') as dynamic).next == (arg2 ?? arg3));
}

void doTests() {
  test1(new A(), null, null);
  Expect.throws(() {
    test2(new A(), null, null);
  });
}

void main() {
  for (int i = 0; i < 20; i++) {
    doTests();
  }
}

[vm] Add test for certain cases of unreachable code

This is the follow-up for https://github.com/dart-lang/sdk/commit/1d10e037ef9e69424f4fce998b4857648a96e740.

Change-Id: Ifd35acb08904d34010ede0fe609076424d146374
Reviewed-on: https://dart-review.googlesource.com/c/81331
Commit-Queue: Alexander Markov <239e774fd29abc1267878f57afe1a8a03e0ca887@google.com>
Commit-Queue: Régis Crelier <c2bf536a10d9f2530c38e4e8da517718be8c39ce@google.com>
Auto-Submit: Alexander Markov <239e774fd29abc1267878f57afe1a8a03e0ca887@google.com>
Reviewed-by: Régis Crelier <c2bf536a10d9f2530c38e4e8da517718be8c39ce@google.com>


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// VMOptions=
// VMOptions=--short_socket_read
// VMOptions=--short_socket_write
// VMOptions=--short_socket_read --short_socket_write

import "package:expect/expect.dart";
import 'dart:async';
import 'dart:io';
import 'dart:isolate';

Future<int> runServer(int port, int connections, bool clean) {
  var completer = new Completer();
  HttpServer.bind("127.0.0.1", port).then((server) {
    int i = 0;
    server.listen((request) {
      request.pipe(request.response);
      i++;
      if (!clean && i == 10) {
        int port = server.port;
        server.close().then((_) => completer.complete(port));
      }
    });

    Future.wait(new List.generate(connections, (_) {
      var client = new HttpClient();
      return client.get("127.0.0.1", server.port, "/")
          .then((request) => request.close())
          .then((response) => response.drain())
          .catchError((e) { if (clean) throw e; });
    })).then((_) {
      if (clean) {
        int port = server.port;
        server.close().then((_) => completer.complete(port));
      }
    });
  });
  return completer.future;
}

void testReusePort() {
  var keepAlive = new ReceivePort();
  runServer(0, 10, true).then((int port) {
    // Stress test the port reusing it 10 times.
    Future.forEach(new List(10), (_) {
      return runServer(port, 10, true);
    }).then((_) {
      keepAlive.close();
    });
  });
}

void testUncleanReusePort() {
  var keepAlive = new ReceivePort();
  runServer(0, 10, false).then((int port) {
    // Stress test the port reusing it 10 times.
    Future.forEach(new List(10), (_) {
      return runServer(port, 10, false);
    }).then((_) {
      keepAlive.close();
    });
  });
}

void main() {
  testReusePort();
  testUncleanReusePort();
}

Add test for reusing the port of a server socket, after the server's close future is completed.

BUG=
R=kustermann@google.com

Review URL: https://codereview.chromium.org//19653004

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@25257 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

library solver.msrand;

import "dart:math";

class MSRandom implements Random {
  int _seed;

  MSRandom(this._seed);

  int _rand() {
    _seed = (_seed * 214013 + 2531011) & 0x7FFFFFFF;
    return ((_seed >> 16) & 0x7fff);
  }

  int nextInt(max) {
    return _rand() % max;
  }

  double nextDouble() {
    return _rand() % 101 / 100.0;
  }

  bool nextBool() {
    return nextDouble() > 0.5;
  }
}

Add the MS random number generator.

Add the MS random number generator.


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/analyzer.dart';
import 'package:analyzer/plugin/options.dart';
import 'package:analyzer/src/lint/registry.dart';
import 'package:yaml/yaml.dart';

/**
 * An error code indicating an undefined lint rule.
 *
 * Parameters:
 * 0: the rule name
 */
const AnalysisOptionsWarningCode UNDEFINED_LINT_WARNING =
    const AnalysisOptionsWarningCode(
        'UNDEFINED_LINT_WARNING', "'{0}' is not a recognized lint rule");

/**
 * Validates `linter` rule configurations.
 */
class LinterRuleOptionsValidator extends OptionsValidator {
  static const linter = 'linter';
  static const rulesKey = 'rules';
  @override
  List<AnalysisError> validate(
      ErrorReporter reporter, Map<String, YamlNode> options) {
    List<AnalysisError> errors = <AnalysisError>[];
    var node = options[linter];
    if (node is YamlMap) {
      var rules = node.nodes[rulesKey];
      validateRules(rules, reporter);
    }
    return errors;
  }

  validateRules(dynamic rules, ErrorReporter reporter) {
    if (rules is YamlList) {
      Iterable<String> registeredLints =
          Registry.ruleRegistry.map((r) => r.name);
      rules.nodes.forEach((YamlNode ruleNode) {
        Object value = ruleNode.value;
        if (value != null && !registeredLints.contains(value)) {
          reporter.reportErrorForSpan(
              UNDEFINED_LINT_WARNING, ruleNode.span, [value]);
        }
      });
    }
  }
}

Add file missed in last commit (TBR)

Add file missed in last commit (TBR)

Review-Url: https://codereview.chromium.org/2562223002 .


part of ThreeD;

class EventEmitterEvent {
  String type;
  String message;
  var content;
  EventEmitterEvent({this.type, this.message, this.content});
}

class EventEmitter {

	var listeners;

	EventEmitter() : listeners = {};

	addEventListener( type, listener ) {

		if ( listeners[ type ] == null ) {
			listeners[ type ] = [];
		}

		if ( listeners[ type ].indexOf( listener ) == - 1 ) {
			listeners[ type ].add( listener );
		}

	}

	dispatchEvent( event ) {
		if ( listeners[ event.type ] != null ) {
			listeners[ event.type ].forEach((listener) => listener( event ));
                }
	}

	removeEventListener ( type, listener ) {

		var index = listeners[ type ].indexOf( listener );

		if ( index != - 1 ) {
			listeners[ type ].removeRange( index, 1 );
		}

	}

}

Fix tabs on closing brace.

Fix tabs on closing brace.


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import "package:expect/expect.dart";

// SharedOptions=--enable-experiment=non-nullable
void main() {
}

/// These tests will all pass only if run with the NNBD migrated SDK.
/// In not migrated SDK all types are unprefixed, so look non-nullable.
void f(List<int> list, Map<int, String> map, int a, int? b) {
  // List: E operator [](int index);
  list[a]; //# 00: ok
  list[b]; //# 01: compile-time error

  // Map: V? operator [](Object? key);
  map[a]; //# 02: ok
  map[b]; //# 03: ok

  // Map: void operator []=(K key, V value);
  map[a].length; //# 04: compile-time error
  map[a]?.length; //# 05: ok

  map[b] = ''; //# 06: compile-time error
  map[a] = b; //# 07: compile-time error
}

Add a NNBD test that needs NNBD migrated SDK.

I tested it locally by updating `SharedOptions` to include not only
`--enable-experiment=non-nullable`, but also the forced path to NNBD
SDK: `--dart-sdk=/Users/scheglov/Applications/dart-sdk-NNBD`.

This will fail for now, I will accept current bot failures.

Change-Id: I72c9b46049de6cd25eddebd43d5c73c2fc9d7825
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/124168
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Reviewed-by: Paul Berry <72d414e3a99fb120308437779d51667bcc0984eb@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE.md file.

import "package:testing/src/run_tests.dart" as run_tests;

main(List<String> arguments) => run_tests.main(arguments);

Add entrypoint to make benefit pub run.

Add entrypoint to make benefit pub run.

R=karlklose@google.com

Review URL: https://codereview.chromium.org/2428903002 .


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:_js_helper";
import "package:expect/expect.dart";

// Test that compiler is cautious with optimizations on native fields.  The
// motivation is that DOM properties are getters and setters with arbitrary
// effects.  Setting CSSStyleDeclaration.borderLeft can canonicalize the value
// and changes the value of CSSStyleDeclaration.border.

@Native("Foo")
class Foo {
  var a;
  var b;
  var ab;
}

Foo makeFoo() native;

void setup() native """
function Foo() { this.i = 0; }

Object.defineProperty(Foo.prototype, 'a', {
  get: function () { return (this._a || '') + ++this.i; },
  set: function (v) { this._a = v.toLowerCase(); }
});

Object.defineProperty(Foo.prototype, 'b', {
  get: function () { return this._b || ''; },
  set: function (v) { this._b = v.toLowerCase(); }
});

Object.defineProperty(Foo.prototype, 'ab', {
  get: function () { return this.a + ' ' + this.b; },
  set: function (v) {
    var s = v.split(' ');
    this.a = s[0];
    this.b = s[1];
  }
});

makeFoo = function() { return new Foo() }
""";

test1() {
  var f = makeFoo();
  f.a = 'Hi';
  f.b = 'There';
  Expect.equals('hi1 there', f.ab);
}

test2() {
  // Test for CSE. dart2js currently does CSE loads. Is this the right choice?
  var f = makeFoo();
  var a1 = f.a;
  var b1 = f.b;
  var a2 = f.a;
  Expect.equals('1', a1);
  if (a2 == a1) {
    // We did CSE.
  } else {
    Expect.equals('2', a2);
  }
}

test3() {
  // Must not CSE over a native field store.
  var f = makeFoo();
  var a1 = f.a;
  f.ab = 'X Y';
  var a2 = f.a;
  Expect.equals('1', a1);
  Expect.equals('x2', a2);
}

test4() {
  // Must not store-forward.
  var f = makeFoo();
  f.a = 'A';
  var a2 = f.a;
  Expect.equals('a1', a2);
}

main() {
  setup();
  (test1)();
  (test2)();
  (test3)();
  (test4)();
}

Test for limited optimizations on native fields

This captures some of the current status on how optimizations interact with native fields.

R=herhut@google.com

Review URL: https://codereview.chromium.org//1031073002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@44783 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';

main() {
  initConfig();

  integration("includes .dart files from dependencies in debug mode", () {
    // Dart2js can take a long time to compile dart code, so we increase the
    // timeout to cope with that.
    currentSchedule.timeout *= 3;

    d.dir("foo", [
      d.libPubspec("foo", "0.0.1"),
      d.dir("lib", [
        d.file('foo.dart', 'foo() => print("hello");'),
        d.dir("sub", [
          d.file('bar.dart', 'bar() => print("hello");'),
        ])
      ])
    ]).create();

    d.dir(appPath, [
      d.appPubspec({
        "foo": {"path": "../foo"}
      }),
      d.dir("example", [
        d.file("main.dart", 'myapp() => print("not entrypoint");'),
        d.dir("sub", [
          d.file("main.dart", 'myapp() => print("not entrypoint");')
        ])
      ])
    ]).create();

    schedulePub(args: ["build", "--mode", "debug", "example"],
        output: new RegExp(r"Built 4 files!"));

    d.dir(appPath, [
      d.dir('build', [
        d.dir('example', [
          d.file("main.dart", 'myapp() => print("not entrypoint");'),
          d.dir('packages', [
            d.dir('foo', [
              d.file('foo.dart', 'foo() => print("hello");'),
              d.dir("sub", [
                d.file('bar.dart', 'bar() => print("hello");'),
              ])
            ])
          ]),
          d.dir("sub", [
            d.file("main.dart", 'myapp() => print("not entrypoint");'),
            // Does *not* copy packages into subdirectories.
            d.nothing("packages")
          ])
        ])
      ])
    ]).validate();
  });
}

Test that .dart files are copied to packages/ in debug mode.

BUG=https://code.google.com/p/dart/issues/detail?id=16567
R=nweiz@google.com

Review URL: https://codereview.chromium.org//149213009

git-svn-id: a962b240025cf0577aa172e20f49ccb159ba6be1@32566 260f80e4-7a28-3924-810f-c04153c831b5


/// This regression test demonstrates why `View.injectorGet()` must null-check
/// the `nodeIndex` argument, a rare and complex case that requires a number of
/// conditions to be met.
///
///   (1) Create a component whose template contains a top-level view container;
///   this ensures the view container has a null parent index.
///
///   (2) Add directive(s) with multiple providers to any node in the
///   component's template with at least one child node; this ensures that a
///   range check on `nodeIndex` is generated in `injectorGetInternal` and not
///   skipped due to short-circuit evaluation when a node only has one provider
///   and the token doesn't match. This range check is what will throw if
///   `nodeIndex` is null.
///
///   (3) Inject a dependency via the top-level view container's
///   `parentInjector`. This causes the null parent index to pass from
///   `ElementInjector.provideUntyped()` to `View.injectorGet()`.
@TestOn('browser')
import 'package:test/test.dart';
import 'package:angular/angular.dart';
import 'package:angular_test/angular_test.dart';

import 'b_133253211_null_node_index_test.template.dart' as ng;

void main() {
  tearDown(disposeAnyRunningTest);

  test('View.injectorGet() should handle a null nodeIndex argument', () async {
    final testValue = 'Hello world!';
    final testBed = NgTestBed.forComponent(
      ng.TestComponentNgFactory,
      rootInjector: ([parent]) => Injector.map({testToken: testValue}, parent),
    );
    final testFixture = await testBed.create();
    final testComponent = testFixture.assertOnlyInstance;
    expect(
      // This parent injector, an `ElementInjector`, passes a null nodeIndex
      // parameter to `View.injectorGet()`. Note that while this looks like a
      // bizarre use case that might not seem worth supporting, this is the
      // simplest reproduction of this pattern that can be achieved far more
      // indirectly via declarative means. Clients do depend on this behavior.
      testComponent.viewContainerRef.parentInjector.provideToken(testToken),
      testValue,
    );
  });
}

@Component(
  selector: 'test',
  directives: [ProvidersDirective],
  template: '''

      Some content to create a range check on nodeIndex

  ''',
)
class TestComponent {
  @ViewChild('container', read: ViewContainerRef)
  ViewContainerRef viewContainerRef;
}

const testToken = OpaqueToken<String>('test');
const tokenA = OpaqueToken<String>('a');
const tokenB = OpaqueToken<String>('b');

@Directive(
  selector: '[providers]',
  // Multiple providers to ensure the range check isn't skipped due to short
  // circuit evaluation of mismatched token query.
  providers: [
    ValueProvider.forToken(tokenA, 'a'),
    ValueProvider.forToken(tokenB, 'b'),
  ],
)
class ProvidersDirective {}

Add regression test for null `nodeIndex` argument passed to `View.injectorGet()`

This demonstrates why `View.injectorGet()` must null-check the `nodeIndex`
argument, a rare and complex case that requires a number of conditions to be
met.

  (1) Create a component whose template contains a top-level view container;
  this ensures the view container has a null parent index.

  (2) Add directive(s) with multiple providers to any node in the component's
  template with at least one child node; this ensures that a range check on
  `nodeIndex` is generated in `injectorGetInternal` and not skipped due to
  short-circuit evaluation when a node only has one provider and the token
  doesn't match. This range check is what will throw if `nodeIndex` is null.

  (3) Inject a dependency via the top-level view container's `parentInjector`.
  This causes the null parent index to pass from
  `ElementInjector.provideUntyped()` to `View.injectorGet()`.

PiperOrigin-RevId: 249476365


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library sintr_common.pubsub_utils;

import 'dart:async';

import 'package:gcloud/pubsub.dart';
import "package:logging/logging.dart" as logging;

final _log = new logging.Logger("PubSub_support");

/// Gets a topic, if it doesn't already exist, create it.
Future<Topic> getTopic(String name, PubSub ps) async {

  // Try and find the topic.
  _log.finer("PRE: Getting topic for $name");

  Topic topic;

  try {
    topic = await ps.lookupTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic lookup failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.finer("OK: Existing topic found: $name");
    return topic;
  }

  // Try and create the topic.
  try {
    topic = await ps.createTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic creation failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.fine("OK: Topic created: $name");
    return topic;
  }

  // The creation make have failed because of a race between the lookup and
  // the creation.
  try {
    topic = await ps.lookupTopic(name);
  } catch (e, st) {
    _log.finer("NOK: Topic lookup failed");
    _log.finest(e);
    _log.finest(st);
  }

  if (topic != null) {
    _log.finer("OK: Topic found after race: $name");
    return topic;
  }

  _log.shout("FAIL: Topic not $name");
  throw "Topic not found: $name";
}

Add library to get a topic creating it if necessary


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Regression test for CL 194523002.

library js_custom_test;

import 'package:unittest/unittest.dart';
import 'package:unittest/html_config.dart';
import 'dart:html';
import '../utils.dart';

class A extends HtmlElement {
  static final tag = 'x-a';
  factory A() => new Element.tag(tag);
  A.created() : super.created();
}

main() {
  useHtmlConfiguration();

  // Adapted from Blink's
  // fast/dom/custom/constructor-calls-created-synchronously test.

  var registered = false;
  setUp(() {
    return customElementsReady.then((_) {
      if (!registered) {
        registered = true;
        document.register(A.tag, A);
      }
    });
  });
}

Add regression test for CL 194523002

Add regression test for CL 194523002

BUG=
R=floitsch@google.com

Review URL: https://codereview.chromium.org//214443002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@34470 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:convert';

import 'package:source_span/source_span.dart';
import 'package:test/test.dart';
import 'package:yaml/yaml.dart';

void _expectSpan(SourceSpan source, String expected) {
  final result = source.message('message');
  printOnFailure("r'''\n$result'''");

  expect(result, expected);
}

void main() {
  YamlMap yaml;

  setUpAll(() {
    yaml = loadYaml(const JsonEncoder.withIndent(' ').convert({
      'num': 42,
      'nested': {
        'null': null,
        'num': 42,
      },
      'null': null,
    })) as YamlMap;
  });

  test('first root key', () {
    _expectSpan(
      yaml.nodes['num'].span,
      r'''
line 2, column 9: message
  ╷
2 │  "num": 42,
  │         ^^
  ╵''',
    );
  });

  test('first root key', () {
    _expectSpan(
      yaml.nodes['null'].span,
      r'''
line 7, column 10: message
  ╷
7 │  "null": null
  │          ^^^^
  ╵''',
    );
  });

  group('nested', () {
    YamlMap nestedMap;

    setUpAll(() {
      nestedMap = yaml.nodes['nested'] as YamlMap;
    });

    test('first root key', () {
      _expectSpan(
        nestedMap.nodes['null'].span,
        r'''
line 4, column 11: message
  ╷
4 │   "null": null,
  │           ^^^^
  ╵''',
      );
    });

    test('first root key', () {
      _expectSpan(
        nestedMap.nodes['num'].span,
        r'''
line 5, column 10: message
  ╷
5 │     "num": 42
  │ ┌──────────^
6 │ │  },
  │ └─^
  ╵''',
      );
    });
  });
}

Add test to validate SourceSpan values for nodes

Preparing for https://github.com/dart-lang/yaml/issues/51


// Copyright (c) 2014, the Liquid project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library liquid.utils;

class AssertionFailure {
  final String message;

  const AssertionFailure(this.message);

  String toString() => message;
}

bool invariant(condition, [message]) {
  if (condition is Function){
    condition = condition();
  }
  if (!condition) {
    if (message is Function) {
      message = message();
    }
    throw new AssertionFailure(message);
  }
  return true;
}

Add functions for runtime checking

Add functions for runtime checking


// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Example of retrieving a sensor using the Sensor API.

// C++ implementation can be found here:
// https://docs.microsoft.com/en-us/windows/win32/sensorsapi/retrieving-a-sensor

import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

void main() {
  CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

  final sensorManager = SensorManager.createInstance();

  // Replace this with the sensor category you're looking for.
  final sampleDateTimeSensorCategory =
      GUIDFromString('{062A5C3B-44C1-4ad1-8EFC-0F65B2E4AD48}');
  final pSensorsColl = calloc<Pointer<COMObject>>();
  var hr = sensorManager.GetSensorsByCategory(
      sampleDateTimeSensorCategory, pSensorsColl);
  if (FAILED(hr)) throw WindowsException(hr);

  final coll = ISensorCollection(pSensorsColl.cast());
  final pCount = calloc<Uint32>();
  if (coll.GetCount(pCount) > 1) {
    print('Found items');
  }

  free(pCount);
  free(pSensorsColl);
  free(sampleDateTimeSensorCategory);

  CoUninitialize();
}

Add trivial example of usage

Add trivial example of usage


import 'package:moor/moor.dart';
import 'package:moor_ffi/moor_ffi.dart';
@TestOn('vm')
import 'package:test/test.dart';

import '../data/tables/todos.dart';

void main() {
  TodoDb db;

  setUp(() {
    db = TodoDb(VmDatabase.memory());
  });

  test('insertOnConflictUpdate', () async {
    await db.into(db.categories).insert(
        CategoriesCompanion.insert(description: 'original description'));

    var row = await db.select(db.categories).getSingle();

    await db.into(db.categories).insertOnConflictUpdate(CategoriesCompanion(
        id: Value(row.id), description: const Value('changed description')));

    row = await db.select(db.categories).getSingle();
    expect(row.description, 'changed description');
  });
}

Add small integration test for generated upserts


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

main() {
  Expect.isTrue(null is Object);
  Expect.isFalse(null is int);
  Expect.isFalse(null is bool);
  Expect.isFalse(null is num);
  Expect.isFalse(null is String);
  Expect.isFalse(null is List);
  Expect.isFalse(null is Expect);
}

Fix 'is' for null.
Review URL: https://chromiumcodereview.appspot.com//9358055

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@4227 260f80e4-7a28-3924-810f-c04153c831b5


import 'dart:convert' show UTF8;
import 'dart:typed_data' show Uint8List;

final _padding = [
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0,
];

Uint8List stringToUint8List(String value) =>
  new Uint8List.fromList(
    (UTF8.encode(value).toList()
      ..addAll(_padding)
    ).sublist(0, 32),
  );

Add the stringtoUint8List utility function


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that a Dart implementation doesn't turn dynamic errors into
// compilation errors.

f(x) {}

class MyClass {
  MyClass(x, y);

  foo() {
    var z;
    // Neither y nor x are defined. So they are simply dynamic
    // (getter) sends to this, not compile-time errors.
    if (false) f(new MyClass(z, y[x.y.z]));
    if (false) print(y[x.y.z]);
  }
}

main() {
  var x;
  // We know the concrete type of f (a function closure) does not
  // support the index operator. However, this is a dynamic error, so
  // this program should compile.
  if (false) print(f[x.y.z]);
  new MyClass(0, 0).foo();
}

Test that expose a few quirks in the Dart VM parser.

Review URL: https://chromiumcodereview.appspot.com//9205003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@6783 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#library('HTMLOptionsCollectionTest');
#import('../../lib/unittest/unittest.dart');
#import('../../lib/unittest/html_config.dart');
#import('dart:html');

main() {
  useHtmlConfiguration();

  test('indexedAccessTest', () {
    // FIXME: we need some massaging to dart:html to enable HTMLOptionsCollection.add
    // and hence programatic building of collection.
    final selectElement = new Element.html('''
      <select>
        <option value="0">Option0</option>
        <option value="1">Option1</option>
        <option value="2">Option2</option>
      ''');
    final optionsCollection = selectElement.options;

    expect(optionsCollection[0].value, equals('0'));
    expect(optionsCollection[1].value, equals('1'));
    expect(optionsCollection[2].value, equals('2'));

    expect(optionsCollection[0].text, equals('Option0'));
    expect(optionsCollection[1].text, equals('Option1'));
    expect(optionsCollection[2].text, equals('Option2'));

    expect(() { optionsCollection[0] = 1; }, throws);

    optionsCollection[0] = new OptionElement(value: '42', data: 'Option42');
    expect(optionsCollection[0].value, equals('42'));
    expect(optionsCollection[0].text, equals('Option42'));
  });
}

Add a simple test for HTMLOptionsCollection.

R=podivilov@chromium.org

Review URL: https://chromiumcodereview.appspot.com//10636002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@8978 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that it is an error for a class with no generative constructors to
// have a final instance variable without an initializing expression, except
// if it is `abstract` or `external`. The latter also holds in a class with
// generative constructors.

// Has factory, hence no default, hence no generative constructors.
abstract class A {
  final dynamic n;
  //            ^
  // [analyzer] COMPILE_TIME_ERROR.FINAL_NOT_INITIALIZED
  // [cfe] unspecified

  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;

  factory A() = B;
}

class B implements A {
  dynamic get n => 1;
  int get x1 => 1;
  int? get x2 => null;
  String get x3 => "";
  String? get x4 => null;
}

class C = Object with A;

// Has a generative constructor: default.
abstract class D {
  // Uninitialized, but no errors.
  abstract final int x1;
  abstract final int? x2;
  external final String x3;
  external final String? x4;
}

void main() {
  A();
  C();
  var _ = D;
}

Add test for missing initializer on final instance variable

Add a test where a class that has no generative constructors
declares an instance variable which is final and has no initializing
expression. With https://github.com/dart-lang/language/pull/1130 this
is an error, and that error is expected by the test. Also test that
it is not an error to have an uninitialized final variable which is
abstract or external.

Change-Id: I6c4a46393f46587448612bd91fb99fa65f89704c
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/157490
Commit-Queue: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>
Reviewed-by: Bob Nystrom <afede3a9ebedb865bee78398feff6fbe97068f17@google.com>


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'package:expect/expect.dart';

class A implements Future<Future<A>> {
  @override
  noSuchMethod(Invocation _) {}
}

void main() {
  Expect.notSubtype<A, Future<A>>();
  Expect.subtype<FutureOr<A>, FutureOr<Future<A>>>();
}

Add test demonstrating that FutureOr<A> <: FutureOr<B> =/=> A <: B.

Change-Id: Iedc60b57f80e77784e54b8d5ed9076c5016edd2f
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/121653
Commit-Queue: Mayank Patke <e0355b78204b67a55a952941c68c8f1b40235938@google.com>
Reviewed-by: Leaf Petersen <9bef692239b5f624cec8e2cd5249ab1939a377aa@google.com>


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

main() {
  int i = 0;
  for (;; i++) {
    if (i == 0) break;
    Expect.fail("Should not enter here");
  }
  Expect.equals(0, i);
}

Support for loops without conditions.
Review URL: https://chromiumcodereview.appspot.com//9657003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@5222 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Dart test for top level declarations involving an imported type.

#library("main");
#import("library11.dart", prefix : "lib11");

lib11.Library11 variable = null;

lib11.Library11 function() => null;

lib11.Library11 get getter() => null;

main() {
  Expect.isTrue(variable == null);
  Expect.isTrue(function() == null);
  Expect.isTrue(getter == null);
}

Add test for issue fixed in r3707.
Review URL: https://chromiumcodereview.appspot.com//9104044

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@3739 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'dart:async';
import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import 'utils.dart';

main() {
  // This is a regression test for http://dartbug.com/21402.
  initConfig();
  withBarbackVersions("any", () {
    integration("picks up files replaced after serving started when using the "
        "native watcher", () {
      d.dir(appPath, [
        d.pubspec({
          "name": "myapp",
          "transformers": ["myapp/src/transformer"]
        }),
        d.dir("lib", [d.dir("src", [
          d.file("transformer.dart", REWRITE_TRANSFORMER)
        ])]),
        d.dir("web", [
          d.file("file.txt", "before"),
        ]),
        d.file("other", "after")
      ]).create();

      createLockFile("myapp", pkg: ["barback"]);

      pubServe(args: ["--no-force-poll"]);
      waitForBuildSuccess();
      requestShouldSucceed("file.out", "before.out");

      schedule(() {
        // Replace file.txt by renaming other on top of it.
        return new File(p.join(sandboxDir, appPath, "other"))
            .rename(p.join(sandboxDir, appPath, "web", "file.txt"));
      });

      // Read the transformed file to ensure the change is actually noticed by
      // pub and not that we just get the new file contents piped through
      // without pub realizing they've changed.
      waitForBuildSuccess();
      requestShouldSucceed("file.out", "after.out");

      endPubServe();
    });
  });
}

Test that safe saves are picked up by pub serve.

BUG=https://code.google.com/p/dart/issues/detail?id=21402
R=nweiz@google.com

Review URL: https://codereview.chromium.org//870703003

git-svn-id: a962b240025cf0577aa172e20f49ccb159ba6be1@43082 260f80e4-7a28-3924-810f-c04153c831b5


/// Selection Sort the input list
void selectionSort(List<int> items) {
  // Iterate through the array, knowing left-of-i is sorted and looking
  // for the lowest to-the-right element to place at the end of left
  for (int i = 0; i < items.length - 1; i++) {
    int lowestIndex = i;
    for (int j = i + 1; j < items.length; j++) {
      if (items[j] < items[lowestIndex]) {
        lowestIndex = j;
      }
    }

    // Swap the lowest item with this position (i)
    final int lowestNumber = items[lowestIndex];
    items[lowestIndex] = items[i];
    items[i] = lowestNumber;
  }
}
 // ----- Test -----
void main() {
  // 1. Arrange
  final List<int> testedList = [10, 2, 8, 5, 6, 1, 4, 7, 9, 3];
  final List<int> expectedOutput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
   // 2. Act
  selectionSort(testedList);
  print(testedList);
   // 3. Assert
  // No simple list equality in dart yet so using 'fold' to recursively check
  // each sorted element compared to the expected output at each index.
  int i = 0;
  final bool isEqual = testedList.fold(
    true,
    (result, item) => result && item == expectedOutput[i++],
  );
  print(isEqual);
}

Add Dart implementation of Selection Sort


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

foo(a, [b]) {
}

class A {
  A(a, [b]);
}

class B {
  B()
    : super(b: 1) /// 01: runtime error
  ;
}

main() {
  new B(); /// 01: continued
  foo(b: 1); /// 02: runtime error
}

Add a test for checking that enough positional arguments were passed in.
Review URL: https://chromiumcodereview.appspot.com//10102001

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@6616 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Dart test program for default constructors.

String message;

foo() {
  message += 'foo';
  return 1;
}

bar() {
  message += 'bar';
  return 2;
}

class X {
  var i;
  var j;
  X([a = 'defa', b = 'defb']) : this.i = a, this.j = b;
  X.foo() : this(b: 1, a: 2);
  X.bar() : this(
                     1,  /// 01: compile-time error
                     a: 2);
  X.baz() : this(a: 1, b: 2);
  X.qux() : this(1, 2);
  X.hest() : this();
  X.fisk() : this(b: bar(), a: foo());
  X.naebdyr() : this(a: foo(), b: bar());
}

test(x, a, b) {
  Expect.equals(x.i, a);
  Expect.equals(x.j, b);
}

main() {
  test(new X.foo(), 2, 1);
  test(new X.bar(), 2, 'defb');
  test(new X.baz(), 1, 2);
  test(new X.qux(), 1, 2);
  test(new X.hest(), 'defa', 'defb');

  message = '';
  new X.fisk();
  Expect.equals('barfoo', message);

  message = '';
  new X.naebdyr();
  Expect.equals('foobar', message);
}

Support named parameters for super initializers and redirections.

Review URL: https://chromiumcodereview.appspot.com//9454014

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@4606 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Check function subtyping of type arguments. These cases use typedefs as type
// arguments, and the typedefs have type parameters that are used more than
// once.

import 'package:expect/expect.dart';

typedef A F<A>(A arg1, A arg2);
typedef B G<A,B>(B arg1, B arg2);

typedef Set<A> FS<A>(Set<A> arg1, Set<A> arg2);

@NoInline() @AssumeDynamic() dyn(x) => x;

class CheckEnv<X, Y> {
  test(bool intX) {
    Expect.isTrue(<F<X>>[] is List<F>);
    Expect.isTrue(<F<X>>[] is List<F<X>>);
    Expect.isTrue(<F<X>>[] is List<G<Y,X>>);

    Expect.isTrue(dyn(<F<X>>[]) is List<F>);
    Expect.isTrue(dyn(<F<X>>[]) is List<F<X>>);
    Expect.isTrue(dyn(<F<X>>[]) is List<G<Y,X>>);

    Expect.isTrue(<F<X>>[] is! List<F<Y>>);
    Expect.isTrue(<F<X>>[] is! List<G<X,Y>>);

    Expect.isTrue(dyn(<F<X>>[]) is! List<F<Y>>);
    Expect.isTrue(dyn(<F<X>>[]) is! List<G<X,Y>>);

    Expect.isTrue(dyn(<FS<X>>[]) is List<FS>);
    Expect.isTrue(dyn(<FS<X>>[]) is List<FS<X>>);
    if (intX) {
      Expect.isTrue(dyn(<FS<X>>[]) is List<FS<int>>);
      Expect.isTrue(dyn(<FS<int>>[]) is List<FS<X>>);
      Expect.isTrue(dyn(<FS<Y>>[]) is! List<FS<int>>);
      Expect.isTrue(dyn(<FS<int>>[]) is! List<FS<Y>>);
    }
  }
}

main() {
  Expect.isTrue(<F<int>>[] is List<F<int>>);
  Expect.isTrue(dyn(<F<int>>[]) is List<F<int>>);
  Expect.isTrue(<F<int>>[] is List<G<bool,int>>);
  Expect.isTrue(dyn(<F<int>>[]) is List<G<bool,int>>);

  new CheckEnv<int,String>().test(true);
  new CheckEnv<String,int>().test(false);
}

Add language test with nested function typedef with two references to argument

R=sigmund@google.com

Review URL: https://codereview.chromium.org/2297783002 .


import 'dart:ffi';

import 'package:ffi/ffi.dart';
import 'package:test/test.dart';
import 'package:win32/win32.dart';

// This test prevents CI from failing on other platforms (GitHub Actions fails
// unless at least one test is run successfully.)
void main() {
  test('Neutral test to give non-Windows platforms something to chew on', () {
    final point = calloc<POINT>()
      ..ref.x = 0x10
      ..ref.y = 0x7F;
    expect(point.ref.x + point.ref.y, equals(0x8F));
    free(point);
  });
}

Add platform-independent test to fix Ubuntu flake


import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

import 'expect_no_changes_dev_mode_test.template.dart' as ng_generated;

void main() {
  ng_generated.initReflector();

  test('should throw during change detection', () async {
    final testBed = new NgTestBed<IllegalChangeDetectionComponent>();
    expect(
      testBed.create(),
      throwsA(predicate(
        (e) => '$e'.contains('Expression has changed after it was checked'),
      )),
    );
  });
}

@Component(
  selector: 'illegal-change-detection',
  template: r'''
    <div>{{counter}}</div>
  ''',
)
class IllegalChangeDetectionComponent {
  var _counter = 0;
  int get counter => _counter++;
}

test(Core): Add a test that shows that "expression has changed" works.

PiperOrigin-RevId: 183892699


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Dart test program checking that optimizations are not too aggresive and
// incorrect:
// - (a * (1.0 / b))
//
// VMOptions=--optimization-counter-threshold=8 --no-use-osr

import "package:expect/expect.dart";

var xx = 23.0;

main() {
  xx = 1e-6;
  scaleIt(1e-310);
  Expect.isTrue(xx.isInfinite);
  for (int i = 0; i < 10; i++) {
    xx = 24.0;
    scaleIt(6.0);
    Expect.equals(4.0, xx);
  }
  xx = 1e-6;
  scaleIt(1e-310);
  Expect.isTrue(xx.isInfinite);
}

scaleIt(double b) {
  scale(1.0 / b);
}

scale(a) {
  xx *= a;
}

Add check that no aggressive & incorrect optimizations is done.

R=sra@google.com

Review URL: https://codereview.chromium.org//1033873003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@44746 260f80e4-7a28-3924-810f-c04153c831b5


/// Computes what the probability should be set for each wheel if
/// there are five of them and success is 3+ successful wheels.
library compute_floating_setup;

import 'dart:math';

void main() {
  for (int i = 0; i <= 100; i++) {
    final p = i / 100;
    print('$p, ${computeTotalProbability(p)}');
  }
}

double computeTotalProbability(double wheelProbability, [int wheelCount = 5]) {
  final possibleResults = getPossibleResults(wheelCount);

  // print("count: ${possibleResults.length}");

  // print(possibleResults);
  // print(possibleResults.where((result) => result.isWinning).length);

  var total = 0.0;
  var winningTotal = 0.0;
  for (final result in possibleResults) {
    final partial = result.probability(wheelProbability);
    // print("$result (${result.isWinning ? 'win' : 'lose'}) = $partial");
    total += partial;
    winningTotal += result.isWinning ? partial : 0;
  }

  // print(total);
  return winningTotal;
}

List<Result> getPossibleResults(int wheelCount) {
  final pools =
      List<List<bool>>.filled(wheelCount, const [true, false], growable: false);
  final set = product(pools);
  assert(
      set.length == pow(2, wheelCount), "The resulting set should be n ** r.");
  return set.map((result) => Result(result)).toList(growable: false);
}

/// Returns Cartesian product of a list of [pools].
/// https://en.wikipedia.org/wiki/Cartesian_product
Iterable<List<T>> product<T>(List<List<T>> pools) sync* {
  if (pools.length < 2) throw ArgumentError(pools);
  if (pools.length == 2) {
    for (final x in pools.first) {
      for (final y in pools.last) {
        yield [x, y];
      }
    }
    return;
  }

  for (final x in pools.first) {
    for (final y in product(pools.sublist(1))) {
      yield [x] + y;
    }
  }
}

class Result {
  final List<bool> wheelResults;

  const Result(this.wheelResults);

  bool get isWinning =>
      wheelResults.where((result) => result).length > wheelResults.length / 2;

  /// Probability that this exact result will be shown, given probability
  /// setting of each wheel.
  double probability(double wheelProbability) {
    double result = 1.0;
    for (final wheelResult in wheelResults) {
      if (wheelResult) {
        result *= wheelProbability;
      } else {
        result *= (1 - wheelProbability);
      }
    }
    return result;
  }

  @override
  String toString() => wheelResults.toString();
}

Add computation for a floating point wheel

Instead of slot reels (with a finite amount of Xs and Os), we are now using “wheels of fortune”. These can have any probability of success. We use them in a row of five, and we want to know what the probability is of them landing on a success with at least a 3:2 advantage.


@Tags(const ['codegen'])
@TestOn('browser')
import 'dart:async';

import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  // Regression test for https://github.com/dart-lang/angular2/issues/164.
  test('should update an NgForm without throwing an NPE', () async {
    final testBed = new NgTestBed<AppComponent>();
    expect(
      (await testBed.create()).rootElement.innerHtml,
      contains(r'<input title="Input #0:true">'),
    );
  });
}

@Component(
  selector: 'root',
  directives: const [
    FORM_DIRECTIVES,
    NgFor,
  ],
  template: r'''
    <form>
      <input *ngFor="let val of values; let idx = index"
             [ngModel]="val"
             ngControl="input-{{idx}}"
             title="Input #{{idx}}:{{val}}">
    </form>
  ''',
)
class AppComponent {
  Iterable<String> values;
  bool b = false;

  AppComponent() {
    _update();
    Timer.run(_update);
  }

  void _update() {
    values = new List.from([b.toString()]);
    print(values);
    b = !b;
  }
}

@Tags(const ['codegen'])
@TestOn('browser')
import 'dart:async';

import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';
import 'package:angular/angular.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  // Regression test for https://github.com/dart-lang/angular2/issues/164.
  test('should update an NgForm without throwing an NPE', () async {
    final testBed = new NgTestBed<AppComponent>();
    expect(
      (await testBed.create()).rootElement.innerHtml,
      contains(r'<input title="Input #0:true">'),
    );
  });
}

@Component(
  selector: 'root',
  directives: const [
    formDirectives,
    NgFor,
  ],
  template: r'''
    <form>
      <input *ngFor="let val of values; let idx = index"
             [ngModel]="val"
             ngControl="input-{{idx}}"
             title="Input #{{idx}}:{{val}}">
    </form>
  ''',
)
class AppComponent {
  Iterable<String> values;
  bool b = false;

  AppComponent() {
    _update();
    Timer.run(_update);
  }

  void _update() {
    values = new List.from([b.toString()]);
    print(values);
    b = !b;
  }
}

Replace FORM_DIRECTIVES with formDirectives in one of the tests, this seems to
work.

PiperOrigin-RevId: 163141550


// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test that dump-info has no effect on the compiler output.

import 'dart:io';

import 'package:path/path.dart' as path;
import 'package:expect/expect.dart';

import 'launch_helper.dart' show dart2JsCommand;

copyDirectory(Directory sourceDir, Directory destinationDir) {
  for (var element in sourceDir.listSync()) {
    if (element.path.endsWith('.git')) continue;
    String newPath =
        path.join(destinationDir.path, path.basename(element.path));
    if (element is File) {
      element.copySync(newPath);
    } else if (element is Directory) {
      Directory newDestinationDir = new Directory(newPath);
      newDestinationDir.createSync();
      copyDirectory(element, newDestinationDir);
    }
  }
}

void main() {
  Directory tmpDir = Directory.systemTemp.createTempSync('dump_info_test_');
  Directory out1 = new Directory.fromUri(tmpDir.uri.resolve('without'));
  out1.createSync();
  Directory out2 = new Directory.fromUri(tmpDir.uri.resolve('with'));
  out2.createSync();
  Directory sunflowerDir =
      new Directory.fromUri(Uri.base.resolve('third_party/sunflower'));

  print("Copying '${sunflowerDir.path}' to '${tmpDir.path}'.");
  copyDirectory(sunflowerDir, tmpDir);
  try {
    var command =
        dart2JsCommand(['--out=without/out.js', 'web/sunflower.dart']);
    print('Run $command');
    var result = Process.runSync(Platform.resolvedExecutable, command,
        workingDirectory: tmpDir.path);
    print('exit code: ${result.exitCode}');
    print('stdout:');
    print(result.stdout);
    print('stderr:');
    print(result.stderr);
    Expect.equals(0, result.exitCode);
    String output1 = new File.fromUri(tmpDir.uri.resolve('without/out.js'))
        .readAsStringSync();

    command = dart2JsCommand(
        ['--out=with/out.js', 'web/sunflower.dart', '--dump-info']);
    print('Run $command');
    result = Process.runSync(Platform.resolvedExecutable, command,
        workingDirectory: tmpDir.path);
    print('exit code: ${result.exitCode}');
    print('stdout:');
    print(result.stdout);
    print('stderr:');
    print(result.stderr);
    Expect.equals(0, result.exitCode);
    String output2 =
        new File.fromUri(tmpDir.uri.resolve('with/out.js')).readAsStringSync();

    print('Compare outputs...');
    Expect.equals(output1, output2);
    print('Done');
  } finally {
    print("Deleting '${tmpDir.path}'.");
    tmpDir.deleteSync(recursive: true);
  }
}

Add dump-info end to end test

Add dump-info end to end test

This test gives the same coverage we are getting from the mist-dump-info bots
today.

Change-Id: Ie6f7f8eba9b5de5c3983d9066aa29709ae4200a4
Reviewed-on: https://dart-review.googlesource.com/63541
Reviewed-by: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>


// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

class A implements B {
  var x;
  A(Object this.x);
}

class B {
  factory B(String s) = A;
}

main() {
  B(42 as dynamic); //# 01: runtime error
}

Test of dynamic argument type check for redirecting factories.

Verify that dynamic type checks are inserted to check arguments to
redirecting factories against the redirector, even when they would
be valid arguments to the redirectee.

Closes https://github.com/dart-lang/sdk/issues/31590

Change-Id: Ic439fd1e125ae8ae156e611402782413600de98e
Reviewed-on: https://dart-review.googlesource.com/71860
Reviewed-by: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>
Commit-Queue: Aske Simon Christensen <589eb3fd9a84f06d0ac46d3aa71dddcfb0814ccd@google.com>


/*
 * Package : dartivity_database
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 05/011/2015
 * Copyright :  S.Hamblett 2015
 */

part of dartivity_database;

class DartivityCache {
  /// The cache
  Map<String, dynamic> _cache;

  DartivityCache() {
    _cache = new Map<String, dynamic>();
  }

  /// get
  dynamic get(String key) {
    if (_cache.containsKey(key)) {
      return _cache[key];
    } else {
      return null;
    }
  }

  /// put
  put(String key, dynamic resource) {
    _cache[key] = resource;
  }

  /// clear
  void clear() {
    _cache.clear();
  }
}

Add the general purpose cache

Add the general purpose cache


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#library('utf8');

class Utf8Decoder {
  final List<int> bytes;
  final int offset;
  final int length;

  Utf8Decoder(List<int> this.bytes, int this.offset, int this.length);

  String toString() {
    return new String.fromCharCodes(decodeUtf8(bytes.getRange(offset, length)));
  }

  static int decodeTrailing(int byte) {
    if (byte < 0x80 || 0xBF < byte) {
      throw new Exception('Cannot decode UTF-8 $byte');
    } else {
      return byte & 0x3F;
    }
  }

  static List<int> decodeUtf8(List<int> bytes) {
    List<int> result = new List<int>();
    for (int i = 0; i < bytes.length; i++) {
      if (bytes[i] < 0x80) {
        result.add(bytes[i]);
      } else if (bytes[i] < 0xC2) {
        throw new Exception('Cannot decode UTF-8 @ $i');
      } else if (bytes[i] < 0xE0) {
        int char = (bytes[i++] & 0x1F) << 6;
        char += decodeTrailing(bytes[i]);
        if (char < 0x80) {
          throw new Exception('Cannot decode UTF-8 @ ${i-1}');
        } else {
          result.add(char);
        }
      } else if (bytes[i] < 0xF0) {
        int char = (bytes[i++] & 0x0F) << 6;
        char += decodeTrailing(bytes[i++]);
        char <<= 6;
        char += decodeTrailing(bytes[i]);
        if (char < 0x800 || (0xD800 <= char && char <= 0xDFFF)) {
          throw new Exception('Cannot decode UTF-8 @ ${i-2}');
        } else {
          result.add(char);
        }
      } else if (bytes[i] < 0xF8) {
        int char = (bytes[i++] & 0x07) << 6;
        char += decodeTrailing(bytes[i++]);
        char <<= 6;
        char += decodeTrailing(bytes[i++]);
        char <<= 6;
        char += decodeTrailing(bytes[i]);
        if (char < 0x10000) {
          throw new Exception('Cannot decode UTF-8 @ ${i-3}');
        } else {
          result.add(char);
        }
      } else {
        throw new Exception('Cannot decode UTF-8 @ $i');
      }
    }
    return result;
  }
}

Move UTF-8 decoder to utils.
Review URL: http://codereview.chromium.org//9185046

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@3231 260f80e4-7a28-3924-810f-c04153c831b5


/// More Dart — Literally.
export 'package:more/async.dart';
export 'package:more/cache.dart';
export 'package:more/char_matcher.dart';
export 'package:more/collection.dart';
export 'package:more/hash.dart';
export 'package:more/iterable.dart';
export 'package:more/math.dart';
export 'package:more/number.dart';
export 'package:more/ordering.dart';
export 'package:more/printer.dart';
export 'package:more/tuple.dart';

Create a parent package that imports all extensions at once.


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test for type literals as compile-time constants.

class C<T> {
  void m() {
    const List lst = const [
                            T /// 01: compile-time error
                             ];
  }
}

main() {
  new C().m();
}

Add const type literal test.

Add const type literal test.

BUG=
R=karlklose@google.com

Review URL: https://codereview.chromium.org//25535009

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@28794 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

class A native "*A" {}

main() {
  var a = [new Object()];
  Expect.isFalse(a[0] is A);
}

Add a proper test for bug fixed in https://codereview.chromium.org/12481013/: using a html test is too heavy weight.
Review URL: https://codereview.chromium.org//12426003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@19605 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// This file is responsible for accepting the results of a map oepration
// and structuring it ready to be passed to the reducer

// This version performs the shuffling in memory and so is a potential scaling
// bottleneck
Map shuffle(List<Map> data) {
  Map results = {};
  for (Map kv in data) {
    assert(kv.length == 1);
    var key = kv.keys.first;
    var value = kv.values.first;

    results.putIfAbsent(key, () => []);
    results[key].add(value);
  }
  return results;
}

_main() {
  print (shuffle([{"a" : 1}, {"b" : 2}, {"a" : 2}]));
}

Add an in memory shuffler

Add an in memory shuffler


import 'dart:async';

import 'package:angular/angular.dart';
import 'package:http/http.dart';

import '../data_model/create_user_request.pb.dart';
import '../data_model/rule.pb.dart';

/// A class to interact with the Rules Builder server.
@Injectable()
class RuleService {
  /// The base URL of the Rules Builder server.
  static const serverUrl =
      'https://rules-server-dot-spreadsheet-dv360-plugin.uc.r.appspot.com';

  /// The endpoint for operations on users.
  static const usersEndpoint = '$serverUrl/users';

  /// The endpoint for operations on rules.
  static const rulesEndpoint = '$serverUrl/rules';

  /// Creates a user using the user's ID token and refresh token.
  Future<void> createUser(String idToken, String refreshToken) async {
    final headers = {
      'Content-Type': 'application/x-protobuf',
      'Authorization': 'Bearer $idToken'
    };
    final createUserRequest = CreateUserRequest()..refreshToken = refreshToken;
    await post(usersEndpoint,
        body: createUserRequest.writeToBuffer(), headers: headers);
  }

  /// Creates a rule using the user's ID token and rule proto.
  Future<void> createRule(String idToken, Rule rule) async {
    final headers = {
      'Content-Type': 'application/x-protobuf',
      'Authorization': 'Bearer $idToken'
    };
    await post(rulesEndpoint, body: rule.writeToBuffer(), headers: headers);
  }
}

Add rule service in client to interact with rule server


// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
library scissors.test.path_resolver_test;

import 'dart:async';
import 'dart:io';

import 'package:test/test.dart';
import 'package:scissors/src/utils/path_resolver.dart' show pathResolver;
import 'package:scissors/testing/transformer_test_utils.dart';

main() {
  if (Platform.environment['TRAVIS'] == 'true') {
    print("WARNING: Skipping path resolver tests on Travis.");
    return;
  }

  group('pathResolver', () {

    var executables = {
      'sassc': pathResolver.defaultSassCPath,
      'pngcrush': pathResolver.defaultPngCrushPath,
      'cssjanus': pathResolver.defaultCssJanusPath,
      'java': pathResolver.defaultJavaPath,
    };
    var files = {
      'jruby': pathResolver.defaultJRubyPath,
      'ruby sass': pathResolver.defaultRubySassPath,
      'closure': pathResolver.defaultClosureCompilerJarPath
    };
    var dirs = {
      'compass stylesheets': pathResolver.defaultCompassStylesheetsPath,
    };

    check(String kind, String name, String path, Future action(String resolved)) {
      if (path == null) {
        print("WARNING: No path set for $name.");
      } else {
        test('finds $kind $name ($path)', () async {
          var resolved = await pathResolver.resolvePath(path);
          await action(resolved);
        });
      }
    }

    executables.forEach((name, path) {
      check('executable', name, path, (resolved) async {
        expect(hasExecutable(resolved), true);
      });
    });
    files.forEach((name, path) {
      check('file', name, path, (resolved) async {
        expect(await new File(resolved).exists(), true);
      });
    });
    dirs.forEach((name, path) {
      check('directory', name, path, (resolved) async {
        expect(await new Directory(resolved).exists(), true);
      });
    });
  });
}

Add test for path resolution

Add test for path resolution


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';
import 'package:args/args.dart';
import 'package:http/http.dart' as http;
import 'package:source_maps/source_maps.dart';

ArgParser parser = new ArgParser()
  ..addFlag('inline',
      abbr: 'i',
      negatable: true,
      help: 'Inline untranslatable parts..',
      defaultsTo: false);

main(List<String> arguments) async {
  ArgResults options = parser.parse(arguments);

  if (options.rest.length != 1) {
    print('Usage: <script.dart> [<options>] <file or url for source map file>\n'
        'Options:\n'
        '${parser.usage}');
    exit(2);
  }

  String url = options.rest[0];
  String data;
  if (url.startsWith("http://") || url.startsWith("https://")) {
    data = (await http.get(url)).body;
  } else {
    data = new File(url).readAsStringSync();
  }

  SingleMapping sourceMap = parse(data);

  print("Now paste the stacktrace here. Finish with at least 3 empty lines...");

  int emptyInARow = 0;
  List<String> lines = [];
  while (true) {
    String line = stdin.readLineSync();
    if (line == null) break;
    if (line == "") {
      ++emptyInARow;
    } else {
      lines.add(line);
      emptyInARow = 0;
    }

    if (emptyInARow >= 3) break;
  }

  List<String> tailMessages = [];

  for (String line in lines) {
    Iterable<Match> ms = new RegExp(r"(\d+):(\d+)").allMatches(line);
    if (ms.isEmpty) {
      if (options['inline']) {
        print("----- (unparseable) -----");
      } else {
        tailMessages.add("Unparseable line: $line");
      }
      continue;
    }
    Match m = ms.first;
    int l = int.parse(m.group(1));
    int c = int.parse(m.group(2));
    SourceMapSpan span = sourceMap.spanFor(l, c);
    if (span?.start == null) {
      if (options['inline']) {
        print("----- (unparseable) -----");
      } else {
        tailMessages.add("No sourcemap entry for line line: $line");
      }
      continue;
    }
    print(span.start.toolString);
  }

  if (tailMessages.isNotEmpty) {
    print("");
    print("Messages:");
    print("");
    for (String line in tailMessages) {
      print(line);
    }
  }
}

Test tool: translate dart2js stacktrace

Test tool: translate dart2js stacktrace

This is a first stab at an internal tool that can translate a dart2js
stacktrace to a "dart stacktrace".

First use figuring out a stacktrace in observatory which was done like
this:

dart translate_dart2js_stacktrace.dart http://localhost:9999/main.dart.js.map
<then copy paste the stacktrace into stdin, followed by a few empty lines>

Change-Id: Id33e66182213a3005bba3338df7dd638218609c2
Reviewed-on: https://dart-review.googlesource.com/3140
Reviewed-by: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Test for initialization of dispatchPropertyName.

import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show Native;

@Native("Foo")
class Foo {
  String method(String x) native;
}

makeFoo() native;

void setup() native r"""
function Foo() {}
Foo.prototype.method = function(x) { return 'Foo ' + x; }

self.makeFoo = function() { return new Foo(); }
""";

main() {
  setup();

  // If the dispatchPropertyName is uninitialized, it will be `undefined` or
  // `null` instead of the secret string or Symbol. These properties on
  // `Object.prototype` will be retrieved by the lookup instead of `undefined`
  // for the dispatch record.
  JS('', r'self.Object.prototype["undefined"] = {}');
  JS('', r'self.Object.prototype["null"] = {}');
  Expect.equals('Foo A', makeFoo().method('A'));

  // Slightly different version that has malformed dispatch records.
  JS('', r'self.Object.prototype["undefined"] = {p: false}');
  JS('', r'self.Object.prototype["null"] = {p: false}');
  Expect.equals('Foo B', makeFoo().method('B'));
}

Add another test for initializing dispatchPropertyName that runs outside the browser

R=johnniwinther@google.com

BUG=

Review URL: https://codereview.chromium.org/2359023002 .


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
import 'package:compiler/implementation/types/types.dart'
    show ContainerTypeMask, TypeMask;

import 'memory_compiler.dart';
import 'compiler_helper.dart' show findElement;
import 'type_mask_test_helper.dart';

const TEST = const {
  'main.dart' : r'''
import 'dart:typed_data';

var myList = new Float32List(42);
var myOtherList = new Uint8List(32);

main() {
  var a = new Float32List(9);
  return myList[0] + myOtherList[0];
}
'''};

void main() {
  var compiler = compilerFor(TEST);
  asyncTest(() => compiler.run(Uri.parse('memory:main.dart')).then((_) {
    var typesInferrer = compiler.typesTask.typesInferrer;

    checkType(String name, type, length) {
      var element = findElement(compiler, name);
      TypeMask mask = typesInferrer.getTypeOfElement(element);
      Expect.isTrue(mask.isContainer);
      ContainerTypeMask container = mask;
      Expect.equals(type, simplify(container.elementType, compiler), name);
      Expect.equals(container.length, length);
    }

    checkType('myList', compiler.typesTask.numType, 42);
    checkType('myOtherList', compiler.typesTask.uint31Type, 32);
  }));
}

Add a test for inferring the length of typed data lists.

BUG=
R=floitsch@google.com

Review URL: https://codereview.chromium.org//424663003

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@38722 260f80e4-7a28-3924-810f-c04153c831b5


import 'dart:io';

class IpAddressHelper {
  /// Returns true if IP address is not a loopback, link local, or private IP
  ///
  /// Throws a generic exception if [ipAddress] cannot be parsed
  static bool isPublic(String ipAddress) {
    final parsedAddress = InternetAddress.tryParse(ipAddress);

    if (parsedAddress == null) {
      throw Exception();
    }

    if (parsedAddress.isLinkLocal || parsedAddress.isLoopback) {
      return false;
    }

    if (parsedAddress.type == InternetAddressType.IPv4) {
      RegExp privateV4 = RegExp(
        r"(^192\.168\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^172\.([1][6-9]|[2][0-9]|[3][0-1])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)|(^10\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])\.([0-9]|[0-9][0-9]|[0-2][0-5][0-5])$)",
      );

      if (privateV4.hasMatch(parsedAddress.address)) {
        return false;
      }
    }

    if (parsedAddress.type == InternetAddressType.IPv6) {
      if (parsedAddress.address.startsWith('fe80')) {
        return false;
      }
    }

    return true;
  }
}

Create helper to detect public IP addresses.


import "package:unittest/unittest.dart";

import "package:furi/furi.dart";

class STest extends ToStringOp {
  String call() => "my calculated string";
}

void main(){
  group( "basic Op extension", (){
    test( "ToStringOp", (){
       expect( new STest()(), equals("my calculated string") );
    });
  });
}

Add some Op tests, and some more docs.

Add some Op tests, and some more docs.


import 'dart:io';

void main() {
  int a = int.parse(stdin.readLineSync() ?? '');
  int b = int.parse(stdin.readLineSync() ?? '');

  int soma = a + b;

  print("SOMA = $soma");
}

Solve Simple Sum in dart

Solve Simple Sum in dart


import 'dart:io';

void main() {
  String _ = stdin.readLineSync() ?? '';
  double a = double.parse(stdin.readLineSync() ?? '');
  double b = double.parse(stdin.readLineSync() ?? '');
  double salary = a + b * 0.15 * 100 / 100;

  print("TOTAL = R\$ ${salary.toStringAsFixed(2)}");
}

Solve Salary with Bonus in dart

Solve Salary with Bonus in dart


// Copyright (c) 2020, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

class C {
  C e() => this;
  C operator -() => this;
  C operator ~() => this;
}

void main() {
  final C? c = new C();
  /**/ -c?.e();
  //    ^^^^^^
  // [analyzer] COMPILE_TIME_ERROR.UNCHECKED_USE_OF_NULLABLE_VALUE
  //   ^
  // [cfe] Operator 'unary-' cannot be called on 'C?' because it is potentially null.

  /**/ ~c?.e();
  //    ^^^^^^
  // [analyzer] COMPILE_TIME_ERROR.UNCHECKED_USE_OF_NULLABLE_VALUE
  //   ^
  // [cfe] Operator '~' cannot be called on 'C?' because it is potentially null.
}

Test error for -e and ~e when e is potentially nullable

This verifies that the operators `unary-` and `~` do not participate
in null-shorting. Cf. https://github.com/dart-lang/language/issues/1081.

Change-Id: Iba446724f00c1c4aaedb4be4425e69fb52cdb5c9
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/166627
Reviewed-by: Lasse R.H. Nielsen <80295e4ef244a07779f93eaa95d582bad8e316a5@google.com>
Commit-Queue: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// SharedOptions=--enable-experiment=non-nullable

// Test that it is an error for a class to extend, implement, or mixin the type
// Never.
class A extends Never {} //# 01: compile-time error

class A implements Never {} //# 02: compile-time error

class A with Never {} //# 03: compile-time error

mixin M on Never {} //# 04: compile-time error

main() {}

Add a test of creating a subtype of Never

Change-Id: I9d28868667667cca5eb122e33226b21850b062bd
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/101067
Reviewed-by: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>
Reviewed-by: Paul Berry <72d414e3a99fb120308437779d51667bcc0984eb@google.com>
Commit-Queue: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>


import 'package:meta/meta.dart';
import 'package:quiver/strings.dart';

enum CastType {
  bool,
  int,
  double,
  string,
}

class ValueHelper {
  /// Casts [value] to specified [CastType].
  ///
  /// If casting fails returns null.
  /// If nullEmptyString is true returns null when item is empty string.
  static dynamic cast({
    @required dynamic value,
    @required CastType type,
    bool nullEmptyString = true,
  }) {
    if (type == CastType.bool) {
      if ([1, true, '1', 'true'].contains(value)) {
        return true;
      } else if ([0, false, '0', 'false'].contains(value)) {
        return false;
      } else {
        return null;
      }
    }
    if (type == CastType.int) {
      return int.tryParse(value.toString());
    }
    if (type == CastType.double) {
      return double.tryParse(value.toString());
    }
    if (type == CastType.string) {
      if (isEmpty(value)) {
        if (nullEmptyString) {
          return null;
        } else {
          return '';
        }
      } else {
        return value.toString();
      }
    }
  }
}

Create helper for casting value to type.


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:html' as dom;

import 'package:angular/angular.dart';
import 'package:js/js_util.dart' as js_util;
import 'package:angular_components/utils/browser/dom_service/dom_service.dart';

/// Directive for elements able to be activated through mouse or keyboard, like
/// list elements.
///
/// Will scroll the item into view as long as it was made active when mouse is
/// not hovering over it.
@Directive(selector: '[itemActive]')
class ActiveItemDirective {
  /// Dom element of the item, that will be scrolled to view on activate.
  dom.HtmlElement _element;

  /// An instance of DomService, used to coordinate scrolling.
  DomService _domService;

  bool _active = false;

  /// Whether the element is active.
  @HostBinding('class.active')
  bool get active => _active;

  ActiveItemDirective(this._element, this._domService);

  /// Marks item as active from keyboard selection.
  @Input()
  set itemActive(bool value) {
    if (value == _active) return;
    _active = value;
    if (_active && !_hasHover) {
      _domService.scheduleWrite(() {
        try {
          var options = js_util.newObject();
          js_util.setProperty(options, 'block', 'nearest');
          js_util.setProperty(options, 'inline', 'nearest');
          js_util.callMethod(_element, 'scrollIntoView', [options]);
        } catch (_) {
          _element.scrollIntoView();
        }
      });
    }
  }

  /// Whether the element has hover.
  bool _hasHover = false;

  @HostListener('mouseenter')
  void onMouseEnter() {
    _hasHover = true;
  }

  @HostListener('mouseleave')
  void onMouseLeave() {
    _hasHover = false;
  }
}

Create a ActiveItemDirective that will replace the ActiveItemMixin.

This allows more performant code when lists aren't using the active logic, which seems to be a good amount of the instances, and allows for lists to work better on mobile when they don't use this logic. Anything that has a mouseover, mouseenter, or mouseleave events will not sent a click event on the first touch event.

See https://github.com/dart-lang/angular_components_example/issues/66

PiperOrigin-RevId: 203634880


@TestOn('!windows')

import 'package:mono_repo/src/package_config.dart';
import 'package:term_glyph/term_glyph.dart' as glyph;
import 'package:test/test.dart';
import 'package:test_descriptor/test_descriptor.dart' as d;
import 'package:test_process/test_process.dart';

import 'shared.dart';

void main() {
  glyph.ascii = false;

  test('integration', () async {
    await d.file('mono_repo.yaml', 'pretty_ansi: false').create();
    await d.dir('pkg_a', [
      d.file(
        monoPkgFileName,
        _monoPkgContent,
      ),
      d.file('pubspec.yaml', '''
name: pkg_a
      ''')
    ]).create();

    await d.dir('pkg_b', [
      d.file(
        monoPkgFileName,
        _monoPkgContent,
      ),
      d.file('pubspec.yaml', '''
name: pkg_b

dependencies:
  not_a_package_at_all: any
      ''')
    ]).create();

    await d.dir('pkg_c', [
      d.file(
        monoPkgFileName,
        _monoPkgContent,
      ),
      d.file('pubspec.yaml', '''
name: pkg_c
''')
    ]).create();

    testGenerateTravisConfig(
      printMatcher: stringContainsInOrder([
        'package:pkg_a',
        'package:pkg_b',
        'Make sure to mark `tool/travis.sh` as executable.'
      ]),
    );

    //print(File(p.join(d.sandbox, travisShPath)).readAsStringSync());

    final proc = await TestProcess.start(
      '/bin/bash',
      [
        'tool/travis.sh',
        'dartanalyzer',
      ],
      environment: {
        'PKGS': 'pkg_a pkg_b pkg_c',
      },
      workingDirectory: d.sandbox,
    );

    final output = await proc.stdoutStream().join('\n');
    expect(output, r'''
PKG: pkg_a
Resolving dependencies...
No dependencies changed.

PKG: pkg_a; TASK: dartanalyzer
dartanalyzer .
Analyzing pkg_a...

PKG: pkg_b
Resolving dependencies...
pub upgrade failed

PKG: pkg_c
Resolving dependencies...
No dependencies changed.

PKG: pkg_c; TASK: dartanalyzer
dartanalyzer .
Analyzing pkg_c...
''');

    await proc.shouldExit(3);
  });
}

const _monoPkgContent = r'''
dart:
 - stable

stages:
  - some_things:
    - dartanalyzer:
''';

Validate the output and behavior of the travis shell script


import 'dart:async';
import 'package:tictac/util.dart';

main(){
  var exitCodes = [];
  var files = findTestFiles();
  for(final test in files){
    exitCodes.add(startProcess([test]));
  }
  Future.wait(exitCodes).then((codes){
    for(int i=0; i< codes.length; i++){
      if(codes[i] != 0){
        print('Error running ${files[i]}. Exit code: ${codes[i]}');
      }
    }
  });
}

Add tictac test command to run all tests in test dir.


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:_js_helper";
import "package:expect/expect.dart";

// Test that native objects cannot accidentally or maliciously be mistaken for
// Dart objects.
// The difference between fake_thing_test and fake_thing_2_test is the
// presence of a used declared native class.

class Thing {
}

@Native("NT")
class NativeThing {
}

make1() native;
make2() native;
make3() native;

void setup() native r"""
function A() {}
A.prototype.$isThing = true;
make1 = function(){return new A;};
make2 = function(){return {$isThing: true}};
function NT() {}
NT.prototype.$isThing = true;
make3 = function(){return new NT;};
""";

var inscrutable;
main() {
  setup();
  inscrutable = (x) => x;

  var a = new Thing();
  var b = make1();
  var c = make2();
  var d = make3();
  Expect.isTrue(inscrutable(a) is Thing);
  Expect.isFalse(inscrutable(b) is Thing);
  Expect.isFalse(inscrutable(c) is Thing);
  Expect.isFalse(inscrutable(d) is Thing);
}

Add version of fake_thing_test that is expected to passes.

BUG=
R=karlklose@google.com

Review URL: https://codereview.chromium.org//516923002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@39900 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2021, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Regression test for https://github.com/dart-lang/sdk/issues/46319.

import 'dart:async';

void main() {}

Future<T> fn<T>() {
  // DDC was crashing during compilation when trying to tag the following
  // function expression with a type.
  return hn(() => gn());
}

S gn<S>() {
  throw 'in gn';
}

Future<R> hn<R>(FutureOr<R> Function() foo) {
  throw 'in hn';
}

[ddc] Add unspecified nullability regression test

Change-Id: If82ef47aac1d67c5f6db636522ed0ef7de180f8d
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/203121
Reviewed-by: Mark Zhou <654f5fe0c4ca6c799b0e735dcf3fc1c389f35bf9@google.com>
Reviewed-by: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>


import 'package:flutter/material.dart';
import 'package:websafe_svg/websafe_svg.dart';

class IconCard extends StatelessWidget {
  final String assetPath;
  final Color backgroundColor;
  final Widget details;

  const IconCard({
    Key key,
    @required this.assetPath,
    this.backgroundColor,
    this.details,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Stack(
          children: [
            Container(
              height: 100,
              color: backgroundColor,
            ),
            if (backgroundColor != null)
              Positioned.fill(
                child: Container(
                  color: Colors.black.withOpacity(0.6),
                ),
              ),
            Positioned.fill(
              child: Padding(
                padding: const EdgeInsets.all(4),
                child: Row(
                  children: [
                    AspectRatio(
                      aspectRatio: 2 / 3,
                      child: Padding(
                        padding: const EdgeInsets.all(4),
                        child: WebsafeSvg.asset(assetPath),
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 8),
                        child: details,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Create icon card global widget.

Create icon card global widget.


/// Returns [code] with filtered out doc tag comment lines.
String removeDocTags(String code) =>
    code.split('\n').where(_isNotDocTagComment).join('\n');

final _docTags = ['#docregion', '#enddocregion', '#docplaster'];
final _commentPrefixes = ['//', '<--'];

/// Returns true if [line] is a not a comment line with a doc tag.
bool _isNotDocTagComment(String line) => !_isDocTagComment(line);

/// Returns true if [line] is a comment line with a doc tag.
bool _isDocTagComment(String line) =>
    _isComment(line) && _docTags.any((String tag) => line.contains(tag));

/// Returns true if [line] starts with any of the prefixes indicating the start
/// of a doc tag comment.
bool _isComment(String line) =>
    _commentPrefixes.any((String prefix) => line.trimLeft().startsWith(prefix));

Add logic to remove doc tag comments from the examples code.


library inventory;

App app(name, {price: 0}) => new App(name)..netPrice = price;
Mobile mobile([name]) => new Mobile()..name = name;
Tablet tablet([name]) => new Tablet()..name = name;
Laptop laptop([name]) => new Laptop()..name = name;

abstract class Inventory {
  String name;
  Inventory(this.name);

  double netPrice;
  double discountPrice() => netPrice;

  void accept(vistor);
}

class InventoryCollection {
  String name;
  List<Inventory> stuff = [];
  InventoryCollection(this.stuff);

  void accept(visitor) {
    stuff.forEach((thing) { thing.accept(visitor); });
  }
}

abstract class Equipment extends Inventory {
  Equipment(name): super(name);
  int watt;
}

class App extends Inventory {
  App(name): super(name);
  void accept(visitor) { visitor.visitApp(this); }
}

abstract class EquipmentWithApps extends Equipment {
  EquipmentWithApps(name): super(name);
  List<App> apps = [];
}

class Mobile extends EquipmentWithApps {
  Mobile(): super('Mobile Phone');
  double netPrice = 350.00;
  void accept(visitor) {
    apps.forEach((app) { app.accept(visitor); });
    visitor.visitMobile(this);
  }
}

class Tablet extends EquipmentWithApps {
  Tablet(): super('Tablet');
  double netPrice = 400.00;
  void accept(visitor) {
    apps.forEach((app) { app.accept(visitor); });
    visitor.visitTablet(this);
  }
}

class Laptop extends Equipment {
  Laptop(): super('Laptop');
  double netPrice = 1000.00;
  double discountPrice() => netPrice * .9;
  void accept(visitor) { visitor.visitLaptop(this); }
}

Add internal iterator node (for visitors)

It is currently an exact copy of the regular inventory node structure


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:sky' as sky;
import 'package:sky/framework/fn2.dart';

class ContainerApp extends App {
  UINode build() {
    return new EventListenerNode(
      new Rectangle(0xFF00FFFF),
      onPointerDown: _handlePointerDown);
  }

  void _handlePointerDown(sky.PointerEvent event) {
    print("_handlePointerDown");
  }
}

void main() {
  new ContainerApp();
}

Mark fn2's EventListenerNode work for PointerEvent

Prevously we listened for events on the document and then walked up the
component hierarchy looking for EventListenerNodes. Now we do something similar
by hooking the event dispatching logic in the AppView.

R=eseidel@chromium.org

Review URL: https://codereview.chromium.org/1153343004


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Add fields with data about the test run and the commit tested, and
// with the result on the last build tested, to the test results file.

import 'dart:convert';
import 'dart:io';

import 'results.dart';

main(List<String> args) async {
  final resultsPath = args[0];
  final priorResultsPath = args[1];
  final flakyPath = args[2];
  final priorFlakyPath = args[3];
  final builderName = args[4];
  final buildNumber = args[5];
  final commitTime = int.parse(args[6]);
  final commitHash = args[7];
  final newResultsPath = args[8];
  // Load the input and the flakiness data if specified.
  final results = await loadResultsMap(resultsPath);
  final priorResults = await loadResultsMap(priorResultsPath);
  final flakes = await loadResultsMap(flakyPath);
  final priorFlakes = await loadResultsMap(priorFlakyPath);

  for (final String key in results.keys) {
    final Map<String, dynamic> result = results[key];
    final Map<String, dynamic> priorResult = priorResults[key];
    final Map<String, dynamic> flaky = flakes[key];
    final Map<String, dynamic> priorFlaky = priorFlakes[key];
    result['commit_hash'] = commitHash;
    result['commit_time'] = commitTime;
    result['build_number'] = buildNumber;
    result['builder_name'] = builderName;
    result['flaky'] = (flaky != null);
    result['previous_flaky'] = (priorFlaky != null);
    if (priorResult != null) {
      result['previous_result'] = priorResult['result'];
      result['previous_commit_hash'] = priorResult['commit_hash'];
      result['previous_commit_time'] = priorResult['commit_time'];
      result['previous_build_number'] = priorResult['build_number'];
    }
    result['changed'] = (result['result'] != result['previous_result'] ||
        result['flaky'] != result['previous_flaky']);
  }
  final sink = new File(newResultsPath).openWrite();
  final sorted = results.keys.toList()..sort();
  for (final key in sorted) {
    sink.writeln(jsonEncode(results[key]));
  }
  sink.close();
}

[infra] Add a script that appends fields with previous results to result data

Change-Id: I19ea044308744c16caee47f4755a18fc19990c77
Reviewed-on: https://dart-review.googlesource.com/c/94544
Reviewed-by: Jonas Termansen <092ec58085ae5e368bc39d18752740ff81a2d09c@google.com>


import 'package:test/test.dart';
import 'package:aqueduct/aqueduct.dart';

main() {
  test("APIResponse empty schema", () {
    var response = new APIResponse()
        ..statusCode = 200;
    expect(response.asMap()["schema"], isNull);
  });
}

Add test for null schema

Add test for null schema


import 'package:version/version.dart';

class MinimumVersion {
  /// Minimum Tautulli version required for Tautulli Remote to function.
  static Version tautulliServer = Version(2, 6, 6);
}

Add minimum server version requirement.

Add minimum server version requirement.


// Copyright (c) 2019, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Post results from Dart continuous integration testers to Cloud Pub/Sub.

import 'dart:convert';
import 'dart:io';

import 'package:args/args.dart';
import 'package:http/http.dart' as http;

void usage(ArgParser parser) {
  print('''
Usage: post_results_to_pubsub.dart [OPTIONS]
Posts Dart CI results as messages to Google cloud pubsub

The options are as follows:

${parser.usage}''');
  exit(1);
}

// Pubsub messages must be < 10MB long. This lower limit lets us add
// a full record at the end.
const messageLengthLimit = 9000000;
const postUrl =
    'https://pubsub.googleapis.com/v1/projects/dart-ci/topics/results:publish';

main(List<String> args) async {
  final parser = new ArgParser();
  parser.addFlag('help', help: 'Show the program usage.', negatable: false);
  parser.addOption('auth_token',
      abbr: 'a',
      help: 'Authorization token with a scope including pubsub publish.');
  parser.addOption('result_file',
      abbr: 'f', help: 'File containing the results to send');

  final options = parser.parse(args);
  if (options['help']) {
    usage(parser);
  }

  var client = http.Client();

  var lines = await File(options['result_file']).readAsLines();
  var token = await File(options['auth_token']).readAsString();
  // Construct pubsub messages.
  var line = 0;
  while (line < lines.length) {
    var message = StringBuffer();
    message.write('[');
    message.write(lines[line++]);
    var messageLines = 1;
    while (message.length < messageLengthLimit && line < lines.length) {
      message.write(',\n');
      message.write(lines[line++]);
      messageLines++;
    }
    message.write(']');
    var base64data = base64Encode(utf8.encode(message.toString()));
    var jsonMessage =
        '{"messages": [{"attributes": {}, "data": "$base64data"}]}';
    var headers = {'Authorization': 'Bearer $token'};
    var response =
        await client.post(postUrl, headers: headers, body: jsonMessage);
    print('Sent pubsub message containing ${messageLines} results');
    print('Status ${response.statusCode}');
    print('Response: ${response.body}');
  }
  client.close();
}

[infra] Add script to publish results.json to Cloud Pub/Sub

Change-Id: I0f04c749710e4882330d3e2fb09a4123264f3009
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/111321
Reviewed-by: Alexander Thomas <29642742b6693024c89de8232f2e2542cf7eedf7@google.com>


/// Print Location details
import 'dart:io';
import 'package:args/args.dart';
import 'package:timezone/standalone.dart';
import 'package:timezone/timezone.dart';

void main(List<String> arguments) {
  // Parse CLI arguments
  final parser = new ArgParser()
  ..addOption('source', abbr: 'd', defaultsTo: 'packages/timezone/data/$dataDefaultFilename')
  ..addOption('location', abbr: 'l');

  final argResults = parser.parse(arguments);

  final String source = argResults['source'];
  final String location = argResults['location'];

  if (source.isEmpty || location == null || location.isEmpty) {
    print(parser.getUsage());
    exit(64);
  }

  initializeTimeZone(source).then((_) {
    final l = getLocation(location);

    for (var i = 0; i < l.transitionAt.length; i++) {
      final t = l.transitionAt[i];
      final z = l.zones[l.transitionZone[i]];

      final dt = new DateTime.fromMillisecondsSinceEpoch(t, isUtc: true);
      print('${dt.toIso8601String()} $z');
    }

    exit(0);
  });
}

Add script to dump location data

Add script to dump location data


import 'package:angular2/angular2.dart';
import 'package:angular_test/angular_test.dart';
import 'package:test/test.dart';

void main() {
  test('$ViewChild#nativeElement should be accessible', () async {
    final fixture = await new NgTestBed<ViewChildTest>().create();
    await fixture.update((component) {
      expect(component.portalElement, isNull);
      component.showChildHost = true;
    });
    await fixture.update((component) {
      expect(component.portalElement.nativeElement, isNotNull);
      expect(component.containerElement.nativeElement, isNotNull);
      expect(component.markerViewContainer, isNotNull);
    });
  });
}

@Component(
  selector: 'view-child-test',
  template: r'''

      <template [ngIf]="showChildHost">

      </template>

  ''',
  directives: const [
    ChildHostDirective,
    NgIf,
  ],
)
class ViewChildTest {
  @ViewChild('portal')
  ElementRef portalElement;

  @ViewChild('container')
  ElementRef containerElement;

  @ViewChild('marker', read: ViewContainerRef)
  ViewContainerRef markerViewContainer;

  var showChildHost = false;
}

@Directive(
  selector: '[childHost]',
)
class ChildHostDirective {}

test(ViewChild): Add a regression test for accessing @ViewChild->ElementRef.

We had a rollback due to using identical(foo.runtimeType, otherType) that would have been caught if we had at least one dart2js test executing this code branch. I'd like this to be the first one.

# Only impacting blaze test //third_party/dart/angular2:all

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=151021743


// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/**
 * Tests internationalization of messages using the basic example as a template.
 */
#library('intl_message_test_2');

#import('../date_format.dart');
#import('../date_symbol_data_local.dart');
#import('../intl.dart');
#import('../message_lookup_local.dart');
#import('../example/basic/basic_example.dart');
#import('../../unittest/unittest.dart');

List list;

main() {
  list = [];
  setup(runAllTests, addToList);
}

addToList(x) {list.add(x);}

runAllTests(_) {
  setup(runProgram, addToList);
  test('Verify basic example printing localized messages', () {
  expect(list[0], "Ran at 00:00:00 on Thursday, January 1, 1970");
  expect(list[1], "Ausgedruckt am 00:00:00 am Donnerstag, 1. Januar 1970.");
  expect(list[2], "วิ่ง 0:00:00 on วันพฤหัสบดี 1 มกราคม 1970.");
  });
}

Add test that uses the basic example code
Review URL: https://codereview.chromium.org//10914272

git-svn-id: a8f079e7cfc3a289d8496d7b88aabbd5c45a3053@12349 260f80e4-7a28-3924-810f-c04153c831b5


library buffer_when_test;

import 'dart:async';
import 'package:guinness/guinness.dart';
import 'package:frappe/src/transformers.dart';
import 'util.dart';

void main() => describe("FlatMap", () {
  StreamController controller;
  Map<int, StreamController> spawnedControllers;

  beforeEach(() {
    controller = new StreamController();
    spawnedControllers = {
      1: new StreamController(),
      2: new StreamController()
    };
  });

  afterEach(() {
    controller.close();
    spawnedControllers.values.forEach((controller) => controller.close());
  });

  it("includes events from spawned streams", () {
    return testStream(controller.stream.transform(new FlatMap((value) => spawnedControllers[value].stream)),
        behavior: () {
          controller.add(1);
          controller.add(2);
          spawnedControllers[1].add(3);
          spawnedControllers[2].add(4);
        },
        expectation: (values) => expect(values).toEqual([3, 4]));
  });

  it("closes transformed stream when source stream is done", () {
    var stream = controller.stream.transform(new FlatMap((value) => spawnedControllers[value].stream));
    controller..add(1)..close();
    return stream.toList().then((values) => expect(values).toEqual([]));
  });
});

Add flat map transformer tests

Add flat map transformer tests


// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// VMOptions=--enable_type_checks --enable_asserts
//
// Dart test program testing generic type allocations and generic type tests.

class A {
  const A();
}

class AA extends A {
  const AA();
}

class AX {
  const AX();
}

class B<T extends A> {
  final A a_;
  final T t_;
  const B(T t) : a_ = t, t_ = t;
  isT(x) {
    return x is T;
  }
}

class C<T> {
  B<T> b_;
  C(T t) : b_ = new B<T>(t) { }
}

class D {
  C<AA> caa_;
  D() : caa_ = new C<AA>(const AA()) { }
}

class E {
  C<AX> cax_;
  E() : cax_ = new C<AX>(const AX()) { }
}

class GenericTest {
  static test() {
    int result = 0;
    try {
      D d = new D();
      Expect.equals(true, d.caa_.b_ is B<AA>);
      Expect.equals(true, d.caa_.b_.isT(const AA()));
      C c = new C(const AA());  // c is of raw type C, T in C<T> is Dynamic.
      Expect.equals(true, c.b_ is B);
      Expect.equals(true, c.b_ is B<AA>);
      Expect.equals(true, c.b_.isT(const AA()));
      Expect.equals(true, c.b_.isT(const AX()));
      E e = new E();  // Throws a type error, if type checks are enabled.
    } catch (TypeError error) {
      result = 1;
      // TODO(regis): The error below is detected too late.
      // It should be reported on line 26, at new B<AX>().
      // This will be detected when we check the subtyping constraints.
      Expect.equals("A", error.dstType);
      Expect.equals("AX", error.srcType);
      Expect.equals("a_", error.dstName);
      int pos = error.url.lastIndexOf("/", error.url.length);
      if (pos == -1) {
        pos = error.url.lastIndexOf("\\", error.url.length);
      }
      String subs = error.url.substring(pos + 1, error.url.length);
      Expect.equals("GenericTest.dart", subs);
      Expect.equals(23, error.line);
      Expect.equals(23, error.column);
    }
    return result;
  }

  static testMain() {
    Expect.equals(1, test());
  }
}

main() {
  GenericTest.testMain();
}

Copy vm-specific test to vm-specific location.
A follow-up cl will make the original test non vm-specific.
Review URL: https://chromiumcodereview.appspot.com//9969122

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@6143 260f80e4-7a28-3924-810f-c04153c831b5


@TestOn('browser')
import 'dart:async';

import 'package:test/test.dart';
import 'package:angular/angular.dart';
import 'package:angular_test/angular_test.dart';
import 'package:angular_test/src/errors/will_never_stabilize.dart';

import 'stabilizer_test.template.dart' as template;

void main() {
  test('should throw error when stabilization threshold is exceeded', () async {
    final testBed =
        NgTestBed.forComponent(template.WillNeverStabilizeComponentNgFactory);
    expect(testBed.create, throwsA(TypeMatcher<WillNeverStabilizeError>()));
  }, skip: 'b/140626607');
}

@Component(
  selector: 'test',
  template: '',
)
class WillNeverStabilizeComponent implements DoCheck {
  @override
  void ngDoCheck() {
    // This creates an infinite change detection loop.
    scheduleMicrotask(() {});
  }
}

Add regression test for a test bed failing to stabilize

The test bed should be throwing an error if the test bed gets stuck in an
infinite, asynchronous change detection loop, but currently just hangs.

PiperOrigin-RevId: 277105349


// Copyright 2016 Google Inc. Use of this source code is governed by an
// MIT-style license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.

import 'dart:collection';

import 'ast/node.dart';
import 'ast/parent.dart';
import 'utils.dart';

class MutableNode<T extends AstNode, N extends T> {
  N get node => _node;

  void set node(N value) {
    _node = value;
    _checkNode();
  }

  N _node;

  final children = new LinkedList<LinkedListValue<MutableNode<T, T>>>();

  MutableNode(this._node) {
    _checkNode();
  }

  void _checkNode() {
    if (node is! Parent) return;
    var parent = node as Parent;
    if (parent.children == null) return;
    if (parent.children.isNotEmpty) return;

    throw new StateError("A mutable node can't have immutable children.");
  }

  N build() {
    if (children.isEmpty) return node;
    if (node is Parent<T, N>) {
      return (node as Parent<T, N>)
          .withChildren(children.map((entry) => entry.value.build()));
    }

    throw new StateError("Non-Parent $node may not have children.");
  }
}

Add a mutable node class for the performer.