Skip to content

Commit

Permalink
Library tour example tests, up to but excluding dart:html (#440)
Browse files Browse the repository at this point in the history
* Library tour example tests, up to but excluding dart:html

Contributes to #407 and #416.

* Post-review edits
  • Loading branch information
chalin committed Nov 21, 2017
1 parent 33c4e8e commit 783590c
Show file tree
Hide file tree
Showing 16 changed files with 1,323 additions and 293 deletions.
23 changes: 23 additions & 0 deletions examples/lib/library_tour/async/basic.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'dart:html';

void miscDeclAnalyzedButNotTested() {
final url = 'humans.txt';

{
// #docregion then
HttpRequest.getString(url).then((String result) {
print(result);
});
// #enddocregion then
}

{
// #docregion catchError
HttpRequest.getString(url).then((String result) {
print(result);
}).catchError((e) {
// Handle or ignore the error.
});
// #enddocregion catchError
}
}
103 changes: 103 additions & 0 deletions examples/lib/library_tour/async/future.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// ignore_for_file: unused_element, type_annotate_public_apis
// #docregion import
import 'dart:async';
// #enddocregion import

void miscDeclAnalyzedButNotTested() {
final args = <String>[];
Future<String> findEntryPoint() async => 'entrypoint';
Future<int> runExecutable(
String entryPoint, List<String> args) async =>
0;
Future<int> flushThenExit(int exitCode) async => 0;

{
// #docregion runUsingFuture
runUsingFuture() {
// ...
findEntryPoint().then((entryPoint) {
return runExecutable(entryPoint, args);
}).then(flushThenExit);
}
// #enddocregion runUsingFuture
}

{
// #docregion runUsingAsyncAwait
runUsingAsyncAwait() async {
// ...
var entryPoint = await findEntryPoint();
var exitCode = await runExecutable(entryPoint, args);
await flushThenExit(exitCode);
}
// #enddocregion runUsingAsyncAwait
}

{
Future catchExample() async {
// #docregion catch
var entryPoint = await findEntryPoint();
try {
var exitCode = await runExecutable(entryPoint, args);
await flushThenExit(exitCode);
} catch (e) {
// Handle the error...
}
// #enddocregion catch
}
}

final url = 'humans.txt';
Future costlyQuery(String url) async {}
Future expensiveWork(dynamic value) async {}
Future lengthyComputation() async {}

{
Future f() {
// #docregion then-chain
Future result = costlyQuery(url);
result
.then((value) => expensiveWork(value))
.then((_) => lengthyComputation())
.then((_) => print('Done!'))
.catchError((exception) {
/* Handle exception... */
});
// #enddocregion then-chain
return null;
}
}

{
Future f() async {
// #docregion then-chain-as-await
try {
final value = await costlyQuery(url);
await expensiveWork(value);
await lengthyComputation();
print('Done!');
} catch (e) {
/* Handle exception... */
}
// #enddocregion then-chain-as-await
}
}

bool elideBody = true;
{
Future f() async {
// #docregion wait
Future deleteLotsOfFiles() async => elideBody;
Future copyLotsOfFiles() async => elideBody;
Future checksumLotsOfOtherFiles() async => elideBody;

await Future.wait([
deleteLotsOfFiles(),
copyLotsOfFiles(),
checksumLotsOfOtherFiles(),
]);
print('Done with all the long steps!');
// #enddocregion wait
}
}
}
96 changes: 96 additions & 0 deletions examples/lib/library_tour/async/stream.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// ignore_for_file: unused_element, unused_local_variable
import 'dart:async';
import 'dart:convert';
import 'dart:io';

void miscDeclAnalyzedButNotTested() {
const recursive = 0, followLinks = 1;
final searchPath = '.', searchTerms = [''];
final argResults = {};
void searchFile(FileSystemEntity e, List<String> terms) {}

{
// #docregion listen
void main(List<String> arguments) {
// ...
FileSystemEntity.isDirectory(searchPath).then((isDir) {
if (isDir) {
final startingDir = new Directory(searchPath);
startingDir
.list(
recursive: argResults[recursive],
followLinks: argResults[followLinks])
.listen((entity) {
if (entity is File) {
searchFile(entity, searchTerms);
}
});
} else {
searchFile(new File(searchPath), searchTerms);
}
});
}
// #enddocregion listen
}

{
// #docregion await-for
Future main(List<String> arguments) async {
// ...
if (await FileSystemEntity.isDirectory(searchPath)) {
final startingDir = new Directory(searchPath);
await for (var entity in startingDir.list(
recursive: argResults[recursive],
followLinks: argResults[followLinks])) {
if (entity is File) {
searchFile(entity, searchTerms);
}
}
} else {
searchFile(new File(searchPath), searchTerms);
}
}
// #enddocregion await-for
}

{
// #docregion readFileAwaitFor
Future readFileAwaitFor() async {
var config = new File('config.txt');
Stream<List<int>> inputStream = config.openRead();

// #docregion transform
var lines = inputStream
.transform(UTF8.decoder)
.transform(new LineSplitter());
// #enddocregion transform
try {
await for (var line in lines) {
print('Got ${line.length} characters from stream');
}
print('file is now closed');
} catch (e) {
print(e);
}
}
// #enddocregion readFileAwaitFor
}

{
// #docregion onDone
var config = new File('config.txt');
Stream<List<int>> inputStream = config.openRead();

inputStream
.transform(UTF8.decoder)
.transform(new LineSplitter())
.listen((String line) {
print('Got ${line.length} characters from stream');
}, onDone: () {
print('file is now closed');
}, onError: (e) {
print(e);
});
// #enddocregion onDone
}
}
14 changes: 14 additions & 0 deletions examples/lib/library_tour/async/stream_web.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import 'dart:html';

void miscDeclAnalyzedButNotTested() {
{
void submitData() {}
// #docregion listen
// Find a button by ID and add an event handler.
querySelector('#submitInfo').onClick.listen((e) {
// When the button is clicked, it runs this code.
submitData();
});
// #enddocregion listen
}
}
13 changes: 13 additions & 0 deletions examples/lib/library_tour/core/comparable.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
class Line implements Comparable<Line> {
final int length;
const Line(this.length);

@override
int compareTo(Line other) => length - other.length;
}

void main() {
var short = const Line(1);
var long = const Line(100);
assert(short.compareTo(long) < 0);
}
8 changes: 8 additions & 0 deletions examples/lib/library_tour/core/exception.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class FooException implements Exception {
final String msg;

const FooException([this.msg]);

@override
String toString() => msg ?? 'FooException';
}
36 changes: 36 additions & 0 deletions examples/lib/library_tour/core/hash_code.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// ignore_for_file: unrelated_type_equality_checks
// #docregion
class Person {
final String firstName, lastName;

Person(this.firstName, this.lastName);

// Override hashCode using strategy from Effective Java,
// Chapter 11.
@override
int get hashCode {
int result = 17;
result = 37 * result + firstName.hashCode;
result = 37 * result + lastName.hashCode;
return result;
}

// You should generally implement operator == if you
// override hashCode.
@override
bool operator ==(dynamic other) {
if (other is! Person) return false;
Person person = other;
return (person.firstName == firstName &&
person.lastName == lastName);
}
}

void main() {
var p1 = new Person('Bob', 'Smith');
var p2 = new Person('Bob', 'Smith');
var p3 = 'not a person';
assert(p1.hashCode == p2.hashCode);
assert(p1 == p2);
assert(p1 != p3);
}
45 changes: 45 additions & 0 deletions examples/lib/library_tour/core/iterator.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// #docplaster
import 'dart:collection';
import '../../util/print.dart';

final Iterator<Process> _it =
[new Process(), new Process(), new Process()].iterator;

// #docregion
class Process {
// Represents a process...
// #enddocregion
static int _nextId = 0;
final int id = _nextId++;
// #docregion
}

class ProcessIterator implements Iterator<Process> {
@override
Process get current => /*...*/
// #enddocregion
_it.current;
// #docregion
@override
bool moveNext() => /*...*/
// #enddocregion
_it.moveNext();
// #docregion
}

// A mythical class that lets you iterate through all
// processes. Extends a subclass of [Iterable].
class Processes extends IterableBase<Process> {
@override
final Iterator<Process> iterator = new ProcessIterator();
}

void main() {
// Iterable objects can be used with for-in.
for (var process in new Processes()) {
// Do something with the process.
// #enddocregion
$print(process.id);
// #docregion
}
}
4 changes: 2 additions & 2 deletions examples/test/language_tour/operators_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ void main() {
int d = 1, i = 1, n = 1;
// #docregion precedence
// Parens improve readability.
if ((n % i == 0) && (d % i == 0)) {/*...*/}
if ((n % i == 0) && (d % i == 0)) {/* ... */}

// Harder to read, but equivalent.
if (n % i == 0 && d % i == 0) {/*...*/}
if (n % i == 0 && d % i == 0) {/* ... */}
// #enddocregion precedence
});

Expand Down
Loading

0 comments on commit 783590c

Please sign in to comment.