diff --git a/tests/standalone/check_for_aot_snapshot_jit_test.dart b/tests/standalone/check_for_aot_snapshot_jit_test.dart index 4a51125f818..83ed4d81f8f 100644 --- a/tests/standalone/check_for_aot_snapshot_jit_test.dart +++ b/tests/standalone/check_for_aot_snapshot_jit_test.dart @@ -13,69 +13,71 @@ main() { final buildDir = path.dirname(Platform.executable); final sdkDir = path.dirname(path.dirname(buildDir)); final platformDill = path.join(buildDir, 'vm_platform_strong.dill'); - final genKernel = - path.join(sdkDir, 'pkg', 'vm', 'tool', 'gen_kernel$_batchSuffix'); - Expect.isTrue(File(genKernel).existsSync(), - "Can't locate gen_kernel$_batchSuffix on this platform"); - Expect.isTrue(File(genKernel).existsSync(), - "Can't locate gen_kernel$_batchSuffix on this platform"); + final genKernel = path.join( + sdkDir, + 'pkg', + 'vm', + 'tool', + 'gen_kernel$_batchSuffix', + ); + Expect.isTrue( + File(genKernel).existsSync(), + "Can't locate gen_kernel$_batchSuffix on this platform", + ); + Expect.isTrue( + File(genKernel).existsSync(), + "Can't locate gen_kernel$_batchSuffix on this platform", + ); final genSnapshot = path.join(buildDir, 'gen_snapshot$_execSuffix'); - Expect.isTrue(File(genSnapshot).existsSync(), - "Can't locate gen_snapshot$_execSuffix on this platform"); + Expect.isTrue( + File(genSnapshot).existsSync(), + "Can't locate gen_snapshot$_execSuffix on this platform", + ); final exePath = path.join(buildDir, 'dart$_execSuffix'); - Expect.isTrue(File(exePath).existsSync(), - "Can't locate dart$_execSuffix on this platform"); + Expect.isTrue( + File(exePath).existsSync(), + "Can't locate dart$_execSuffix on this platform", + ); final powTest = path.join(sdkDir, 'tests', 'standalone', 'pow_test.dart'); - Expect.isTrue(File(powTest).existsSync(), - "Can't locate dart$_execSuffix on this platform"); + Expect.isTrue( + File(powTest).existsSync(), + "Can't locate dart$_execSuffix on this platform", + ); final d = Directory.systemTemp.createTempSync('aot_tmp'); final kernelOutput = File.fromUri(d.uri.resolve('pow_test.dill')).path; final aotOutput = File.fromUri(d.uri.resolve('pow_test.aot')).path; - final genKernelResult = runAndPrintOutput( - genKernel, - [ - '--aot', - '--platform=$platformDill', - '-o', - kernelOutput, - powTest, - ], - ); + final genKernelResult = runAndPrintOutput(genKernel, [ + '--aot', + '--platform=$platformDill', + '-o', + kernelOutput, + powTest, + ]); Expect.equals(genKernelResult.exitCode, 0); print("Ran successfully.\n"); - final genAotResult = runAndPrintOutput( - genSnapshot, - [ - '--snapshot_kind=app-aot-elf', - '--elf=$aotOutput', - kernelOutput, - ], - ); + final genAotResult = runAndPrintOutput(genSnapshot, [ + '--snapshot_kind=app-aot-elf', + '--elf=$aotOutput', + kernelOutput, + ]); Expect.equals(genAotResult.exitCode, 0); print("Ran successfully.\n"); - final runAotDirectlyResult = runAndPrintOutput( - exePath, - [ - aotOutput, - ], - ); + final runAotDirectlyResult = runAndPrintOutput(exePath, [aotOutput]); Expect.equals(runAotDirectlyResult.exitCode, 255); Expect.contains( - "pow_test.aot is an AOT snapshot and should be run with 'dartaotruntime'", - runAotDirectlyResult.stderr); + "pow_test.aot is an AOT snapshot and should be run with 'dartaotruntime'", + runAotDirectlyResult.stderr, + ); print('Got expected error result.'); - final runAotUsingCommandResult = runAndPrintOutput( - exePath, - [ - 'run', - aotOutput, - ], - ); + final runAotUsingCommandResult = runAndPrintOutput(exePath, [ + 'run', + aotOutput, + ]); Expect.equals(runAotUsingCommandResult.exitCode, 255); Expect.containsAny([ "pow_test.aot is an AOT snapshot and should be run with 'dartaotruntime'", diff --git a/tests/standalone/dwarf_stack_trace_invisible_functions_test.dart b/tests/standalone/dwarf_stack_trace_invisible_functions_test.dart index da91c2e170e..6a52db379b6 100644 --- a/tests/standalone/dwarf_stack_trace_invisible_functions_test.dart +++ b/tests/standalone/dwarf_stack_trace_invisible_functions_test.dart @@ -22,7 +22,7 @@ const int LINE_E = 57; bar() { // Keep the 'throw' and its argument on separate lines. throw // force linebreak with dart format // LINE_A - "Hello, Dwarf!"; + "Hello, Dwarf!"; } @pragma("vm:never-inline") @@ -67,12 +67,18 @@ Future main() async { return; // Generated dwarf.so not available on the test device. } - final dwarf = Dwarf.fromFile(path.join( + final dwarf = Dwarf.fromFile( + path.join( Platform.environment["TEST_COMPILATION_DIR"]!, - "dwarf_invisible_functions.so"))!; + "dwarf_invisible_functions.so", + ), + )!; await dwarf_stack_trace_test.checkStackTrace( - rawStack, dwarf, expectedCallsInfo); + rawStack, + dwarf, + expectedCallsInfo, + ); } final expectedCallsInfo = >[ @@ -80,44 +86,49 @@ final expectedCallsInfo = >[ // into foo (so we'll get information for two calls for that PC address). [ DartCallInfo( - function: "bar", - filename: "dwarf_stack_trace_invisible_functions_test.dart", - line: LINE_A, - column: 3, - inlined: true), + function: "bar", + filename: "dwarf_stack_trace_invisible_functions_test.dart", + line: LINE_A, + column: 3, + inlined: true, + ), DartCallInfo( - function: "foo", - filename: "dwarf_stack_trace_invisible_functions_test.dart", - line: LINE_B, - column: 3, - inlined: false) + function: "foo", + filename: "dwarf_stack_trace_invisible_functions_test.dart", + line: LINE_B, + column: 3, + inlined: false, + ), ], // Frame 2: call to foo in bazz. [ DartCallInfo( - function: "bazz", - filename: "dwarf_stack_trace_invisible_functions_test.dart", - line: LINE_C, - column: 3, - inlined: false) + function: "bazz", + filename: "dwarf_stack_trace_invisible_functions_test.dart", + line: LINE_C, + column: 3, + inlined: false, + ), ], // Frame 3: call to bazz in A.method. [ DartCallInfo( - function: "A.add", - filename: "dwarf_stack_trace_invisible_functions_test.dart", - line: LINE_D, - column: 5, - inlined: false) + function: "A.add", + filename: "dwarf_stack_trace_invisible_functions_test.dart", + line: LINE_D, + column: 5, + inlined: false, + ), ], // Frame 4: the call to foo in main. [ DartCallInfo( - function: "main", - filename: "dwarf_stack_trace_invisible_functions_test.dart", - line: LINE_E, - column: 8, - inlined: false) + function: "main", + filename: "dwarf_stack_trace_invisible_functions_test.dart", + line: LINE_E, + column: 8, + inlined: false, + ), ], // Don't assume anything about any of the frames below the main, // as this makes the test too brittle. diff --git a/tests/standalone/dwarf_stack_trace_obfuscate_test.dart b/tests/standalone/dwarf_stack_trace_obfuscate_test.dart index a6f09a78126..0429a827f9f 100644 --- a/tests/standalone/dwarf_stack_trace_obfuscate_test.dart +++ b/tests/standalone/dwarf_stack_trace_obfuscate_test.dart @@ -16,7 +16,7 @@ import 'dwarf_stack_trace_test.dart' as base; bar() { // Keep the 'throw' and its argument on separate lines. throw // force linebreak with dart format - "Hello, Dwarf!"; + "Hello, Dwarf!"; } @pragma("vm:never-inline") @@ -40,8 +40,12 @@ Future main() async { return; // Generated dwarf.so not available on the test device. } - final dwarf = Dwarf.fromFile(path.join( - Platform.environment['TEST_COMPILATION_DIR']!, "dwarf_obfuscate.so"))!; + final dwarf = Dwarf.fromFile( + path.join( + Platform.environment['TEST_COMPILATION_DIR']!, + "dwarf_obfuscate.so", + ), + )!; await base.checkStackTrace(rawStack, dwarf, expectedCallsInfo); } @@ -51,26 +55,29 @@ final expectedCallsInfo = >[ // into foo (so we'll get information for two calls for that PC address). [ DartCallInfo( - function: "bar", - filename: "dwarf_stack_trace_obfuscate_test.dart", - line: 18, - column: 3, - inlined: true), + function: "bar", + filename: "dwarf_stack_trace_obfuscate_test.dart", + line: 18, + column: 3, + inlined: true, + ), DartCallInfo( - function: "foo", - filename: "dwarf_stack_trace_obfuscate_test.dart", - line: 24, - column: 3, - inlined: false) + function: "foo", + filename: "dwarf_stack_trace_obfuscate_test.dart", + line: 24, + column: 3, + inlined: false, + ), ], // The second frame corresponds to call to foo in main. [ DartCallInfo( - function: "main", - filename: "dwarf_stack_trace_obfuscate_test.dart", - line: 30, - column: 5, - inlined: false) + function: "main", + filename: "dwarf_stack_trace_obfuscate_test.dart", + line: 30, + column: 5, + inlined: false, + ), ], // Don't assume anything about any of the frames below the call to foo // in main, as this makes the test too brittle. diff --git a/tests/standalone/dwarf_stack_trace_test.dart b/tests/standalone/dwarf_stack_trace_test.dart index f6bfad83a1d..196b1116e26 100644 --- a/tests/standalone/dwarf_stack_trace_test.dart +++ b/tests/standalone/dwarf_stack_trace_test.dart @@ -16,7 +16,7 @@ import 'package:path/path.dart' as path; bar() { // Keep the 'throw' and its argument on separate lines. throw // force linebreak with dart format - "Hello, Dwarf!"; + "Hello, Dwarf!"; } @pragma("vm:never-inline") @@ -41,19 +41,24 @@ Future main() async { } final dwarf = Dwarf.fromFile( - path.join(Platform.environment["TEST_COMPILATION_DIR"]!, "dwarf.so"))!; + path.join(Platform.environment["TEST_COMPILATION_DIR"]!, "dwarf.so"), + )!; await checkStackTrace(rawStack, dwarf, expectedCallsInfo); } -Future checkStackTrace(String rawStack, Dwarf dwarf, - List> expectedCallsInfo) async { +Future checkStackTrace( + String rawStack, + Dwarf dwarf, + List> expectedCallsInfo, +) async { print(""); print("Raw stack trace:"); print(rawStack); - final rawLines = - await Stream.value(rawStack).transform(const LineSplitter()).toList(); + final rawLines = await Stream.value( + rawStack, + ).transform(const LineSplitter()).toList(); final pcOffsets = collectPCOffsets(rawLines).toList(); Expect.isNotEmpty(pcOffsets); @@ -73,8 +78,9 @@ Future checkStackTrace(String rawStack, Dwarf dwarf, print('Isolate start offset: 0x${isolateStart!.toRadixString(16)}'); // The addresses of the stack frames in the separate DWARF debugging info. - final virtualAddresses = - pcOffsets.map((o) => dwarf.virtualAddressOf(o)).toList(); + final virtualAddresses = pcOffsets + .map((o) => dwarf.virtualAddressOf(o)) + .toList(); print('Virtual addresses from PCOffsets:'); for (final address in virtualAddresses) { @@ -87,8 +93,10 @@ Future checkStackTrace(String rawStack, Dwarf dwarf, print('DSO base address: 0x${dsoBase.toRadixString(16)}'); final absoluteIsolateStart = isolateStartAddresses(rawLines).single; - print('Absolute isolate start address: ' - '0x${absoluteIsolateStart.toRadixString(16)}'); + print( + 'Absolute isolate start address: ' + '0x${absoluteIsolateStart.toRadixString(16)}', + ); final absolutes = absoluteAddresses(rawLines); // The relocated addresses of the stack frames in the loaded DSO. These is @@ -125,19 +133,25 @@ Future checkStackTrace(String rawStack, Dwarf dwarf, for (final offset in pcOffsets) { final externalCallInfo = dwarf.callInfoForPCOffset(offset); Expect.isNotNull(externalCallInfo); - final allCallInfo = - dwarf.callInfoForPCOffset(offset, includeInternalFrames: true); + final allCallInfo = dwarf.callInfoForPCOffset( + offset, + includeInternalFrames: true, + ); Expect.isNotNull(allCallInfo); for (final call in externalCallInfo!) { Expect.isTrue(call is DartCallInfo, "got non-Dart call info ${call}"); Expect.isFalse(call.isInternal); - Expect.isTrue(allCallInfo!.contains(call), - "External call info ${call} is not among all calls"); + Expect.isTrue( + allCallInfo!.contains(call), + "External call info ${call} is not among all calls", + ); } for (final call in allCallInfo!) { if (!call.isInternal) { - Expect.isTrue(externalCallInfo.contains(call), - "External call info ${call} is not among external calls"); + Expect.isTrue( + externalCallInfo.contains(call), + "External call info ${call} is not among external calls", + ); } } gotCallsInfo.add(externalCallInfo.cast().toList()); @@ -160,8 +174,9 @@ Future checkStackTrace(String rawStack, Dwarf dwarf, .transform(DwarfStackTraceDecoder(dwarf, includeInternalFrames: false)) .toList(); - final gotSymbolizedCalls = - gotSymbolizedLines.where((s) => s.startsWith('#')).toList(); + final gotSymbolizedCalls = gotSymbolizedLines + .where((s) => s.startsWith('#')) + .toList(); print(""); print("Symbolized stack trace:"); @@ -178,8 +193,9 @@ Future checkStackTrace(String rawStack, Dwarf dwarf, // Strip off any unexpected lines, so we can also make sure we didn't get // unexpected calls prior to those calls we expect. - final gotCallsTrace = - gotSymbolizedCalls.sublist(0, expectedCallCount).join('\n'); + final gotCallsTrace = gotSymbolizedCalls + .sublist(0, expectedCallCount) + .join('\n'); Expect.containsInOrder(expectedStrings, gotCallsTrace); } @@ -189,33 +205,38 @@ final expectedCallsInfo = >[ // into foo (so we'll get information for two calls for that PC address). [ DartCallInfo( - function: "bar", - filename: "dwarf_stack_trace_test.dart", - line: 17, - column: 3, - inlined: true), + function: "bar", + filename: "dwarf_stack_trace_test.dart", + line: 17, + column: 3, + inlined: true, + ), DartCallInfo( - function: "foo", - filename: "dwarf_stack_trace_test.dart", - line: 23, - column: 3, - inlined: false) + function: "foo", + filename: "dwarf_stack_trace_test.dart", + line: 23, + column: 3, + inlined: false, + ), ], // The second frame corresponds to call to foo in main. [ DartCallInfo( - function: "main", - filename: "dwarf_stack_trace_test.dart", - line: 29, - column: 5, - inlined: false) + function: "main", + filename: "dwarf_stack_trace_test.dart", + line: 29, + column: 5, + inlined: false, + ), ], // Don't assume anything about any of the frames below the call to foo // in main, as this makes the test too brittle. ]; void checkFrames( - List> gotInfo, List> expectedInfo) { + List> gotInfo, + List> expectedInfo, +) { // There may be frames below those we check. Expect.isTrue(gotInfo.length >= expectedInfo.length); diff --git a/tests/standalone/from_env_test.dart b/tests/standalone/from_env_test.dart index 360ea2ea4d7..5336afcb9fe 100644 --- a/tests/standalone/from_env_test.dart +++ b/tests/standalone/from_env_test.dart @@ -13,12 +13,16 @@ import "package:expect/expect.dart"; main() { // User string entry, const. Expect.isTrue(const bool.hasEnvironment("testFlag")); - Expect.equals("testValue", - const String.fromEnvironment("testFlag", defaultValue: "nonce")); + Expect.equals( + "testValue", + const String.fromEnvironment("testFlag", defaultValue: "nonce"), + ); // User string entry, runtime. Expect.isTrue(bool.hasEnvironment("testFlag")); Expect.equals( - "testValue", String.fromEnvironment("testFlag", defaultValue: "nonce")); + "testValue", + String.fromEnvironment("testFlag", defaultValue: "nonce"), + ); // User number entry, const. Expect.isTrue(const bool.hasEnvironment("numFlag")); @@ -33,7 +37,9 @@ main() { Expect.isTrue(const bool.hasEnvironment("boolFlag")); Expect.equals("false", const String.fromEnvironment("boolFlag")); Expect.equals( - false, const bool.fromEnvironment("boolFlag", defaultValue: true)); + false, + const bool.fromEnvironment("boolFlag", defaultValue: true), + ); // User bool entry, runtime. Expect.isTrue(bool.hasEnvironment("boolFlag")); Expect.equals("false", String.fromEnvironment("boolFlag")); @@ -43,7 +49,9 @@ main() { Expect.isFalse(const bool.hasEnvironment("noEntry")); Expect.equals("", const String.fromEnvironment("noEntry")); Expect.equals( - "nonce", const String.fromEnvironment("noEntry", defaultValue: "nonce")); + "nonce", + const String.fromEnvironment("noEntry", defaultValue: "nonce"), + ); Expect.equals(0, const int.fromEnvironment("noEntry")); Expect.equals(42, const int.fromEnvironment("noEntry", defaultValue: 42)); Expect.isFalse(const bool.fromEnvironment("noEntry")); @@ -52,7 +60,9 @@ main() { Expect.isFalse(bool.hasEnvironment("noEntry")); Expect.equals("", String.fromEnvironment("noEntry")); Expect.equals( - "nonce", String.fromEnvironment("noEntry", defaultValue: "nonce")); + "nonce", + String.fromEnvironment("noEntry", defaultValue: "nonce"), + ); Expect.equals(0, int.fromEnvironment("noEntry")); Expect.equals(42, int.fromEnvironment("noEntry", defaultValue: 42)); Expect.isFalse(bool.fromEnvironment("noEntry")); @@ -60,57 +70,77 @@ main() { // General platform library entry, const. Expect.isTrue(const bool.hasEnvironment("dart.library.core")); - Expect.equals("true", - const String.fromEnvironment("dart.library.core", defaultValue: "nonce")); + Expect.equals( + "true", + const String.fromEnvironment("dart.library.core", defaultValue: "nonce"), + ); Expect.isTrue( - const bool.fromEnvironment("dart.library.core", defaultValue: false)); + const bool.fromEnvironment("dart.library.core", defaultValue: false), + ); // General platform library entry, runtime. Expect.isTrue(bool.hasEnvironment("dart.library.core")); - Expect.equals("true", - String.fromEnvironment("dart.library.core", defaultValue: "nonce")); + Expect.equals( + "true", + String.fromEnvironment("dart.library.core", defaultValue: "nonce"), + ); Expect.isTrue(bool.fromEnvironment("dart.library.core", defaultValue: false)); // Standalone VM-specific library, const. Expect.isTrue(const bool.hasEnvironment("dart.library.io")); - Expect.equals("true", - const String.fromEnvironment("dart.library.io", defaultValue: "nonce")); + Expect.equals( + "true", + const String.fromEnvironment("dart.library.io", defaultValue: "nonce"), + ); Expect.isTrue( - const bool.fromEnvironment("dart.library.io", defaultValue: false)); + const bool.fromEnvironment("dart.library.io", defaultValue: false), + ); // Standalone VM-specific library, runtime. Expect.isTrue(bool.hasEnvironment("dart.library.io")); Expect.equals( - "true", String.fromEnvironment("dart.library.io", defaultValue: "nonce")); + "true", + String.fromEnvironment("dart.library.io", defaultValue: "nonce"), + ); Expect.isTrue(bool.fromEnvironment("dart.library.io", defaultValue: false)); // Web-specific library, not available here, const. Expect.isFalse(const bool.hasEnvironment("dart.library.html")); Expect.equals("", const String.fromEnvironment("dart.library.html")); - Expect.equals("nonce", - const String.fromEnvironment("dart.library.html", defaultValue: "nonce")); + Expect.equals( + "nonce", + const String.fromEnvironment("dart.library.html", defaultValue: "nonce"), + ); Expect.isFalse(const bool.fromEnvironment("dart.library.html")); Expect.isTrue( - const bool.fromEnvironment("dart.library.html", defaultValue: true)); + const bool.fromEnvironment("dart.library.html", defaultValue: true), + ); // Web-specific library, not available here, runtime. Expect.isFalse(bool.hasEnvironment("dart.library.html")); Expect.equals("", String.fromEnvironment("dart.library.html")); - Expect.equals("nonce", - String.fromEnvironment("dart.library.html", defaultValue: "nonce")); + Expect.equals( + "nonce", + String.fromEnvironment("dart.library.html", defaultValue: "nonce"), + ); Expect.isFalse(bool.fromEnvironment("dart.library.html")); Expect.isTrue(bool.fromEnvironment("dart.library.html", defaultValue: true)); // Non-existing library, const. Expect.isFalse(const bool.hasEnvironment("dart.library.not")); Expect.equals("", const String.fromEnvironment("dart.library.not")); - Expect.equals("nonce", - const String.fromEnvironment("dart.library.not", defaultValue: "nonce")); + Expect.equals( + "nonce", + const String.fromEnvironment("dart.library.not", defaultValue: "nonce"), + ); Expect.isFalse(const bool.fromEnvironment("dart.library.not")); Expect.isTrue( - const bool.fromEnvironment("dart.library.not", defaultValue: true)); + const bool.fromEnvironment("dart.library.not", defaultValue: true), + ); // Non-existing library, runtime. Expect.isFalse(bool.hasEnvironment("dart.library.not")); Expect.equals("", String.fromEnvironment("dart.library.not")); - Expect.equals("nonce", - String.fromEnvironment("dart.library.not", defaultValue: "nonce")); + Expect.equals( + "nonce", + String.fromEnvironment("dart.library.not", defaultValue: "nonce"), + ); Expect.isFalse(bool.fromEnvironment("dart.library.not")); Expect.isTrue(bool.fromEnvironment("dart.library.not", defaultValue: true)); } diff --git a/tests/standalone/http_launch_data/http_spawn_main.dart b/tests/standalone/http_launch_data/http_spawn_main.dart index e6b1a24ff79..7189f93bb84 100644 --- a/tests/standalone/http_launch_data/http_spawn_main.dart +++ b/tests/standalone/http_launch_data/http_spawn_main.dart @@ -10,8 +10,11 @@ import 'dart:io'; main(List arguments) { int port = int.parse(arguments[0]); ReceivePort receivePort = new ReceivePort(); - Isolate.spawnUri(Uri.parse('http://127.0.0.1:$port/http_isolate_main.dart'), - ['hello'], receivePort.sendPort); + Isolate.spawnUri( + Uri.parse('http://127.0.0.1:$port/http_isolate_main.dart'), + ['hello'], + receivePort.sendPort, + ); receivePort.first.then((response) { print(response); }); diff --git a/tests/standalone/http_launch_test.dart b/tests/standalone/http_launch_test.dart index b888bdd4be8..be11eda16d7 100644 --- a/tests/standalone/http_launch_test.dart +++ b/tests/standalone/http_launch_test.dart @@ -55,31 +55,39 @@ serverRunning(HttpServer server) { port = server.port; server.listen(handleRequest); Future no_http_run = Process.run( - pathToExecutable, - [] - ..add('--verbosity=warning') - ..addAll(executableArguments) - ..add(pathOfData.resolve('http_launch_main.dart').toFilePath())); + pathToExecutable, + [] + ..add('--verbosity=warning') + ..addAll(executableArguments) + ..add(pathOfData.resolve('http_launch_main.dart').toFilePath()), + ); Future http_run = Process.run( - pathToExecutable, - [] - ..add('--verbosity=warning') - ..addAll(executableArguments) - ..add('http://127.0.0.1:$port/http_launch_main.dart')); + pathToExecutable, + [] + ..add('--verbosity=warning') + ..addAll(executableArguments) + ..add('http://127.0.0.1:$port/http_launch_main.dart'), + ); Future http_pkg_root_run = Process.run( - pathToExecutable, - [] - ..add('--verbosity=warning') - ..addAll(executableArguments) - ..addAll(['http://127.0.0.1:$port/http_launch_main.dart'])); + pathToExecutable, + [] + ..add('--verbosity=warning') + ..addAll(executableArguments) + ..addAll(['http://127.0.0.1:$port/http_launch_main.dart']), + ); Future isolate_run = Process.run( - pathToExecutable, - [] - ..add('--verbosity=warning') - ..addAll(executableArguments) - ..addAll(['http://127.0.0.1:$port/http_spawn_main.dart', '$port'])); - Future> results = - Future.wait([no_http_run, http_run, http_pkg_root_run, isolate_run]); + pathToExecutable, + [] + ..add('--verbosity=warning') + ..addAll(executableArguments) + ..addAll(['http://127.0.0.1:$port/http_spawn_main.dart', '$port']), + ); + Future> results = Future.wait([ + no_http_run, + http_run, + http_pkg_root_run, + isolate_run, + ]); results.then((results) { // Close server. server.close(); diff --git a/tests/standalone/io/addlatexhash_test.dart b/tests/standalone/io/addlatexhash_test.dart index 0f9b69b8151..ec42ee41c8e 100755 --- a/tests/standalone/io/addlatexhash_test.dart +++ b/tests/standalone/io/addlatexhash_test.dart @@ -94,7 +94,7 @@ testSameHash(String tmpDirPath) { path.join(dartRootPath, "tools", "addlatexhash.dart"), tmpPar8timesPath, hashPath, - listPath + listPath, ]); return Process.runSync(dartExecutable, args); } @@ -167,7 +167,7 @@ testSameDVI(String tmpDirPath) { path.join(dartRootPath, "tools", "addlatexhash.dart"), tmpSpecPath, hashPath, - listPath + listPath, ]); return Process.runSync(dartExecutable, args); } diff --git a/tests/standalone/io/address_lookup_test.dart b/tests/standalone/io/address_lookup_test.dart index effa3301a5b..fd95b2aa163 100644 --- a/tests/standalone/io/address_lookup_test.dart +++ b/tests/standalone/io/address_lookup_test.dart @@ -14,8 +14,11 @@ void main() async { asyncStart(); final result = []; try { - result.addAll(await InternetAddress.lookup("some.bad.host.name.7654321") - .timeout(const Duration(milliseconds: 1), onTimeout: () => [])); + result.addAll( + await InternetAddress.lookup( + "some.bad.host.name.7654321", + ).timeout(const Duration(milliseconds: 1), onTimeout: () => []), + ); } catch (e) { print('managed to fail with $e lookup before timeout'); } diff --git a/tests/standalone/io/async_catch_errors_test.dart b/tests/standalone/io/async_catch_errors_test.dart index 84f66d5f2db..96c9fdc8e29 100644 --- a/tests/standalone/io/async_catch_errors_test.dart +++ b/tests/standalone/io/async_catch_errors_test.dart @@ -12,27 +12,33 @@ var events = []; Future testSocketException() { var completer = new Completer(); - runZonedGuarded(() { - Socket.connect("4", 1, timeout: Duration(seconds: 5)).then((Socket s) { - Expect.fail("Socket should not be able to connect"); - }); - }, (err, s) { - if (err is! SocketException) Expect.fail("Not expected error: $err"); - completer.complete("socket test, ok."); - events.add("SocketException"); - }); + runZonedGuarded( + () { + Socket.connect("4", 1, timeout: Duration(seconds: 5)).then((Socket s) { + Expect.fail("Socket should not be able to connect"); + }); + }, + (err, s) { + if (err is! SocketException) Expect.fail("Not expected error: $err"); + completer.complete("socket test, ok."); + events.add("SocketException"); + }, + ); return completer.future; } Future testFileSystemException() { var completer = new Completer(); - runZonedGuarded(() { - new File("lol it's not a file\n").openRead().listen(null); - }, (err, s) { - if (err is! FileSystemException) Expect.fail("Not expected error: $err"); - completer.complete("file test, ok."); - events.add("FileSystemException"); - }); + runZonedGuarded( + () { + new File("lol it's not a file\n").openRead().listen(null); + }, + (err, s) { + if (err is! FileSystemException) Expect.fail("Not expected error: $err"); + completer.complete("file test, ok."); + events.add("FileSystemException"); + }, + ); return completer.future; } diff --git a/tests/standalone/io/client_socket_add_close_error_test.dart b/tests/standalone/io/client_socket_add_close_error_test.dart index 0c7dafdd361..9f12135580d 100644 --- a/tests/standalone/io/client_socket_add_close_error_test.dart +++ b/tests/standalone/io/client_socket_add_close_error_test.dart @@ -20,26 +20,33 @@ void clientSocketAddCloseErrorTest() { Socket.connect("127.0.0.1", server.port).then((client) { const int SIZE = 1024 * 1024; int errors = 0; - client.listen((data) => Expect.fail("Unexpected data"), onError: (error) { - Expect.isTrue(error is SocketException); - errors++; - }, onDone: () { - // We get either a close or an error followed by a close - // on the socket. Whether we get both depends on - // whether the system notices the error for the read - // event or only for the write event. - Expect.isTrue(errors <= 1); - server.close(); - }); + client.listen( + (data) => Expect.fail("Unexpected data"), + onError: (error) { + Expect.isTrue(error is SocketException); + errors++; + }, + onDone: () { + // We get either a close or an error followed by a close + // on the socket. Whether we get both depends on + // whether the system notices the error for the read + // event or only for the write event. + Expect.isTrue(errors <= 1); + server.close(); + }, + ); client.add(new List.filled(SIZE, 0)); // Destroy other socket now. completer.complete(null); - client.done.then((_) { - Expect.fail("Expected error"); - }, onError: (error) { - Expect.isTrue(error is SocketException); - asyncEnd(); - }); + client.done.then( + (_) { + Expect.fail("Expected error"); + }, + onError: (error) { + Expect.isTrue(error is SocketException); + asyncEnd(); + }, + ); }); }); } diff --git a/tests/standalone/io/client_socket_add_close_no_error_test.dart b/tests/standalone/io/client_socket_add_close_no_error_test.dart index 0d8c98529cd..2b1c80406bf 100644 --- a/tests/standalone/io/client_socket_add_close_no_error_test.dart +++ b/tests/standalone/io/client_socket_add_close_no_error_test.dart @@ -20,10 +20,13 @@ void clientSocketAddCloseNoErrorTest() { Socket.connect("127.0.0.1", server.port).then((client) { const int SIZE = 1024 * 1024; int count = 0; - client.listen((data) => count += data.length, onDone: () { - Expect.equals(SIZE, count); - server.close(); - }); + client.listen( + (data) => count += data.length, + onDone: () { + Expect.equals(SIZE, count); + server.close(); + }, + ); client.add(new List.filled(SIZE, 0)); client.close(); // Start piping now. diff --git a/tests/standalone/io/client_socket_destroy_and_add_stream_test.dart b/tests/standalone/io/client_socket_destroy_and_add_stream_test.dart index 509c221e523..da05d69149c 100644 --- a/tests/standalone/io/client_socket_destroy_and_add_stream_test.dart +++ b/tests/standalone/io/client_socket_destroy_and_add_stream_test.dart @@ -28,8 +28,10 @@ void main() async { client.listen((data) {}, onDone: server.close); client.add(new List.filled(1024 * 1024, 0)); client.destroy(); - await client.addStream(Stream.fromIterable([ - [1, 2, 3, 4] - ])); + await client.addStream( + Stream.fromIterable([ + [1, 2, 3, 4], + ]), + ); asyncEnd(); } diff --git a/tests/standalone/io/create_recursive_test.dart b/tests/standalone/io/create_recursive_test.dart index 2f92c5c5435..f30096f156c 100644 --- a/tests/standalone/io/create_recursive_test.dart +++ b/tests/standalone/io/create_recursive_test.dart @@ -78,8 +78,9 @@ Future expectFutureIsTrue(Future future) => Future expectFileSystemException(Function f, String message) { return f().then( - (_) => Expect.fail('Expected a FileSystemException: $message'), - onError: (e) => Expect.isTrue(e is FileSystemException)); + (_) => Expect.fail('Expected a FileSystemException: $message'), + onError: (e) => Expect.isTrue(e is FileSystemException), + ); } testCreateDirectoryRecursive() { @@ -123,16 +124,21 @@ testCreateLinkRecursive() { Directory.systemTemp.createTemp('dart_directory').then((temp) { var link = new Link(join(temp.path, 'a', 'b', 'c')); return expectFileSystemException( - () => link.create(temp.path), 'link.create') + () => link.create(temp.path), + 'link.create', + ) .then((_) => link.create(temp.path, recursive: true)) .then((_) => expectFutureIsTrue(link.exists())) // Test cases where the link or parent directory already exists. .then((_) => link.delete()) .then((_) => link.create(temp.path, recursive: true)) .then((_) => expectFutureIsTrue(link.exists())) - .then((_) => expectFileSystemException( + .then( + (_) => expectFileSystemException( () => link.create(temp.path, recursive: true), - 'existing link.create')) + 'existing link.create', + ), + ) .then((_) => expectFutureIsTrue(link.exists())) .then((_) => asyncEnd()) .whenComplete(() => temp.delete(recursive: true)); diff --git a/tests/standalone/io/directory_create_race_test.dart b/tests/standalone/io/directory_create_race_test.dart index 4ec301a90b5..34ce715afc5 100644 --- a/tests/standalone/io/directory_create_race_test.dart +++ b/tests/standalone/io/directory_create_race_test.dart @@ -27,7 +27,7 @@ void testCreateRecursiveRace() { d.create(recursive: true), d.create(recursive: true), d.create(recursive: true), - d.create(recursive: true) + d.create(recursive: true), ]).then((_) { Expect.isTrue(new Directory('${temp.path}/a').existsSync()); Expect.isTrue(new Directory('${temp.path}/a/b').existsSync()); diff --git a/tests/standalone/io/directory_error_test.dart b/tests/standalone/io/directory_error_test.dart index c3570130bf1..f852d72d707 100644 --- a/tests/standalone/io/directory_error_test.dart +++ b/tests/standalone/io/directory_error_test.dart @@ -31,8 +31,10 @@ bool checkCreateInNonExistentFileSystemException(e) { void testCreateInNonExistent(Directory temp, Function done) { Directory inNonExistent = new Directory("${temp.path}/nonExistent/xxx"); - Expect.throws(() => inNonExistent.createSync(), - (e) => checkCreateInNonExistentFileSystemException(e)); + Expect.throws( + () => inNonExistent.createSync(), + (e) => checkCreateInNonExistentFileSystemException(e), + ); Future.value(inNonExistent.create()).catchError((error) { checkCreateInNonExistentFileSystemException(error); @@ -56,11 +58,14 @@ bool checkCreateTempInNonExistentFileSystemException(e) { void testCreateTempInNonExistent(Directory temp, Function done) { Directory nonExistent = new Directory("${temp.path}/nonExistent/xxx"); - Expect.throws(() => nonExistent.createTempSync('tempdir'), - (e) => checkCreateTempInNonExistentFileSystemException(e)); + Expect.throws( + () => nonExistent.createTempSync('tempdir'), + (e) => checkCreateTempInNonExistentFileSystemException(e), + ); - Future.value(nonExistent.createTemp('tempdir')) - .catchError((error) { + Future.value(nonExistent.createTemp('tempdir')).catchError(( + error, + ) { checkCreateTempInNonExistentFileSystemException(error); done(); }); @@ -77,8 +82,10 @@ bool checkDeleteNonExistentFileSystemException(e) { void testDeleteNonExistent(Directory temp, Function done) { Directory nonExistent = new Directory("${temp.path}/nonExistent"); - Expect.throws(() => nonExistent.deleteSync(), - (e) => checkDeleteNonExistentFileSystemException(e)); + Expect.throws( + () => nonExistent.deleteSync(), + (e) => checkDeleteNonExistentFileSystemException(e), + ); Future.value(nonExistent.delete()).catchError((error) { checkDeleteNonExistentFileSystemException(error); @@ -98,11 +105,14 @@ bool checkDeleteRecursivelyNonExistentFileSystemException(e) { void testDeleteRecursivelyNonExistent(Directory temp, Function done) { Directory nonExistent = new Directory("${temp.path}/nonExistent"); - Expect.throws(() => nonExistent.deleteSync(recursive: true), - (e) => checkDeleteRecursivelyNonExistentFileSystemException(e)); + Expect.throws( + () => nonExistent.deleteSync(recursive: true), + (e) => checkDeleteRecursivelyNonExistentFileSystemException(e), + ); - Future.value(nonExistent.delete(recursive: true)) - .catchError((error) { + Future.value( + nonExistent.delete(recursive: true), + ).catchError((error) { checkDeleteRecursivelyNonExistentFileSystemException(error); done(); }); @@ -130,22 +140,26 @@ bool checkAsyncListNonExistentFileSystemException(error) { void testListNonExistent(Directory temp, Function done) { Directory nonExistent = new Directory("${temp.path}/nonExistent"); Expect.throws(() => nonExistent.listSync(), (e) => e is FileSystemException); - nonExistent.list().listen((_) => Expect.fail("listing should not succeed"), - onError: (e) { - checkAsyncListNonExistentFileSystemException(e); - done(); - }); + nonExistent.list().listen( + (_) => Expect.fail("listing should not succeed"), + onError: (e) { + checkAsyncListNonExistentFileSystemException(e); + done(); + }, + ); } void testRenameNonExistent(Directory temp, Function done) { Directory nonExistent = new Directory("${temp.path}/nonExistent"); var newPath = "${temp.path}/nonExistent2"; Expect.throws( - () => nonExistent.renameSync(newPath), (e) => e is PathNotFoundException); + () => nonExistent.renameSync(newPath), + (e) => e is PathNotFoundException, + ); var renameDone = nonExistent.rename(newPath); - renameDone - .then((ignore) => Expect.fail('rename non existent')) - .catchError((error) { + renameDone.then((ignore) => Expect.fail('rename non existent')).catchError(( + error, + ) { Expect.isTrue(error is PathNotFoundException); done(); }); @@ -161,9 +175,9 @@ void testRenameFileAsDirectory(Directory temp, Function done) { renameDone .then((ignore) => Expect.fail('rename file as directory')) .catchError((error) { - Expect.isTrue(error is FileSystemException); - done(); - }); + Expect.isTrue(error is FileSystemException); + done(); + }); } testRenameOverwriteFile(Directory temp, Function done) { @@ -171,15 +185,17 @@ testRenameOverwriteFile(Directory temp, Function done) { var fileName = '${temp.path}/x'; new File(fileName).createSync(); Expect.throws( - () => temp1.renameSync(fileName), (e) => e is FileSystemException); + () => temp1.renameSync(fileName), + (e) => e is FileSystemException, + ); var renameDone = temp1.rename(fileName); renameDone .then((ignore) => Expect.fail('rename dir overwrite file')) .catchError((error) { - Expect.isTrue(error is FileSystemException); - temp1.deleteSync(recursive: true); - done(); - }); + Expect.isTrue(error is FileSystemException); + temp1.deleteSync(recursive: true); + done(); + }); } void runTest(Function test) { diff --git a/tests/standalone/io/directory_fuzz_test.dart b/tests/standalone/io/directory_fuzz_test.dart index d4527059234..3b48522ecc6 100644 --- a/tests/standalone/io/directory_fuzz_test.dart +++ b/tests/standalone/io/directory_fuzz_test.dart @@ -51,11 +51,13 @@ fuzzAsyncMethods() async { await withTempDir('dart_directory_fuzz', (temp) async { final futures = []; typeMapping.forEach((k, v) { - futures.add(doItAsync(() { - Directory.systemTemp - .createTempSync("${temp.path}/${v as String}") - .deleteSync(); - })); + futures.add( + doItAsync(() { + Directory.systemTemp + .createTempSync("${temp.path}/${v as String}") + .deleteSync(); + }), + ); if (v is! String) { return; } @@ -63,22 +65,28 @@ fuzzAsyncMethods() async { futures.add(doItAsync(d.exists)); futures.add(doItAsync(d.create)); futures.add(doItAsync(d.delete)); - futures.add(doItAsync(() { - return d.createTemp('tempdir').then((temp) { - return temp.delete(); - }); - })); - futures.add(doItAsync(() { - return d.exists().then((res) { - if (!res) return d.delete(recursive: true); - return new Future.value(true); - }); - })); + futures.add( + doItAsync(() { + return d.createTemp('tempdir').then((temp) { + return temp.delete(); + }); + }), + ); + futures.add( + doItAsync(() { + return d.exists().then((res) { + if (!res) return d.delete(recursive: true); + return new Future.value(true); + }); + }), + ); typeMapping.forEach((k2, v2) { futures.add(doItAsync(() => d.rename(v2 as String))); - futures.add(doItAsync(() { - d.list(recursive: v2 as bool).listen((_) {}, onError: (e) => null); - })); + futures.add( + doItAsync(() { + d.list(recursive: v2 as bool).listen((_) {}, onError: (e) => null); + }), + ); }); }); await Future.wait(futures).then((_) => asyncEnd()); diff --git a/tests/standalone/io/directory_list_nonexistent_test.dart b/tests/standalone/io/directory_list_nonexistent_test.dart index e2d414ce141..b21cf0a6c2c 100644 --- a/tests/standalone/io/directory_list_nonexistent_test.dart +++ b/tests/standalone/io/directory_list_nonexistent_test.dart @@ -18,7 +18,9 @@ void testListNonExistent() { d.delete().then((ignore) { Expect.throws(() => d.listSync(), (e) => e is PathNotFoundException); Expect.throws( - () => d.listSync(recursive: true), (e) => e is PathNotFoundException); + () => d.listSync(recursive: true), + (e) => e is PathNotFoundException, + ); asyncEnd(); }); }); @@ -39,8 +41,10 @@ void testListTooLongName() { } var long = new Directory("${buffer.toString()}"); Expect.throws(() => long.listSync(), (e) => e is FileSystemException); - Expect.throws(() => long.listSync(recursive: true), - (e) => e is FileSystemException); + Expect.throws( + () => long.listSync(recursive: true), + (e) => e is FileSystemException, + ); d.deleteSync(recursive: true); asyncEnd(); }); diff --git a/tests/standalone/io/directory_list_pause_test.dart b/tests/standalone/io/directory_list_pause_test.dart index b895558da7a..6e8439a6555 100644 --- a/tests/standalone/io/directory_list_pause_test.dart +++ b/tests/standalone/io/directory_list_pause_test.dart @@ -20,25 +20,30 @@ void testPauseList() { bool first = true; var subscription; int count = 0; - subscription = d.list(recursive: true).listen((file) { - if (file is File) { - if (first) { - first = false; - subscription.pause(); - Timer.run(() { - for (int i = 0; i < TOTAL; i++) { - new File("${d.path}/$i/file").deleteSync(); + subscription = d + .list(recursive: true) + .listen( + (file) { + if (file is File) { + if (first) { + first = false; + subscription.pause(); + Timer.run(() { + for (int i = 0; i < TOTAL; i++) { + new File("${d.path}/$i/file").deleteSync(); + } + subscription.resume(); + }); + } + count++; } - subscription.resume(); - }); - } - count++; - } - }, onDone: () { - Expect.notEquals(TOTAL, count); - Expect.isTrue(count > 0); - d.delete(recursive: true).then((ignore) => asyncEnd()); - }); + }, + onDone: () { + Expect.notEquals(TOTAL, count); + Expect.isTrue(count > 0); + d.delete(recursive: true).then((ignore) => asyncEnd()); + }, + ); }); } @@ -52,23 +57,28 @@ void testPauseResumeCancelList() { new File("${d.path}/$i/file").createSync(); } var subscription; - subscription = d.list(recursive: true).listen((entity) { - subscription.pause(); - subscription.resume(); - void close() { - d.deleteSync(recursive: true); - asyncEnd(); - } + subscription = d + .list(recursive: true) + .listen( + (entity) { + subscription.pause(); + subscription.resume(); + void close() { + d.deleteSync(recursive: true); + asyncEnd(); + } - var future = subscription.cancel(); - if (future != null) { - future.whenComplete(close); - } else { - close(); - } - }, onDone: () { - Expect.fail('the stream was canceled, onDone should not happen'); - }); + var future = subscription.cancel(); + if (future != null) { + future.whenComplete(close); + } else { + close(); + } + }, + onDone: () { + Expect.fail('the stream was canceled, onDone should not happen'); + }, + ); }); } diff --git a/tests/standalone/io/directory_list_sync_test.dart b/tests/standalone/io/directory_list_sync_test.dart index 6e3b257cfc0..8d1a5788cbf 100644 --- a/tests/standalone/io/directory_list_sync_test.dart +++ b/tests/standalone/io/directory_list_sync_test.dart @@ -7,11 +7,14 @@ import 'dart:io'; import 'package:path/path.dart' as path; void testList() { - final startingDir = - Directory(path.normalize(path.join(Platform.executable, '../../../'))); + final startingDir = Directory( + path.normalize(path.join(Platform.executable, '../../../')), + ); print("Recursively listing entries in directory ${startingDir.path} ..."); - List each = - startingDir.listSync(recursive: true, followLinks: false); + List each = startingDir.listSync( + recursive: true, + followLinks: false, + ); print("Found: ${each.length} entities"); } diff --git a/tests/standalone/io/directory_non_ascii_sync_test.dart b/tests/standalone/io/directory_non_ascii_sync_test.dart index df2283fc0c5..20c9ed31510 100644 --- a/tests/standalone/io/directory_non_ascii_sync_test.dart +++ b/tests/standalone/io/directory_non_ascii_sync_test.dart @@ -6,8 +6,9 @@ import "package:expect/expect.dart"; import 'dart:io'; main() { - Directory tempDir = - Directory.systemTemp.createTempSync('dart_directory_non_ascii_sync'); + Directory tempDir = Directory.systemTemp.createTempSync( + 'dart_directory_non_ascii_sync', + ); var nonAsciiDir = new Directory("${tempDir.path}/æøå"); // On MacOS you get the decomposed utf8 form of file and directory // names from the system. Therefore, we have to check for both here. @@ -18,11 +19,13 @@ main() { Expect.isTrue(nonAsciiDir.existsSync()); var temp = new Directory("${tempDir.path}/æøå").createTempSync('tempdir'); Expect.isTrue( - temp.path.contains(precomposed) || temp.path.contains(decomposed)); + temp.path.contains(precomposed) || temp.path.contains(decomposed), + ); temp.deleteSync(); temp = tempDir.createTempSync('æøå'); Expect.isTrue( - temp.path.contains(precomposed) || temp.path.contains(decomposed)); + temp.path.contains(precomposed) || temp.path.contains(decomposed), + ); temp.deleteSync(); tempDir.deleteSync(recursive: true); Expect.isFalse(nonAsciiDir.existsSync()); diff --git a/tests/standalone/io/directory_non_ascii_test.dart b/tests/standalone/io/directory_non_ascii_test.dart index 89cc09e80d0..bc1fa5c829f 100644 --- a/tests/standalone/io/directory_non_ascii_test.dart +++ b/tests/standalone/io/directory_non_ascii_test.dart @@ -25,14 +25,16 @@ main() { .then((e) => Expect.isTrue(e)) .then((_) => new Directory("${tempDir.path}/æøå").createTemp('temp')) .then((temp) { - Expect.isTrue(temp.path.contains(precomposed) || - temp.path.contains(decomposed)); + Expect.isTrue( + temp.path.contains(precomposed) || temp.path.contains(decomposed), + ); return temp.delete(); }) .then((_) => tempDir.createTemp('æøå')) .then((temp) { - Expect.isTrue(temp.path.contains(precomposed) || - temp.path.contains(decomposed)); + Expect.isTrue( + temp.path.contains(precomposed) || temp.path.contains(decomposed), + ); return temp.delete(); }) .then((temp) => Expect.isFalse(temp.existsSync())) diff --git a/tests/standalone/io/directory_rename_test.dart b/tests/standalone/io/directory_rename_test.dart index bb0a96aefc5..254772f721c 100644 --- a/tests/standalone/io/directory_rename_test.dart +++ b/tests/standalone/io/directory_rename_test.dart @@ -28,13 +28,15 @@ testRenamePath() async { final newDir = oldDir.renameSync("${tempDir.path}/dir2"); Expect.isTrue( - oldDir.path == "${tempDir.path}/dir1", - "${oldDir.path} != '${tempDir.path}/dir1'" - "- path should not be updated"); + oldDir.path == "${tempDir.path}/dir1", + "${oldDir.path} != '${tempDir.path}/dir1'" + "- path should not be updated", + ); Expect.isTrue( - newDir.path == "${tempDir.path}/dir2", - "${newDir.path} != '${tempDir.path}/dir2'" - "- path should be updated"); + newDir.path == "${tempDir.path}/dir2", + "${newDir.path} != '${tempDir.path}/dir2'" + "- path should be updated", + ); }); } @@ -63,19 +65,24 @@ testRenameToExistingFile() async { Expect.fail('Directory.rename should fail to rename a non-directory'); } on FileSystemException catch (e) { if (Platform.isWindows) { - Expect.isTrue(e.osError!.message.contains('file already exists'), - 'Unexpected error: $e'); + Expect.isTrue( + e.osError!.message.contains('file already exists'), + 'Unexpected error: $e', + ); } else if (Platform.isLinux || Platform.isMacOS) { - Expect.isTrue(e.osError!.message.contains('Not a directory'), - 'Unexpected error: $e'); + Expect.isTrue( + e.osError!.message.contains('Not a directory'), + 'Unexpected error: $e', + ); } } }); } testRenameToExistingEmptyDirectory() async { - await withTempDir('testRenameToExistingEmptyDirectory', - (Directory tempDir) async { + await withTempDir('testRenameToExistingEmptyDirectory', ( + Directory tempDir, + ) async { final dir1 = Directory("${tempDir.path}/dir1"); dir1.createSync(); File("${dir1.path}/file").createSync(); @@ -88,8 +95,9 @@ testRenameToExistingEmptyDirectory() async { // Verify that the file contained in dir1 has been moved. if (Platform.isWindows) { Expect.fail( - 'Directory.rename should fail to rename over an existing directory ' - 'on Windows'); + 'Directory.rename should fail to rename over an existing directory ' + 'on Windows', + ); } else { Expect.isTrue(File("${dir2.path}/file").existsSync()); } @@ -104,8 +112,9 @@ testRenameToExistingEmptyDirectory() async { } testRenameToExistingNonEmptyDirectory() async { - await withTempDir('testRenameToExistingNonEmptyDirectory', - (Directory tempDir) async { + await withTempDir('testRenameToExistingNonEmptyDirectory', ( + Directory tempDir, + ) async { final dir1 = Directory("${tempDir.path}/dir1"); dir1.createSync(); File("${dir1.path}/file1").createSync(); @@ -117,14 +126,19 @@ testRenameToExistingNonEmptyDirectory() async { try { dir1.renameSync(dir2.path); Expect.fail( - 'Directory.rename should fail to rename a non-empty directory'); + 'Directory.rename should fail to rename a non-empty directory', + ); } on FileSystemException catch (e) { if (Platform.isWindows) { - Expect.isTrue(e.osError!.message.contains('file already exists'), - 'Unexpected error: $e'); + Expect.isTrue( + e.osError!.message.contains('file already exists'), + 'Unexpected error: $e', + ); } else if (Platform.isLinux || Platform.isMacOS) { - Expect.isTrue(e.osError!.message.contains('Directory not empty'), - 'Unexpected error: $e'); + Expect.isTrue( + e.osError!.message.contains('Directory not empty'), + 'Unexpected error: $e', + ); } } }); @@ -140,13 +154,19 @@ testRenameButActuallyFile() async { Expect.fail("Expected a failure to rename the file."); } on FileSystemException catch (e) { Expect.isTrue( - e.message.contains('Rename failed'), 'Unexpected error: $e'); + e.message.contains('Rename failed'), + 'Unexpected error: $e', + ); if (Platform.isWindows) { - Expect.isTrue(e.osError!.message.contains('cannot find the file'), - 'Unexpected error: $e'); + Expect.isTrue( + e.osError!.message.contains('cannot find the file'), + 'Unexpected error: $e', + ); } else if (Platform.isLinux || Platform.isMacOS) { - Expect.isTrue(e.osError!.message.contains('Not a directory'), - 'Unexpected error: $e'); + Expect.isTrue( + e.osError!.message.contains('Not a directory'), + 'Unexpected error: $e', + ); } } }); diff --git a/tests/standalone/io/directory_test.dart b/tests/standalone/io/directory_test.dart index de192bb25ec..a95070025d8 100644 --- a/tests/standalone/io/directory_test.dart +++ b/tests/standalone/io/directory_test.dart @@ -15,8 +15,9 @@ class DirectoryTest { bool listedDir = false; bool listedFile = false; - Directory directory = - Directory.systemTemp.createTempSync('dart_directory_test'); + Directory directory = Directory.systemTemp.createTempSync( + 'dart_directory_test', + ); Directory subDirectory = new Directory("${directory.path}/subdir"); Expect.isTrue('$directory'.contains(directory.path)); Expect.isFalse(subDirectory.existsSync()); @@ -52,33 +53,40 @@ class DirectoryTest { testSyncListing(true); testSyncListing(false); Expect.equals( - f.resolveSymbolicLinksSync(), fLong.resolveSymbolicLinksSync()); + f.resolveSymbolicLinksSync(), + fLong.resolveSymbolicLinksSync(), + ); asyncStart(); - directory.list(recursive: true).listen((FileSystemEntity entity) { - if (entity is File) { - var path = entity.path; - listedFile = true; - Expect.isTrue(path.contains(directory.path)); - Expect.isTrue(path.contains('subdir')); - Expect.isTrue(path.contains('file.txt')); - } else { - var path = entity.path; - Expect.isTrue(entity is Directory); - listedDir = true; - Expect.isTrue(path.contains(directory.path)); - Expect.isTrue(path.contains('subdir')); - } - }, onDone: () { - Expect.isTrue(listedDir, "directory not found"); - Expect.isTrue(listedFile, "file not found"); - directory.delete(recursive: true).then((ignore) { - f.exists().then((exists) => Expect.isFalse(exists)); - directory.exists().then((exists) => Expect.isFalse(exists)); - subDirectory.exists().then((exists) => Expect.isFalse(exists)); - asyncEnd(); - }); - }); + directory + .list(recursive: true) + .listen( + (FileSystemEntity entity) { + if (entity is File) { + var path = entity.path; + listedFile = true; + Expect.isTrue(path.contains(directory.path)); + Expect.isTrue(path.contains('subdir')); + Expect.isTrue(path.contains('file.txt')); + } else { + var path = entity.path; + Expect.isTrue(entity is Directory); + listedDir = true; + Expect.isTrue(path.contains(directory.path)); + Expect.isTrue(path.contains('subdir')); + } + }, + onDone: () { + Expect.isTrue(listedDir, "directory not found"); + Expect.isTrue(listedFile, "file not found"); + directory.delete(recursive: true).then((ignore) { + f.exists().then((exists) => Expect.isFalse(exists)); + directory.exists().then((exists) => Expect.isFalse(exists)); + subDirectory.exists().then((exists) => Expect.isFalse(exists)); + asyncEnd(); + }); + }, + ); // Listing is asynchronous, so nothing should be listed at this // point. @@ -87,8 +95,9 @@ class DirectoryTest { } static void testListingTailingPaths() { - Directory directory = - Directory.systemTemp.createTempSync('dart_directory_test'); + Directory directory = Directory.systemTemp.createTempSync( + 'dart_directory_test', + ); Directory subDirectory = new Directory("${directory.path}/subdir/"); subDirectory.createSync(); File f = new File('${subDirectory.path}/file.txt'); @@ -100,18 +109,22 @@ class DirectoryTest { subDirectory.listSync().forEach(test); - subDirectory.list().listen(test, onDone: () { - directory.deleteSync(recursive: true); - }); + subDirectory.list().listen( + test, + onDone: () { + directory.deleteSync(recursive: true); + }, + ); } static void testListNonExistent() { setupListerHandlers(Stream stream) { stream.listen( - (_) => Expect.fail("Listing of non-existing directory should fail"), - onError: (error) { - Expect.isTrue(error is FileSystemException); - }); + (_) => Expect.fail("Listing of non-existing directory should fail"), + onError: (error) { + Expect.isTrue(error is FileSystemException); + }, + ); } Directory.systemTemp.createTemp('dart_directory').then((d) { @@ -128,15 +141,16 @@ class DirectoryTest { var errors = 0; setupListHandlers(Stream stream) { stream.listen( - (_) => Expect.fail("Listing of non-existing directory should fail"), - onError: (error) { - Expect.isTrue(error is FileSystemException); - if (++errors == 2) { - d.delete(recursive: true).then((_) { - asyncEnd(); - }); - } - }); + (_) => Expect.fail("Listing of non-existing directory should fail"), + onError: (error) { + Expect.isTrue(error is FileSystemException); + if (++errors == 2) { + d.delete(recursive: true).then((_) { + asyncEnd(); + }); + } + }, + ); } var subDirName = 'subdir'; @@ -159,11 +173,13 @@ class DirectoryTest { static void testDeleteNonExistent() { // Test that deleting a non-existing directory fails. setupFutureHandlers(future) { - future.then((ignore) { - Expect.fail("Deletion of non-existing directory should fail"); - }).catchError((error) { - Expect.isTrue(error is PathNotFoundException); - }); + future + .then((ignore) { + Expect.fail("Deletion of non-existing directory should fail"); + }) + .catchError((error) { + Expect.isTrue(error is PathNotFoundException); + }); } Directory.systemTemp.createTemp('dart_directory').then((d) { @@ -221,15 +237,20 @@ class DirectoryTest { } var long = new Directory("${buffer.toString()}"); // Works only on Windows. - long.delete(recursive: true).then((_) { - if (Platform.isWindows) { - asyncEnd(); - } - }, onError: ((_) { - if (!Platform.isWindows) { - asyncEnd(); - } - })); + long + .delete(recursive: true) + .then( + (_) { + if (Platform.isWindows) { + asyncEnd(); + } + }, + onError: ((_) { + if (!Platform.isWindows) { + asyncEnd(); + } + }), + ); }); }); } @@ -411,14 +432,19 @@ class DirectoryTest { l.createSync("${path}target"); d.deleteSync(); int count = 0; - tmp.list(followLinks: true).listen((file) { - count++; - Expect.isTrue(file is Link); - }, onDone: () { - Expect.equals(1, count); - l.deleteSync(); - tmp.deleteSync(); - }); + tmp + .list(followLinks: true) + .listen( + (file) { + count++; + Expect.isTrue(file is Link); + }, + onDone: () { + Expect.equals(1, count); + l.deleteSync(); + tmp.deleteSync(); + }, + ); } static void testListLinkSync() { @@ -429,15 +455,20 @@ class DirectoryTest { Link l = new Link("${path}symlink"); l.createSync("${path}target"); int count = 0; - tmp.list(followLinks: true).listen((file) { - count++; - Expect.isTrue(file is Directory); - }, onDone: () { - Expect.equals(2, count); - l.deleteSync(); - d.deleteSync(); - tmp.deleteSync(); - }); + tmp + .list(followLinks: true) + .listen( + (file) { + count++; + Expect.isTrue(file is Directory); + }, + onDone: () { + Expect.equals(2, count); + l.deleteSync(); + d.deleteSync(); + tmp.deleteSync(); + }, + ); } static void testCreateTemp() { @@ -445,8 +476,9 @@ class DirectoryTest { String template = 'dart_temp_dir'; if (base.existsSync()) { asyncStart(); - Future.wait([base.createTemp(template), base.createTemp(template)]) - .then((tempDirs) { + Future.wait([base.createTemp(template), base.createTemp(template)]).then(( + tempDirs, + ) { Expect.notEquals(tempDirs[0].path, tempDirs[1].path); for (Directory t in tempDirs) { Expect.isTrue(t.existsSync()); @@ -463,7 +495,7 @@ class DirectoryTest { asyncStart(); Future.wait([ Directory.systemTemp.createTemp(template), - Directory.systemTemp.createTemp(template) + Directory.systemTemp.createTemp(template), ]).then((tempDirs) { Expect.notEquals(tempDirs[0].path, tempDirs[1].path); for (Directory t in tempDirs) { @@ -589,8 +621,10 @@ String? illegalTempDirectoryLocation() { testCreateTempErrorSync() { var location = illegalTempDirectoryLocation(); if (location != null) { - Expect.throws(() => new Directory(location).createTempSync('dart_tempdir'), - (e) => e is FileSystemException); + Expect.throws( + () => new Directory(location).createTempSync('dart_tempdir'), + (e) => e is FileSystemException, + ); } } @@ -647,7 +681,9 @@ testCreateDirExistingFileSync() { file.createSync(); Expect.isTrue(file.existsSync()); Expect.throws( - new Directory(path).createSync, (e) => e is FileSystemException); + new Directory(path).createSync, + (e) => e is FileSystemException, + ); temp.deleteSync(recursive: true); } @@ -659,14 +695,17 @@ testCreateDirExistingFile() { var file = new File(path); var subDir = new Directory(path); file.create().then((_) { - subDir.create().then((_) { - Expect.fail("dir create should fail on existing file"); - }).catchError((error) { - Expect.isTrue(error is FileSystemException); - temp.delete(recursive: true).then((_) { - asyncEnd(); - }); - }); + subDir + .create() + .then((_) { + Expect.fail("dir create should fail on existing file"); + }) + .catchError((error) { + Expect.isTrue(error is FileSystemException); + temp.delete(recursive: true).then((_) { + asyncEnd(); + }); + }); }); }); } diff --git a/tests/standalone/io/directory_uri_test.dart b/tests/standalone/io/directory_uri_test.dart index 16d43d7ea3d..17bd1e0fec6 100644 --- a/tests/standalone/io/directory_uri_test.dart +++ b/tests/standalone/io/directory_uri_test.dart @@ -19,11 +19,13 @@ void testFromUri() { dir.createSync(); Expect.isTrue(new Directory.fromUri(dirUri).existsSync()); Expect.isTrue( - new Directory.fromUri(Uri.base.resolveUri(dirUri)).existsSync()); + new Directory.fromUri(Uri.base.resolveUri(dirUri)).existsSync(), + ); Directory.current = temp.path; Expect.isTrue(new Directory.fromUri(Uri.parse('from_uri')).existsSync()); Expect.isTrue( - new Directory.fromUri(Uri.base.resolve('from_uri')).existsSync()); + new Directory.fromUri(Uri.base.resolve('from_uri')).existsSync(), + ); Directory.current = originalWorkingDirectory; dir.deleteSync(); temp.deleteSync(recursive: true); @@ -32,12 +34,15 @@ void testFromUri() { } void testFromUriUnsupported() { - Expect.throwsUnsupportedError(() => - new Directory.fromUri(Uri.parse('http://localhost:8080/index.html'))); Expect.throwsUnsupportedError( - () => new Directory.fromUri(Uri.parse('ftp://localhost/tmp/xxx'))); + () => new Directory.fromUri(Uri.parse('http://localhost:8080/index.html')), + ); Expect.throwsUnsupportedError( - () => new Directory.fromUri(Uri.parse('name#fragment'))); + () => new Directory.fromUri(Uri.parse('ftp://localhost/tmp/xxx')), + ); + Expect.throwsUnsupportedError( + () => new Directory.fromUri(Uri.parse('name#fragment')), + ); } void main() { diff --git a/tests/standalone/io/exit_works_with_blocked_isolate_test.dart b/tests/standalone/io/exit_works_with_blocked_isolate_test.dart index 76b26ecdbeb..99ed4cfa7ad 100644 --- a/tests/standalone/io/exit_works_with_blocked_isolate_test.dart +++ b/tests/standalone/io/exit_works_with_blocked_isolate_test.dart @@ -5,8 +5,9 @@ import "dart:io"; import "dart:isolate"; -final bool isAppJitTrainingRun = - Platform.executableArguments.any((arg) => arg == '--snapshot-kind=app-jit'); +final bool isAppJitTrainingRun = Platform.executableArguments.any( + (arg) => arg == '--snapshot-kind=app-jit', +); child(msg) { // This should work even though the parent isolate is blocked and won't diff --git a/tests/standalone/io/file_absolute_path_test.dart b/tests/standalone/io/file_absolute_path_test.dart index bd5d97e0a2e..473fd29f1d4 100644 --- a/tests/standalone/io/file_absolute_path_test.dart +++ b/tests/standalone/io/file_absolute_path_test.dart @@ -39,7 +39,7 @@ testWindows() { 'c:/abd', 'D:\\rf', '\\\\a_share\\folder', - '\\\\?\\c:\\prefixed\path\\' + '\\\\?\\c:\\prefixed\path\\', ]) { Expect.isTrue(new File(absolute).absolute.path == absolute); Expect.isTrue(new File(absolute).absolute.isAbsolute); @@ -55,8 +55,10 @@ testPosix() { Expect.equals(new File(relative).absolute.path, '$current/$relative'); } Expect.isTrue(new File(relative).absolute.isAbsolute); - Expect.equals(new Directory(relative).absolute.path, - new Link(relative).absolute.path); + Expect.equals( + new Directory(relative).absolute.path, + new Link(relative).absolute.path, + ); Expect.isTrue(new File(relative).absolute is File); Expect.isTrue(new Directory(relative).absolute is Directory); Expect.isTrue(new Link(relative).absolute is Link); diff --git a/tests/standalone/io/file_blocking_lock_test.dart b/tests/standalone/io/file_blocking_lock_test.dart index 5df2fd191e2..b6de6cd0865 100644 --- a/tests/standalone/io/file_blocking_lock_test.dart +++ b/tests/standalone/io/file_blocking_lock_test.dart @@ -21,8 +21,9 @@ import "package:path/path.dart"; // Check whether the file is locked or not. runPeer(String path, int len, FileLock mode) { - var script = - Platform.script.resolve('file_blocking_lock_script.dart').toFilePath(); + var script = Platform.script + .resolve('file_blocking_lock_script.dart') + .toFilePath(); var arguments = [] ..addAll(Platform.executableArguments) ..add(script) diff --git a/tests/standalone/io/file_copy_test.dart b/tests/standalone/io/file_copy_test.dart index af4ad7fa2e2..605a6182022 100644 --- a/tests/standalone/io/file_copy_test.dart +++ b/tests/standalone/io/file_copy_test.dart @@ -83,30 +83,33 @@ void testCopy() { Expect.equals(FILE_CONTENT1, file1.readAsStringSync()); // Copy to new file works. - file1.copy('${tmp.path}/file2').then((file2) { - Expect.equals(FILE_CONTENT1, file1.readAsStringSync()); - Expect.equals(FILE_CONTENT1, file2.readAsStringSync()); + file1 + .copy('${tmp.path}/file2') + .then((file2) { + Expect.equals(FILE_CONTENT1, file1.readAsStringSync()); + Expect.equals(FILE_CONTENT1, file2.readAsStringSync()); - // Override works for files. - file2.writeAsStringSync(FILE_CONTENT2); - return file2.copy(file1.path).then((_) { - Expect.equals(FILE_CONTENT2, file1.readAsStringSync()); - Expect.equals(FILE_CONTENT2, file2.readAsStringSync()); + // Override works for files. + file2.writeAsStringSync(FILE_CONTENT2); + return file2.copy(file1.path).then((_) { + Expect.equals(FILE_CONTENT2, file1.readAsStringSync()); + Expect.equals(FILE_CONTENT2, file2.readAsStringSync()); - // Fail when coping to directory. - var dir = new Directory('${tmp.path}/dir')..createSync(); + // Fail when coping to directory. + var dir = new Directory('${tmp.path}/dir')..createSync(); - return file1 - .copy(dir.path) - .then((_) => Expect.fail('expected error'), onError: (_) {}) - .then((_) { - Expect.equals(FILE_CONTENT2, file1.readAsStringSync()); + return file1 + .copy(dir.path) + .then((_) => Expect.fail('expected error'), onError: (_) {}) + .then((_) { + Expect.equals(FILE_CONTENT2, file1.readAsStringSync()); + }); + }); + }) + .whenComplete(() { + tmp.deleteSync(recursive: true); + asyncEnd(); }); - }); - }).whenComplete(() { - tmp.deleteSync(recursive: true); - asyncEnd(); - }); } main() { diff --git a/tests/standalone/io/file_create_test.dart b/tests/standalone/io/file_create_test.dart index fab52a23c99..a3162949e9d 100644 --- a/tests/standalone/io/file_create_test.dart +++ b/tests/standalone/io/file_create_test.dart @@ -31,7 +31,9 @@ testExclusiveCreate() async { Expect.equals(file, createdFile); Expect.isTrue(await createdFile.exists()); Expect.throws( - () => file.createSync(exclusive: true), (e) => e is FileSystemException); + () => file.createSync(exclusive: true), + (e) => e is FileSystemException, + ); bool createFailed = false; try { await file.create(exclusive: true); diff --git a/tests/standalone/io/file_error2_test.dart b/tests/standalone/io/file_error2_test.dart index 431721117c9..94bc505ec08 100644 --- a/tests/standalone/io/file_error2_test.dart +++ b/tests/standalone/io/file_error2_test.dart @@ -21,7 +21,9 @@ testReadSyncBigInt() { var bigint = 9223372036854775807; var openedFile = file.openSync(); Expect.throws( - () => openedFile.readSync(bigint), (e) => e is FileSystemException); + () => openedFile.readSync(bigint), + (e) => e is FileSystemException, + ); openedFile.closeSync(); done(); }); diff --git a/tests/standalone/io/file_error_test.dart b/tests/standalone/io/file_error_test.dart index 27626bf77b5..068ca3c531c 100644 --- a/tests/standalone/io/file_error_test.dart +++ b/tests/standalone/io/file_error_test.dart @@ -47,7 +47,9 @@ bool checkDeleteNonExistentFileSystemException(e) { bool checkLengthNonExistentFileSystemException(e) { return checkNonExistentFileSystemException( - e, "Cannot retrieve length of file"); + e, + "Cannot retrieve length of file", + ); } void testOpenBlankFilename() { @@ -72,7 +74,9 @@ void testOpenNonExistent() { // Non-existing file should throw exception. Expect.throws( - () => file.openSync(), (e) => checkOpenNonExistentFileSystemException(e)); + () => file.openSync(), + (e) => checkOpenNonExistentFileSystemException(e), + ); var openFuture = file.open(mode: FileMode.read); openFuture.then((raf) => Expect.fail("Unreachable code")).catchError((error) { @@ -89,8 +93,10 @@ void testDeleteNonExistent() { var file = new File("${temp.path}/nonExistentFile"); // Non-existing file should throw exception. - Expect.throws(() => file.deleteSync(), - (e) => checkDeleteNonExistentFileSystemException(e)); + Expect.throws( + () => file.deleteSync(), + (e) => checkDeleteNonExistentFileSystemException(e), + ); var delete = file.delete(); delete.then((ignore) => Expect.fail("Unreachable code")).catchError((error) { @@ -107,8 +113,10 @@ void testLengthNonExistent() { var file = new File("${temp.path}/nonExistentFile"); // Non-existing file should throw exception. - Expect.throws(() => file.lengthSync(), - (e) => checkLengthNonExistentFileSystemException(e)); + Expect.throws( + () => file.lengthSync(), + (e) => checkLengthNonExistentFileSystemException(e), + ); var lenFuture = file.length(); lenFuture.then((len) => Expect.fail("Unreachable code")).catchError((error) { @@ -140,8 +148,10 @@ void testCreateInNonExistentDirectory() { var file = new File("${temp.path}/nonExistentDirectory/newFile"); // Create in nonexistent directory should throw exception. - Expect.throws(() => file.createSync(), - (e) => checkCreateInNonExistentFileSystemException(e)); + Expect.throws( + () => file.createSync(), + (e) => checkCreateInNonExistentFileSystemException(e), + ); var create = file.create(); create.then((ignore) => Expect.fail("Unreachable code")).catchError((error) { @@ -168,18 +178,20 @@ void testResolveSymbolicLinksOnNonExistentDirectory() { var file = new File("${temp.path}/nonExistentDirectory"); // Full path nonexistent directory should throw exception. - Expect.throws(() => file.resolveSymbolicLinksSync(), - (e) => checkResolveSymbolicLinksOnNonExistentFileSystemException(e)); + Expect.throws( + () => file.resolveSymbolicLinksSync(), + (e) => checkResolveSymbolicLinksOnNonExistentFileSystemException(e), + ); var resolvedFuture = file.resolveSymbolicLinks(); resolvedFuture .then((path) => Expect.fail("Unreachable code $path")) .catchError((error) { - checkResolveSymbolicLinksOnNonExistentFileSystemException(error); - temp.deleteSync(recursive: true); - asyncEnd(); - return file; - }); + checkResolveSymbolicLinksOnNonExistentFileSystemException(error); + temp.deleteSync(recursive: true); + asyncEnd(); + return file; + }); } void testReadAsBytesNonExistent() { @@ -188,13 +200,15 @@ void testReadAsBytesNonExistent() { var file = new File("${temp.path}/nonExistentFile3"); // Non-existing file should throw exception. - Expect.throws(() => file.readAsBytesSync(), - (e) => checkOpenNonExistentFileSystemException(e)); + Expect.throws( + () => file.readAsBytesSync(), + (e) => checkOpenNonExistentFileSystemException(e), + ); var readAsBytesFuture = file.readAsBytes(); - readAsBytesFuture - .then((data) => Expect.fail("Unreachable code")) - .catchError((error) { + readAsBytesFuture.then((data) => Expect.fail("Unreachable code")).catchError(( + error, + ) { checkOpenNonExistentFileSystemException(error); temp.deleteSync(recursive: true); asyncEnd(); @@ -208,18 +222,20 @@ void testReadAsTextNonExistent() { var file = new File("${temp.path}/nonExistentFile4"); // Non-existing file should throw exception. - Expect.throws(() => file.readAsStringSync(), - (e) => checkOpenNonExistentFileSystemException(e)); + Expect.throws( + () => file.readAsStringSync(), + (e) => checkOpenNonExistentFileSystemException(e), + ); var readAsStringFuture = file.readAsString(encoding: ascii); - readAsStringFuture - .then((data) => Expect.fail("Unreachable code")) - .catchError((error) { - checkOpenNonExistentFileSystemException(error); - temp.deleteSync(recursive: true); - asyncEnd(); - return file; - }); + readAsStringFuture.then((data) => Expect.fail("Unreachable code")).catchError( + (error) { + checkOpenNonExistentFileSystemException(error); + temp.deleteSync(recursive: true); + asyncEnd(); + return file; + }, + ); } testReadAsLinesNonExistent() { @@ -228,13 +244,15 @@ testReadAsLinesNonExistent() { var file = new File("${temp.path}/nonExistentFile5"); // Non-existing file should throw exception. - Expect.throws(() => file.readAsLinesSync(), - (e) => checkOpenNonExistentFileSystemException(e)); + Expect.throws( + () => file.readAsLinesSync(), + (e) => checkOpenNonExistentFileSystemException(e), + ); var readAsLinesFuture = file.readAsLines(encoding: ascii); - readAsLinesFuture - .then((data) => Expect.fail("Unreachable code")) - .catchError((error) { + readAsLinesFuture.then((data) => Expect.fail("Unreachable code")).catchError(( + error, + ) { checkOpenNonExistentFileSystemException(error); temp.deleteSync(recursive: true); asyncEnd(); @@ -268,8 +286,10 @@ testWriteByteToReadOnlyFile() { var openedFile = file.openSync(mode: FileMode.read); // Writing to read only file should throw an exception. - Expect.throws(() => openedFile.writeByteSync(0), - (e) => checkWriteReadOnlyFileSystemException(e)); + Expect.throws( + () => openedFile.writeByteSync(0), + (e) => checkWriteReadOnlyFileSystemException(e), + ); var writeByteFuture = openedFile.writeByte(0); writeByteFuture.catchError((error) { @@ -286,8 +306,10 @@ testWriteFromToReadOnlyFile() { List data = [0, 1, 2, 3]; // Writing to read only file should throw an exception. - Expect.throws(() => openedFile.writeFromSync(data, 0, data.length), - (e) => checkWriteReadOnlyFileSystemException(e)); + Expect.throws( + () => openedFile.writeFromSync(data, 0, data.length), + (e) => checkWriteReadOnlyFileSystemException(e), + ); var writeFromFuture = openedFile.writeFrom(data, 0, data.length); writeFromFuture.catchError((error) { @@ -306,17 +328,19 @@ testTruncateReadOnlyFile() { openedFile = file.openSync(mode: FileMode.read); // Truncating read only file should throw an exception. - Expect.throws(() => openedFile.truncateSync(0), - (e) => checkWriteReadOnlyFileSystemException(e)); + Expect.throws( + () => openedFile.truncateSync(0), + (e) => checkWriteReadOnlyFileSystemException(e), + ); var truncateFuture = openedFile.truncate(0); - truncateFuture - .then((ignore) => Expect.fail("Unreachable code")) - .catchError((error) { - checkWriteReadOnlyFileSystemException(error); - openedFile.close().then((_) => done()); - return openedFile; - }); + truncateFuture.then((ignore) => Expect.fail("Unreachable code")).catchError( + (error) { + checkWriteReadOnlyFileSystemException(error); + openedFile.close().then((_) => done()); + return openedFile; + }, + ); }); } @@ -334,25 +358,45 @@ testOperateOnClosedFile() { List data = [0, 1, 2, 3]; Expect.throws( - () => openedFile.readByteSync(), (e) => checkFileClosedException(e)); + () => openedFile.readByteSync(), + (e) => checkFileClosedException(e), + ); Expect.throws( - () => openedFile.writeByteSync(0), (e) => checkFileClosedException(e)); - Expect.throws(() => openedFile.writeFromSync(data, 0, data.length), - (e) => checkFileClosedException(e)); - Expect.throws(() => openedFile.readIntoSync(data, 0, data.length), - (e) => checkFileClosedException(e)); - Expect.throws(() => openedFile.writeStringSync("Hello"), - (e) => checkFileClosedException(e)); + () => openedFile.writeByteSync(0), + (e) => checkFileClosedException(e), + ); Expect.throws( - () => openedFile.positionSync(), (e) => checkFileClosedException(e)); - Expect.throws(() => openedFile.setPositionSync(0), - (e) => checkFileClosedException(e)); + () => openedFile.writeFromSync(data, 0, data.length), + (e) => checkFileClosedException(e), + ); Expect.throws( - () => openedFile.truncateSync(0), (e) => checkFileClosedException(e)); + () => openedFile.readIntoSync(data, 0, data.length), + (e) => checkFileClosedException(e), + ); Expect.throws( - () => openedFile.lengthSync(), (e) => checkFileClosedException(e)); + () => openedFile.writeStringSync("Hello"), + (e) => checkFileClosedException(e), + ); Expect.throws( - () => openedFile.flushSync(), (e) => checkFileClosedException(e)); + () => openedFile.positionSync(), + (e) => checkFileClosedException(e), + ); + Expect.throws( + () => openedFile.setPositionSync(0), + (e) => checkFileClosedException(e), + ); + Expect.throws( + () => openedFile.truncateSync(0), + (e) => checkFileClosedException(e), + ); + Expect.throws( + () => openedFile.lengthSync(), + (e) => checkFileClosedException(e), + ); + Expect.throws( + () => openedFile.flushSync(), + (e) => checkFileClosedException(e), + ); var errorCount = 0; @@ -445,7 +489,9 @@ testReadSyncClosedFile() { var openedFile = file.openSync(); openedFile.closeSync(); Expect.throws( - () => openedFile.readSync(1), (e) => e is FileSystemException); + () => openedFile.readSync(1), + (e) => e is FileSystemException, + ); done(); }); } diff --git a/tests/standalone/io/file_input_stream_test.dart b/tests/standalone/io/file_input_stream_test.dart index fc2c7d5b87c..fbd1a3229dc 100644 --- a/tests/standalone/io/file_input_stream_test.dart +++ b/tests/standalone/io/file_input_stream_test.dart @@ -45,11 +45,13 @@ void testOpenStreamAsync() { // File contains "Hello Dart\nwassup!\n" var expected = "Hello Dart\nwassup!\n".codeUnits; var byteCount = 0; - (new File(fileName)).openRead().listen((d) => byteCount += d.length, - onDone: () { - Expect.equals(expected.length, byteCount); - asyncEnd(); - }); + (new File(fileName)).openRead().listen( + (d) => byteCount += d.length, + onDone: () { + Expect.equals(expected.length, byteCount); + asyncEnd(); + }, + ); } // Create a file that is big enough that a file stream will @@ -76,24 +78,28 @@ void testInputStreamTruncate() { // without getting all data. var streamedBytes = 0; var subscription; - subscription = file.openRead().listen((d) { - if (streamedBytes == 0) { - subscription.pause(); - // Truncate the file by opening it for writing. - file.open(mode: FileMode.write).then((opened) { - opened.close().then((_) { - Expect.equals(0, file.lengthSync()); - subscription.resume(); + subscription = file.openRead().listen( + (d) { + if (streamedBytes == 0) { + subscription.pause(); + // Truncate the file by opening it for writing. + file.open(mode: FileMode.write).then((opened) { + opened.close().then((_) { + Expect.equals(0, file.lengthSync()); + subscription.resume(); + }); }); - }); - } - streamedBytes += d.length; - }, onDone: () { - Expect.isTrue(streamedBytes > 0 && streamedBytes <= originalLength); - temp.delete(recursive: true).then((_) => asyncEnd()); - }, onError: (e) { - Expect.fail("Unexpected error"); - }); + } + streamedBytes += d.length; + }, + onDone: () { + Expect.isTrue(streamedBytes > 0 && streamedBytes <= originalLength); + temp.delete(recursive: true).then((_) => asyncEnd()); + }, + onError: (e) { + Expect.fail("Unexpected error"); + }, + ); } void testInputStreamDelete() { @@ -106,28 +112,35 @@ void testInputStreamDelete() { // without getting all data. var streamedBytes = 0; var subscription; - subscription = file.openRead().listen((d) { - if (streamedBytes == 0) { - subscription.pause(); - // Delete the underlying file by opening it for writing. - file.delete().then((deleted) { - Expect.isFalse(deleted.existsSync()); - subscription.resume(); - }).catchError((e) { - // On Windows, you cannot delete a file that is open - // somewhere else. The stream has this file open - // and therefore we get an error on deletion on Windows. - Expect.equals('windows', Platform.operatingSystem); - subscription.resume(); - }); - } - streamedBytes += d.length; - }, onDone: () { - Expect.equals(originalLength, streamedBytes); - temp.delete(recursive: true).then((_) => asyncEnd()); - }, onError: (e) { - Expect.fail("Unexpected error"); - }); + subscription = file.openRead().listen( + (d) { + if (streamedBytes == 0) { + subscription.pause(); + // Delete the underlying file by opening it for writing. + file + .delete() + .then((deleted) { + Expect.isFalse(deleted.existsSync()); + subscription.resume(); + }) + .catchError((e) { + // On Windows, you cannot delete a file that is open + // somewhere else. The stream has this file open + // and therefore we get an error on deletion on Windows. + Expect.equals('windows', Platform.operatingSystem); + subscription.resume(); + }); + } + streamedBytes += d.length; + }, + onDone: () { + Expect.equals(originalLength, streamedBytes); + temp.delete(recursive: true).then((_) => asyncEnd()); + }, + onError: (e) { + Expect.fail("Unexpected error"); + }, + ); } void testInputStreamAppend() { @@ -139,24 +152,28 @@ void testInputStreamAppend() { // underlying file and check that the stream gets all the data. var streamedBytes = 0; var subscription; - subscription = file.openRead().listen((d) { - if (streamedBytes == 0) { - subscription.pause(); - // Double the length of the underlying file. - file.readAsBytes().then((bytes) { - file.writeAsBytes(bytes, mode: FileMode.append).then((_) { - Expect.equals(2 * originalLength, file.lengthSync()); - subscription.resume(); + subscription = file.openRead().listen( + (d) { + if (streamedBytes == 0) { + subscription.pause(); + // Double the length of the underlying file. + file.readAsBytes().then((bytes) { + file.writeAsBytes(bytes, mode: FileMode.append).then((_) { + Expect.equals(2 * originalLength, file.lengthSync()); + subscription.resume(); + }); }); - }); - } - streamedBytes += d.length; - }, onDone: () { - Expect.equals(2 * originalLength, streamedBytes); - temp.delete(recursive: true).then((_) => asyncEnd()); - }, onError: (e) { - Expect.fail("Unexpected error"); - }); + } + streamedBytes += d.length; + }, + onDone: () { + Expect.equals(2 * originalLength, streamedBytes); + temp.delete(recursive: true).then((_) => asyncEnd()); + }, + onError: (e) { + Expect.fail("Unexpected error"); + }, + ); } void testInputStreamOffset() { @@ -167,14 +184,20 @@ void testInputStreamOffset() { var originalLength = writeLongFileSync(file); var streamedBytes = 0; if (expectedBytes < 0) expectedBytes = originalLength + expectedBytes; - file.openRead(start, end).listen((d) { - streamedBytes += d.length; - }, onDone: () { - Expect.equals(expectedBytes, streamedBytes); - temp.delete(recursive: true).then((_) => asyncEnd()); - }, onError: (e) { - Expect.fail("Unexpected error"); - }); + file + .openRead(start, end) + .listen( + (d) { + streamedBytes += d.length; + }, + onDone: () { + Expect.equals(expectedBytes, streamedBytes); + temp.delete(recursive: true).then((_) => asyncEnd()); + }, + onError: (e) { + Expect.fail("Unexpected error"); + }, + ); } test(10, 20, 10); @@ -195,15 +218,21 @@ void testInputStreamBadOffset() { var originalLength = writeLongFileSync(file); var streamedBytes = 0; bool error = false; - file.openRead(start, end).listen((d) { - streamedBytes += d.length; - }, onDone: () { - Expect.isTrue(error); - temp.deleteSync(recursive: true); - asyncEnd(); - }, onError: (e) { - error = true; - }); + file + .openRead(start, end) + .listen( + (d) { + streamedBytes += d.length; + }, + onDone: () { + Expect.isTrue(error); + temp.deleteSync(recursive: true); + asyncEnd(); + }, + onError: (e) { + error = true; + }, + ); } test(-1, null); @@ -222,15 +251,18 @@ void testStringLineSplitterEnding(String name, int length) { .transform(utf8.decoder) .transform(new LineSplitter()); int lineCount = 0; - lineStream.listen((line) { - lineCount++; - Expect.isTrue(lineCount <= 10); - if (line[0] != "#") { - Expect.equals("Line $lineCount", line); - } - }, onDone: () { - Expect.equals(10, lineCount); - }); + lineStream.listen( + (line) { + lineCount++; + Expect.isTrue(lineCount <= 10); + if (line[0] != "#") { + Expect.equals("Line $lineCount", line); + } + }, + onDone: () { + Expect.equals(10, lineCount); + }, + ); } main() { diff --git a/tests/standalone/io/file_leak_test.dart b/tests/standalone/io/file_leak_test.dart index ddfffde71df..da5e3c52146 100644 --- a/tests/standalone/io/file_leak_test.dart +++ b/tests/standalone/io/file_leak_test.dart @@ -94,11 +94,13 @@ class FileTest { var expected = [206, 187, 120, 46, 32, 120, 10]; Expect.listEquals(expected, text.codeUnits); var readAsStringFuture = f.readAsString(encoding: ascii); - readAsStringFuture.then((text) { - Expect.fail("Non-ascii char should cause error"); - }).catchError((e) { - asyncTestDone("testReadAsText"); - }); + readAsStringFuture + .then((text) { + Expect.fail("Non-ascii char should cause error"); + }) + .catchError((e) { + asyncTestDone("testReadAsText"); + }); }); }); }); @@ -116,12 +118,15 @@ class FileTest { static testMain() { asyncStart(); var outerZone = Zone.current; - var firstZone = Zone.current.fork(specification: ZoneSpecification( + var firstZone = Zone.current.fork( + specification: ZoneSpecification( handleUncaughtError: (self, parent, zone, error, stacktrace) { - asyncEnd(); - print("unittest-suite-success"); // For the test harness. - exit(0); - })); + asyncEnd(); + print("unittest-suite-success"); // For the test harness. + exit(0); + }, + ), + ); firstZone.run(() async { Expect.identical(firstZone, Zone.current); createTempDirectory(() { diff --git a/tests/standalone/io/file_lock_test.dart b/tests/standalone/io/file_lock_test.dart index 1f314f8ca22..3702ddb8ccf 100644 --- a/tests/standalone/io/file_lock_test.dart +++ b/tests/standalone/io/file_lock_test.dart @@ -23,8 +23,9 @@ check(String path, int start, int end, FileLock mode, {required bool locked}) { ..add('$start') ..add('$end'); var stacktrace = StackTrace.current; - return Process.run(Platform.executable, arguments) - .then((ProcessResult result) { + return Process.run(Platform.executable, arguments).then(( + ProcessResult result, + ) { if (result.exitCode != 0 || !result.stdout.contains(expected)) { print("Client failed, exit code ${result.exitCode}"); print(" stdout:"); @@ -40,13 +41,19 @@ check(String path, int start, int end, FileLock mode, {required bool locked}) { }); } -checkLocked(String path, - [int start = 0, int end = -1, FileLock mode = FileLock.exclusive]) => - check(path, start, end, mode, locked: true); +checkLocked( + String path, [ + int start = 0, + int end = -1, + FileLock mode = FileLock.exclusive, +]) => check(path, start, end, mode, locked: true); -checkNotLocked(String path, - [int start = 0, int end = -1, FileLock mode = FileLock.exclusive]) => - check(path, start, end, mode, locked: false); +checkNotLocked( + String path, [ + int start = 0, + int end = -1, + FileLock mode = FileLock.exclusive, +]) => check(path, start, end, mode, locked: false); void testLockWholeFile() { Directory directory = Directory.systemTemp.createTempSync('dart_file_lock'); @@ -55,16 +62,18 @@ void testLockWholeFile() { var raf = file.openSync(mode: FileMode.write); raf.lockSync(); asyncStart(); - checkLocked(file.path).then((_) { - return checkLocked(file.path, 0, 2).then((_) { - raf.unlockSync(); - return checkNotLocked(file.path).then((_) {}); - }); - }).whenComplete(() { - raf.closeSync(); - directory.deleteSync(recursive: true); - asyncEnd(); - }); + checkLocked(file.path) + .then((_) { + return checkLocked(file.path, 0, 2).then((_) { + raf.unlockSync(); + return checkNotLocked(file.path).then((_) {}); + }); + }) + .whenComplete(() { + raf.closeSync(); + directory.deleteSync(recursive: true); + asyncEnd(); + }); } void testLockWholeFileAsync() { @@ -116,11 +125,13 @@ void testLockRange() { () => checkLocked(file.path, 6), () => checkNotLocked(file.path, 7), () => raf2.unlockSync(6, 7), - () => checkNotLocked(file.path) + () => checkNotLocked(file.path), ]); } else { - tests - .addAll([() => raf2.unlockSync(5, 7), () => checkNotLocked(file.path)]); + tests.addAll([ + () => raf2.unlockSync(5, 7), + () => checkNotLocked(file.path), + ]); } Future.forEach(tests, (f) => f()).whenComplete(() { raf1.closeSync(); @@ -160,7 +171,7 @@ void testLockRangeAsync() { () => checkLocked(file.path, 6), () => checkNotLocked(file.path, 7), () => raf2.unlock(6, 7), - () => checkNotLocked(file.path) + () => checkNotLocked(file.path), ]); } else { tests.addAll([() => raf2.unlock(5, 7), () => checkNotLocked(file.path)]); @@ -188,7 +199,7 @@ void testLockEnd() { () => checkLocked(file.path, 10), () => checkLocked(file.path, 19), () => raf.unlockSync(2), - () => checkNotLocked(file.path) + () => checkNotLocked(file.path), ], (f) => f()).whenComplete(() { raf.closeSync(); directory.deleteSync(recursive: true); @@ -211,7 +222,7 @@ void testLockEndAsync() { () => checkLocked(file.path, 10), () => checkLocked(file.path, 19), () => raf.unlock(2), - () => checkNotLocked(file.path) + () => checkNotLocked(file.path), ], (f) => f()).whenComplete(() { raf.closeSync(); directory.deleteSync(recursive: true); @@ -229,7 +240,7 @@ void testLockShared() { () => raf.lock(FileLock.shared), () => checkLocked(file.path), () => checkLocked(file.path, 0, 2), - () => checkNotLocked(file.path, 0, 2, FileLock.shared) + () => checkNotLocked(file.path, 0, 2, FileLock.shared), ], (f) => f()).then((_) { raf.closeSync(); directory.deleteSync(recursive: true); @@ -247,7 +258,7 @@ void testLockSharedAsync() { () => raf.lock(FileLock.shared), () => checkLocked(file.path), () => checkLocked(file.path, 0, 2), - () => checkNotLocked(file.path, 0, 2, FileLock.shared) + () => checkNotLocked(file.path, 0, 2, FileLock.shared), ], (f) => f()).whenComplete(() { raf.closeSync(); directory.deleteSync(recursive: true); @@ -271,7 +282,7 @@ void testLockAfterLength() { () => checkLocked(file.path, 10), () => checkNotLocked(file.path, 15), () => raf.unlockSync(2, 15), - () => checkNotLocked(file.path) + () => checkNotLocked(file.path), ], (f) => f()).whenComplete(() { raf.closeSync(); directory.deleteSync(recursive: true); @@ -295,7 +306,7 @@ void testLockAfterLengthAsync() { () => checkLocked(file.path, 10), () => checkNotLocked(file.path, 15), () => raf.unlock(2, 15), - () => checkNotLocked(file.path) + () => checkNotLocked(file.path), ], (f) => f()).whenComplete(() { raf.closeSync(); directory.deleteSync(recursive: true); diff --git a/tests/standalone/io/file_long_path_test.dart b/tests/standalone/io/file_long_path_test.dart index bf82bf310d8..25c6e432cc0 100644 --- a/tests/standalone/io/file_long_path_test.dart +++ b/tests/standalone/io/file_long_path_test.dart @@ -99,11 +99,15 @@ void testFileStat(String dir) { file.setLastModifiedSync(dateTime); Expect.notEquals( - stat.modified.toString(), file.lastModifiedSync().toString()); + stat.modified.toString(), + file.lastModifiedSync().toString(), + ); file.setLastAccessedSync(dateTime); Expect.notEquals( - stat.accessed.toString(), file.lastAccessedSync().toString()); + stat.accessed.toString(), + file.lastAccessedSync().toString(), + ); } String _createDirectoryHelper(String currentDir, String targetDir) { @@ -122,10 +126,14 @@ void testCreateLinkToDir(String dir, String dir2) { Expect.isTrue(linkPath.length > maxPath); Expect.isTrue(renamedPath.length > maxPath); - final targetDirectory1 = - _createDirectoryHelper(dir, p.join(dir2, 'a_long_directory_target1')); - final targetDirectory2 = - _createDirectoryHelper(dir, p.join(dir2, 'a_long_directory_target2')); + final targetDirectory1 = _createDirectoryHelper( + dir, + p.join(dir2, 'a_long_directory_target1'), + ); + final targetDirectory2 = _createDirectoryHelper( + dir, + p.join(dir2, 'a_long_directory_target2'), + ); final linkTarget1 = p.isRelative(dir2) ? p.relative(targetDirectory1, from: p.dirname(p.absolute(linkPath))) @@ -140,8 +148,9 @@ void testCreateLinkToDir(String dir, String dir2) { Expect.isTrue(link.existsSync()); final resolvedCreatePath = link.resolveSymbolicLinksSync(); Expect.isTrue( - FileSystemEntity.identicalSync(targetDirectory1, resolvedCreatePath), - '${link.path} should resolve to $targetDirectory1 but resolved to $resolvedCreatePath'); + FileSystemEntity.identicalSync(targetDirectory1, resolvedCreatePath), + '${link.path} should resolve to $targetDirectory1 but resolved to $resolvedCreatePath', + ); // Rename link var renamedLink = link.renameSync(renamedPath); @@ -149,15 +158,17 @@ void testCreateLinkToDir(String dir, String dir2) { Expect.isFalse(link.existsSync()); final resolvedRenamePath = renamedLink.resolveSymbolicLinksSync(); Expect.isTrue( - FileSystemEntity.identicalSync(targetDirectory1, resolvedRenamePath), - '${link.path} should resolve to $targetDirectory1 but resolved to $resolvedRenamePath'); + FileSystemEntity.identicalSync(targetDirectory1, resolvedRenamePath), + '${link.path} should resolve to $targetDirectory1 but resolved to $resolvedRenamePath', + ); // Update link target renamedLink.updateSync(linkTarget2); final resolvedUpdatedPath = renamedLink.resolveSymbolicLinksSync(); Expect.isTrue( - FileSystemEntity.identicalSync(targetDirectory2, resolvedUpdatedPath), - '${link.path} should resolve to $targetDirectory2 but resolved to $resolvedRenamePath'); + FileSystemEntity.identicalSync(targetDirectory2, resolvedUpdatedPath), + '${link.path} should resolve to $targetDirectory2 but resolved to $resolvedRenamePath', + ); Directory(targetDirectory1).deleteSync(); Directory(targetDirectory2).deleteSync(); @@ -194,8 +205,10 @@ void testCreateLinkToFile(String dir, String dir2) { Expect.isTrue(link.existsSync()); final resolvedPath = link.resolveSymbolicLinksSync(); - Expect.isTrue(FileSystemEntity.identicalSync(target, resolvedPath), - '${link.path} should resolve to $target but resolved to $resolvedPath'); + Expect.isTrue( + FileSystemEntity.identicalSync(target, resolvedPath), + '${link.path} should resolve to $target but resolved to $resolvedPath', + ); // Rename link var renamedLink = link.renameSync(p.join(dir, 'a_renamed_long_path_link')); diff --git a/tests/standalone/io/file_non_ascii_sync_test.dart b/tests/standalone/io/file_non_ascii_sync_test.dart index f664797adbb..a7f7233d83e 100644 --- a/tests/standalone/io/file_non_ascii_sync_test.dart +++ b/tests/standalone/io/file_non_ascii_sync_test.dart @@ -6,8 +6,9 @@ import "package:expect/expect.dart"; import 'dart:io'; main() { - Directory tempDir = - Directory.systemTemp.createTempSync('dart_file_non_ascii_sync'); + Directory tempDir = Directory.systemTemp.createTempSync( + 'dart_file_non_ascii_sync', + ); Directory nonAsciiDir = new Directory('${tempDir.path}/æøå'); nonAsciiDir.createSync(); Expect.isTrue(nonAsciiDir.existsSync()); @@ -26,7 +27,8 @@ main() { Expect.equals(6, nonAsciiFile.lengthSync()); nonAsciiFile.lastModifiedSync(); path = nonAsciiFile.resolveSymbolicLinksSync(); - Expect.isTrue(path.endsWith('${precomposed}.txt') || - path.endsWith('${decomposed}.txt')); + Expect.isTrue( + path.endsWith('${precomposed}.txt') || path.endsWith('${decomposed}.txt'), + ); tempDir.deleteSync(recursive: true); } diff --git a/tests/standalone/io/file_non_ascii_test.dart b/tests/standalone/io/file_non_ascii_test.dart index 4eeac1c5b37..acb715434ff 100644 --- a/tests/standalone/io/file_non_ascii_test.dart +++ b/tests/standalone/io/file_non_ascii_test.dart @@ -15,30 +15,38 @@ main() { var precomposed = 'æøå'; var decomposed = new String.fromCharCodes([47, 230, 248, 97, 778]); - Directory.systemTemp.createTemp('dart_file_non_ascii').then((tempDir) { - Directory nonAsciiDir = new Directory('${tempDir.path}/æøå'); - nonAsciiDir.create().then((nonAsciiDir) { - nonAsciiDir.exists().then((result) { - Expect.isTrue(result); - File nonAsciiFile = new File('${nonAsciiDir.path}/æøå.txt'); - nonAsciiFile.writeAsString('æøå').then((_) { - nonAsciiFile.exists().then((result) { + Directory.systemTemp + .createTemp('dart_file_non_ascii') + .then((tempDir) { + Directory nonAsciiDir = new Directory('${tempDir.path}/æøå'); + nonAsciiDir.create().then((nonAsciiDir) { + nonAsciiDir.exists().then((result) { Expect.isTrue(result); - nonAsciiFile.readAsString().then((contents) { - // The contents of the file is precomposed utf8. - Expect.equals(precomposed, contents); - nonAsciiFile.create().then((_) { - var d = nonAsciiFile.parent; - Expect.isTrue(d.path.endsWith(precomposed) || - d.path.endsWith(decomposed)); - nonAsciiFile.length().then((length) { - Expect.equals(6, length); - nonAsciiFile.lastModified().then((_) { - nonAsciiFile.resolveSymbolicLinks().then((path) { - Expect.isTrue(path.endsWith('${precomposed}.txt') || - path.endsWith('${decomposed}.txt')); - tempDir.delete(recursive: true).then((_) { - asyncEnd(); + File nonAsciiFile = new File('${nonAsciiDir.path}/æøå.txt'); + nonAsciiFile.writeAsString('æøå').then((_) { + nonAsciiFile.exists().then((result) { + Expect.isTrue(result); + nonAsciiFile.readAsString().then((contents) { + // The contents of the file is precomposed utf8. + Expect.equals(precomposed, contents); + nonAsciiFile.create().then((_) { + var d = nonAsciiFile.parent; + Expect.isTrue( + d.path.endsWith(precomposed) || + d.path.endsWith(decomposed), + ); + nonAsciiFile.length().then((length) { + Expect.equals(6, length); + nonAsciiFile.lastModified().then((_) { + nonAsciiFile.resolveSymbolicLinks().then((path) { + Expect.isTrue( + path.endsWith('${precomposed}.txt') || + path.endsWith('${decomposed}.txt'), + ); + tempDir.delete(recursive: true).then((_) { + asyncEnd(); + }); + }); }); }); }); @@ -47,9 +55,8 @@ main() { }); }); }); + }) + .catchError((e) { + Expect.fail("File not found"); }); - }); - }).catchError((e) { - Expect.fail("File not found"); - }); } diff --git a/tests/standalone/io/file_output_stream_test.dart b/tests/standalone/io/file_output_stream_test.dart index cc89fcef53c..1d02b0fdbbf 100644 --- a/tests/standalone/io/file_output_stream_test.dart +++ b/tests/standalone/io/file_output_stream_test.dart @@ -9,8 +9,9 @@ import "package:expect/async_helper.dart"; import "package:expect/expect.dart"; void testOpenOutputStreamSync() { - Directory tempDirectory = - Directory.systemTemp.createTempSync('dart_file_output_stream'); + Directory tempDirectory = Directory.systemTemp.createTempSync( + 'dart_file_output_stream', + ); asyncStart(); String fileName = "${tempDirectory.path}/test"; diff --git a/tests/standalone/io/file_read_encoded_test.dart b/tests/standalone/io/file_read_encoded_test.dart index f5f85844065..31944ab12ee 100644 --- a/tests/standalone/io/file_read_encoded_test.dart +++ b/tests/standalone/io/file_read_encoded_test.dart @@ -17,12 +17,15 @@ void testReadAsString() { Expect.throws(file.readAsStringSync, (e) => e is FileSystemException); asyncStart(); - file.readAsString().then((_) { - Expect.fail("expected exception"); - }).catchError((e) { - tmp.deleteSync(recursive: true); - asyncEnd(); - }, test: (e) => e is FileSystemException); + file + .readAsString() + .then((_) { + Expect.fail("expected exception"); + }) + .catchError((e) { + tmp.deleteSync(recursive: true); + asyncEnd(); + }, test: (e) => e is FileSystemException); } void testReadAsLines() { @@ -36,12 +39,15 @@ void testReadAsLines() { Expect.throws(file.readAsLinesSync, (e) => e is FileSystemException); asyncStart(); - file.readAsLines().then((_) { - Expect.fail("expected exception"); - }).catchError((e) { - tmp.deleteSync(recursive: true); - asyncEnd(); - }, test: (e) => e is FileSystemException); + file + .readAsLines() + .then((_) { + Expect.fail("expected exception"); + }) + .catchError((e) { + tmp.deleteSync(recursive: true); + asyncEnd(); + }, test: (e) => e is FileSystemException); } void main() { diff --git a/tests/standalone/io/file_read_special_device_test.dart b/tests/standalone/io/file_read_special_device_test.dart index fcfd9cbb11e..19b91385b4d 100644 --- a/tests/standalone/io/file_read_special_device_test.dart +++ b/tests/standalone/io/file_read_special_device_test.dart @@ -14,7 +14,7 @@ void openAndWriteScript(String script) { var file = script; // Use script as file. Process.start("bash", [ "-c", - "$executable ${Platform.executableArguments.join(' ')} $script < $file" + "$executable ${Platform.executableArguments.join(' ')} $script < $file", ]).then((process) { process.exitCode.then((exitCode) { Expect.equals(0, exitCode); diff --git a/tests/standalone/io/file_stat_test.dart b/tests/standalone/io/file_stat_test.dart index ca75e32634e..d52297cfe65 100644 --- a/tests/standalone/io/file_stat_test.dart +++ b/tests/standalone/io/file_stat_test.dart @@ -44,9 +44,11 @@ void testStat() { Expect.equals(FileSystemEntityType.directory, directoryStatDirect.type); if (Platform.operatingSystem != 'windows') { Expect.isTrue( - directoryStat.modified.compareTo(directoryStat.accessed) < 0); + directoryStat.modified.compareTo(directoryStat.accessed) < 0, + ); Expect.isTrue( - directoryStat.changed.compareTo(directoryStat.accessed) < 0); + directoryStat.changed.compareTo(directoryStat.accessed) < 0, + ); } Expect.equals(7 << 6, directoryStat.mode & (7 << 6)); // Includes +urwx. @@ -64,63 +66,87 @@ Future testStatAsync() { return Directory.systemTemp.createTemp('dart_file_stat').then((directory) { File file = new File(join(directory.path, "file")); return FileStat.stat(file.path) - .then((fileStat) => - Expect.equals(FileSystemEntityType.notFound, fileStat.type)) + .then( + (fileStat) => + Expect.equals(FileSystemEntityType.notFound, fileStat.type), + ) .then((_) => file.stat()) - .then((fileStat) => - Expect.equals(FileSystemEntityType.notFound, fileStat.type)) + .then( + (fileStat) => + Expect.equals(FileSystemEntityType.notFound, fileStat.type), + ) .then((_) => file.writeAsString("Dart IO library test of FileStat")) .then((_) => new Future.delayed(const Duration(seconds: 2))) .then((_) => file.readAsString()) .then((_) => directory.list().last) .then((_) => FileStat.stat(file.path)) .then((FileStat fileStat) { - Expect.equals(FileSystemEntityType.file, fileStat.type); - Expect.equals(32, fileStat.size); - if (Platform.operatingSystem != 'windows') { - Expect.isTrue(fileStat.modified.compareTo(fileStat.accessed) < 0); - Expect.isTrue(fileStat.changed.compareTo(fileStat.accessed) < 0); - } - Expect.equals(6 << 6, fileStat.mode & (6 << 6)); // Mode includes +urw. - return file.stat(); - }).then((FileStat fileStat) { - Expect.equals(FileSystemEntityType.file, fileStat.type); - Expect.equals(32, fileStat.size); - if (Platform.operatingSystem != 'windows') { - Expect.isTrue(fileStat.modified.compareTo(fileStat.accessed) < 0); - Expect.isTrue(fileStat.changed.compareTo(fileStat.accessed) < 0); - } - Expect.equals(6 << 6, fileStat.mode & (6 << 6)); // Mode includes +urw. - return FileStat.stat(directory.path); - }).then((FileStat directoryStat) { - Expect.equals(FileSystemEntityType.directory, directoryStat.type); - if (Platform.operatingSystem != 'windows') { - Expect.isTrue( - directoryStat.modified.compareTo(directoryStat.accessed) < 0); - Expect.isTrue( - directoryStat.changed.compareTo(directoryStat.accessed) < 0); - } - Expect.equals(7 << 6, directoryStat.mode & (7 << 6)); // Includes +urwx. - return directory.stat(); - }).then((FileStat directoryStat) { - Expect.equals(FileSystemEntityType.directory, directoryStat.type); - if (Platform.operatingSystem != 'windows') { - Expect.isTrue( - directoryStat.modified.compareTo(directoryStat.accessed) < 0); - Expect.isTrue( - directoryStat.changed.compareTo(directoryStat.accessed) < 0); - } - Expect.equals(7 << 6, directoryStat.mode & (7 << 6)); // Includes +urwx. - return new Link(directory.path).stat(); - }).then((FileStat linkStat) { - Expect.equals(FileSystemEntityType.directory, linkStat.type); - if (Platform.operatingSystem != 'windows') { - Expect.isTrue(linkStat.modified.compareTo(linkStat.accessed) < 0); - Expect.isTrue(linkStat.changed.compareTo(linkStat.accessed) < 0); - } - Expect.equals(7 << 6, linkStat.mode & (7 << 6)); // Includes +urwx. - return directory.delete(recursive: true); - }); + Expect.equals(FileSystemEntityType.file, fileStat.type); + Expect.equals(32, fileStat.size); + if (Platform.operatingSystem != 'windows') { + Expect.isTrue(fileStat.modified.compareTo(fileStat.accessed) < 0); + Expect.isTrue(fileStat.changed.compareTo(fileStat.accessed) < 0); + } + Expect.equals( + 6 << 6, + fileStat.mode & (6 << 6), + ); // Mode includes +urw. + return file.stat(); + }) + .then((FileStat fileStat) { + Expect.equals(FileSystemEntityType.file, fileStat.type); + Expect.equals(32, fileStat.size); + if (Platform.operatingSystem != 'windows') { + Expect.isTrue(fileStat.modified.compareTo(fileStat.accessed) < 0); + Expect.isTrue(fileStat.changed.compareTo(fileStat.accessed) < 0); + } + Expect.equals( + 6 << 6, + fileStat.mode & (6 << 6), + ); // Mode includes +urw. + return FileStat.stat(directory.path); + }) + .then((FileStat directoryStat) { + Expect.equals(FileSystemEntityType.directory, directoryStat.type); + if (Platform.operatingSystem != 'windows') { + Expect.isTrue( + directoryStat.modified.compareTo(directoryStat.accessed) < 0, + ); + Expect.isTrue( + directoryStat.changed.compareTo(directoryStat.accessed) < 0, + ); + } + Expect.equals( + 7 << 6, + directoryStat.mode & (7 << 6), + ); // Includes +urwx. + return directory.stat(); + }) + .then((FileStat directoryStat) { + Expect.equals(FileSystemEntityType.directory, directoryStat.type); + if (Platform.operatingSystem != 'windows') { + Expect.isTrue( + directoryStat.modified.compareTo(directoryStat.accessed) < 0, + ); + Expect.isTrue( + directoryStat.changed.compareTo(directoryStat.accessed) < 0, + ); + } + Expect.equals( + 7 << 6, + directoryStat.mode & (7 << 6), + ); // Includes +urwx. + return new Link(directory.path).stat(); + }) + .then((FileStat linkStat) { + Expect.equals(FileSystemEntityType.directory, linkStat.type); + if (Platform.operatingSystem != 'windows') { + Expect.isTrue(linkStat.modified.compareTo(linkStat.accessed) < 0); + Expect.isTrue(linkStat.changed.compareTo(linkStat.accessed) < 0); + } + Expect.equals(7 << 6, linkStat.mode & (7 << 6)); // Includes +urwx. + return directory.delete(recursive: true); + }); }); } diff --git a/tests/standalone/io/file_stream_test.dart b/tests/standalone/io/file_stream_test.dart index 526936e15bd..0ff50d860cc 100644 --- a/tests/standalone/io/file_stream_test.dart +++ b/tests/standalone/io/file_stream_test.dart @@ -12,29 +12,30 @@ void testPauseResumeCancelStream() { asyncStart(); Directory.systemTemp.createTemp('dart_file_stream').then((d) { var file = new File("${d.path}/file"); - new File(Platform.executable) - .openRead() - .cast>() - .pipe(file.openWrite()) - .then((_) { + new File( + Platform.executable, + ).openRead().cast>().pipe(file.openWrite()).then((_) { var subscription; - subscription = file.openRead().listen((data) { - subscription.pause(); - subscription.resume(); - void close() { - d.deleteSync(recursive: true); - asyncEnd(); - } + subscription = file.openRead().listen( + (data) { + subscription.pause(); + subscription.resume(); + void close() { + d.deleteSync(recursive: true); + asyncEnd(); + } - var future = subscription.cancel(); - if (future != null) { - future.whenComplete(close); - } else { - close(); - } - }, onDone: () { - Expect.fail('the stream was canceled, onDone should not happen'); - }); + var future = subscription.cancel(); + if (future != null) { + future.whenComplete(close); + } else { + close(); + } + }, + onDone: () { + Expect.fail('the stream was canceled, onDone should not happen'); + }, + ); }); }); } @@ -43,11 +44,9 @@ void testStreamIsEmpty() { asyncStart(); Directory.systemTemp.createTemp('dart_file_stream').then((d) { var file = new File("${d.path}/file"); - new File(Platform.executable) - .openRead() - .cast>() - .pipe(file.openWrite()) - .then((_) { + new File( + Platform.executable, + ).openRead().cast>().pipe(file.openWrite()).then((_) { // isEmpty will cancel the stream after first data event. file.openRead().isEmpty.then((empty) { Expect.isFalse(empty); diff --git a/tests/standalone/io/file_system_async_links_test.dart b/tests/standalone/io/file_system_async_links_test.dart index ec90f38c4a5..ce8779c1db6 100644 --- a/tests/standalone/io/file_system_async_links_test.dart +++ b/tests/standalone/io/file_system_async_links_test.dart @@ -18,9 +18,10 @@ class FutureExpect { static Future listEquals(expected, Future result) => result.then((value) => Expect.listEquals(expected, value)); static Future throws(Future result) => result.then((value) { - throw new ExpectException( - "FutureExpect.throws received $value instead of an exception"); - }, onError: (_) => null); + throw new ExpectException( + "FutureExpect.throws received $value instead of an exception", + ); + }, onError: (_) => null); } Future testFileExistsCreate() { @@ -34,14 +35,30 @@ Future testFileExistsCreate() { .then((_) => FutureExpect.isFalse(new File(x).exists())) .then((_) => FutureExpect.isTrue(FileSystemEntity.isLink(y))) .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.notFound, FileSystemEntity.type(y))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.notFound, FileSystemEntity.type(x))) - .then((_) => FutureExpect.equals(FileSystemEntityType.link, - FileSystemEntity.type(y, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.notFound, - FileSystemEntity.type(x, followLinks: false))) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(y), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(x), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.link, + FileSystemEntity.type(y, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(x, followLinks: false), + ), + ) .then((_) => FutureExpect.equals(x, new Link(y).target())) .then((_) => new File(y).create()) .then((yFile) => Expect.equals(y, yFile.path)) @@ -51,14 +68,30 @@ Future testFileExistsCreate() { .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) .then((_) => FutureExpect.isTrue(FileSystemEntity.isFile(y))) .then((_) => FutureExpect.isTrue(FileSystemEntity.isFile(x))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.file, FileSystemEntity.type(y))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.file, FileSystemEntity.type(x))) - .then((_) => FutureExpect.equals(FileSystemEntityType.link, - FileSystemEntity.type(y, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.file, - FileSystemEntity.type(x, followLinks: false))) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.file, + FileSystemEntity.type(y), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.file, + FileSystemEntity.type(x), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.link, + FileSystemEntity.type(y, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.file, + FileSystemEntity.type(x, followLinks: false), + ), + ) .then((_) => FutureExpect.equals(x, new Link(y).target())) .then((_) => new File(x).delete()) .then((xDeletedFile) => Expect.equals(x, xDeletedFile.path)) @@ -68,22 +101,46 @@ Future testFileExistsCreate() { .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) .then((_) => FutureExpect.isTrue(FileSystemEntity.isDirectory(y))) .then((_) => FutureExpect.isTrue(FileSystemEntity.isDirectory(x))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.directory, FileSystemEntity.type(y))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.directory, FileSystemEntity.type(x))) - .then((_) => FutureExpect.equals(FileSystemEntityType.link, - FileSystemEntity.type(y, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.directory, - FileSystemEntity.type(x, followLinks: false))) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(y), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.link, + FileSystemEntity.type(y, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x, followLinks: false), + ), + ) .then((_) => FutureExpect.equals(x, new Link(y).target())) .then((_) => new Link(y).delete()) .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(y))) .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.notFound, FileSystemEntity.type(y))) .then( - (_) => FutureExpect.equals(FileSystemEntityType.directory, FileSystemEntity.type(x))) + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(y), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x), + ), + ) .then((_) => FutureExpect.throws(new Link(y).target())) .then((_) => temp.delete(recursive: true)); }); @@ -119,8 +176,10 @@ Future testFileWriteRead() { return new File(x) .create() .then((_) => new Link(y).create(x)) - .then((_) => - (new File(y).openWrite(mode: FileMode.write)..add(data)).close()) + .then( + (_) => + (new File(y).openWrite(mode: FileMode.write)..add(data)).close(), + ) .then((_) => FutureExpect.listEquals(data, new File(y).readAsBytes())) .then((_) => FutureExpect.listEquals(data, new File(x).readAsBytes())) .then((_) => temp.delete(recursive: true)); @@ -142,9 +201,9 @@ Future testDirectoryExistsCreate() { Future testDirectoryDelete() { return Directory.systemTemp.createTemp('dart_file_system_async').then((temp) { - return Directory.systemTemp - .createTemp('dart_file_system_async') - .then((temp2) { + return Directory.systemTemp.createTemp('dart_file_system_async').then(( + temp2, + ) { var y = '${temp.path}${Platform.pathSeparator}y'; var x = '${temp2.path}${Platform.pathSeparator}x'; var link = new Directory(y); @@ -170,25 +229,30 @@ Future testDirectoryDelete() { Future testDirectoryListing() { return Directory.systemTemp.createTemp('dart_file_system_async').then((temp) { - return Directory.systemTemp - .createTemp('dart_file_system_async_links') - .then((temp2) { - var sep = Platform.pathSeparator; - var y = '${temp.path}${sep}y'; - var x = '${temp2.path}${sep}x'; - return new File(x) - .create() - .then((_) => new Link(y).create(temp2.path)) - .then((_) => - temp.list(recursive: true).singleWhere((entry) => entry is File)) - .then((file) => Expect.isTrue(file.path.endsWith('$y${sep}x'))) - .then((_) => temp - .list(recursive: true) - .singleWhere((entry) => entry is Directory)) - .then((dir) => Expect.isTrue(dir.path.endsWith('y'))) - .then((_) => temp.delete(recursive: true)) - .then((_) => temp2.delete(recursive: true)); - }); + return Directory.systemTemp.createTemp('dart_file_system_async_links').then( + (temp2) { + var sep = Platform.pathSeparator; + var y = '${temp.path}${sep}y'; + var x = '${temp2.path}${sep}x'; + return new File(x) + .create() + .then((_) => new Link(y).create(temp2.path)) + .then( + (_) => temp + .list(recursive: true) + .singleWhere((entry) => entry is File), + ) + .then((file) => Expect.isTrue(file.path.endsWith('$y${sep}x'))) + .then( + (_) => temp + .list(recursive: true) + .singleWhere((entry) => entry is Directory), + ) + .then((dir) => Expect.isTrue(dir.path.endsWith('y'))) + .then((_) => temp.delete(recursive: true)) + .then((_) => temp2.delete(recursive: true)); + }, + ); }); } @@ -202,18 +266,20 @@ Future testDirectoryListingBrokenLink() { return new File(x) .create() .then((_) => new Link(link).create(doesNotExist)) - .then((_) => temp.list(recursive: true).forEach((entity) { - if (entity is File) { - Expect.isFalse(sawFile); - sawFile = true; - Expect.isTrue(entity.path.endsWith(x)); - } else { - Expect.isTrue(entity is Link); - Expect.isFalse(sawLink); - sawLink = true; - Expect.isTrue(entity.path.endsWith(link)); - } - })) + .then( + (_) => temp.list(recursive: true).forEach((entity) { + if (entity is File) { + Expect.isFalse(sawFile); + sawFile = true; + Expect.isTrue(entity.path.endsWith(x)); + } else { + Expect.isTrue(entity is Link); + Expect.isFalse(sawLink); + sawLink = true; + Expect.isTrue(entity.path.endsWith(link)); + } + }), + ) .then((_) => temp.delete(recursive: true)); }); } diff --git a/tests/standalone/io/file_system_links_test.dart b/tests/standalone/io/file_system_links_test.dart index 0ab431d99de..6fd603cffb8 100644 --- a/tests/standalone/io/file_system_links_test.dart +++ b/tests/standalone/io/file_system_links_test.dart @@ -22,10 +22,14 @@ testFileExistsCreate() { Expect.isFalse(FileSystemEntity.isLinkSync(x)); Expect.equals(FileSystemEntityType.notFound, FileSystemEntity.typeSync(y)); Expect.equals(FileSystemEntityType.notFound, FileSystemEntity.typeSync(x)); - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(y, followLinks: false)); - Expect.equals(FileSystemEntityType.notFound, - FileSystemEntity.typeSync(x, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(y, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.typeSync(x, followLinks: false), + ); Expect.equals(x, new Link(y).targetSync()); new File(y).createSync(); @@ -37,10 +41,14 @@ testFileExistsCreate() { Expect.isTrue(FileSystemEntity.isFileSync(x)); Expect.equals(FileSystemEntityType.file, FileSystemEntity.typeSync(y)); Expect.equals(FileSystemEntityType.file, FileSystemEntity.typeSync(x)); - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(y, followLinks: false)); - Expect.equals(FileSystemEntityType.file, - FileSystemEntity.typeSync(x, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(y, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.file, + FileSystemEntity.typeSync(x, followLinks: false), + ); Expect.equals(x, new Link(y).targetSync()); new File(x).deleteSync(); @@ -51,10 +59,14 @@ testFileExistsCreate() { Expect.isTrue(FileSystemEntity.isDirectorySync(x)); Expect.equals(FileSystemEntityType.directory, FileSystemEntity.typeSync(y)); Expect.equals(FileSystemEntityType.directory, FileSystemEntity.typeSync(x)); - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(y, followLinks: false)); - Expect.equals(FileSystemEntityType.directory, - FileSystemEntity.typeSync(x, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(y, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(x, followLinks: false), + ); Expect.equals(x, new Link(y).targetSync()); new Link(y).deleteSync(); @@ -171,22 +183,27 @@ testDirectoryListing() { files = []; dirs = []; - var lister = temp.list(recursive: true).listen((entity) { - if (entity is File) { - files.add(entity.path); - } else { - Expect.isTrue(entity is Directory); - dirs.add(entity.path); - } - }, onDone: () { - Expect.equals(1, files.length); - Expect.isTrue(files[0].endsWith('$y${Platform.pathSeparator}x')); - Expect.equals(1, dirs.length); - Expect.isTrue(dirs[0].endsWith(y)); - temp.deleteSync(recursive: true); - temp2.deleteSync(recursive: true); - asyncEnd(); - }); + var lister = temp + .list(recursive: true) + .listen( + (entity) { + if (entity is File) { + files.add(entity.path); + } else { + Expect.isTrue(entity is Directory); + dirs.add(entity.path); + } + }, + onDone: () { + Expect.equals(1, files.length); + Expect.isTrue(files[0].endsWith('$y${Platform.pathSeparator}x')); + Expect.equals(1, dirs.length); + Expect.isTrue(dirs[0].endsWith(y)); + temp.deleteSync(recursive: true); + temp2.deleteSync(recursive: true); + asyncEnd(); + }, + ); }); } @@ -203,28 +220,31 @@ testDirectoryListingBrokenLink() { var dirs = []; var links = []; var errors = []; - temp.list(recursive: true).listen( - (entity) { - if (entity is File) { - files.add(entity.path); - } else if (entity is Link) { - links.add(entity.path); - } else { - Expect.isTrue(entity is Directory); - dirs.add(entity.path); - } - }, - onError: (e) => errors.add(e), - onDone: () { - Expect.equals(1, files.length); - Expect.isTrue(files[0].endsWith(x)); - Expect.equals(1, links.length); - Expect.isTrue(links[0].endsWith(link)); - Expect.equals(0, dirs.length); - Expect.equals(0, errors.length); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + temp + .list(recursive: true) + .listen( + (entity) { + if (entity is File) { + files.add(entity.path); + } else if (entity is Link) { + links.add(entity.path); + } else { + Expect.isTrue(entity is Directory); + dirs.add(entity.path); + } + }, + onError: (e) => errors.add(e), + onDone: () { + Expect.equals(1, files.length); + Expect.isTrue(files[0].endsWith(x)); + Expect.equals(1, links.length); + Expect.isTrue(links[0].endsWith(link)); + Expect.equals(0, dirs.length); + Expect.equals(0, errors.length); + temp.deleteSync(recursive: true); + asyncEnd(); + }, + ); }); } diff --git a/tests/standalone/io/file_system_watcher_test.dart b/tests/standalone/io/file_system_watcher_test.dart index f15d4710849..7b30c292a42 100644 --- a/tests/standalone/io/file_system_watcher_test.dart +++ b/tests/standalone/io/file_system_watcher_test.dart @@ -18,17 +18,20 @@ void testWatchCreateFile() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event is FileSystemCreateEvent && event.path.endsWith('file')) { - Expect.isFalse(event.isDirectory); - asyncEnd(); - sub.cancel(); + sub = watcher.listen( + (event) { + if (event is FileSystemCreateEvent && event.path.endsWith('file')) { + Expect.isFalse(event.isDirectory); + asyncEnd(); + sub.cancel(); + dir.deleteSync(recursive: true); + } + }, + onError: (e) { dir.deleteSync(recursive: true); - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + throw e; + }, + ); file.createSync(); } @@ -41,17 +44,20 @@ void testWatchCreateDir() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event is FileSystemCreateEvent && event.path.endsWith('dir')) { - Expect.isTrue(event.isDirectory); - asyncEnd(); - sub.cancel(); + sub = watcher.listen( + (event) { + if (event is FileSystemCreateEvent && event.path.endsWith('dir')) { + Expect.isTrue(event.isDirectory); + asyncEnd(); + sub.cancel(); + dir.deleteSync(recursive: true); + } + }, + onError: (e) { dir.deleteSync(recursive: true); - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + throw e; + }, + ); subdir.createSync(); } @@ -65,17 +71,20 @@ void testWatchModifyFile() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event is FileSystemModifyEvent) { - Expect.isTrue(event.path.endsWith('file')); - sub.cancel(); - asyncEnd(); + sub = watcher.listen( + (event) { + if (event is FileSystemModifyEvent) { + Expect.isTrue(event.path.endsWith('file')); + sub.cancel(); + asyncEnd(); + dir.deleteSync(recursive: true); + } + }, + onError: (e) { dir.deleteSync(recursive: true); - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + throw e; + }, + ); file.writeAsStringSync('a'); } @@ -90,19 +99,22 @@ void testWatchTruncateFile() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event is FileSystemModifyEvent) { - Expect.isTrue(event.path.endsWith('file')); - Expect.isTrue(event.contentChanged); - sub.cancel(); - asyncEnd(); - fileHandle.closeSync(); + sub = watcher.listen( + (event) { + if (event is FileSystemModifyEvent) { + Expect.isTrue(event.path.endsWith('file')); + Expect.isTrue(event.contentChanged); + sub.cancel(); + asyncEnd(); + fileHandle.closeSync(); + dir.deleteSync(recursive: true); + } + }, + onError: (e) { dir.deleteSync(recursive: true); - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + throw e; + }, + ); fileHandle.truncateSync(1); } @@ -118,21 +130,24 @@ void testWatchMoveFile() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event is FileSystemMoveEvent) { - Expect.isTrue(event.path.endsWith('file')); - final destination = event.destination; - if (destination != null) { - Expect.isTrue(destination.endsWith('file2')); + sub = watcher.listen( + (event) { + if (event is FileSystemMoveEvent) { + Expect.isTrue(event.path.endsWith('file')); + final destination = event.destination; + if (destination != null) { + Expect.isTrue(destination.endsWith('file2')); + } + sub.cancel(); + asyncEnd(); + dir.deleteSync(recursive: true); } - sub.cancel(); - asyncEnd(); + }, + onError: (e) { dir.deleteSync(recursive: true); - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + throw e; + }, + ); file.renameSync(join(dir.path, 'file2')); } @@ -146,17 +161,20 @@ void testWatchDeleteFile() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event is FileSystemDeleteEvent) { - Expect.isTrue(event.path.endsWith('file')); - sub.cancel(); - asyncEnd(); + sub = watcher.listen( + (event) { + if (event is FileSystemDeleteEvent) { + Expect.isTrue(event.path.endsWith('file')); + sub.cancel(); + asyncEnd(); + dir.deleteSync(recursive: true); + } + }, + onError: (e) { dir.deleteSync(recursive: true); - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + throw e; + }, + ); file.deleteSync(); } @@ -169,13 +187,16 @@ void testWatchDeleteDir() { var watcher = dir.watch(events: 0); asyncStart(); - watcher.listen((event) { - if (event is FileSystemDeleteEvent) { - Expect.isTrue(event.path == dir.path); - } - }, onDone: () { - asyncEnd(); - }); + watcher.listen( + (event) { + if (event is FileSystemDeleteEvent) { + Expect.isTrue(event.path == dir.path); + } + }, + onDone: () { + asyncEnd(); + }, + ); dir.deleteSync(); } @@ -188,16 +209,19 @@ void testWatchOnlyModifyFile() { asyncStart(); var sub; - sub = watcher.listen((event) { - Expect.isTrue(event is FileSystemModifyEvent); - Expect.isTrue(event.path.endsWith('file')); - sub.cancel(); - asyncEnd(); - dir.deleteSync(recursive: true); - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + sub = watcher.listen( + (event) { + Expect.isTrue(event is FileSystemModifyEvent); + Expect.isTrue(event.path.endsWith('file')); + sub.cancel(); + asyncEnd(); + dir.deleteSync(recursive: true); + }, + onError: (e) { + dir.deleteSync(recursive: true); + throw e; + }, + ); file.createSync(); file.writeAsStringSync('a'); @@ -261,16 +285,19 @@ void testWatchRecursive() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event.path.endsWith('file')) { - sub.cancel(); - asyncEnd(); + sub = watcher.listen( + (event) { + if (event.path.endsWith('file')) { + sub.cancel(); + asyncEnd(); + dir.deleteSync(recursive: true); + } + }, + onError: (e) { dir.deleteSync(recursive: true); - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + throw e; + }, + ); file.createSync(); } @@ -285,14 +312,17 @@ void testWatchNonRecursive() { asyncStart(); var sub; - sub = watcher.listen((event) { - if (event.path.endsWith('file')) { - throw "File change event not expected"; - } - }, onError: (e) { - dir.deleteSync(recursive: true); - throw e; - }); + sub = watcher.listen( + (event) { + if (event.path.endsWith('file')) { + throw "File change event not expected"; + } + }, + onError: (e) { + dir.deleteSync(recursive: true); + throw e; + }, + ); file.createSync(); @@ -307,12 +337,15 @@ void testWatchNonExisting() { // MacOS allows listening on non-existing paths. if (Platform.isMacOS) return; asyncStart(); - new Directory('__some_none_existing_dir__').watch().listen((_) { - Expect.fail('unexpected error'); - }, onError: (e) { - asyncEnd(); - Expect.isTrue(e is PathNotFoundException); - }); + new Directory('__some_none_existing_dir__').watch().listen( + (_) { + Expect.fail('unexpected error'); + }, + onError: (e) { + asyncEnd(); + Expect.isTrue(e is PathNotFoundException); + }, + ); } void testWatchMoveSelf() { @@ -326,16 +359,19 @@ void testWatchMoveSelf() { asyncStart(); bool gotDelete = false; - watcher.listen((event) { - if (event is FileSystemDeleteEvent) { - Expect.isTrue(event.path.endsWith('dir')); - gotDelete = true; - } - }, onDone: () { - Expect.isTrue(gotDelete); - dir.deleteSync(recursive: true); - asyncEnd(); - }); + watcher.listen( + (event) { + if (event is FileSystemDeleteEvent) { + Expect.isTrue(event.path.endsWith('dir')); + gotDelete = true; + } + }, + onDone: () { + Expect.isTrue(gotDelete); + dir.deleteSync(recursive: true); + asyncEnd(); + }, + ); dir2.renameSync(join(dir.path, 'new_dir')); } @@ -386,8 +422,12 @@ testWatchConsistentModifiedFile() async { RawReceivePort errorReceivePort = RawReceivePort((object) { print('worker errored: $object'); }); - Isolate isolate = await Isolate.spawn(modifyFiles, receivePort.sendPort, - onExit: exitReceivePort.sendPort, onError: errorReceivePort.sendPort); + Isolate isolate = await Isolate.spawn( + modifyFiles, + receivePort.sendPort, + onExit: exitReceivePort.sendPort, + onError: errorReceivePort.sendPort, + ); await modificationEventReceived.future; workerSendPort.send('end'); @@ -443,13 +483,17 @@ testWatchOverflow() async { ReceivePort receivePort = ReceivePort(); Completer exiting = Completer(); - Directory dir = - Directory.systemTemp.createTempSync('dart_file_system_watcher'); + Directory dir = Directory.systemTemp.createTempSync( + 'dart_file_system_watcher', + ); var file = new File(join(dir.path, 'file')); file.createSync(); - Isolate isolate = - await Isolate.spawn(watcher, receivePort.sendPort, paused: true); + Isolate isolate = await Isolate.spawn( + watcher, + receivePort.sendPort, + paused: true, + ); var subscription; subscription = receivePort.listen((object) async { @@ -476,14 +520,17 @@ testWatchOverflow() async { } void watcher(SendPort sendPort) async { - runZonedGuarded(() { - var watcher = Directory.systemTemp.watch(recursive: true); - watcher.listen((data) async {}); - sendPort.send('start'); - }, (error, stack) { - print(error); - sendPort.send('end'); - }); + runZonedGuarded( + () { + var watcher = Directory.systemTemp.watch(recursive: true); + watcher.listen((data) async {}); + sendPort.send('start'); + }, + (error, stack) { + print(error); + sendPort.send('end'); + }, + ); } void main() { diff --git a/tests/standalone/io/file_test.dart b/tests/standalone/io/file_test.dart index 122b0f1a74f..7ba33378f3f 100644 --- a/tests/standalone/io/file_test.dart +++ b/tests/standalone/io/file_test.dart @@ -1684,7 +1684,8 @@ class FileTest { } static void testRename({required bool targetExists}) { - lift(Function f) => (futureValue) => futureValue.then((value) => f(value)); + lift(Function f) => + (futureValue) => futureValue.then((value) => f(value)); asyncTestStarted(); String source = join(tempDirectory.path, 'rename_${targetExists}_source'); diff --git a/tests/standalone/io/file_typed_data_test.dart b/tests/standalone/io/file_typed_data_test.dart index 76bb5677639..a25e6577c8f 100644 --- a/tests/standalone/io/file_typed_data_test.dart +++ b/tests/standalone/io/file_typed_data_test.dart @@ -18,26 +18,34 @@ void testWriteInt8ListAndView() { const int VIEW_LENGTH = 4; Int8List list = new Int8List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Int8List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Int8List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom(list, 0, LIST_LENGTH); - }).then((raf) { - return raf.writeFrom(view, 0, VIEW_LENGTH); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - Expect.listEquals(expected, content); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom(list, 0, LIST_LENGTH); + }) + .then((raf) { + return raf.writeFrom(view, 0, VIEW_LENGTH); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + Expect.listEquals(expected, content); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -48,26 +56,34 @@ void testWriteUint8ListAndView() { const int VIEW_LENGTH = 4; Uint8List list = new Uint8List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Uint8List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Uint8List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom(list, 0, LIST_LENGTH); - }).then((raf) { - return raf.writeFrom(view, 0, VIEW_LENGTH); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - Expect.listEquals(expected, content); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom(list, 0, LIST_LENGTH); + }) + .then((raf) { + return raf.writeFrom(view, 0, VIEW_LENGTH); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + Expect.listEquals(expected, content); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -79,25 +95,33 @@ void testWriteUint8ClampedListAndView() { Uint8ClampedList list = new Uint8ClampedList(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; var view = new Uint8ClampedList.view( - list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom(list, 0, LIST_LENGTH); - }).then((raf) { - return raf.writeFrom(view, 0, VIEW_LENGTH); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - Expect.listEquals(expected, content); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom(list, 0, LIST_LENGTH); + }) + .then((raf) { + return raf.writeFrom(view, 0, VIEW_LENGTH); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + Expect.listEquals(expected, content); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -110,36 +134,53 @@ void testWriteInt16ListAndView() { const int VIEW_LENGTH_IN_BYTES = VIEW_LENGTH * Int16List.bytesPerElement; var list = new Int16List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Int16List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Int16List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom( - new Uint8List.view(list.buffer), 0, LIST_LENGTH_IN_BYTES); - }).then((raf) { - return raf.writeFrom( - new Uint8List.view( - view.buffer, view.offsetInBytes, view.lengthInBytes), - 0, - VIEW_LENGTH_IN_BYTES); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - var typed_data_content = new Uint8List(content.length); - for (int i = 0; i < content.length; i++) { - typed_data_content[i] = content[i]; - } - Expect.listEquals( - expected, new Int16List.view(typed_data_content.buffer)); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom( + new Uint8List.view(list.buffer), + 0, + LIST_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.writeFrom( + new Uint8List.view( + view.buffer, + view.offsetInBytes, + view.lengthInBytes, + ), + 0, + VIEW_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + var typed_data_content = new Uint8List(content.length); + for (int i = 0; i < content.length; i++) { + typed_data_content[i] = content[i]; + } + Expect.listEquals( + expected, + new Int16List.view(typed_data_content.buffer), + ); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -152,36 +193,53 @@ void testWriteUint16ListAndView() { const int VIEW_LENGTH_IN_BYTES = VIEW_LENGTH * Uint16List.bytesPerElement; var list = new Uint16List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Uint16List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Uint16List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom( - new Uint8List.view(list.buffer), 0, LIST_LENGTH_IN_BYTES); - }).then((raf) { - return raf.writeFrom( - new Uint8List.view( - view.buffer, view.offsetInBytes, view.lengthInBytes), - 0, - VIEW_LENGTH_IN_BYTES); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - var typed_data_content = new Uint8List(content.length); - for (int i = 0; i < content.length; i++) { - typed_data_content[i] = content[i]; - } - Expect.listEquals( - expected, new Uint16List.view(typed_data_content.buffer)); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom( + new Uint8List.view(list.buffer), + 0, + LIST_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.writeFrom( + new Uint8List.view( + view.buffer, + view.offsetInBytes, + view.lengthInBytes, + ), + 0, + VIEW_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + var typed_data_content = new Uint8List(content.length); + for (int i = 0; i < content.length; i++) { + typed_data_content[i] = content[i]; + } + Expect.listEquals( + expected, + new Uint16List.view(typed_data_content.buffer), + ); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -194,36 +252,53 @@ void testWriteInt32ListAndView() { const int VIEW_LENGTH_IN_BYTES = VIEW_LENGTH * Int32List.bytesPerElement; var list = new Int32List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Int32List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Int32List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom( - new Uint8List.view(list.buffer), 0, LIST_LENGTH_IN_BYTES); - }).then((raf) { - return raf.writeFrom( - new Uint8List.view( - view.buffer, view.offsetInBytes, view.lengthInBytes), - 0, - VIEW_LENGTH_IN_BYTES); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - var typed_data_content = new Uint8List(content.length); - for (int i = 0; i < content.length; i++) { - typed_data_content[i] = content[i]; - } - Expect.listEquals( - expected, new Int32List.view(typed_data_content.buffer)); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom( + new Uint8List.view(list.buffer), + 0, + LIST_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.writeFrom( + new Uint8List.view( + view.buffer, + view.offsetInBytes, + view.lengthInBytes, + ), + 0, + VIEW_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + var typed_data_content = new Uint8List(content.length); + for (int i = 0; i < content.length; i++) { + typed_data_content[i] = content[i]; + } + Expect.listEquals( + expected, + new Int32List.view(typed_data_content.buffer), + ); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -236,36 +311,53 @@ void testWriteUint32ListAndView() { const int VIEW_LENGTH_IN_BYTES = VIEW_LENGTH * Int32List.bytesPerElement; var list = new Uint32List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Uint32List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Uint32List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom( - new Uint8List.view(list.buffer), 0, LIST_LENGTH_IN_BYTES); - }).then((raf) { - return raf.writeFrom( - new Uint8List.view( - view.buffer, view.offsetInBytes, view.lengthInBytes), - 0, - VIEW_LENGTH_IN_BYTES); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - var typed_data_content = new Uint8List(content.length); - for (int i = 0; i < content.length; i++) { - typed_data_content[i] = content[i]; - } - Expect.listEquals( - expected, new Uint32List.view(typed_data_content.buffer)); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom( + new Uint8List.view(list.buffer), + 0, + LIST_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.writeFrom( + new Uint8List.view( + view.buffer, + view.offsetInBytes, + view.lengthInBytes, + ), + 0, + VIEW_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + var typed_data_content = new Uint8List(content.length); + for (int i = 0; i < content.length; i++) { + typed_data_content[i] = content[i]; + } + Expect.listEquals( + expected, + new Uint32List.view(typed_data_content.buffer), + ); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -278,36 +370,53 @@ void testWriteInt64ListAndView() { const int VIEW_LENGTH_IN_BYTES = VIEW_LENGTH * Int64List.bytesPerElement; var list = new Int64List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Int64List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Int64List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom( - new Uint8List.view(list.buffer), 0, LIST_LENGTH_IN_BYTES); - }).then((raf) { - return raf.writeFrom( - new Uint8List.view( - view.buffer, view.offsetInBytes, view.lengthInBytes), - 0, - VIEW_LENGTH_IN_BYTES); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - var typed_data_content = new Uint8List(content.length); - for (int i = 0; i < content.length; i++) { - typed_data_content[i] = content[i]; - } - Expect.listEquals( - expected, new Int64List.view(typed_data_content.buffer)); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom( + new Uint8List.view(list.buffer), + 0, + LIST_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.writeFrom( + new Uint8List.view( + view.buffer, + view.offsetInBytes, + view.lengthInBytes, + ), + 0, + VIEW_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + var typed_data_content = new Uint8List(content.length); + for (int i = 0; i < content.length; i++) { + typed_data_content[i] = content[i]; + } + Expect.listEquals( + expected, + new Int64List.view(typed_data_content.buffer), + ); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } @@ -320,36 +429,53 @@ void testWriteUint64ListAndView() { const int VIEW_LENGTH_IN_BYTES = VIEW_LENGTH * Uint64List.bytesPerElement; var list = new Uint64List(LIST_LENGTH); for (int i = 0; i < LIST_LENGTH; i++) list[i] = i; - var view = - new Uint64List.view(list.buffer, OFFSET_IN_BYTES_FOR_VIEW, VIEW_LENGTH); + var view = new Uint64List.view( + list.buffer, + OFFSET_IN_BYTES_FOR_VIEW, + VIEW_LENGTH, + ); Directory.systemTemp.createTemp('dart_file_typed_data').then((temp) { var file = new File("${temp.path}/test"); - file.open(mode: FileMode.write).then((raf) { - return raf.writeFrom( - new Uint8List.view(list.buffer), 0, LIST_LENGTH_IN_BYTES); - }).then((raf) { - return raf.writeFrom( - new Uint8List.view( - view.buffer, view.offsetInBytes, view.lengthInBytes), - 0, - VIEW_LENGTH_IN_BYTES); - }).then((raf) { - return raf.close(); - }).then((_) { - var expected = []; - expected.addAll(list); - expected.addAll(view); - var content = file.readAsBytesSync(); - var typed_data_content = new Uint8List(content.length); - for (int i = 0; i < content.length; i++) { - typed_data_content[i] = content[i]; - } - Expect.listEquals( - expected, new Uint64List.view(typed_data_content.buffer)); - temp.deleteSync(recursive: true); - asyncEnd(); - }); + file + .open(mode: FileMode.write) + .then((raf) { + return raf.writeFrom( + new Uint8List.view(list.buffer), + 0, + LIST_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.writeFrom( + new Uint8List.view( + view.buffer, + view.offsetInBytes, + view.lengthInBytes, + ), + 0, + VIEW_LENGTH_IN_BYTES, + ); + }) + .then((raf) { + return raf.close(); + }) + .then((_) { + var expected = []; + expected.addAll(list); + expected.addAll(view); + var content = file.readAsBytesSync(); + var typed_data_content = new Uint8List(content.length); + for (int i = 0; i < content.length; i++) { + typed_data_content[i] = content[i]; + } + Expect.listEquals( + expected, + new Uint64List.view(typed_data_content.buffer), + ); + temp.deleteSync(recursive: true); + asyncEnd(); + }); }); } diff --git a/tests/standalone/io/file_uri_test.dart b/tests/standalone/io/file_uri_test.dart index 0061eedb6d8..0173d98e3a2 100644 --- a/tests/standalone/io/file_uri_test.dart +++ b/tests/standalone/io/file_uri_test.dart @@ -31,11 +31,14 @@ void testFromUri() { void testFromUriUnsupported() { Expect.throwsUnsupportedError( - () => new File.fromUri(Uri.parse('http://localhost:8080/index.html'))); + () => new File.fromUri(Uri.parse('http://localhost:8080/index.html')), + ); Expect.throwsUnsupportedError( - () => new File.fromUri(Uri.parse('ftp://localhost/tmp/xxx'))); + () => new File.fromUri(Uri.parse('ftp://localhost/tmp/xxx')), + ); Expect.throwsUnsupportedError( - () => new File.fromUri(Uri.parse('name#fragment'))); + () => new File.fromUri(Uri.parse('name#fragment')), + ); } void main() { diff --git a/tests/standalone/io/file_windows_test.dart b/tests/standalone/io/file_windows_test.dart index 08b69eda399..89ca668c0ad 100644 --- a/tests/standalone/io/file_windows_test.dart +++ b/tests/standalone/io/file_windows_test.dart @@ -40,8 +40,10 @@ void testDriveLetterNoBackslash() { } } noBackslash += path.substring(3); - Expect.equals("${Directory(noBackslash).statSync()}", - "${Directory(path).statSync()}"); + Expect.equals( + "${Directory(noBackslash).statSync()}", + "${Directory(path).statSync()}", + ); } } } diff --git a/tests/standalone/io/file_write_as_test.dart b/tests/standalone/io/file_write_as_test.dart index d00224b1a3d..eff63d16749 100644 --- a/tests/standalone/io/file_write_as_test.dart +++ b/tests/standalone/io/file_write_as_test.dart @@ -21,8 +21,9 @@ testWriteAsBytesSync(dir) { } void testWriteAsBytesOutsideOf0to256Sync(dir) { - final f = - new File('${dir.path}${Platform.pathSeparator}outside_bytes_sync.txt'); + final f = new File( + '${dir.path}${Platform.pathSeparator}outside_bytes_sync.txt', + ); final data = [-256, -255, -1, 0, 255, 256]; f.writeAsBytesSync(data); diff --git a/tests/standalone/io/file_write_only_test.dart b/tests/standalone/io/file_write_only_test.dart index bb29caab9c2..c95456e9208 100644 --- a/tests/standalone/io/file_write_only_test.dart +++ b/tests/standalone/io/file_write_only_test.dart @@ -40,12 +40,16 @@ Future write(Directory dir) async { await raf.writeString('Hello'); await raf.setPosition(0); await expectThrowsAsync( - raf.readByte(), 'Read from write only file succeeded'); + raf.readByte(), + 'Read from write only file succeeded', + ); await raf.close(); raf = await f.open(mode: FileMode.writeOnlyAppend); await raf.writeString('Hello'); await expectThrowsAsync( - raf.readByte(), 'Read from write only file succeeded'); + raf.readByte(), + 'Read from write only file succeeded', + ); await raf.setPosition(0); await raf.writeString('Hello'); await raf.close(); diff --git a/tests/standalone/io/fuzz_support.dart b/tests/standalone/io/fuzz_support.dart index 4b9d59d5c80..c50e7a57bb9 100644 --- a/tests/standalone/io/fuzz_support.dart +++ b/tests/standalone/io/fuzz_support.dart @@ -16,7 +16,7 @@ const typeMapping = const { 'FileMode': FileMode.read, 'num': 0.50, 'List': const [1, 2, 3], - 'Map': const {"a": 23} + 'Map': const {"a": 23}, }; typePermutations(int argCount) { @@ -52,7 +52,8 @@ doItSync(Function f) { // completion. Future doItAsync(FutureOr f()) { // Ignore value and errors. - return new Future.delayed(Duration.zero, f) - .catchError((_) {}) - .then((_) => true); + return new Future.delayed( + Duration.zero, + f, + ).catchError((_) {}).then((_) => true); } diff --git a/tests/standalone/io/http_100_continue_test.dart b/tests/standalone/io/http_100_continue_test.dart index 61af5989639..4fbfe8febc6 100644 --- a/tests/standalone/io/http_100_continue_test.dart +++ b/tests/standalone/io/http_100_continue_test.dart @@ -33,12 +33,15 @@ void test(responseBytes, bodyLength) async { server.listen(handleSocket); var client = new HttpClient(); - var request = - await client.getUrl(Uri.parse('http://127.0.0.1:${server.port}/')); + var request = await client.getUrl( + Uri.parse('http://127.0.0.1:${server.port}/'), + ); var response = await request.close(); Expect.equals(response.statusCode, 200); - Expect.equals(bodyLength, - (await response.fold>([], (p, e) => p..addAll(e))).length); + Expect.equals( + bodyLength, + (await response.fold>([], (p, e) => p..addAll(e))).length, + ); server.close(); } diff --git a/tests/standalone/io/http_10_test.dart b/tests/standalone/io/http_10_test.dart index 92ecc6fdf97..405a7252eb0 100644 --- a/tests/standalone/io/http_10_test.dart +++ b/tests/standalone/io/http_10_test.dart @@ -17,26 +17,29 @@ import "package:expect/expect.dart"; // connection as there is no keep alive. void testHttp10NoKeepAlive() { HttpServer.bind("127.0.0.1", 0).then((server) { - server.listen((HttpRequest request) { - Expect.isNull(request.headers.value('content-length')); - Expect.equals(-1, request.contentLength); - var response = request.response; - response.contentLength = 1; - Expect.equals("1.0", request.protocolVersion); - response.done - .then((_) => Expect.fail("Unexpected response completion")) - .catchError((error) => Expect.isTrue(error is HttpException)); - response.write("Z"); - response.write("Z"); - response.close(); - Expect.throws(() { - response.write("x"); - }, (e) => e is StateError); - }, onError: (e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + server.listen( + (HttpRequest request) { + Expect.isNull(request.headers.value('content-length')); + Expect.equals(-1, request.contentLength); + var response = request.response; + response.contentLength = 1; + Expect.equals("1.0", request.protocolVersion); + response.done + .then((_) => Expect.fail("Unexpected response completion")) + .catchError((error) => Expect.isTrue(error is HttpException)); + response.write("Z"); + response.write("Z"); + response.close(); + Expect.throws(() { + response.write("x"); + }, (e) => e is StateError); + }, + onError: (e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); int count = 0; makeRequest() { @@ -44,17 +47,20 @@ void testHttp10NoKeepAlive() { socket.write("GET / HTTP/1.0\r\n\r\n"); List response = []; - socket.listen(response.addAll, onDone: () { - count++; - socket.destroy(); - String s = new String.fromCharCodes(response).toLowerCase(); - Expect.equals(-1, s.indexOf("keep-alive")); - if (count < 10) { - makeRequest(); - } else { - server.close(); - } - }); + socket.listen( + response.addAll, + onDone: () { + count++; + socket.destroy(); + String s = new String.fromCharCodes(response).toLowerCase(); + Expect.equals(-1, s.indexOf("keep-alive")); + if (count < 10) { + makeRequest(); + } else { + server.close(); + } + }, + ); }); } @@ -67,20 +73,26 @@ void testHttp10NoKeepAlive() { // the response. void testHttp10ServerClose() { HttpServer.bind("127.0.0.1", 0).then((server) { - server.listen((HttpRequest request) { - Expect.isNull(request.headers.value('content-length')); - Expect.equals(-1, request.contentLength); - request.listen((_) {}, onDone: () { - var response = request.response; - Expect.equals("1.0", request.protocolVersion); - response.write("Z"); - response.close(); - }); - }, onError: (e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + server.listen( + (HttpRequest request) { + Expect.isNull(request.headers.value('content-length')); + Expect.equals(-1, request.contentLength); + request.listen( + (_) {}, + onDone: () { + var response = request.response; + Expect.equals("1.0", request.protocolVersion); + response.write("Z"); + response.close(); + }, + ); + }, + onError: (e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); int count = 0; makeRequest() { @@ -89,21 +101,23 @@ void testHttp10ServerClose() { socket.write("Connection: Keep-Alive\r\n\r\n"); List response = []; - socket.listen(response.addAll, - onDone: () { - socket.destroy(); - count++; - String s = new String.fromCharCodes(response).toLowerCase(); - Expect.equals("z", s[s.length - 1]); - Expect.equals(-1, s.indexOf("content-length:")); - Expect.equals(-1, s.indexOf("keep-alive")); - if (count < 10) { - makeRequest(); - } else { - server.close(); - } - }, - onError: (e) => print(e)); + socket.listen( + response.addAll, + onDone: () { + socket.destroy(); + count++; + String s = new String.fromCharCodes(response).toLowerCase(); + Expect.equals("z", s[s.length - 1]); + Expect.equals(-1, s.indexOf("content-length:")); + Expect.equals(-1, s.indexOf("keep-alive")); + if (count < 10) { + makeRequest(); + } else { + server.close(); + } + }, + onError: (e) => print(e), + ); }); } @@ -116,20 +130,23 @@ void testHttp10ServerClose() { // used. void testHttp10KeepAlive() { HttpServer.bind("127.0.0.1", 0).then((server) { - server.listen((HttpRequest request) { - Expect.isNull(request.headers.value('content-length')); - Expect.equals(-1, request.contentLength); - var response = request.response; - response.contentLength = 1; - response.persistentConnection = true; - Expect.equals("1.0", request.protocolVersion); - response.write("Z"); - response.close(); - }, onError: (e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + server.listen( + (HttpRequest request) { + Expect.isNull(request.headers.value('content-length')); + Expect.equals(-1, request.contentLength); + var response = request.response; + response.contentLength = 1; + response.persistentConnection = true; + Expect.equals("1.0", request.protocolVersion); + response.write("Z"); + response.close(); + }, + onError: (e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); Socket.connect("127.0.0.1", server.port).then((socket) { void sendRequest() { @@ -139,24 +156,27 @@ void testHttp10KeepAlive() { List response = []; int count = 0; - socket.listen((d) { - response.addAll(d); - if (response[response.length - 1] == "Z".codeUnitAt(0)) { - String s = new String.fromCharCodes(response).toLowerCase(); - Expect.isTrue(s.indexOf("\r\nconnection: keep-alive\r\n") > 0); - Expect.isTrue(s.indexOf("\r\ncontent-length: 1\r\n") > 0); - count++; - if (count < 10) { - response = []; - sendRequest(); - } else { - socket.close(); + socket.listen( + (d) { + response.addAll(d); + if (response[response.length - 1] == "Z".codeUnitAt(0)) { + String s = new String.fromCharCodes(response).toLowerCase(); + Expect.isTrue(s.indexOf("\r\nconnection: keep-alive\r\n") > 0); + Expect.isTrue(s.indexOf("\r\ncontent-length: 1\r\n") > 0); + count++; + if (count < 10) { + response = []; + sendRequest(); + } else { + socket.close(); + } } - } - }, onDone: () { - socket.destroy(); - server.close(); - }); + }, + onDone: () { + socket.destroy(); + server.close(); + }, + ); sendRequest(); }); }); @@ -167,18 +187,21 @@ void testHttp10KeepAlive() { // keep alive. void testHttp10KeepAliveServerCloses() { HttpServer.bind("127.0.0.1", 0).then((server) { - server.listen((HttpRequest request) { - Expect.isNull(request.headers.value('content-length')); - Expect.equals(-1, request.contentLength); - var response = request.response; - Expect.equals("1.0", request.protocolVersion); - response.write("Z"); - response.close(); - }, onError: (e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + server.listen( + (HttpRequest request) { + Expect.isNull(request.headers.value('content-length')); + Expect.equals(-1, request.contentLength); + var response = request.response; + Expect.equals("1.0", request.protocolVersion); + response.write("Z"); + response.close(); + }, + onError: (e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); int count = 0; makeRequest() { @@ -187,19 +210,22 @@ void testHttp10KeepAliveServerCloses() { socket.write("Connection: Keep-Alive\r\n\r\n"); List response = []; - socket.listen(response.addAll, onDone: () { - socket.destroy(); - count++; - String s = new String.fromCharCodes(response).toLowerCase(); - Expect.equals("z", s[s.length - 1]); - Expect.equals(-1, s.indexOf("content-length")); - Expect.equals(-1, s.indexOf("connection")); - if (count < 10) { - makeRequest(); - } else { - server.close(); - } - }); + socket.listen( + response.addAll, + onDone: () { + socket.destroy(); + count++; + String s = new String.fromCharCodes(response).toLowerCase(); + Expect.equals("z", s[s.length - 1]); + Expect.equals(-1, s.indexOf("content-length")); + Expect.equals(-1, s.indexOf("connection")); + if (count < 10) { + makeRequest(); + } else { + server.close(); + } + }, + ); }); } diff --git a/tests/standalone/io/http_advanced_test.dart b/tests/standalone/io/http_advanced_test.dart index 344e0daebc4..5191c4edc03 100644 --- a/tests/standalone/io/http_advanced_test.dart +++ b/tests/standalone/io/http_advanced_test.dart @@ -40,8 +40,10 @@ class IsolatedHttpServer { void shutdown() { // Send server stop message to the server. - _serverPort - .send([new IsolatedHttpServerCommand.stop(), _statusPort.sendPort]); + _serverPort.send([ + new IsolatedHttpServerCommand.stop(), + _statusPort.sendPort, + ]); _statusPort.close(); } @@ -49,7 +51,7 @@ class IsolatedHttpServer { // Send chunked encoding message to the server. _serverPort.send([ new IsolatedHttpServerCommand.chunkedEncoding(), - _statusPort.sendPort + _statusPort.sendPort, ]); } @@ -158,8 +160,10 @@ class TestServer { Expect.equals("html", request.headers.contentType!.subType); Expect.equals("utf-8", request.headers.contentType!.parameters["charset"]); - response.headers - .set(HttpHeaders.contentTypeHeader, "text/html; charset = utf-8"); + response.headers.set( + HttpHeaders.contentTypeHeader, + "text/html; charset = utf-8", + ); response.close(); } @@ -247,36 +251,42 @@ Future testHost() { IsolatedHttpServer server = new IsolatedHttpServer(); server.setServerStartedHandler((int port) { HttpClient httpClient = new HttpClient(); - httpClient.get("127.0.0.1", port, "/host").then((request) { - Expect.equals("127.0.0.1:$port", request.headers["host"]![0]); - request.headers.host = "www.dartlang.com"; - Expect.equals("www.dartlang.com:$port", request.headers["host"]![0]); - Expect.equals("www.dartlang.com", request.headers.host); - Expect.equals(port, request.headers.port); - request.headers.port = 1234; - Expect.equals("www.dartlang.com:1234", request.headers["host"]![0]); - Expect.equals(1234, request.headers.port); - request.headers.port = HttpClient.defaultHttpPort; - Expect.equals(HttpClient.defaultHttpPort, request.headers.port); - Expect.equals("www.dartlang.com", request.headers["host"]![0]); - request.headers.set("Host", "www.dartlang.org"); - Expect.equals("www.dartlang.org", request.headers.host); - Expect.equals(HttpClient.defaultHttpPort, request.headers.port); - request.headers.set("Host", "www.dartlang.org:"); - Expect.equals("www.dartlang.org", request.headers.host); - Expect.equals(HttpClient.defaultHttpPort, request.headers.port); - request.headers.set("Host", "www.dartlang.org:1234"); - Expect.equals("www.dartlang.org", request.headers.host); - Expect.equals(1234, request.headers.port); - return request.close(); - }).then((response) { - Expect.equals(HttpStatus.ok, response.statusCode); - response.listen((_) {}, onDone: () { - httpClient.close(); - server.shutdown(); - completer.complete(true); - }); - }); + httpClient + .get("127.0.0.1", port, "/host") + .then((request) { + Expect.equals("127.0.0.1:$port", request.headers["host"]![0]); + request.headers.host = "www.dartlang.com"; + Expect.equals("www.dartlang.com:$port", request.headers["host"]![0]); + Expect.equals("www.dartlang.com", request.headers.host); + Expect.equals(port, request.headers.port); + request.headers.port = 1234; + Expect.equals("www.dartlang.com:1234", request.headers["host"]![0]); + Expect.equals(1234, request.headers.port); + request.headers.port = HttpClient.defaultHttpPort; + Expect.equals(HttpClient.defaultHttpPort, request.headers.port); + Expect.equals("www.dartlang.com", request.headers["host"]![0]); + request.headers.set("Host", "www.dartlang.org"); + Expect.equals("www.dartlang.org", request.headers.host); + Expect.equals(HttpClient.defaultHttpPort, request.headers.port); + request.headers.set("Host", "www.dartlang.org:"); + Expect.equals("www.dartlang.org", request.headers.host); + Expect.equals(HttpClient.defaultHttpPort, request.headers.port); + request.headers.set("Host", "www.dartlang.org:1234"); + Expect.equals("www.dartlang.org", request.headers.host); + Expect.equals(1234, request.headers.port); + return request.close(); + }) + .then((response) { + Expect.equals(HttpStatus.ok, response.statusCode); + response.listen( + (_) {}, + onDone: () { + httpClient.close(); + server.shutdown(); + completer.complete(true); + }, + ); + }); }); server.start(); return completer.future; @@ -292,17 +302,24 @@ Future testExpires() { void processResponse(HttpClientResponse response) { Expect.equals(HttpStatus.ok, response.statusCode); Expect.equals( - "Fri, 11 Jun 1999 18:46:53 GMT", response.headers["expires"]![0]); - Expect.equals(new DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0), - response.headers.expires); - response.listen((_) {}, onDone: () { - responses++; - if (responses == 2) { - httpClient.close(); - server.shutdown(); - completer.complete(true); - } - }); + "Fri, 11 Jun 1999 18:46:53 GMT", + response.headers["expires"]![0], + ); + Expect.equals( + new DateTime.utc(1999, DateTime.june, 11, 18, 46, 53, 0), + response.headers.expires, + ); + response.listen( + (_) {}, + onDone: () { + responses++; + if (responses == 2) { + httpClient.close(); + server.shutdown(); + completer.complete(true); + } + }, + ); } httpClient @@ -328,33 +345,51 @@ Future testContentType() { void processResponse(HttpClientResponse response) { Expect.equals(HttpStatus.ok, response.statusCode); Expect.equals( - "text/html; charset=utf-8", response.headers.contentType.toString()); + "text/html; charset=utf-8", + response.headers.contentType.toString(), + ); Expect.equals("text/html", response.headers.contentType!.value); Expect.equals("text", response.headers.contentType!.primaryType); Expect.equals("html", response.headers.contentType!.subType); Expect.equals( - "utf-8", response.headers.contentType!.parameters["charset"]); - response.listen((_) {}, onDone: () { - responses++; - if (responses == 2) { - httpClient.close(); - server.shutdown(); - completer.complete(true); - } - }); + "utf-8", + response.headers.contentType!.parameters["charset"], + ); + response.listen( + (_) {}, + onDone: () { + responses++; + if (responses == 2) { + httpClient.close(); + server.shutdown(); + completer.complete(true); + } + }, + ); } - httpClient.get("127.0.0.1", port, "/contenttype1").then((request) { - request.headers.contentType = - new ContentType("text", "html", charset: "utf-8"); - return request.close(); - }).then(processResponse); + httpClient + .get("127.0.0.1", port, "/contenttype1") + .then((request) { + request.headers.contentType = new ContentType( + "text", + "html", + charset: "utf-8", + ); + return request.close(); + }) + .then(processResponse); - httpClient.get("127.0.0.1", port, "/contenttype2").then((request) { - request.headers - .set(HttpHeaders.contentTypeHeader, "text/html; charset = utf-8"); - return request.close(); - }).then(processResponse); + httpClient + .get("127.0.0.1", port, "/contenttype2") + .then((request) { + request.headers.set( + HttpHeaders.contentTypeHeader, + "text/html; charset = utf-8", + ); + return request.close(); + }) + .then(processResponse); }); server.start(); return completer.future; @@ -371,39 +406,55 @@ Future testCookies() { .get("127.0.0.1", port, "/cookie1") .then((request) => request.close()) .then((response) { - Expect.equals(2, response.cookies.length); - response.cookies.forEach((cookie) { - if (cookie.name == "name1") { - Expect.equals("value1", cookie.value); - DateTime date = - new DateTime.utc(2014, DateTime.january, 5, 23, 59, 59, 0); - Expect.equals(date, cookie.expires); - Expect.equals("www.example.com", cookie.domain); - Expect.isTrue(cookie.httpOnly); - } else if (cookie.name == "name2") { - Expect.equals("value2", cookie.value); - Expect.equals(100, cookie.maxAge); - Expect.equals(".example.com", cookie.domain); - Expect.equals("/shop", cookie.path); - } else { - Expect.fail("Unexpected cookie"); - } - }); - - response.listen((_) {}, onDone: () { - httpClient.get("127.0.0.1", port, "/cookie2").then((request) { - request.cookies.add(response.cookies[0]); - request.cookies.add(response.cookies[1]); - return request.close(); - }).then((response) { - response.listen((_) {}, onDone: () { - httpClient.close(); - server.shutdown(); - completer.complete(true); + Expect.equals(2, response.cookies.length); + response.cookies.forEach((cookie) { + if (cookie.name == "name1") { + Expect.equals("value1", cookie.value); + DateTime date = new DateTime.utc( + 2014, + DateTime.january, + 5, + 23, + 59, + 59, + 0, + ); + Expect.equals(date, cookie.expires); + Expect.equals("www.example.com", cookie.domain); + Expect.isTrue(cookie.httpOnly); + } else if (cookie.name == "name2") { + Expect.equals("value2", cookie.value); + Expect.equals(100, cookie.maxAge); + Expect.equals(".example.com", cookie.domain); + Expect.equals("/shop", cookie.path); + } else { + Expect.fail("Unexpected cookie"); + } }); + + response.listen( + (_) {}, + onDone: () { + httpClient + .get("127.0.0.1", port, "/cookie2") + .then((request) { + request.cookies.add(response.cookies[0]); + request.cookies.add(response.cookies[1]); + return request.close(); + }) + .then((response) { + response.listen( + (_) {}, + onDone: () { + httpClient.close(); + server.shutdown(); + completer.complete(true); + }, + ); + }); + }, + ); }); - }); - }); }); server.start(); return completer.future; diff --git a/tests/standalone/io/http_auth_digest_test.dart b/tests/standalone/io/http_auth_digest_test.dart index 18b51b5fa64..667625e9469 100644 --- a/tests/standalone/io/http_auth_digest_test.dart +++ b/tests/standalone/io/http_auth_digest_test.dart @@ -375,8 +375,8 @@ void testMalformedAuthenticateHeaderWithAuthHandler() { ); // Request should throw an exception if the authenticate handler is set - client.authenticate = - (Uri url, String scheme, String? realm) async => false; + client.authenticate = (Uri url, String scheme, String? realm) async => + false; await asyncExpectThrows( client.getUrl(uri).then((request) => request.close()), ); diff --git a/tests/standalone/io/http_basic_test.dart b/tests/standalone/io/http_basic_test.dart index 9d001b01960..bec69308f09 100644 --- a/tests/standalone/io/http_basic_test.dart +++ b/tests/standalone/io/http_basic_test.dart @@ -26,8 +26,10 @@ class TestServerMain { if (chunkedEncoding) { // Send chunked encoding message to the server. - port.send( - [new TestServerCommand.chunkedEncoding(), _statusPort.sendPort]); + port.send([ + new TestServerCommand.chunkedEncoding(), + _statusPort.sendPort, + ]); } // Send server start message to the server. @@ -110,10 +112,13 @@ class TestServer { void _zeroToTenHandler(HttpRequest request) { var response = request.response; Expect.equals("GET", request.method); - request.listen((_) {}, onDone: () { - response.write("01234567890"); - response.close(); - }); + request.listen( + (_) {}, + onDone: () { + response.write("01234567890"); + response.close(); + }, + ); } // Return a 404. @@ -208,15 +213,17 @@ void testGET() { .get("127.0.0.1", port, "/0123456789") .then((request) => request.close()) .then((response) { - Expect.equals(HttpStatus.ok, response.statusCode); - StringBuffer body = new StringBuffer(); - response.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () { - Expect.equals("01234567890", body.toString()); - httpClient.close(); - testServerMain.close(); - }); - }); + Expect.equals(HttpStatus.ok, response.statusCode); + StringBuffer body = new StringBuffer(); + response.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () { + Expect.equals("01234567890", body.toString()); + httpClient.close(); + testServerMain.close(); + }, + ); + }); }); testServerMain.start(); } @@ -231,30 +238,35 @@ void testPOST(bool chunkedEncoding) { int count = 0; HttpClient httpClient = new HttpClient(); void sendRequest() { - httpClient.post("127.0.0.1", port, "/echo").then((request) { - if (chunkedEncoding) { - request.write(data.substring(0, 10)); - request.write(data.substring(10, data.length)); - } else { - request.contentLength = data.length; - request.write(data); - } - return request.close(); - }).then((response) { - Expect.equals(HttpStatus.ok, response.statusCode); - StringBuffer body = new StringBuffer(); - response.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () { - Expect.equals(data, body.toString()); - count++; - if (count < kMessageCount) { - sendRequest(); - } else { - httpClient.close(); - testServerMain.close(); - } - }); - }); + httpClient + .post("127.0.0.1", port, "/echo") + .then((request) { + if (chunkedEncoding) { + request.write(data.substring(0, 10)); + request.write(data.substring(10, data.length)); + } else { + request.contentLength = data.length; + request.write(data); + } + return request.close(); + }) + .then((response) { + Expect.equals(HttpStatus.ok, response.statusCode); + StringBuffer body = new StringBuffer(); + response.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () { + Expect.equals(data, body.toString()); + count++; + if (count < kMessageCount) { + sendRequest(); + } else { + httpClient.close(); + testServerMain.close(); + } + }, + ); + }); } sendRequest(); @@ -272,15 +284,17 @@ void test404() { .get("127.0.0.1", port, "/thisisnotfound") .then((request) => request.close()) .then((response) { - Expect.equals(HttpStatus.notFound, response.statusCode); - var body = new StringBuffer(); - response.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () { - Expect.equals("Page not found", body.toString()); - httpClient.close(); - testServerMain.close(); - }); - }); + Expect.equals(HttpStatus.notFound, response.statusCode); + var body = new StringBuffer(); + response.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () { + Expect.equals("Page not found", body.toString()); + httpClient.close(); + testServerMain.close(); + }, + ); + }); }); testServerMain.start(); } @@ -289,17 +303,26 @@ void testReasonPhrase() { TestServerMain testServerMain = new TestServerMain(); testServerMain.setServerStartedHandler((int port) { HttpClient httpClient = new HttpClient(); - httpClient.get("127.0.0.1", port, "/reasonformoving").then((request) { - request.followRedirects = false; - return request.close(); - }).then((response) { - Expect.equals(HttpStatus.movedPermanently, response.statusCode); - Expect.equals("Don't come looking here any more", response.reasonPhrase); - response.listen((data) => Expect.fail("No data expected"), onDone: () { - httpClient.close(); - testServerMain.close(); - }); - }); + httpClient + .get("127.0.0.1", port, "/reasonformoving") + .then((request) { + request.followRedirects = false; + return request.close(); + }) + .then((response) { + Expect.equals(HttpStatus.movedPermanently, response.statusCode); + Expect.equals( + "Don't come looking here any more", + response.reasonPhrase, + ); + response.listen( + (data) => Expect.fail("No data expected"), + onDone: () { + httpClient.close(); + testServerMain.close(); + }, + ); + }); }); testServerMain.start(); } diff --git a/tests/standalone/io/http_client_connect_test.dart b/tests/standalone/io/http_client_connect_test.dart index fec5f7ee026..70e08775580 100644 --- a/tests/standalone/io/http_client_connect_test.dart +++ b/tests/standalone/io/http_client_connect_test.dart @@ -25,8 +25,8 @@ void testGetEmptyRequest() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.listen((data) {}, onDone: server.close); - }); + response.listen((data) {}, onDone: server.close); + }); }); } @@ -43,12 +43,15 @@ void testGetDataRequest() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - int count = 0; - response.listen((data) => count += data.length, onDone: () { - server.close(); - Expect.equals(data.length, count); - }); - }); + int count = 0; + response.listen( + (data) => count += data.length, + onDone: () { + server.close(); + Expect.equals(data.length, count); + }, + ); + }); }); } @@ -56,8 +59,8 @@ void testGetInvalidHost() { asyncStart(); var client = new HttpClient(); Future.value( - client.get("__SOMETHING_INVALID__", 8888, "/")) - .catchError((error) { + client.get("__SOMETHING_INVALID__", 8888, "/"), + ).catchError((error) { client.close(); asyncEnd(); }); @@ -112,9 +115,12 @@ void testGetServerForceClose() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - Expect.fail("Request not expected"); - }).catchError((error) => asyncEnd(), - test: (error) => error is HttpException); + Expect.fail("Request not expected"); + }) + .catchError( + (error) => asyncEnd(), + test: (error) => error is HttpException, + ); }); } @@ -135,17 +141,19 @@ void testGetDataServerForceClose() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - // Close the (incomplete) response, now that we have seen - // the response object. - completer.complete(null); - int errors = 0; - response.listen((data) {}, - onError: (error) => errors++, - onDone: () { - Expect.equals(1, errors); - asyncEnd(); - }); - }); + // Close the (incomplete) response, now that we have seen + // the response object. + completer.complete(null); + int errors = 0; + response.listen( + (data) {}, + onError: (error) => errors++, + onDone: () { + Expect.equals(1, errors); + asyncEnd(); + }, + ); + }); }); } @@ -158,7 +166,7 @@ void testOpenEmptyRequest() { [client.put, 'PUT'], [client.delete, 'DELETE'], [client.patch, 'PATCH'], - [client.head, 'HEAD'] + [client.head, 'HEAD'], ]; for (var method in methods) { @@ -169,11 +177,11 @@ void testOpenEmptyRequest() { }); Callback1 cb = method[0] as Callback1; - cb("127.0.0.1", server.port, "/") - .then((request) => request.close()) - .then((response) { - response.listen((data) {}, onDone: server.close); - }); + cb("127.0.0.1", server.port, "/").then((request) => request.close()).then( + (response) { + response.listen((data) {}, onDone: server.close); + }, + ); }); } } @@ -187,7 +195,7 @@ void testOpenUrlEmptyRequest() { [client.putUrl, 'PUT'], [client.deleteUrl, 'DELETE'], [client.patchUrl, 'PATCH'], - [client.headUrl, 'HEAD'] + [client.headUrl, 'HEAD'], ]; for (var method in methods) { @@ -198,9 +206,9 @@ void testOpenUrlEmptyRequest() { }); Callback2 cb = method[0] as Callback2; - cb(Uri.parse("http://127.0.0.1:${server.port}/")) - .then((request) => request.close()) - .then((response) { + cb( + Uri.parse("http://127.0.0.1:${server.port}/"), + ).then((request) => request.close()).then((response) { response.listen((data) {}, onDone: server.close); }); }); @@ -222,36 +230,38 @@ void testNoBuffer() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((clientResponse) { - var iterator = new StreamIterator(clientResponse - .cast>() - .transform(utf8.decoder) - .transform(new LineSplitter())); - iterator.moveNext().then((hasValue) { - Expect.isTrue(hasValue); - Expect.equals('init', iterator.current); - int count = 0; - void run() { - if (count == 10) { - response.close(); - iterator.moveNext().then((hasValue) { - Expect.isFalse(hasValue); - server.close(); - asyncEnd(); - }); - } else { - response.writeln('output$count'); - iterator.moveNext().then((hasValue) { - Expect.isTrue(hasValue); - Expect.equals('output$count', iterator.current); - count++; - run(); - }); - } - } + var iterator = new StreamIterator( + clientResponse + .cast>() + .transform(utf8.decoder) + .transform(new LineSplitter()), + ); + iterator.moveNext().then((hasValue) { + Expect.isTrue(hasValue); + Expect.equals('init', iterator.current); + int count = 0; + void run() { + if (count == 10) { + response.close(); + iterator.moveNext().then((hasValue) { + Expect.isFalse(hasValue); + server.close(); + asyncEnd(); + }); + } else { + response.writeln('output$count'); + iterator.moveNext().then((hasValue) { + Expect.isTrue(hasValue); + Expect.equals('output$count', iterator.current); + count++; + run(); + }); + } + } - run(); - }); - }); + run(); + }); + }); }); } @@ -261,9 +271,10 @@ void testMaxConnectionsPerHost(int connectionCap, int connections) { int handled = 0; server.listen((request) { Expect.isTrue( - server.connectionsInfo().total <= connectionCap, - '${server.connectionsInfo().total} <= $connectionCap ' + - '(connections: $connections)'); + server.connectionsInfo().total <= connectionCap, + '${server.connectionsInfo().total} <= $connectionCap ' + + '(connections: $connections)', + ); request.response.close(); handled++; if (handled == connections) { @@ -280,10 +291,13 @@ void testMaxConnectionsPerHost(int connectionCap, int connections) { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.listen(null, onDone: () { - asyncEnd(); - }); - }); + response.listen( + null, + onDone: () { + asyncEnd(); + }, + ); + }); } }); } @@ -303,8 +317,10 @@ Future testMaxConnectionsWithFailure() async { } try { await client.getUrl(Uri.parse('http://domain.invalid')); - Expect.fail("Calls exceed client's maxConnectionsPerHost should throw " - "exceptions as well"); + Expect.fail( + "Calls exceed client's maxConnectionsPerHost should throw " + "exceptions as well", + ); } catch (e) { if (e is! SocketException) { Expect.fail("Unexpected exception $e is thrown"); @@ -334,13 +350,16 @@ Future testHttpAbort() async { asyncEnd(); }); }); - request.close().then((response) { - Expect.fail('abort() prevents a response being returned'); - }, onError: (e) { - Expect.type(e); - Expect.isTrue(e.toString().contains('abort')); - asyncEnd(); - }); + request.close().then( + (response) { + Expect.fail('abort() prevents a response being returned'); + }, + onError: (e) { + Expect.type(e); + Expect.isTrue(e.toString().contains('abort')); + asyncEnd(); + }, + ); } Future testHttpAbortBeforeWrite() async { @@ -368,12 +387,15 @@ Future testHttpAbortBeforeWrite() async { server.close(); asyncEnd(); }); - request.close().then((response) { - Expect.fail('abort() prevents a response being returned'); - }, onError: (e) { - Expect.type(e); - asyncEnd(); - }); + request.close().then( + (response) { + Expect.fail('abort() prevents a response being returned'); + }, + onError: (e) { + Expect.type(e); + asyncEnd(); + }, + ); } Future testHttpAbortBeforeClose() async { @@ -401,13 +423,16 @@ Future testHttpAbortBeforeClose() async { await completer.future; final string = 'abort message'; request.abort(string); - request.close().then((response) { - Expect.fail('abort() prevents a response being returned'); - }, onError: (e) { - Expect.type(e); - Expect.equals(string, e); - asyncEnd(); - }); + request.close().then( + (response) { + Expect.fail('abort() prevents a response being returned'); + }, + onError: (e) { + Expect.type(e); + Expect.equals(string, e); + asyncEnd(); + }, + ); } Future testHttpAbortAfterClose() async { diff --git a/tests/standalone/io/http_client_exception_test.dart b/tests/standalone/io/http_client_exception_test.dart index dce825e82f5..35f8edc776e 100644 --- a/tests/standalone/io/http_client_exception_test.dart +++ b/tests/standalone/io/http_client_exception_test.dart @@ -10,31 +10,48 @@ import "package:expect/expect.dart"; void testInvalidUrl() { HttpClient client = new HttpClient(); - Expect.throws(() => client.getUrl(Uri.parse('ftp://www.google.com')), - (e) => e.toString().contains("Unsupported scheme")); - Expect.throws(() => client.getUrl(Uri.parse('httpx://www.google.com')), - (e) => e.toString().contains("Unsupported scheme")); + Expect.throws( + () => client.getUrl(Uri.parse('ftp://www.google.com')), + (e) => e.toString().contains("Unsupported scheme"), + ); + Expect.throws( + () => client.getUrl(Uri.parse('httpx://www.google.com')), + (e) => e.toString().contains("Unsupported scheme"), + ); Expect.throwsFormatException(() => client.getUrl(Uri.parse('http://::1'))); - Expect.throws(() => client.getUrl(Uri.parse('http://user@:1')), - (e) => e.toString().contains("No host specified")); - Expect.throws(() => client.getUrl(Uri.parse('http:///')), - (e) => e.toString().contains("No host specified")); - Expect.throws(() => client.getUrl(Uri.parse('http:///index.html')), - (e) => e.toString().contains("No host specified")); - Expect.throws(() => client.getUrl(Uri.parse('///')), - (e) => e.toString().contains("No host specified")); - Expect.throws(() => client.getUrl(Uri.parse('///index.html')), - (e) => e.toString().contains("No host specified")); + Expect.throws( + () => client.getUrl(Uri.parse('http://user@:1')), + (e) => e.toString().contains("No host specified"), + ); + Expect.throws( + () => client.getUrl(Uri.parse('http:///')), + (e) => e.toString().contains("No host specified"), + ); + Expect.throws( + () => client.getUrl(Uri.parse('http:///index.html')), + (e) => e.toString().contains("No host specified"), + ); + Expect.throws( + () => client.getUrl(Uri.parse('///')), + (e) => e.toString().contains("No host specified"), + ); + Expect.throws( + () => client.getUrl(Uri.parse('///index.html')), + (e) => e.toString().contains("No host specified"), + ); } void testBadHostName() { asyncStart(); HttpClient client = new HttpClient(); - client.get("some.bad.host.name.7654321", 0, "/").then((request) { - Expect.fail("Should not open a request on bad hostname"); - }).catchError((error) { - asyncEnd(); // We expect onError to be called, due to bad host name. - }, test: (error) => error is! String); + client + .get("some.bad.host.name.7654321", 0, "/") + .then((request) { + Expect.fail("Should not open a request on bad hostname"); + }) + .catchError((error) { + asyncEnd(); // We expect onError to be called, due to bad host name. + }, test: (error) => error is! String); } void main() { diff --git a/tests/standalone/io/http_client_parser_crlfs_tolerant_test.dart b/tests/standalone/io/http_client_parser_crlfs_tolerant_test.dart index d29e424f882..5053302644d 100644 --- a/tests/standalone/io/http_client_parser_crlfs_tolerant_test.dart +++ b/tests/standalone/io/http_client_parser_crlfs_tolerant_test.dart @@ -24,24 +24,32 @@ Future testHttpClient(header) { }); }); - await runZonedGuarded(() { - var client = new HttpClient(); - client.userAgent = null; - client - .get("127.0.0.1", server.port, "/") - .then((request) => request.close()) - .then((response) { - response.transform(utf8.decoder).listen((contents) { - completer.complete(); - }, onDone: () { - client.close(force: true); - server.close(); - }); - }); - }, (e, st) { - server.close(); - completer.completeError(e, st); - }); + await runZonedGuarded( + () { + var client = new HttpClient(); + client.userAgent = null; + client + .get("127.0.0.1", server.port, "/") + .then((request) => request.close()) + .then((response) { + response + .transform(utf8.decoder) + .listen( + (contents) { + completer.complete(); + }, + onDone: () { + client.close(force: true); + server.close(); + }, + ); + }); + }, + (e, st) { + server.close(); + completer.completeError(e, st); + }, + ); }); return completer.future; } diff --git a/tests/standalone/io/http_close_stack_overflow_test.dart b/tests/standalone/io/http_close_stack_overflow_test.dart index 27055f8467b..f89776d313b 100644 --- a/tests/standalone/io/http_close_stack_overflow_test.dart +++ b/tests/standalone/io/http_close_stack_overflow_test.dart @@ -19,8 +19,9 @@ Future main() async { for (var i = 0; i < max; i++) { new Future(() async { try { - final request = await client - .getUrl(Uri.parse("http://localhost:${servers[i].port}/")); + final request = await client.getUrl( + Uri.parse("http://localhost:${servers[i].port}/"), + ); got++; if (got == max) { // Test that no stack overflow happens. diff --git a/tests/standalone/io/http_close_test.dart b/tests/standalone/io/http_close_test.dart index 7de6f947917..abcf2a08314 100644 --- a/tests/standalone/io/http_close_test.dart +++ b/tests/standalone/io/http_close_test.dart @@ -23,7 +23,9 @@ testClientAndServerCloseNoListen(int connections) { if (closed == connections) { Expect.equals(0, server.connectionsInfo().active); Expect.equals( - server.connectionsInfo().total, server.connectionsInfo().idle); + server.connectionsInfo().total, + server.connectionsInfo().idle, + ); server.close(); } }); @@ -46,16 +48,21 @@ testClientCloseServerListen(int connections) { if (closed == connections * 2) { Expect.equals(0, server.connectionsInfo().active); Expect.equals( - server.connectionsInfo().total, server.connectionsInfo().idle); + server.connectionsInfo().total, + server.connectionsInfo().idle, + ); server.close(); } } server.listen((request) { - request.listen((_) {}, onDone: () { - request.response.close(); - request.response.done.then((_) => check()); - }); + request.listen( + (_) {}, + onDone: () { + request.response.close(); + request.response.done.then((_) => check()); + }, + ); }); var client = HttpClient(); for (int i = 0; i < connections; i++) { @@ -81,7 +88,9 @@ testClientCloseSendingResponse(int connections) { if (closed == connections * 2) { Expect.equals(0, server.connectionsInfo().active); Expect.equals( - server.connectionsInfo().total, server.connectionsInfo().idle); + server.connectionsInfo().total, + server.connectionsInfo().idle, + ); server.close(); } } @@ -101,14 +110,14 @@ testClientCloseSendingResponse(int connections) { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - // Ensure we don't accept the response until we have send the entire - // request. - var subscription = response.listen((_) {}); - Timer(const Duration(milliseconds: 20), () { - subscription.cancel(); - check(); - }); - }); + // Ensure we don't accept the response until we have send the entire + // request. + var subscription = response.listen((_) {}); + Timer(const Duration(milliseconds: 20), () { + subscription.cancel(); + check(); + }); + }); } }); } @@ -119,25 +128,32 @@ testClientCloseWhileSendingRequest(int connections) { HttpServer.bind("127.0.0.1", 0).then((server) { int serverErrors = 0; int clientErrors = 0; - server.listen((request) { - request.listen((_) {}, onError: (_) { - serverErrors++; - if (serverErrors == connections) { - server.close(); - } - }); - }, onDone: () { - Expect.equals(connections, clientErrors); - Expect.equals(connections, serverErrors); - }); + server.listen( + (request) { + request.listen( + (_) {}, + onError: (_) { + serverErrors++; + if (serverErrors == connections) { + server.close(); + } + }, + ); + }, + onDone: () { + Expect.equals(connections, clientErrors); + Expect.equals(connections, serverErrors); + }, + ); var client = HttpClient(); for (int i = 0; i < connections; i++) { Future.value( - client.post("127.0.0.1", server.port, "/").then((request) { - request.contentLength = 110; - request.write("0123456789"); - return request.close(); - })).catchError((_) { + client.post("127.0.0.1", server.port, "/").then((request) { + request.contentLength = 110; + request.write("0123456789"); + return request.close(); + }), + ).catchError((_) { clientErrors++; }); } diff --git a/tests/standalone/io/http_compression_test.dart b/tests/standalone/io/http_compression_test.dart index 1682ae8e736..64e27ea79c3 100644 --- a/tests/standalone/io/http_compression_test.dart +++ b/tests/standalone/io/http_compression_test.dart @@ -25,9 +25,13 @@ Future testServerCompress({bool clientAutoUncompress = true}) async { request.headers.set(HttpHeaders.acceptEncodingHeader, "gzip,deflate"); final response = await request.close(); Expect.equals( - "gzip", response.headers.value(HttpHeaders.contentEncodingHeader)); - final list = - await response.fold>([], (list, b) => list..addAll(b)); + "gzip", + response.headers.value(HttpHeaders.contentEncodingHeader), + ); + final list = await response.fold>( + [], + (list, b) => list..addAll(b), + ); if (clientAutoUncompress) { Expect.listEquals(data, list); } else { @@ -57,8 +61,10 @@ Future testAcceptEncodingHeader() async { final request = await client.get("127.0.0.1", server.port, "/"); request.headers.set(HttpHeaders.acceptEncodingHeader, encoding); final response = await request.close(); - Expect.equals(valid, - ("gzip" == response.headers.value(HttpHeaders.contentEncodingHeader))); + Expect.equals( + valid, + ("gzip" == response.headers.value(HttpHeaders.contentEncodingHeader)), + ); await response.listen((_) {}).asFuture(); server.close(); client.close(); @@ -83,7 +89,9 @@ Future testDisableCompressTest() async { Expect.equals(false, server.autoCompress); server.listen((request) { Expect.equals( - 'gzip', request.headers.value(HttpHeaders.acceptEncodingHeader)); + 'gzip', + request.headers.value(HttpHeaders.acceptEncodingHeader), + ); request.response.write("data"); request.response.close(); }); @@ -91,7 +99,9 @@ Future testDisableCompressTest() async { final request = await client.get("127.0.0.1", server.port, "/"); final response = await request.close(); Expect.equals( - null, response.headers.value(HttpHeaders.contentEncodingHeader)); + null, + response.headers.value(HttpHeaders.contentEncodingHeader), + ); await response.listen((_) {}).asFuture(); server.close(); client.close(); diff --git a/tests/standalone/io/http_connection_close_test.dart b/tests/standalone/io/http_connection_close_test.dart index 2ec57fbb2be..33e75743b40 100644 --- a/tests/standalone/io/http_connection_close_test.dart +++ b/tests/standalone/io/http_connection_close_test.dart @@ -15,10 +15,13 @@ void testHttp10Close(bool closeRequest) { Socket.connect("127.0.0.1", server.port).then((socket) { socket.write("GET / HTTP/1.0\r\n\r\n"); - socket.listen((data) {}, onDone: () { - if (!closeRequest) socket.destroy(); - server.close(); - }); + socket.listen( + (data) {}, + onDone: () { + if (!closeRequest) socket.destroy(); + server.close(); + }, + ); if (closeRequest) socket.close(); }); }); @@ -33,10 +36,13 @@ void testHttp11Close(bool closeRequest) { Socket.connect("127.0.0.1", server.port).then((socket) { List buffer = new List.filled(1024, 0); socket.write("GET / HTTP/1.1\r\nConnection: close\r\n\r\n"); - socket.listen((data) {}, onDone: () { - if (!closeRequest) socket.destroy(); - server.close(); - }); + socket.listen( + (data) {}, + onDone: () { + if (!closeRequest) socket.destroy(); + server.close(); + }, + ); if (closeRequest) socket.close(); }); }); @@ -46,12 +52,15 @@ void testStreamResponse() { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { var timer = new Timer.periodic(const Duration(milliseconds: 0), (_) { - request.response - .write('data:${new DateTime.now().millisecondsSinceEpoch}\n\n'); + request.response.write( + 'data:${new DateTime.now().millisecondsSinceEpoch}\n\n', + ); }); - request.response.done.whenComplete(() { - timer.cancel(); - }).catchError((_) {}); + request.response.done + .whenComplete(() { + timer.cancel(); + }) + .catchError((_) {}); }); var client = new HttpClient(); @@ -59,16 +68,19 @@ void testStreamResponse() { .getUrl(Uri.parse("http://127.0.0.1:${server.port}")) .then((request) => request.close()) .then((response) { - int bytes = 0; - response.listen((data) { - bytes += data.length; - if (bytes > 100) { - client.close(force: true); - } - }, onError: (error) { - server.close(); - }); - }); + int bytes = 0; + response.listen( + (data) { + bytes += data.length; + if (bytes > 100) { + client.close(force: true); + } + }, + onError: (error) { + server.close(); + }, + ); + }); }); } diff --git a/tests/standalone/io/http_connection_factory_test.dart b/tests/standalone/io/http_connection_factory_test.dart index c805838f47f..b2412216932 100644 --- a/tests/standalone/io/http_connection_factory_test.dart +++ b/tests/standalone/io/http_connection_factory_test.dart @@ -141,17 +141,20 @@ testDifferentAddressFamiliesAndProxySettings(String dir) async { Expect.equals("Hello via Proxy", inet6ResponseText); // Fetch a URL from the Unix server and verify the results. final unixResponse = await client - .getUrl(Uri( + .getUrl( + Uri( scheme: "unix", // Connection pooling is based on the host/port combination // so ensure that the host is unique for unique logical // endpoints. Also, the `host` property is converted to // lowercase so you cannot use it directly for file paths. host: 'dummy', - path: "/")) + path: "/", + ), + ) .then((request) { - return request.close(); - }); + return request.close(); + }); Expect.equals(200, unixResponse.statusCode); final unixResponseText = await unixResponse .transform(utf8.decoder) diff --git a/tests/standalone/io/http_connection_header_test.dart b/tests/standalone/io/http_connection_header_test.dart index 55c8cd85d53..3b1752a997b 100644 --- a/tests/standalone/io/http_connection_header_test.dart +++ b/tests/standalone/io/http_connection_header_test.dart @@ -15,19 +15,30 @@ void setConnectionHeaders(HttpHeaders headers) { } void checkExpectedConnectionHeaders( - HttpHeaders headers, bool persistentConnection) { + HttpHeaders headers, + bool persistentConnection, +) { Expect.equals("some-value1", headers.value("My-Connection-Header1")); Expect.equals("some-value2", headers.value("My-Connection-Header2")); - Expect.isTrue(headers[HttpHeaders.connectionHeader]! - .any((value) => value.toLowerCase() == "my-connection-header1")); - Expect.isTrue(headers[HttpHeaders.connectionHeader]! - .any((value) => value.toLowerCase() == "my-connection-header2")); + Expect.isTrue( + headers[HttpHeaders.connectionHeader]!.any( + (value) => value.toLowerCase() == "my-connection-header1", + ), + ); + Expect.isTrue( + headers[HttpHeaders.connectionHeader]!.any( + (value) => value.toLowerCase() == "my-connection-header2", + ), + ); if (persistentConnection) { Expect.equals(2, headers[HttpHeaders.connectionHeader]!.length); } else { Expect.equals(3, headers[HttpHeaders.connectionHeader]!.length); - Expect.isTrue(headers[HttpHeaders.connectionHeader]! - .any((value) => value.toLowerCase() == "close")); + Expect.isTrue( + headers[HttpHeaders.connectionHeader]!.any( + (value) => value.toLowerCase() == "close", + ), + ); } } @@ -37,9 +48,13 @@ void test(int totalConnections, bool clientPersistentConnection) { // Check expected request. Expect.equals(clientPersistentConnection, request.persistentConnection); Expect.equals( - clientPersistentConnection, request.response.persistentConnection); + clientPersistentConnection, + request.response.persistentConnection, + ); checkExpectedConnectionHeaders( - request.headers, request.persistentConnection); + request.headers, + request.persistentConnection, + ); // Generate response. If the client signaled non-persistent // connection the server should not need to set it. @@ -56,21 +71,27 @@ void test(int totalConnections, bool clientPersistentConnection) { client .get("127.0.0.1", server.port, "/") .then((HttpClientRequest request) { - setConnectionHeaders(request.headers); - request.persistentConnection = clientPersistentConnection; - return request.close(); - }).then((HttpClientResponse response) { - Expect.isFalse(response.persistentConnection); - checkExpectedConnectionHeaders( - response.headers, response.persistentConnection); - response.listen((_) {}, onDone: () { - count++; - if (count == totalConnections) { - client.close(); - server.close(); - } - }); - }); + setConnectionHeaders(request.headers); + request.persistentConnection = clientPersistentConnection; + return request.close(); + }) + .then((HttpClientResponse response) { + Expect.isFalse(response.persistentConnection); + checkExpectedConnectionHeaders( + response.headers, + response.persistentConnection, + ); + response.listen( + (_) {}, + onDone: () { + count++; + if (count == totalConnections) { + client.close(); + server.close(); + } + }, + ); + }); } }); } diff --git a/tests/standalone/io/http_connection_info_test.dart b/tests/standalone/io/http_connection_info_test.dart index 967c2ed8768..0c7c1134699 100644 --- a/tests/standalone/io/http_connection_info_test.dart +++ b/tests/standalone/io/http_connection_info_test.dart @@ -18,25 +18,36 @@ void testHttpConnectionInfo() { Expect.isNotNull(clientPort); Expect.equals(request.connectionInfo!.remotePort, clientPort); Expect.equals(response.connectionInfo!.remotePort, clientPort); - request.listen((_) {}, onDone: () { - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.close(); + }, + ); }); HttpClient client = new HttpClient(); - client.get("127.0.0.1", server.port, "/").then((request) { - Expect.isTrue(request.connectionInfo!.remoteAddress is InternetAddress); - Expect.equals(request.connectionInfo!.remotePort, server.port); - clientPort = request.connectionInfo!.localPort; - return request.close(); - }).then((response) { - Expect.equals(server.port, response.connectionInfo!.remotePort); - Expect.equals(clientPort, response.connectionInfo!.localPort); - response.listen((_) {}, onDone: () { - client.close(); - server.close(); - }); - }); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + Expect.isTrue( + request.connectionInfo!.remoteAddress is InternetAddress, + ); + Expect.equals(request.connectionInfo!.remotePort, server.port); + clientPort = request.connectionInfo!.localPort; + return request.close(); + }) + .then((response) { + Expect.equals(server.port, response.connectionInfo!.remotePort); + Expect.equals(clientPort, response.connectionInfo!.localPort); + response.listen( + (_) {}, + onDone: () { + client.close(); + server.close(); + }, + ); + }); }); } diff --git a/tests/standalone/io/http_content_length_test.dart b/tests/standalone/io/http_content_length_test.dart index 12e1e99a810..7ed7ed96b53 100644 --- a/tests/standalone/io/http_content_length_test.dart +++ b/tests/standalone/io/http_content_length_test.dart @@ -15,51 +15,60 @@ import "package:expect/expect.dart"; void testNoBody(int totalConnections, bool explicitContentLength) { int count = 0; HttpServer.bind("127.0.0.1", 0, backlog: totalConnections).then((server) { - server.listen((HttpRequest request) { - Expect.equals(null, request.headers.value('content-length')); - Expect.equals(-1, request.contentLength); - var response = request.response; - response.contentLength = 0; - response.done.then((_) { - Expect.fail("Unexpected successful response completion"); - }).catchError((error) { - Expect.isTrue(error is HttpException); - if (++count == totalConnections) { - server.close(); - } - }); - // write with content length 0 closes the connection and - // reports an error. - response.write("x"); - // Subsequent write are ignored as there is already an - // error. - response.write("x"); - // After an explicit close, write becomes a state error - // because we have said we will not add more. - response.close(); - Expect.throws(() { + server.listen( + (HttpRequest request) { + Expect.equals(null, request.headers.value('content-length')); + Expect.equals(-1, request.contentLength); + var response = request.response; + response.contentLength = 0; + response.done + .then((_) { + Expect.fail("Unexpected successful response completion"); + }) + .catchError((error) { + Expect.isTrue(error is HttpException); + if (++count == totalConnections) { + server.close(); + } + }); + // write with content length 0 closes the connection and + // reports an error. response.write("x"); - }, (e) => e is StateError); - }, onError: (e, trace) { - String msg = "Unexpected server error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + // Subsequent write are ignored as there is already an + // error. + response.write("x"); + // After an explicit close, write becomes a state error + // because we have said we will not add more. + response.close(); + Expect.throws(() { + response.write("x"); + }, (e) => e is StateError); + }, + onError: (e, trace) { + String msg = "Unexpected server error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); HttpClient client = new HttpClient(); for (int i = 0; i < totalConnections; i++) { - client.get("127.0.0.1", server.port, "/").then((request) { - if (explicitContentLength) { - request.contentLength = 0; - } - return request.close(); - }).then((response) { - Expect.equals("0", response.headers.value('content-length')); - Expect.equals(0, response.contentLength); - response.drain(); - }).catchError((e, trace) { - // It's also okay to fail, as headers may not be written. - }); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + if (explicitContentLength) { + request.contentLength = 0; + } + return request.close(); + }) + .then((response) { + Expect.equals("0", response.headers.value('content-length')); + Expect.equals(0, response.contentLength); + response.drain(); + }) + .catchError((e, trace) { + // It's also okay to fail, as headers may not be written. + }); } }); } @@ -67,133 +76,173 @@ void testNoBody(int totalConnections, bool explicitContentLength) { void testBody(int totalConnections, bool useHeader) { HttpServer.bind("127.0.0.1", 0, backlog: totalConnections).then((server) { int serverCount = 0; - server.listen((HttpRequest request) { - Expect.equals("2", request.headers.value('content-length')); - Expect.equals(2, request.contentLength); - var response = request.response; - if (useHeader) { - response.contentLength = 2; - } else { - response.headers.set("content-length", 2); - } - request.listen((d) {}, onDone: () { - response.write("x"); - Expect.throws( - () => response.contentLength = 3, (e) => e is HttpException); - response.write("x"); - response.write("x"); - response.done.then((_) { - Expect.fail("Unexpected successful response completion"); - }).catchError((error) { - Expect.isTrue(error is HttpException, "[$error]"); - if (++serverCount == totalConnections) { - server.close(); - } - }); - response.close(); - Expect.throws(() { - response.write("x"); - }, (e) => e is StateError); - }); - }, onError: (e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + server.listen( + (HttpRequest request) { + Expect.equals("2", request.headers.value('content-length')); + Expect.equals(2, request.contentLength); + var response = request.response; + if (useHeader) { + response.contentLength = 2; + } else { + response.headers.set("content-length", 2); + } + request.listen( + (d) {}, + onDone: () { + response.write("x"); + Expect.throws( + () => response.contentLength = 3, + (e) => e is HttpException, + ); + response.write("x"); + response.write("x"); + response.done + .then((_) { + Expect.fail("Unexpected successful response completion"); + }) + .catchError((error) { + Expect.isTrue(error is HttpException, "[$error]"); + if (++serverCount == totalConnections) { + server.close(); + } + }); + response.close(); + Expect.throws(() { + response.write("x"); + }, (e) => e is StateError); + }, + ); + }, + onError: (e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); int clientCount = 0; HttpClient client = new HttpClient(); for (int i = 0; i < totalConnections; i++) { - client.get("127.0.0.1", server.port, "/").then((request) { - if (useHeader) { - request.contentLength = 2; - } else { - request.headers.add(HttpHeaders.contentLengthHeader, "7"); - request.headers.add(HttpHeaders.contentLengthHeader, "2"); - } - request.write("x"); - Expect.throws( - () => request.contentLength = 3, (e) => e is HttpException); - request.write("x"); - return request.close(); - }).then((response) { - Expect.equals("2", response.headers.value('content-length')); - Expect.equals(2, response.contentLength); - response.listen((d) {}, onDone: () { - if (++clientCount == totalConnections) { - client.close(); - } - }, onError: (error, trace) { - // Undefined what server response sends. - }); - }).catchError((error) { - // It's also okay to fail, as headers may not be written. - }); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + if (useHeader) { + request.contentLength = 2; + } else { + request.headers.add(HttpHeaders.contentLengthHeader, "7"); + request.headers.add(HttpHeaders.contentLengthHeader, "2"); + } + request.write("x"); + Expect.throws( + () => request.contentLength = 3, + (e) => e is HttpException, + ); + request.write("x"); + return request.close(); + }) + .then((response) { + Expect.equals("2", response.headers.value('content-length')); + Expect.equals(2, response.contentLength); + response.listen( + (d) {}, + onDone: () { + if (++clientCount == totalConnections) { + client.close(); + } + }, + onError: (error, trace) { + // Undefined what server response sends. + }, + ); + }) + .catchError((error) { + // It's also okay to fail, as headers may not be written. + }); } }); } void testBodyChunked(int totalConnections, bool useHeader) { HttpServer.bind("127.0.0.1", 0, backlog: totalConnections).then((server) { - server.listen((HttpRequest request) { - Expect.isNull(request.headers.value('content-length')); - Expect.equals(-1, request.contentLength); - var response = request.response; - if (useHeader) { - response.contentLength = 2; - response.headers.chunkedTransferEncoding = true; - } else { - response.headers.set("content-length", 2); - response.headers.set("transfer-encoding", "chunked"); - } - request.listen((d) {}, onDone: () { - response.write("x"); - Expect.throws(() => response.headers.chunkedTransferEncoding = false, - (e) => e is HttpException); - response.write("x"); - response.write("x"); - response.close(); - Expect.throws(() { - response.write("x"); - }, (e) => e is StateError); - }); - }, onError: (e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + server.listen( + (HttpRequest request) { + Expect.isNull(request.headers.value('content-length')); + Expect.equals(-1, request.contentLength); + var response = request.response; + if (useHeader) { + response.contentLength = 2; + response.headers.chunkedTransferEncoding = true; + } else { + response.headers.set("content-length", 2); + response.headers.set("transfer-encoding", "chunked"); + } + request.listen( + (d) {}, + onDone: () { + response.write("x"); + Expect.throws( + () => response.headers.chunkedTransferEncoding = false, + (e) => e is HttpException, + ); + response.write("x"); + response.write("x"); + response.close(); + Expect.throws(() { + response.write("x"); + }, (e) => e is StateError); + }, + ); + }, + onError: (e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); int count = 0; HttpClient client = new HttpClient(); for (int i = 0; i < totalConnections; i++) { - client.get("127.0.0.1", server.port, "/").then((request) { - if (useHeader) { - request.contentLength = 2; - request.headers.chunkedTransferEncoding = true; - } else { - request.headers.add(HttpHeaders.contentLengthHeader, "2"); - request.headers.set(HttpHeaders.transferEncodingHeader, "chunked"); - } - request.write("x"); - Expect.throws(() => request.headers.chunkedTransferEncoding = false, - (e) => e is HttpException); - request.write("x"); - request.write("x"); - return request.close(); - }).then((response) { - Expect.isNull(response.headers.value('content-length')); - Expect.equals(-1, response.contentLength); - response.listen((d) {}, onDone: () { - if (++count == totalConnections) { - client.close(); - server.close(); - } - }); - }).catchError((e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + if (useHeader) { + request.contentLength = 2; + request.headers.chunkedTransferEncoding = true; + } else { + request.headers.add(HttpHeaders.contentLengthHeader, "2"); + request.headers.set( + HttpHeaders.transferEncodingHeader, + "chunked", + ); + } + request.write("x"); + Expect.throws( + () => request.headers.chunkedTransferEncoding = false, + (e) => e is HttpException, + ); + request.write("x"); + request.write("x"); + return request.close(); + }) + .then((response) { + Expect.isNull(response.headers.value('content-length')); + Expect.equals(-1, response.contentLength); + response.listen( + (d) {}, + onDone: () { + if (++count == totalConnections) { + client.close(); + server.close(); + } + }, + ); + }) + .catchError((e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }); } }); } @@ -216,11 +265,14 @@ void testSetContentLength() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.listen((_) {}, onDone: () { - client.close(); - server.close(); - }); - }); + response.listen( + (_) {}, + onDone: () { + client.close(); + server.close(); + }, + ); + }); }); } diff --git a/tests/standalone/io/http_cookie_date_test.dart b/tests/standalone/io/http_cookie_date_test.dart index b4c42bf9bb5..036deab5e2a 100644 --- a/tests/standalone/io/http_cookie_date_test.dart +++ b/tests/standalone/io/http_cookie_date_test.dart @@ -12,10 +12,24 @@ var _parseCookieDate = Testing$HttpDate.test$_parseCookieDate; void testParseHttpCookieDate() { Expect.throws(() => _parseCookieDate("")); - test(int year, int month, int day, int hours, int minutes, int seconds, - String formatted) { - DateTime date = - new DateTime.utc(year, month, day, hours, minutes, seconds, 0); + test( + int year, + int month, + int day, + int hours, + int minutes, + int seconds, + String formatted, + ) { + DateTime date = new DateTime.utc( + year, + month, + day, + hours, + minutes, + seconds, + 0, + ); Expect.equals(date, _parseCookieDate(formatted)); } diff --git a/tests/standalone/io/http_cookie_test.dart b/tests/standalone/io/http_cookie_test.dart index ac62a179cbd..525a79df44d 100644 --- a/tests/standalone/io/http_cookie_test.dart +++ b/tests/standalone/io/http_cookie_test.dart @@ -11,7 +11,7 @@ void testCookies() { {'abc': 'def'}, {'ABC': 'DEF'}, {'Abc': 'Def'}, - {'Abc': 'Def', 'SID': 'sffFSDF4FsdfF56765'} + {'Abc': 'Def', 'SID': 'sffFSDF4FsdfF56765'}, ]; HttpServer.bind("127.0.0.1", 0).then((server) { @@ -31,29 +31,36 @@ void testCookies() { int count = 0; HttpClient client = new HttpClient(); for (int i = 0; i < cookies.length; i++) { - client.get("127.0.0.1", server.port, "/$i").then((request) { - // Send the cookies to the server. - cookies[i].forEach((k, v) { - request.cookies.add(new Cookie(k, v)); - }); - return request.close(); - }).then((response) { - // Expect the same cookies back. - var cookiesMap = {}; - response.cookies.forEach((c) => cookiesMap[c.name] = c.value); - Expect.mapEquals(cookies[i], cookiesMap); - response.cookies.forEach((c) => Expect.isTrue(c.httpOnly)); - response.listen((d) {}, onDone: () { - if (++count == cookies.length) { - client.close(); - server.close(); - } - }); - }).catchError((e, trace) { - String msg = "Unexpected error $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + client + .get("127.0.0.1", server.port, "/$i") + .then((request) { + // Send the cookies to the server. + cookies[i].forEach((k, v) { + request.cookies.add(new Cookie(k, v)); + }); + return request.close(); + }) + .then((response) { + // Expect the same cookies back. + var cookiesMap = {}; + response.cookies.forEach((c) => cookiesMap[c.name] = c.value); + Expect.mapEquals(cookies[i], cookiesMap); + response.cookies.forEach((c) => Expect.isTrue(c.httpOnly)); + response.listen( + (d) {}, + onDone: () { + if (++count == cookies.length) { + client.close(); + server.close(); + } + }, + ); + }) + .catchError((e, trace) { + String msg = "Unexpected error $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }); } }); } @@ -63,24 +70,35 @@ void testValidateCookieWithDoubleQuotes() { Expect.equals(Cookie('key', '').toString(), 'key=; HttpOnly'); Expect.equals(Cookie('key', '""').toString(), 'key=""; HttpOnly'); Expect.equals(Cookie('key', '"value"').toString(), 'key="value"; HttpOnly'); - Expect.equals(Cookie.fromSetCookieValue('key=value; HttpOnly').toString(), - 'key=value; HttpOnly'); Expect.equals( - Cookie.fromSetCookieValue('key=; HttpOnly').toString(), 'key=; HttpOnly'); - Expect.equals(Cookie.fromSetCookieValue('key=""; HttpOnly').toString(), - 'key=""; HttpOnly'); - Expect.equals(Cookie.fromSetCookieValue('key="value"; HttpOnly').toString(), - 'key="value"; HttpOnly'); + Cookie.fromSetCookieValue('key=value; HttpOnly').toString(), + 'key=value; HttpOnly', + ); + Expect.equals( + Cookie.fromSetCookieValue('key=; HttpOnly').toString(), + 'key=; HttpOnly', + ); + Expect.equals( + Cookie.fromSetCookieValue('key=""; HttpOnly').toString(), + 'key=""; HttpOnly', + ); + Expect.equals( + Cookie.fromSetCookieValue('key="value"; HttpOnly').toString(), + 'key="value"; HttpOnly', + ); Expect.throwsFormatException(() => Cookie('key', '"')); Expect.throwsFormatException(() => Cookie('key', '"""')); Expect.throwsFormatException(() => Cookie('key', '"x""')); Expect.throwsFormatException(() => Cookie('key', '"x"y"')); Expect.throwsFormatException( - () => Cookie.fromSetCookieValue('key="; HttpOnly')); + () => Cookie.fromSetCookieValue('key="; HttpOnly'), + ); Expect.throwsFormatException( - () => Cookie.fromSetCookieValue('key="""; HttpOnly')); + () => Cookie.fromSetCookieValue('key="""; HttpOnly'), + ); Expect.throwsFormatException( - () => Cookie.fromSetCookieValue('key="x""; HttpOnly')); + () => Cookie.fromSetCookieValue('key="x""; HttpOnly'), + ); } void testValidatePath() { @@ -112,37 +130,51 @@ void testValidatePath() { void testCookieSameSite() { Cookie cookie1 = Cookie.fromSetCookieValue( - "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; Secure; " - "HttpOnly; Path=/; SameSite=None"); + "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; Secure; " + "HttpOnly; Path=/; SameSite=None", + ); Expect.equals(cookie1.sameSite, SameSite.none); Cookie cookie2 = Cookie.fromSetCookieValue( - "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " - "Path=/; SameSite=Lax"); + "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " + "Path=/; SameSite=Lax", + ); Expect.equals(cookie2.sameSite, SameSite.lax); Cookie cookie3 = Cookie.fromSetCookieValue( - "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " - "Path=/; SameSite=LAX"); + "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " + "Path=/; SameSite=LAX", + ); Expect.equals(cookie3.sameSite, SameSite.lax); Cookie cookie4 = Cookie.fromSetCookieValue( - "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " - "Path=/; SameSite= Lax"); + "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " + "Path=/; SameSite= Lax", + ); Expect.equals(cookie4.sameSite, SameSite.lax); Cookie cookie5 = Cookie.fromSetCookieValue( - "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " - "Path=/; sAmEsItE= nOnE"); + "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " + "Path=/; sAmEsItE= nOnE", + ); Expect.equals(cookie5.sameSite, SameSite.none); - Expect.throws(() => Cookie.fromSetCookieValue( + Expect.throws( + () => Cookie.fromSetCookieValue( "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " - "Path=/; SameSite=Relax"), - (e) => e.message == "SameSite value should be one of Lax, Strict or None."); - Expect.throws(() => Cookie.fromSetCookieValue( + "Path=/; SameSite=Relax", + ), + (e) => e.message == "SameSite value should be one of Lax, Strict or None.", + ); + Expect.throws( + () => Cookie.fromSetCookieValue( "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " - "Path=/; SameSite="), - (e) => e.message == "SameSite value should be one of Lax, Strict or None."); - Expect.throws(() => Cookie.fromSetCookieValue( + "Path=/; SameSite=", + ), + (e) => e.message == "SameSite value should be one of Lax, Strict or None.", + ); + Expect.throws( + () => Cookie.fromSetCookieValue( "name=cookie_name; Expires=Sat, 01 Apr 2023 00:00:00 GMT; HttpOnly; " - "Path=/; SameSite=无"), - (e) => e.message == "SameSite value should be one of Lax, Strict or None."); + "Path=/; SameSite=无", + ), + (e) => e.message == "SameSite value should be one of Lax, Strict or None.", + ); } void main() { diff --git a/tests/standalone/io/http_cross_process_test.dart b/tests/standalone/io/http_cross_process_test.dart index 598ac685d35..1693f13fe34 100644 --- a/tests/standalone/io/http_cross_process_test.dart +++ b/tests/standalone/io/http_cross_process_test.dart @@ -35,13 +35,13 @@ Future makeServer() { Future runClientProcess(int port) { return Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add(Platform.script.toFilePath()) - ..add('--client') - ..add(port.toString())) - .then((ProcessResult result) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add(Platform.script.toFilePath()) + ..add('--client') + ..add(port.toString()), + ).then((ProcessResult result) { if (result.exitCode != 0 || !result.stdout.contains('SUCCESS')) { print("Client failed, exit code ${result.exitCode}"); print(" stdout:"); diff --git a/tests/standalone/io/http_date_test.dart b/tests/standalone/io/http_date_test.dart index baa879f1e73..81240811663 100644 --- a/tests/standalone/io/http_date_test.dart +++ b/tests/standalone/io/http_date_test.dart @@ -26,8 +26,15 @@ void testParseHttpDate() { } void testFormatParseHttpDate() { - test(int year, int month, int day, int hours, int minutes, int seconds, - String expectedFormatted) { + test( + int year, + int month, + int day, + int hours, + int minutes, + int seconds, + String expectedFormatted, + ) { DateTime date; String formatted; date = new DateTime.utc(year, month, day, hours, minutes, seconds, 0); diff --git a/tests/standalone/io/http_detach_socket_test.dart b/tests/standalone/io/http_detach_socket_test.dart index 047132cb00a..c263c1d8afb 100644 --- a/tests/standalone/io/http_detach_socket_test.dart +++ b/tests/standalone/io/http_detach_socket_test.dart @@ -22,8 +22,10 @@ void testServerDetachSocket() { response.detachSocket().then((socket) { Expect.isNotNull(socket); var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () => Expect.equals("Some data", body.toString())); + socket.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () => Expect.equals("Some data", body.toString()), + ); socket.write("Test!"); socket.close(); }); @@ -31,20 +33,25 @@ void testServerDetachSocket() { }); Socket.connect("127.0.0.1", server.port).then((socket) { - socket.write("GET / HTTP/1.1\r\n" - "content-length: 0\r\n\r\n" - "Some data"); + socket.write( + "GET / HTTP/1.1\r\n" + "content-length: 0\r\n\r\n" + "Some data", + ); var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () { - Expect.equals( + socket.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () { + Expect.equals( "HTTP/1.1 200 OK\r\n" "content-length: 0\r\n" "\r\n" "Test!", - body.toString()); - socket.close(); - }); + body.toString(), + ); + socket.close(); + }, + ); }); }); } @@ -57,8 +64,10 @@ void testServerDetachSocketNoWriteHeaders() { response.detachSocket(writeHeaders: false).then((socket) { Expect.isNotNull(socket); var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () => Expect.equals("Some data", body.toString())); + socket.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () => Expect.equals("Some data", body.toString()), + ); socket.write("Test!"); socket.close(); }); @@ -66,15 +75,19 @@ void testServerDetachSocketNoWriteHeaders() { }); Socket.connect("127.0.0.1", server.port).then((socket) { - socket.write("GET / HTTP/1.1\r\n" - "content-length: 0\r\n\r\n" - "Some data"); + socket.write( + "GET / HTTP/1.1\r\n" + "content-length: 0\r\n\r\n" + "Some data", + ); var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () { - Expect.equals("Test!", body.toString()); - socket.close(); - }); + socket.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () { + Expect.equals("Test!", body.toString()); + socket.close(); + }, + ); }); }); } @@ -90,11 +103,16 @@ void testBadServerDetachSocket() { }); Socket.connect("127.0.0.1", server.port).then((socket) { - socket.write("GET / HTTP/1.1\r\n" - "content-length: 0\r\n\r\n"); - socket.listen((_) {}, onDone: () { - socket.close(); - }); + socket.write( + "GET / HTTP/1.1\r\n" + "content-length: 0\r\n\r\n", + ); + socket.listen( + (_) {}, + onDone: () { + socket.close(); + }, + ); }); }); } @@ -103,22 +121,26 @@ void testClientDetachSocket() { ServerSocket.bind("127.0.0.1", 0).then((server) { server.listen((socket) { int port = server.port; - socket.write("HTTP/1.1 200 OK\r\n" - "\r\n" - "Test!"); + socket.write( + "HTTP/1.1 200 OK\r\n" + "\r\n" + "Test!", + ); var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () { - List lines = body.toString().split("\r\n"); - Expect.equals(5, lines.length); - Expect.equals("GET / HTTP/1.1", lines[0]); - Expect.equals("", lines[3]); - Expect.equals("Some data", lines[4]); - lines.sort(); // Lines 1-2 becomes 3-4 in a fixed order. - Expect.equals("accept-encoding: gzip", lines[3]); - Expect.equals("host: 127.0.0.1:${port}", lines[4]); - socket.close(); - }); + socket.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () { + List lines = body.toString().split("\r\n"); + Expect.equals(5, lines.length); + Expect.equals("GET / HTTP/1.1", lines[0]); + Expect.equals("", lines[3]); + Expect.equals("Some data", lines[4]); + lines.sort(); // Lines 1-2 becomes 3-4 in a fixed order. + Expect.equals("accept-encoding: gzip", lines[3]); + Expect.equals("host: 127.0.0.1:${port}", lines[4]); + socket.close(); + }, + ); server.close(); }); @@ -128,17 +150,19 @@ void testClientDetachSocket() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.detachSocket().then((socket) { - var body = new StringBuffer(); - socket.listen((data) => body.write(new String.fromCharCodes(data)), - onDone: () { - Expect.equals("Test!", body.toString()); - client.close(); + response.detachSocket().then((socket) { + var body = new StringBuffer(); + socket.listen( + (data) => body.write(new String.fromCharCodes(data)), + onDone: () { + Expect.equals("Test!", body.toString()); + client.close(); + }, + ); + socket.write("Some data"); + socket.close(); + }); }); - socket.write("Some data"); - socket.close(); - }); - }); }); } @@ -161,30 +185,36 @@ void testUpgradedConnection() { var client = new HttpClient(); client.userAgent = null; - client.get("127.0.0.1", server.port, "/").then((request) { - request.headers.set('upgrade', 'mine'); - return request.close(); - }).then((response) { - client.get("127.0.0.1", server.port, "/").then((request) { - response.detachSocket().then((socket) { - // We are testing that we can detach the socket, even though - // we made a new connection (testing it was not reused). - request.close().then((response) { - asyncStart(); - response.listen(null, onDone: () { - server.close(); - asyncEnd(); - }); - socket.add([0]); - socket.close(); - socket.fold>([], (l, d) => l..addAll(d)).then((data) { - asyncEnd(); - Expect.listEquals([0], data); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + request.headers.set('upgrade', 'mine'); + return request.close(); + }) + .then((response) { + client.get("127.0.0.1", server.port, "/").then((request) { + response.detachSocket().then((socket) { + // We are testing that we can detach the socket, even though + // we made a new connection (testing it was not reused). + request.close().then((response) { + asyncStart(); + response.listen( + null, + onDone: () { + server.close(); + asyncEnd(); + }, + ); + socket.add([0]); + socket.close(); + socket.fold>([], (l, d) => l..addAll(d)).then((data) { + asyncEnd(); + Expect.listEquals([0], data); + }); + }); }); }); }); - }); - }); }); } diff --git a/tests/standalone/io/http_force_staggered_ipv6_lookup_test.dart b/tests/standalone/io/http_force_staggered_ipv6_lookup_test.dart index effbb0ec51c..009641dd3d6 100644 --- a/tests/standalone/io/http_force_staggered_ipv6_lookup_test.dart +++ b/tests/standalone/io/http_force_staggered_ipv6_lookup_test.dart @@ -15,11 +15,14 @@ const sampleData = [1, 2, 3, 4, 5]; void testBadHostName() { asyncStart(); HttpClient client = new HttpClient(); - client.get("some.bad.host.name.7654321", 0, "/").then((request) { - Expect.fail("Should not open a request on bad hostname"); - }).catchError((error) { - asyncEnd(); // We expect onError to be called, due to bad host name. - }, test: (error) => error is! String); + client + .get("some.bad.host.name.7654321", 0, "/") + .then((request) { + Expect.fail("Should not open a request on bad hostname"); + }) + .catchError((error) { + asyncEnd(); // We expect onError to be called, due to bad host name. + }, test: (error) => error is! String); } void testConnect(InternetAddress loopback, {int expectedElapsedMs = 0}) async { @@ -37,24 +40,31 @@ void testConnect(InternetAddress loopback, {int expectedElapsedMs = 0}) async { final sw = Stopwatch()..start(); var got = 0; for (var i = 0; i < max; i++) { - final client = await Socket.connect('localhost', servers[i].port, - sourceAddress: loopback); - client.listen((received) { - Expect.listEquals(sampleData, received); - }, onError: (e) { - Expect.fail('Unexpected failure $e'); - }, onDone: () { - client.close(); - got++; - if (got == max) { - // Test that no stack overflow happens. - for (final server in servers) { - server.close(); + final client = await Socket.connect( + 'localhost', + servers[i].port, + sourceAddress: loopback, + ); + client.listen( + (received) { + Expect.listEquals(sampleData, received); + }, + onError: (e) { + Expect.fail('Unexpected failure $e'); + }, + onDone: () { + client.close(); + got++; + if (got == max) { + // Test that no stack overflow happens. + for (final server in servers) { + server.close(); + } + Expect.isTrue(sw.elapsedMilliseconds > expectedElapsedMs); + asyncEnd(); } - Expect.isTrue(sw.elapsedMilliseconds > expectedElapsedMs); - asyncEnd(); - } - }); + }, + ); } } @@ -68,8 +78,10 @@ void main() async { if (localhosts.contains(InternetAddress.loopbackIPv6)) { // matches value in socket_patch.dart const concurrentLookupDelay = Duration(milliseconds: 10); - testConnect(InternetAddress.loopbackIPv6, - expectedElapsedMs: concurrentLookupDelay.inMilliseconds); + testConnect( + InternetAddress.loopbackIPv6, + expectedElapsedMs: concurrentLookupDelay.inMilliseconds, + ); } asyncEnd(); } diff --git a/tests/standalone/io/http_head_test.dart b/tests/standalone/io/http_head_test.dart index de19182fc6d..7a008827f6a 100644 --- a/tests/standalone/io/http_head_test.dart +++ b/tests/standalone/io/http_head_test.dart @@ -48,19 +48,23 @@ void testHEAD(int totalConnections) { .open("HEAD", "127.0.0.1", server.port, "/test$len") .then((request) => request.close()) .then((HttpClientResponse response) { - Expect.equals(len, response.contentLength); - response.listen((_) => Expect.fail("Data from HEAD request"), - onDone: requestDone); - }); + Expect.equals(len, response.contentLength); + response.listen( + (_) => Expect.fail("Data from HEAD request"), + onDone: requestDone, + ); + }); client .open("HEAD", "127.0.0.1", server.port, "/testChunked$len") .then((request) => request.close()) .then((HttpClientResponse response) { - Expect.equals(-1, response.contentLength); - response.listen((_) => Expect.fail("Data from HEAD request"), - onDone: requestDone); - }); + Expect.equals(-1, response.contentLength); + response.listen( + (_) => Expect.fail("Data from HEAD request"), + onDone: requestDone, + ); + }); } }); } diff --git a/tests/standalone/io/http_headers_state_test.dart b/tests/standalone/io/http_headers_state_test.dart index 764b3cd76dc..da935ce6751 100644 --- a/tests/standalone/io/http_headers_state_test.dart +++ b/tests/standalone/io/http_headers_state_test.dart @@ -12,30 +12,38 @@ void test(int totalConnections, [String? body]) { server.listen((HttpRequest request) { HttpResponse response = request.response; // Cannot mutate request headers. - Expect.throws(() => request.headers.add("X-Request-Header", "value"), - (e) => e is HttpException); + Expect.throws( + () => request.headers.add("X-Request-Header", "value"), + (e) => e is HttpException, + ); Expect.equals("value", request.headers.value("X-Request-Header")); - request.listen((_) {}, onDone: () { - // Can still mutate response headers as long as no data has been sent. - response.headers.add("X-Response-Header", "value"); - if (body != null) { - response.write(body); - // Cannot change state or reason when data has been sent. + request.listen( + (_) {}, + onDone: () { + // Can still mutate response headers as long as no data has been sent. + response.headers.add("X-Response-Header", "value"); + if (body != null) { + response.write(body); + // Cannot change state or reason when data has been sent. + Expect.throwsStateError(() => response.statusCode = 200); + Expect.throwsStateError(() => response.reasonPhrase = "OK"); + // Cannot mutate response headers when data has been sent. + Expect.throws( + () => response.headers.add("X-Request-Header", "value2"), + (e) => e is HttpException, + ); + } + response..close(); + // Cannot change state or reason after connection is closed. Expect.throwsStateError(() => response.statusCode = 200); Expect.throwsStateError(() => response.reasonPhrase = "OK"); - // Cannot mutate response headers when data has been sent. + // Cannot mutate response headers after connection is closed. Expect.throws( - () => response.headers.add("X-Request-Header", "value2"), - (e) => e is HttpException); - } - response..close(); - // Cannot change state or reason after connection is closed. - Expect.throwsStateError(() => response.statusCode = 200); - Expect.throwsStateError(() => response.reasonPhrase = "OK"); - // Cannot mutate response headers after connection is closed. - Expect.throws(() => response.headers.add("X-Request-Header", "value3"), - (e) => e is HttpException); - }); + () => response.headers.add("X-Request-Header", "value3"), + (e) => e is HttpException, + ); + }, + ); }); int count = 0; @@ -44,36 +52,46 @@ void test(int totalConnections, [String? body]) { client .get("127.0.0.1", server.port, "/") .then((HttpClientRequest request) { - if (body != null) { - request.contentLength = -1; - } - // Can still mutate request headers as long as no data has been sent. - request.headers.add("X-Request-Header", "value"); - if (body != null) { - request.write(body); - // Cannot mutate request headers when data has been sent. - Expect.throws(() => request.headers.add("X-Request-Header", "value2"), - (e) => e is HttpException); - } - request.close(); - // Cannot mutate request headers when data has been sent. - Expect.throws(() => request.headers.add("X-Request-Header", "value3"), - (e) => e is HttpException); - return request.done; - }).then((HttpClientResponse response) { - // Cannot mutate response headers. - Expect.throws(() => response.headers.add("X-Response-Header", "value"), - (e) => e is HttpException); - Expect.equals("value", response.headers.value("X-Response-Header")); - response.listen((_) {}, onDone: () { - // Do not close the connections before we have read the - // full response bodies for all connections. - if (++count == totalConnections) { - client.close(); - server.close(); - } - }); - }); + if (body != null) { + request.contentLength = -1; + } + // Can still mutate request headers as long as no data has been sent. + request.headers.add("X-Request-Header", "value"); + if (body != null) { + request.write(body); + // Cannot mutate request headers when data has been sent. + Expect.throws( + () => request.headers.add("X-Request-Header", "value2"), + (e) => e is HttpException, + ); + } + request.close(); + // Cannot mutate request headers when data has been sent. + Expect.throws( + () => request.headers.add("X-Request-Header", "value3"), + (e) => e is HttpException, + ); + return request.done; + }) + .then((HttpClientResponse response) { + // Cannot mutate response headers. + Expect.throws( + () => response.headers.add("X-Response-Header", "value"), + (e) => e is HttpException, + ); + Expect.equals("value", response.headers.value("X-Response-Header")); + response.listen( + (_) {}, + onDone: () { + // Do not close the connections before we have read the + // full response bodies for all connections. + if (++count == totalConnections) { + client.close(); + server.close(); + } + }, + ); + }); } }); } diff --git a/tests/standalone/io/http_headers_test.dart b/tests/standalone/io/http_headers_test.dart index b1ced547356..67f1f2e3d47 100644 --- a/tests/standalone/io/http_headers_test.dart +++ b/tests/standalone/io/http_headers_test.dart @@ -26,16 +26,25 @@ void testMultiValue() { headers.add(HttpHeaders.pragmaHeader, "pragma2"); Expect.equals(2, headers[HttpHeaders.pragmaHeader]!.length); Expect.throws( - () => headers.value(HttpHeaders.pragmaHeader), (e) => e is HttpException); + () => headers.value(HttpHeaders.pragmaHeader), + (e) => e is HttpException, + ); headers.add(HttpHeaders.pragmaHeader, ["pragma3", "pragma4"]); - Expect.listEquals(["pragma1", "pragma2", "pragma3", "pragma4"], - headers[HttpHeaders.pragmaHeader]!); + Expect.listEquals([ + "pragma1", + "pragma2", + "pragma3", + "pragma4", + ], headers[HttpHeaders.pragmaHeader]!); headers.remove(HttpHeaders.pragmaHeader, "pragma3"); Expect.equals(3, headers[HttpHeaders.pragmaHeader]!.length); - Expect.listEquals( - ["pragma1", "pragma2", "pragma4"], headers[HttpHeaders.pragmaHeader]!); + Expect.listEquals([ + "pragma1", + "pragma2", + "pragma4", + ], headers[HttpHeaders.pragmaHeader]!); headers.remove(HttpHeaders.pragmaHeader, "pragma3"); Expect.equals(3, headers[HttpHeaders.pragmaHeader]!.length); @@ -269,8 +278,11 @@ void testEnumeration() { } void testHeaderValue() { - void check(HeaderValue headerValue, String value, - [Map? parameters]) { + void check( + HeaderValue headerValue, + String value, [ + Map? parameters, + ]) { Expect.equals(value, headerValue.value); if (parameters != null) { Expect.equals(parameters.length, headerValue.parameters.length); @@ -298,28 +310,38 @@ void testHeaderValue() { check(headerValue, "v", {"a": ""}); Expect.throws(() => HeaderValue.parse("v;a=\"\\"), (e) => e is HttpException); Expect.throws( - () => HeaderValue.parse("v;a=\";b=\"c\""), (e) => e is HttpException); + () => HeaderValue.parse("v;a=\";b=\"c\""), + (e) => e is HttpException, + ); Expect.throws(() => HeaderValue.parse("v;a=b c"), (e) => e is HttpException); headerValue = HeaderValue.parse("æ;ø=å"); check(headerValue, "æ", {"ø": "å"}); - headerValue = - HeaderValue.parse("xxx; aaa=bbb; ccc=\"\\\";\\a\"; ddd=\" \""); + headerValue = HeaderValue.parse( + "xxx; aaa=bbb; ccc=\"\\\";\\a\"; ddd=\" \"", + ); check(headerValue, "xxx", {"aaa": "bbb", "ccc": '\";a', "ddd": " "}); - headerValue = - new HeaderValue("xxx", {"aaa": "bbb", "ccc": '\";a', "ddd": " "}); + headerValue = new HeaderValue("xxx", { + "aaa": "bbb", + "ccc": '\";a', + "ddd": " ", + }); check(headerValue, "xxx", {"aaa": "bbb", "ccc": '\";a', "ddd": " "}); - headerValue = HeaderValue.parse("attachment; filename=genome.jpeg;" - "modification-date=\"Wed, 12 February 1997 16:29:51 -0500\""); + headerValue = HeaderValue.parse( + "attachment; filename=genome.jpeg;" + "modification-date=\"Wed, 12 February 1997 16:29:51 -0500\"", + ); var parameters = { "filename": "genome.jpeg", - "modification-date": "Wed, 12 February 1997 16:29:51 -0500" + "modification-date": "Wed, 12 February 1997 16:29:51 -0500", }; check(headerValue, "attachment", parameters); headerValue = new HeaderValue("attachment", parameters); check(headerValue, "attachment", parameters); - headerValue = HeaderValue.parse(" attachment ;filename=genome.jpeg ;" - "modification-date = \"Wed, 12 February 1997 16:29:51 -0500\""); + headerValue = HeaderValue.parse( + " attachment ;filename=genome.jpeg ;" + "modification-date = \"Wed, 12 February 1997 16:29:51 -0500\"", + ); check(headerValue, "attachment", parameters); headerValue = HeaderValue.parse("xxx; aaa; bbb; ccc"); check(headerValue, "xxx", {"aaa": null, "bbb": null, "ccc": null}); @@ -337,14 +359,20 @@ void testHeaderValue() { Expect.equals("v; a", HeaderValue("v", {"a": null}).toString()); Expect.equals("v; a; b", HeaderValue("v", {"a": null, "b": null}).toString()); Expect.equals( - "v; a; b=c", HeaderValue("v", {"a": null, "b": "c"}).toString()); + "v; a; b=c", + HeaderValue("v", {"a": null, "b": "c"}).toString(), + ); Expect.equals( - "v; a=c; b", HeaderValue("v", {"a": "c", "b": null}).toString()); + "v; a=c; b", + HeaderValue("v", {"a": "c", "b": null}).toString(), + ); Expect.equals("v; a=\"\"", HeaderValue("v", {"a": ""}).toString()); Expect.equals("v; a=\"b c\"", HeaderValue("v", {"a": "b c"}).toString()); Expect.equals("v; a=\",\"", HeaderValue("v", {"a": ","}).toString()); Expect.equals( - "v; a=\"\\\\\\\"\"", HeaderValue("v", {"a": "\\\""}).toString()); + "v; a=\"\\\\\\\"\"", + HeaderValue("v", {"a": "\\\""}).toString(), + ); Expect.equals("v; a=\"ø\"", HeaderValue("v", {"a": "ø"}).toString()); } @@ -364,7 +392,8 @@ void testContentLength() { headers = new _HttpHeaders("1.1"); var e = Expect.throws( - () => headers.set("content-length", ["cat"])); + () => headers.set("content-length", ["cat"]), + ); Expect.isTrue(e.message.contains("Content-Length must contain only digits")); headers = new _HttpHeaders("1.1"); @@ -378,7 +407,8 @@ void testContentLength() { headers = new _HttpHeaders("1.1"); e = Expect.throws(() => headers.set("content-length", [[]])); Expect.isTrue( - e.message.contains("Unexpected type for header named content-length")); + e.message.contains("Unexpected type for header named content-length"), + ); headers = new _HttpHeaders("1.1"); headers.set("content-length", ["1", "2"]); @@ -388,8 +418,12 @@ void testContentLength() { } void testContentType() { - void check(ContentType contentType, String primaryType, String subType, - [Map? parameters]) { + void check( + ContentType contentType, + String primaryType, + String subType, [ + Map? parameters, + ]) { Expect.equals(primaryType, contentType.primaryType); Expect.equals(subType, contentType.subType); Expect.equals("$primaryType/$subType", contentType.value); @@ -418,22 +452,31 @@ void testContentType() { Expect.equals("text/html; charset=utf-8", contentType.toString()); Expect.throwsUnsupportedError(() => contentType.parameters["xxx"] = "yyy"); - contentType = new ContentType("text", "html", - parameters: {"CHARSET": "UTF-8", "xxx": "YYY"}); + contentType = new ContentType( + "text", + "html", + parameters: {"CHARSET": "UTF-8", "xxx": "YYY"}, + ); check(contentType, "text", "html", {"charset": "utf-8", "xxx": "YYY"}); String s = contentType.toString(); - bool expectedToString = (s == "text/html; charset=utf-8; xxx=YYY" || + bool expectedToString = + (s == "text/html; charset=utf-8; xxx=YYY" || s == "text/html; xxx=YYY; charset=utf-8"); Expect.isTrue(expectedToString); contentType = ContentType.parse("text/html; CHARSET=UTF-8; xxx=YYY"); check(contentType, "text", "html", {"charset": "utf-8", "xxx": "YYY"}); Expect.throwsUnsupportedError(() => contentType.parameters["xxx"] = "yyy"); - contentType = new ContentType("text", "html", - charset: "ISO-8859-1", parameters: {"CHARSET": "UTF-8", "xxx": "yyy"}); + contentType = new ContentType( + "text", + "html", + charset: "ISO-8859-1", + parameters: {"CHARSET": "UTF-8", "xxx": "yyy"}, + ); check(contentType, "text", "html", {"charset": "iso-8859-1", "xxx": "yyy"}); s = contentType.toString(); - expectedToString = (s == "text/html; charset=iso-8859-1; xxx=yyy" || + expectedToString = + (s == "text/html; charset=iso-8859-1; xxx=yyy" || s == "text/html; xxx=yyy; charset=iso-8859-1"); Expect.isTrue(expectedToString); @@ -447,13 +490,15 @@ void testContentType() { check(contentType, "text", "html", {"charset": "utf-8"}); contentType = ContentType.parse("text/html; charset=utf-8; xxx=yyy"); check(contentType, "text", "html", {"charset": "utf-8", "xxx": "yyy"}); - contentType = - ContentType.parse(" text/html ; charset = utf-8 ; xxx=yyy "); + contentType = ContentType.parse( + " text/html ; charset = utf-8 ; xxx=yyy ", + ); check(contentType, "text", "html", {"charset": "utf-8", "xxx": "yyy"}); contentType = ContentType.parse('text/html; charset=utf-8; xxx="yyy"'); check(contentType, "text", "html", {"charset": "utf-8", "xxx": "yyy"}); - contentType = - ContentType.parse(" text/html ; charset = utf-8 ; xxx=yyy "); + contentType = ContentType.parse( + " text/html ; charset = utf-8 ; xxx=yyy ", + ); check(contentType, "text", "html", {"charset": "utf-8", "xxx": "yyy"}); contentType = ContentType.parse("text/html; charset=;"); @@ -517,79 +562,89 @@ void testCookie() { DateTime date = new DateTime.utc(2014, DateTime.january, 5, 23, 59, 59, 0); cookie.expires = date; checkCookie( - cookie, - "$name=$value" - "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" - "; HttpOnly"); + cookie, + "$name=$value" + "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" + "; HttpOnly", + ); cookie.maxAge = 567; checkCookie( - cookie, - "$name=$value" - "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" - "; Max-Age=567" - "; HttpOnly"); + cookie, + "$name=$value" + "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" + "; Max-Age=567" + "; HttpOnly", + ); cookie.domain = "example.com"; checkCookie( - cookie, - "$name=$value" - "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" - "; Max-Age=567" - "; Domain=example.com" - "; HttpOnly"); + cookie, + "$name=$value" + "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" + "; Max-Age=567" + "; Domain=example.com" + "; HttpOnly", + ); cookie.path = "/xxx"; checkCookie( - cookie, - "$name=$value" - "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" - "; Max-Age=567" - "; Domain=example.com" - "; Path=/xxx" - "; HttpOnly"); + cookie, + "$name=$value" + "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" + "; Max-Age=567" + "; Domain=example.com" + "; Path=/xxx" + "; HttpOnly", + ); cookie.secure = true; checkCookie( - cookie, - "$name=$value" - "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" - "; Max-Age=567" - "; Domain=example.com" - "; Path=/xxx" - "; Secure" - "; HttpOnly"); + cookie, + "$name=$value" + "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" + "; Max-Age=567" + "; Domain=example.com" + "; Path=/xxx" + "; Secure" + "; HttpOnly", + ); cookie.httpOnly = false; checkCookie( - cookie, - "$name=$value" - "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" - "; Max-Age=567" - "; Domain=example.com" - "; Path=/xxx" - "; Secure"); + cookie, + "$name=$value" + "; Expires=Sun, 05 Jan 2014 23:59:59 GMT" + "; Max-Age=567" + "; Domain=example.com" + "; Path=/xxx" + "; Secure", + ); cookie.expires = null; checkCookie( - cookie, - "$name=$value" - "; Max-Age=567" - "; Domain=example.com" - "; Path=/xxx" - "; Secure"); + cookie, + "$name=$value" + "; Max-Age=567" + "; Domain=example.com" + "; Path=/xxx" + "; Secure", + ); cookie.maxAge = null; checkCookie( - cookie, - "$name=$value" - "; Domain=example.com" - "; Path=/xxx" - "; Secure"); + cookie, + "$name=$value" + "; Domain=example.com" + "; Path=/xxx" + "; Secure", + ); cookie.domain = null; checkCookie( - cookie, - "$name=$value" - "; Path=/xxx" - "; Secure"); + cookie, + "$name=$value" + "; Path=/xxx" + "; Secure", + ); cookie.path = null; checkCookie( - cookie, - "$name=$value" - "; Secure"); + cookie, + "$name=$value" + "; Secure", + ); cookie.secure = false; checkCookie(cookie, "$name=$value"); } @@ -607,17 +662,22 @@ void testInvalidCookie() { Expect.throws(() => new _Cookie.fromSetCookieValue("=xxx")); Expect.throws(() => new _Cookie.fromSetCookieValue("xxx")); Expect.throws( - () => new _Cookie.fromSetCookieValue("xxx=yyy; expires=12 jan 2013")); + () => new _Cookie.fromSetCookieValue("xxx=yyy; expires=12 jan 2013"), + ); Expect.throws(() => new _Cookie.fromSetCookieValue("x x = y y")); Expect.throws(() => new _Cookie("[4", "y")); Expect.throws(() => new _Cookie("4", "y\"")); _HttpHeaders headers = new _HttpHeaders("1.1"); headers.set( - 'Cookie', 'DARTSESSID=d3d6fdd78d51aaaf2924c32e991f4349; undefined'); + 'Cookie', + 'DARTSESSID=d3d6fdd78d51aaaf2924c32e991f4349; undefined', + ); Expect.equals('DARTSESSID', headers.test$_parseCookies().single.name); - Expect.equals('d3d6fdd78d51aaaf2924c32e991f4349', - headers.test$_parseCookies().single.value); + Expect.equals( + 'd3d6fdd78d51aaaf2924c32e991f4349', + headers.test$_parseCookies().single.value, + ); } void testHeaderLists() { diff --git a/tests/standalone/io/http_ipv6_test.dart b/tests/standalone/io/http_ipv6_test.dart index b491b626cd2..a2ba7f67664 100644 --- a/tests/standalone/io/http_ipv6_test.dart +++ b/tests/standalone/io/http_ipv6_test.dart @@ -32,12 +32,13 @@ void testHttpIPv6() { .openUrl('GET', url) .then((request) => request.close()) .then((response) { - Expect.equals(response.statusCode, HttpStatus.ok); - }).whenComplete(() { - server.close(); - client.close(); - asyncEnd(); - }); + Expect.equals(response.statusCode, HttpStatus.ok); + }) + .whenComplete(() { + server.close(); + client.close(); + asyncEnd(); + }); }); } diff --git a/tests/standalone/io/http_keep_alive_test.dart b/tests/standalone/io/http_keep_alive_test.dart index a9d794bbbba..b93c9488ef5 100644 --- a/tests/standalone/io/http_keep_alive_test.dart +++ b/tests/standalone/io/http_keep_alive_test.dart @@ -16,12 +16,12 @@ Future getData(HttpClient client, int port, bool chunked, int length) { .get("127.0.0.1", port, "/?chunked=$chunked&length=$length") .then((request) => request.close()) .then((response) { - return response - .fold(0, (bytes, data) => bytes + data.length) - .then((bytes) { - Expect.equals(length, bytes); - }); - }); + return response.fold(0, (bytes, data) => bytes + data.length).then( + (bytes) { + Expect.equals(length, bytes); + }, + ); + }); } Future startServer() { @@ -48,9 +48,9 @@ testKeepAliveNonChunked() { .then((_) => getData(client, server.port, false, 100)) .then((_) => getData(client, server.port, false, 100)) .then((_) { - server.close(); - client.close(); - }); + server.close(); + client.close(); + }); }); } @@ -64,9 +64,9 @@ testKeepAliveChunked() { .then((_) => getData(client, server.port, true, 100)) .then((_) => getData(client, server.port, true, 100)) .then((_) { - server.close(); - client.close(); - }); + server.close(); + client.close(); + }); }); } @@ -83,9 +83,9 @@ testKeepAliveMixed() { .then((_) => getData(client, server.port, true, 100)) .then((_) => getData(client, server.port, false, 100)) .then((_) { - server.close(); - client.close(); - }); + server.close(); + client.close(); + }); }); } diff --git a/tests/standalone/io/http_key_log_test.dart b/tests/standalone/io/http_key_log_test.dart index fee9f207469..5354ef03afa 100644 --- a/tests/standalone/io/http_key_log_test.dart +++ b/tests/standalone/io/http_key_log_test.dart @@ -22,8 +22,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); Future startEchoServer() { return HttpServer.bindSecure(HOST, 0, serverContext).then((server) { @@ -45,8 +47,9 @@ testSuccess(HttpServer server) async { client.keyLog = (String line) { log += line; }; - final request = - await client.getUrl(Uri.parse('https://localhost:${server.port}/test')); + final request = await client.getUrl( + Uri.parse('https://localhost:${server.port}/test'), + ); final response = await request.close(); await response.drain(); @@ -63,8 +66,9 @@ testExceptionInKeyLogFunction(HttpServer server) async { ++numCalls; throw FileSystemException("Something bad happened"); }; - final request = - await client.getUrl(Uri.parse('https://localhost:${server.port}/test')); + final request = await client.getUrl( + Uri.parse('https://localhost:${server.port}/test'), + ); final response = await request.close(); await response.drain(); diff --git a/tests/standalone/io/http_linklocal_ipv6_test.dart b/tests/standalone/io/http_linklocal_ipv6_test.dart index 2fcc66d4745..08d96bb3ffc 100644 --- a/tests/standalone/io/http_linklocal_ipv6_test.dart +++ b/tests/standalone/io/http_linklocal_ipv6_test.dart @@ -26,12 +26,15 @@ void main() { HttpServer.bind(ipv6, 0).then((server) { server.listen((request) { var timer = new Timer.periodic(const Duration(milliseconds: 0), (_) { - request.response - .write('data:${new DateTime.now().millisecondsSinceEpoch}\n\n'); + request.response.write( + 'data:${new DateTime.now().millisecondsSinceEpoch}\n\n', + ); }); - request.response.done.whenComplete(() { - timer.cancel(); - }).catchError((_) {}); + request.response.done + .whenComplete(() { + timer.cancel(); + }) + .catchError((_) {}); }); var client = new HttpClient(); @@ -39,18 +42,22 @@ void main() { .getUrl(Uri.parse("http://[${ipv6}]:${server.port}")) .then((request) => request.close()) .then((response) { - print( - 'response: status code: ${response.statusCode}, reason: ${response.reasonPhrase}'); - int bytes = 0; - response.listen((data) { - bytes += data.length; - if (bytes > 100) { - client.close(force: true); - } - }, onError: (error) { - server.close(); - }); - }); + print( + 'response: status code: ${response.statusCode}, reason: ${response.reasonPhrase}', + ); + int bytes = 0; + response.listen( + (data) { + bytes += data.length; + if (bytes > 100) { + client.close(force: true); + } + }, + onError: (error) { + server.close(); + }, + ); + }); asyncEnd(); }); } catch (e) { diff --git a/tests/standalone/io/http_loopback_test.dart b/tests/standalone/io/http_loopback_test.dart index 83238c0b1e1..d7eefed43ea 100644 --- a/tests/standalone/io/http_loopback_test.dart +++ b/tests/standalone/io/http_loopback_test.dart @@ -23,7 +23,9 @@ makeListener([List? remotePorts]) { /// Verify that you can't connect to loopback via mismatching protocol, e.g. /// if the server is listening to IPv4 then you can't connect via IPv6. Future failureTest( - InternetAddress serverAddr, InternetAddress clientAddr) async { + InternetAddress serverAddr, + InternetAddress clientAddr, +) async { final remotePorts = []; final server = await RawServerSocket.bind(serverAddr, 0); server.listen(makeListener(remotePorts)); @@ -48,8 +50,10 @@ Future failureTest( } catch (e) { Expect.fail('Unexpected exception: $e'); } finally { - Expect.isTrue(success, - 'Unexpected connection to $serverAddr via $clientAddr address!'); + Expect.isTrue( + success, + 'Unexpected connection to $serverAddr via $clientAddr address!', + ); await server.close(); } } diff --git a/tests/standalone/io/http_no_reason_phrase_test.dart b/tests/standalone/io/http_no_reason_phrase_test.dart index 2a1558e161d..fb4845a6593 100644 --- a/tests/standalone/io/http_no_reason_phrase_test.dart +++ b/tests/standalone/io/http_no_reason_phrase_test.dart @@ -29,10 +29,11 @@ void missingReasonPhrase(int statusCode, bool includeSpace) { .getUrl(Uri.parse("http://127.0.0.1:${server.port}/")) .then((request) => request.close()) .then((response) { - Expect.equals(statusCode, response.statusCode); - Expect.equals("", response.reasonPhrase); - return response.drain(); - }).whenComplete(() => server.close()); + Expect.equals(statusCode, response.statusCode); + Expect.equals("", response.reasonPhrase); + return response.drain(); + }) + .whenComplete(() => server.close()); }); } diff --git a/tests/standalone/io/http_on_unix_socket_test.dart b/tests/standalone/io/http_on_unix_socket_test.dart index e9611dcec9f..33e70abce26 100644 --- a/tests/standalone/io/http_on_unix_socket_test.dart +++ b/tests/standalone/io/http_on_unix_socket_test.dart @@ -13,17 +13,23 @@ Future testHttpServer(String name) async { var address = InternetAddress('$sockname', type: InternetAddressType.unix); var httpServer = await HttpServer.bind(address, 0); var sub; - sub = httpServer.listen((HttpRequest request) { - request.response.write('Hello, world!'); - request.response.close(); - sub.cancel(); - }, onDone: () { - httpServer.close(); - }); + sub = httpServer.listen( + (HttpRequest request) { + request.response.write('Hello, world!'); + request.response.close(); + sub.cancel(); + }, + onDone: () { + httpServer.close(); + }, + ); var option = "--unix-socket $sockname"; - var result = - await Process.run("curl", ["--unix-socket", "$sockname", "localhost"]); + var result = await Process.run("curl", [ + "--unix-socket", + "$sockname", + "localhost", + ]); Expect.isTrue(result.stdout.toString().contains('Hello, world!')); } diff --git a/tests/standalone/io/http_open_method_validate_test.dart b/tests/standalone/io/http_open_method_validate_test.dart index 484a4abbf65..fa4f9d91027 100644 --- a/tests/standalone/io/http_open_method_validate_test.dart +++ b/tests/standalone/io/http_open_method_validate_test.dart @@ -8,11 +8,14 @@ import "dart:io"; import "package:expect/expect.dart"; void testInvalidArgumentException(String method) { - Expect.throws(() => HttpClient()..open(method, "127.0.0.1", 8080, "/"), - (e) => e is ArgumentError); Expect.throws( - () => HttpClient()..openUrl(method, Uri.parse("http://127.0.0.1/")), - (e) => e is ArgumentError); + () => HttpClient()..open(method, "127.0.0.1", 8080, "/"), + (e) => e is ArgumentError, + ); + Expect.throws( + () => HttpClient()..openUrl(method, Uri.parse("http://127.0.0.1/")), + (e) => e is ArgumentError, + ); } main() { diff --git a/tests/standalone/io/http_outgoing_size_test.dart b/tests/standalone/io/http_outgoing_size_test.dart index 06a33a80922..c283b33f12c 100644 --- a/tests/standalone/io/http_outgoing_size_test.dart +++ b/tests/standalone/io/http_outgoing_size_test.dart @@ -33,19 +33,25 @@ void testChunkedBufferSizeMsg() { request.response.close(); }); var client = new HttpClient(); - client.get('127.0.0.1', server.port, '/').then((request) { - request.headers.set(HttpHeaders.acceptEncodingHeader, ""); - return request.close(); - }).then((response) { - var buffer = []; - response.listen((data) => buffer.addAll(data), onDone: () { - Expect.equals(sendData.length * 8, buffer.length); - for (int i = 0; i < buffer.length; i++) { - Expect.equals(sendData[i % sendData.length], buffer[i]); - } - server.close(); - }); - }); + client + .get('127.0.0.1', server.port, '/') + .then((request) { + request.headers.set(HttpHeaders.acceptEncodingHeader, ""); + return request.close(); + }) + .then((response) { + var buffer = []; + response.listen( + (data) => buffer.addAll(data), + onDone: () { + Expect.equals(sendData.length * 8, buffer.length); + for (int i = 0; i < buffer.length; i++) { + Expect.equals(sendData[i % sendData.length], buffer[i]); + } + server.close(); + }, + ); + }); }); } diff --git a/tests/standalone/io/http_override_test.dart b/tests/standalone/io/http_override_test.dart index 258a055849d..3caa901559f 100644 --- a/tests/standalone/io/http_override_test.dart +++ b/tests/standalone/io/http_override_test.dart @@ -19,8 +19,11 @@ class MyHttpClient1 implements HttpClient { bool enableTimelineLogging = false; Future open( - String method, String host, int port, String path) => - throw ""; + String method, + String host, + int port, + String path, + ) => throw ""; Future openUrl(String method, Uri url) => throw ""; Future get(String host, int port, String path) => throw ""; Future getUrl(Uri url) => throw ""; @@ -40,18 +43,31 @@ class MyHttpClient1 implements HttpClient { Future headUrl(Uri url) => throw ""; set authenticate(Future f(Uri url, String scheme, String realm)?) {} void addCredentials( - Uri url, String realm, HttpClientCredentials credentials) {} + Uri url, + String realm, + HttpClientCredentials credentials, + ) {} set connectionFactory( - Future> Function( - Uri url, String? proxyHost, int? proxyPort)? - f) {} + Future> Function( + Uri url, + String? proxyHost, + int? proxyPort, + )? + f, + ) {} set findProxy(String f(Uri url)?) {} set authenticateProxy( - Future f(String host, int port, String scheme, String realm)?) {} + Future f(String host, int port, String scheme, String realm)?, + ) {} void addProxyCredentials( - String host, int port, String realm, HttpClientCredentials credentials) {} + String host, + int port, + String realm, + HttpClientCredentials credentials, + ) {} set badCertificateCallback( - bool callback(X509Certificate cert, String host, int port)?) {} + bool callback(X509Certificate cert, String host, int port)?, + ) {} void set keyLog(Function(String line)? callback) {} void close({bool force = false}) {} } @@ -68,8 +84,11 @@ class MyHttpClient2 implements HttpClient { bool enableTimelineLogging = false; Future open( - String method, String host, int port, String path) => - throw ""; + String method, + String host, + int port, + String path, + ) => throw ""; Future openUrl(String method, Uri url) => throw ""; Future get(String host, int port, String path) => throw ""; Future getUrl(Uri url) => throw ""; @@ -89,18 +108,31 @@ class MyHttpClient2 implements HttpClient { Future headUrl(Uri url) => throw ""; set authenticate(Future f(Uri url, String scheme, String realm)?) {} void addCredentials( - Uri url, String realm, HttpClientCredentials credentials) {} + Uri url, + String realm, + HttpClientCredentials credentials, + ) {} set connectionFactory( - Future> Function( - Uri url, String? proxyHost, int? proxyPort)? - f) {} + Future> Function( + Uri url, + String? proxyHost, + int? proxyPort, + )? + f, + ) {} set findProxy(String f(Uri url)?) {} set authenticateProxy( - Future f(String host, int port, String scheme, String realm)?) {} + Future f(String host, int port, String scheme, String realm)?, + ) {} void addProxyCredentials( - String host, int port, String realm, HttpClientCredentials credentials) {} + String host, + int port, + String realm, + HttpClientCredentials credentials, + ) {} set badCertificateCallback( - bool callback(X509Certificate cert, String host, int port)?) {} + bool callback(X509Certificate cert, String host, int port)?, + ) {} void set keyLog(Function(String line)? callback) {} void close({bool force = false}) {} } @@ -170,8 +202,10 @@ nestedDifferentOverridesTest() { Expect.isNotNull(httpClient); Expect.isTrue(httpClient is MyHttpClient1); Expect.equals((new MyHttpClient1(null)).userAgent, httpClient.userAgent); - Expect.equals(myFindProxyFromEnvironment(new Uri(), null), - HttpClient.findProxyFromEnvironment(new Uri())); + Expect.equals( + myFindProxyFromEnvironment(new Uri(), null), + HttpClient.findProxyFromEnvironment(new Uri()), + ); }, findProxyFromEnvironment: myFindProxyFromEnvironment); httpClient = new HttpClient(); Expect.isNotNull(httpClient); diff --git a/tests/standalone/io/http_parser_connect_method_test.dart b/tests/standalone/io/http_parser_connect_method_test.dart index d02fda01a95..f87fce4ada0 100644 --- a/tests/standalone/io/http_parser_connect_method_test.dart +++ b/tests/standalone/io/http_parser_connect_method_test.dart @@ -23,24 +23,25 @@ Future test(String header, value) async { client .open(connect, "127.0.0.1", server.port, "/") .then((HttpClientRequest request) { - return request.close(); - }).then((HttpClientResponse response) { - Expect.equals(200, response.statusCode); - // Headers except Content-Length and Transfer-Encoding header will be read. - if (header == HttpHeaders.contentLengthHeader || - header == HttpHeaders.transferEncodingHeader) { - Expect.isNull(response.headers[header]); - } else { - final list = response.headers[header]; - Expect.isNotNull(list); - Expect.equals(1, list!.length); - Expect.equals(value, list[0]); - } + return request.close(); + }) + .then((HttpClientResponse response) { + Expect.equals(200, response.statusCode); + // Headers except Content-Length and Transfer-Encoding header will be read. + if (header == HttpHeaders.contentLengthHeader || + header == HttpHeaders.transferEncodingHeader) { + Expect.isNull(response.headers[header]); + } else { + final list = response.headers[header]; + Expect.isNotNull(list); + Expect.equals(1, list!.length); + Expect.equals(value, list[0]); + } - client.close(force: true); - server.close(); - completer.complete(); - }); + client.close(force: true); + server.close(); + completer.complete(); + }); await completer.future; } diff --git a/tests/standalone/io/http_parser_header_add_test.dart b/tests/standalone/io/http_parser_header_add_test.dart index 41f35229ec7..40580745552 100644 --- a/tests/standalone/io/http_parser_header_add_test.dart +++ b/tests/standalone/io/http_parser_header_add_test.dart @@ -25,7 +25,8 @@ Future testFormatException() async { final client = HttpClient()..userAgent = 'Bob’s browser'; try { await asyncExpectThrows( - client.open("CONNECT", "127.0.0.1", server.port, "/")); + client.open("CONNECT", "127.0.0.1", server.port, "/"), + ); } finally { client.close(force: true); server.close(); diff --git a/tests/standalone/io/http_proxy_advanced_test.dart b/tests/standalone/io/http_proxy_advanced_test.dart index 294e6fac22b..1579b4f2550 100644 --- a/tests/standalone/io/http_proxy_advanced_test.dart +++ b/tests/standalone/io/http_proxy_advanced_test.dart @@ -18,8 +18,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); final SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); final SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -38,10 +40,10 @@ class Server { ? HttpServer.bindSecure("localhost", 0, serverContext) : HttpServer.bind("localhost", 0)) .then((s) { - server = s; - server.listen(requestHandler); - return this; - }); + server = s; + server.listen(requestHandler); + return this; + }); } void requestHandler(HttpRequest request) { @@ -49,12 +51,16 @@ class Server { requestCount++; // Check whether a proxy or direct connection is expected. bool direct = directRequestPaths.fold( - false, (prev, path) => prev ? prev : path == request.uri.path); + false, + (prev, path) => prev ? prev : path == request.uri.path, + ); if (!secure && !direct && proxyHops > 0) { Expect.isNotNull(request.headers[HttpHeaders.viaHeader]); Expect.equals(1, request.headers[HttpHeaders.viaHeader]!.length); - Expect.equals(proxyHops, - request.headers[HttpHeaders.viaHeader]![0].split(",").length); + Expect.equals( + proxyHops, + request.headers[HttpHeaders.viaHeader]![0].split(",").length, + ); } else { Expect.isNull(request.headers[HttpHeaders.viaHeader]); } @@ -81,8 +87,11 @@ class Server { int get port => server.port; } -Future setupServer(int proxyHops, - {List directRequestPaths = const [], secure = false}) { +Future setupServer( + int proxyHops, { + List directRequestPaths = const [], + secure = false, +}) { Server server = new Server(proxyHops, directRequestPaths, secure); return server.start(); } @@ -125,8 +134,10 @@ class ProxyServer { basicAuthenticationRequired(request) { request.fold(null, (x, y) {}).then((_) { var response = request.response; - response.headers - .set(HttpHeaders.proxyAuthenticateHeader, "Basic, realm=$realm"); + response.headers.set( + HttpHeaders.proxyAuthenticateHeader, + "Basic, realm=$realm", + ); response.statusCode = HttpStatus.proxyAuthenticationRequired; response.close(); }); @@ -167,8 +178,10 @@ class ProxyServer { } return; } else { - Expect.equals(1, - request.headers[HttpHeaders.proxyAuthorizationHeader]!.length); + Expect.equals( + 1, + request.headers[HttpHeaders.proxyAuthorizationHeader]!.length, + ); String authorization = request.headers[HttpHeaders.proxyAuthorizationHeader]![0]; if (authScheme == "Basic") { @@ -180,8 +193,10 @@ class ProxyServer { return; } } else { - HeaderValue header = - HeaderValue.parse(authorization, parameterSeparator: ","); + HeaderValue header = HeaderValue.parse( + authorization, + parameterSeparator: ",", + ); Expect.equals("Digest", header.value); var uri = header.parameters["uri"]; var qop = header.parameters["qop"]; @@ -214,13 +229,17 @@ class ProxyServer { digest = md5.convert("$ha1:${nonce}:$ha2".codeUnits); } else { digest = md5.convert( - "$ha1:${nonce}:${nc}:${cnonce}:${qop}:$ha2".codeUnits); + "$ha1:${nonce}:${nc}:${cnonce}:${qop}:$ha2".codeUnits, + ); } Expect.equals( - hex.encode(digest.bytes), header.parameters["response"]); + hex.encode(digest.bytes), + header.parameters["response"], + ); // Add a bogus Proxy-Authentication-Info for testing. - var info = 'rspauth="77180d1ab3d6c9de084766977790f482", ' + var info = + 'rspauth="77180d1ab3d6c9de084766977790f482", ' 'cnonce="8f971178", ' 'nc=000002c74, ' 'qop=auth'; @@ -242,27 +261,30 @@ class ProxyServer { client .openUrl(request.method, request.uri) .then((HttpClientRequest clientRequest) { - // Forward all headers. - request.headers.forEach((String name, List values) { - values.forEach((String value) { - if (name != "content-length" && name != "via") { - clientRequest.headers.add(name, value); - } + // Forward all headers. + request.headers.forEach((String name, List values) { + values.forEach((String value) { + if (name != "content-length" && name != "via") { + clientRequest.headers.add(name, value); + } + }); + }); + // Special handling of Content-Length and Via. + clientRequest.contentLength = request.contentLength; + List? via = request.headers[HttpHeaders.viaHeader]; + String viaPrefix = via == null ? "" : "${via[0]}, "; + clientRequest.headers.add( + HttpHeaders.viaHeader, + "${viaPrefix}1.1 localhost:$port", + ); + // Copy all content. + return request.cast>().pipe(clientRequest); + }) + .then((clientResponse) { + (clientResponse as HttpClientResponse).cast>().pipe( + request.response, + ); }); - }); - // Special handling of Content-Length and Via. - clientRequest.contentLength = request.contentLength; - List? via = request.headers[HttpHeaders.viaHeader]; - String viaPrefix = via == null ? "" : "${via[0]}, "; - clientRequest.headers - .add(HttpHeaders.viaHeader, "${viaPrefix}1.1 localhost:$port"); - // Copy all content. - return request.cast>().pipe(clientRequest); - }).then((clientResponse) { - (clientResponse as HttpClientResponse) - .cast>() - .pipe(request.response); - }); } }); }); @@ -286,8 +308,9 @@ int testProxyIPV6DoneCount = 0; void testProxyIPV6() { setupProxyServer(ipV6: true).then((proxyServer) { setupServer(1, directRequestPaths: ["/4"]).then((server) { - setupServer(1, directRequestPaths: ["/4"], secure: true) - .then((secureServer) { + setupServer(1, directRequestPaths: ["/4"], secure: true).then(( + secureServer, + ) { HttpClient client = new HttpClient(context: clientContext); List proxy = ["PROXY [::1]:${proxyServer.port}"]; @@ -306,22 +329,26 @@ void testProxyIPV6() { client .postUrl(Uri.parse(url)) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - testProxyIPV6DoneCount++; - if (testProxyIPV6DoneCount == proxy.length * 2) { - Expect.equals(proxy.length, server.requestCount); - Expect.equals(proxy.length, secureServer.requestCount); - proxyServer.shutdown(); - server.shutdown(); - secureServer.shutdown(); - client.close(); - } - }); - }); + String content = "$i$i$i"; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + testProxyIPV6DoneCount++; + if (testProxyIPV6DoneCount == proxy.length * 2) { + Expect.equals(proxy.length, server.requestCount); + Expect.equals(proxy.length, secureServer.requestCount); + proxyServer.shutdown(); + server.shutdown(); + secureServer.shutdown(); + client.close(); + } + }, + ); + }); } test(false); @@ -340,10 +367,13 @@ void testProxyFromEnvironment() { HttpClient client = new HttpClient(context: clientContext); client.findProxy = (Uri uri) { - return HttpClient.findProxyFromEnvironment(uri, environment: { - "http_proxy": "localhost:${proxyServer.port}", - "https_proxy": "localhost:${proxyServer.port}" - }); + return HttpClient.findProxyFromEnvironment( + uri, + environment: { + "http_proxy": "localhost:${proxyServer.port}", + "https_proxy": "localhost:${proxyServer.port}", + }, + ); }; const int loopCount = 5; @@ -356,22 +386,26 @@ void testProxyFromEnvironment() { client .postUrl(Uri.parse(url)) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - testProxyFromEnvironmentDoneCount++; - if (testProxyFromEnvironmentDoneCount == loopCount * 2) { - Expect.equals(loopCount, server.requestCount); - Expect.equals(loopCount, secureServer.requestCount); - proxyServer.shutdown(); - server.shutdown(); - secureServer.shutdown(); - client.close(); - } - }); - }); + String content = "$i$i$i"; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + testProxyFromEnvironmentDoneCount++; + if (testProxyFromEnvironmentDoneCount == loopCount * 2) { + Expect.equals(loopCount, server.requestCount); + Expect.equals(loopCount, secureServer.requestCount); + proxyServer.shutdown(); + server.shutdown(); + secureServer.shutdown(); + client.close(); + } + }, + ); + }); } test(false); @@ -384,7 +418,10 @@ void testProxyFromEnvironment() { int testProxyAuthenticateCount = 0; Future testProxyAuthenticate( - bool useDigestAuthentication, String username, String password) { + bool useDigestAuthentication, + String username, + String password, +) { testProxyAuthenticateCount = 0; var completer = new Completer(); @@ -417,19 +454,21 @@ Future testProxyAuthenticate( client .postUrl(Uri.parse(url)) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - Expect.fail("No response expected"); - }).catchError((e) { - testProxyAuthenticateCount++; - if (testProxyAuthenticateCount == loopCount * 2) { - Expect.equals(0, server.requestCount); - Expect.equals(0, secureServer.requestCount); - step1.complete(null); - } - }); + String content = "$i$i$i"; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + Expect.fail("No response expected"); + }) + .catchError((e) { + testProxyAuthenticateCount++; + if (testProxyAuthenticateCount == loopCount * 2) { + Expect.equals(0, server.requestCount); + Expect.equals(0, secureServer.requestCount); + step1.complete(null); + } + }); } test(false); @@ -438,10 +477,14 @@ Future testProxyAuthenticate( step1.future.then((_) { testProxyAuthenticateCount = 0; if (useDigestAuthentication) { - client.findProxy = - (Uri uri) => "PROXY localhost:${proxyServer.port}"; - client.addProxyCredentials("localhost", proxyServer.port, "test", - new HttpClientDigestCredentials(username, password)); + client.findProxy = (Uri uri) => + "PROXY localhost:${proxyServer.port}"; + client.addProxyCredentials( + "localhost", + proxyServer.port, + "test", + new HttpClientDigestCredentials(username, password), + ); } else { client.findProxy = (Uri uri) { return "PROXY ${username}:${password}@localhost:${proxyServer.port}"; @@ -458,20 +501,24 @@ Future testProxyAuthenticate( client .postUrl(Uri.parse(url)) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - testProxyAuthenticateCount++; - Expect.equals(HttpStatus.ok, response.statusCode); - if (testProxyAuthenticateCount == loopCount * 2) { - Expect.equals(loopCount, server.requestCount); - Expect.equals(loopCount, secureServer.requestCount); - step2.complete(null); - } - }); - }); + String content = "$i$i$i"; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + testProxyAuthenticateCount++; + Expect.equals(HttpStatus.ok, response.statusCode); + if (testProxyAuthenticateCount == loopCount * 2) { + Expect.equals(loopCount, server.requestCount); + Expect.equals(loopCount, secureServer.requestCount); + step2.complete(null); + } + }, + ); + }); } test(false); @@ -486,8 +533,12 @@ Future testProxyAuthenticate( }; client.authenticateProxy = (host, port, scheme, realm) { - client.addProxyCredentials("localhost", proxyServer.port, "realm", - new HttpClientBasicCredentials(username, password)); + client.addProxyCredentials( + "localhost", + proxyServer.port, + "realm", + new HttpClientBasicCredentials(username, password), + ); return new Future.value(true); }; @@ -500,24 +551,31 @@ Future testProxyAuthenticate( client .postUrl(Uri.parse(url)) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - testProxyAuthenticateCount++; - Expect.equals(HttpStatus.ok, response.statusCode); - if (testProxyAuthenticateCount == loopCount * 2) { - Expect.equals(loopCount * 2, server.requestCount); - Expect.equals(loopCount * 2, secureServer.requestCount); - proxyServer.shutdown(); - server.shutdown(); - secureServer.shutdown(); - client.close(); - completer.complete(null); - } - }); - }); + String content = "$i$i$i"; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + testProxyAuthenticateCount++; + Expect.equals(HttpStatus.ok, response.statusCode); + if (testProxyAuthenticateCount == loopCount * 2) { + Expect.equals(loopCount * 2, server.requestCount); + Expect.equals( + loopCount * 2, + secureServer.requestCount, + ); + proxyServer.shutdown(); + server.shutdown(); + secureServer.shutdown(); + client.close(); + completer.complete(null); + } + }, + ); + }); } test(false); @@ -535,14 +593,18 @@ int testRealProxyDoneCount = 0; void testRealProxy() { setupServer(1).then((server) { HttpClient client = new HttpClient(context: clientContext); - client.addProxyCredentials("localhost", 8080, "test", - new HttpClientBasicCredentials("dart", "password")); + client.addProxyCredentials( + "localhost", + 8080, + "test", + new HttpClientBasicCredentials("dart", "password"), + ); List proxy = [ "PROXY localhost:8080", "PROXY localhost:8080; PROXY hede.hule.hest:8080", "PROXY hede.hule.hest:8080; PROXY localhost:8080", - "PROXY localhost:8080; DIRECT" + "PROXY localhost:8080; DIRECT", ]; client.findProxy = (Uri uri) { @@ -555,19 +617,23 @@ void testRealProxy() { client .getUrl(Uri.parse("http://localhost:${server.port}/$i")) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.contentLength = content.length; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - if (++testRealProxyDoneCount == proxy.length) { - Expect.equals(proxy.length, server.requestCount); - server.shutdown(); - client.close(); - } - }); - }); + String content = "$i$i$i"; + clientRequest.contentLength = content.length; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + if (++testRealProxyDoneCount == proxy.length) { + Expect.equals(proxy.length, server.requestCount); + server.shutdown(); + client.close(); + } + }, + ); + }); } }); } @@ -581,7 +647,7 @@ void testRealProxyAuth() { "PROXY dart:password@localhost:8080", "PROXY dart:password@localhost:8080; PROXY hede.hule.hest:8080", "PROXY hede.hule.hest:8080; PROXY dart:password@localhost:8080", - "PROXY dart:password@localhost:8080; DIRECT" + "PROXY dart:password@localhost:8080; DIRECT", ]; client.findProxy = (Uri uri) { @@ -594,19 +660,23 @@ void testRealProxyAuth() { client .getUrl(Uri.parse("http://localhost:${server.port}/$i")) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.contentLength = content.length; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - if (++testRealProxyAuthDoneCount == proxy.length) { - Expect.equals(proxy.length, server.requestCount); - server.shutdown(); - client.close(); - } - }); - }); + String content = "$i$i$i"; + clientRequest.contentLength = content.length; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + if (++testRealProxyAuthDoneCount == proxy.length) { + Expect.equals(proxy.length, server.requestCount); + server.shutdown(); + client.close(); + } + }, + ); + }); } }); } diff --git a/tests/standalone/io/http_proxy_configuration_test.dart b/tests/standalone/io/http_proxy_configuration_test.dart index c94826a1b8d..f8bd2c4a8ca 100644 --- a/tests/standalone/io/http_proxy_configuration_test.dart +++ b/tests/standalone/io/http_proxy_configuration_test.dart @@ -7,16 +7,22 @@ import "package:expect/expect.dart"; expect(expected, String uri, environment) { Expect.equals( - expected, - HttpClient.findProxyFromEnvironment(Uri.parse(uri), - environment: environment)); + expected, + HttpClient.findProxyFromEnvironment( + Uri.parse(uri), + environment: environment, + ), + ); } expectDirect(String uri, Map environment) { Expect.equals( - "DIRECT", - HttpClient.findProxyFromEnvironment(Uri.parse(uri), - environment: environment)); + "DIRECT", + HttpClient.findProxyFromEnvironment( + Uri.parse(uri), + environment: environment, + ), + ); } main() { @@ -24,111 +30,143 @@ main() { expectDirect("http://www.google.com", {"http_proxy": ""}); expectDirect("http://www.google.com", {"http_proxy": " "}); - expect("PROXY www.proxy.com:1080", "http://www.google.com", - {"http_proxy": "www.proxy.com"}); - expect("PROXY www.proxys.com:1080", "https://www.google.com", - {"https_proxy": "www.proxys.com"}); - expect("PROXY www.proxy.com:8080", "http://www.google.com", - {"http_proxy": "www.proxy.com:8080"}); - expect("PROXY www.proxys.com:8080", "https://www.google.com", - {"https_proxy": "www.proxys.com:8080"}); + expect("PROXY www.proxy.com:1080", "http://www.google.com", { + "http_proxy": "www.proxy.com", + }); + expect("PROXY www.proxys.com:1080", "https://www.google.com", { + "https_proxy": "www.proxys.com", + }); expect("PROXY www.proxy.com:8080", "http://www.google.com", { "http_proxy": "www.proxy.com:8080", - "https_proxy": "www.proxys.com:8080" + }); + expect("PROXY www.proxys.com:8080", "https://www.google.com", { + "https_proxy": "www.proxys.com:8080", + }); + expect("PROXY www.proxy.com:8080", "http://www.google.com", { + "http_proxy": "www.proxy.com:8080", + "https_proxy": "www.proxys.com:8080", }); expect("PROXY www.proxys.com:8080", "https://www.google.com", { "http_proxy": "www.proxy.com:8080", - "https_proxy": "www.proxys.com:8080" + "https_proxy": "www.proxys.com:8080", }); - expect("PROXY [::ffff:1]:1080", "http://www.google.com", - {"http_proxy": "[::ffff:1]"}); - expect("PROXY [::ffff:2]:1080", "https://www.google.com", - {"https_proxy": "[::ffff:2]"}); - expect("PROXY [::ffff:1]:8080", "http://www.google.com", - {"http_proxy": "[::ffff:1]:8080"}); - expect("PROXY [::ffff:2]:8080", "https://www.google.com", - {"https_proxy": "[::ffff:2]:8080"}); - expect("PROXY [::ffff:1]:8080", "http://www.google.com", - {"http_proxy": "[::ffff:1]:8080", "https_proxy": "[::ffff:2]:8080"}); - expect("PROXY [::ffff:2]:8080", "https://www.google.com", - {"http_proxy": "[::ffff:1]:8080", "https_proxy": "[::ffff:2]:8080"}); - - expect("PROXY www.proxy.com:1080", "http://www.google.com", - {"http_proxy": "http://www.proxy.com"}); - expect("PROXY www.proxy.com:1080", "http://www.google.com", - {"http_proxy": "http://www.proxy.com/"}); - expect("PROXY www.proxy.com:8080", "http://www.google.com", - {"http_proxy": "http://www.proxy.com:8080/"}); - expect("PROXY www.proxy.com:8080", "http://www.google.com", - {"http_proxy": "http://www.proxy.com:8080/index.html"}); - expect("PROXY www.proxy.com:8080", "http://www.google.com", { - "http_proxy": "http://www.proxy.com:8080/", - "https_proxy": "http://www.proxys.com:8080/" + expect("PROXY [::ffff:1]:1080", "http://www.google.com", { + "http_proxy": "[::ffff:1]", }); - expect("PROXY www.proxys.com:8080", "https://www.google.com", { - "http_proxy": "http://www.proxy.com:8080/", - "https_proxy": "http://www.proxys.com:8080/" + expect("PROXY [::ffff:2]:1080", "https://www.google.com", { + "https_proxy": "[::ffff:2]", + }); + expect("PROXY [::ffff:1]:8080", "http://www.google.com", { + "http_proxy": "[::ffff:1]:8080", + }); + expect("PROXY [::ffff:2]:8080", "https://www.google.com", { + "https_proxy": "[::ffff:2]:8080", + }); + expect("PROXY [::ffff:1]:8080", "http://www.google.com", { + "http_proxy": "[::ffff:1]:8080", + "https_proxy": "[::ffff:2]:8080", + }); + expect("PROXY [::ffff:2]:8080", "https://www.google.com", { + "http_proxy": "[::ffff:1]:8080", + "https_proxy": "[::ffff:2]:8080", + }); + + expect("PROXY www.proxy.com:1080", "http://www.google.com", { + "http_proxy": "http://www.proxy.com", + }); + expect("PROXY www.proxy.com:1080", "http://www.google.com", { + "http_proxy": "http://www.proxy.com/", }); expect("PROXY www.proxy.com:8080", "http://www.google.com", { "http_proxy": "http://www.proxy.com:8080/", - "https_proxy": "http://www.proxys.com:8080/index.html" + }); + expect("PROXY www.proxy.com:8080", "http://www.google.com", { + "http_proxy": "http://www.proxy.com:8080/index.html", + }); + expect("PROXY www.proxy.com:8080", "http://www.google.com", { + "http_proxy": "http://www.proxy.com:8080/", + "https_proxy": "http://www.proxys.com:8080/", }); expect("PROXY www.proxys.com:8080", "https://www.google.com", { "http_proxy": "http://www.proxy.com:8080/", - "https_proxy": "http://www.proxys.com:8080/index.html" + "https_proxy": "http://www.proxys.com:8080/", + }); + expect("PROXY www.proxy.com:8080", "http://www.google.com", { + "http_proxy": "http://www.proxy.com:8080/", + "https_proxy": "http://www.proxys.com:8080/index.html", + }); + expect("PROXY www.proxys.com:8080", "https://www.google.com", { + "http_proxy": "http://www.proxy.com:8080/", + "https_proxy": "http://www.proxys.com:8080/index.html", }); - expect("PROXY [::ffff:1]:1080", "http://www.google.com", - {"http_proxy": "http://[::ffff:1]"}); - expect("PROXY [::ffff:1]:1080", "http://www.google.com", - {"http_proxy": "http://[::ffff:1]/"}); - expect("PROXY [::ffff:1]:8080", "http://www.google.com", - {"http_proxy": "http://[::ffff:1]:8080/"}); - expect("PROXY [::ffff:1]:8080", "http://www.google.com", - {"http_proxy": "http://[::ffff:1]:8080/index.html"}); - expect("PROXY [::ffff:1]:8080", "http://www.google.com", { - "http_proxy": "http://[::ffff:1]:8080/", - "https_proxy": "http://[::ffff:1]:8080/" + expect("PROXY [::ffff:1]:1080", "http://www.google.com", { + "http_proxy": "http://[::ffff:1]", }); - expect("PROXY [::ffff:2]:8080", "https://www.google.com", { - "http_proxy": "http://[::ffff:1]:8080/", - "https_proxy": "http://[::ffff:2]:8080/" + expect("PROXY [::ffff:1]:1080", "http://www.google.com", { + "http_proxy": "http://[::ffff:1]/", }); expect("PROXY [::ffff:1]:8080", "http://www.google.com", { "http_proxy": "http://[::ffff:1]:8080/", - "https_proxy": "http://[::ffff:1]:8080/index.html" + }); + expect("PROXY [::ffff:1]:8080", "http://www.google.com", { + "http_proxy": "http://[::ffff:1]:8080/index.html", + }); + expect("PROXY [::ffff:1]:8080", "http://www.google.com", { + "http_proxy": "http://[::ffff:1]:8080/", + "https_proxy": "http://[::ffff:1]:8080/", }); expect("PROXY [::ffff:2]:8080", "https://www.google.com", { "http_proxy": "http://[::ffff:1]:8080/", - "https_proxy": "http://[::ffff:2]:8080/index.html" + "https_proxy": "http://[::ffff:2]:8080/", + }); + expect("PROXY [::ffff:1]:8080", "http://www.google.com", { + "http_proxy": "http://[::ffff:1]:8080/", + "https_proxy": "http://[::ffff:1]:8080/index.html", + }); + expect("PROXY [::ffff:2]:8080", "https://www.google.com", { + "http_proxy": "http://[::ffff:1]:8080/", + "https_proxy": "http://[::ffff:2]:8080/index.html", }); - expectDirect("http://www.google.com", - {"http_proxy": "www.proxy.com:8080", "no_proxy": "www.google.com"}); - expectDirect("http://www.google.com", - {"http_proxy": "www.proxy.com:8080", "no_proxy": "google.com"}); - expectDirect("http://www.google.com", - {"http_proxy": "www.proxy.com:8080", "no_proxy": ".com"}); expectDirect("http://www.google.com", { "http_proxy": "www.proxy.com:8080", - "no_proxy": ",, , www.google.edu,,.com " + "no_proxy": "www.google.com", + }); + expectDirect("http://www.google.com", { + "http_proxy": "www.proxy.com:8080", + "no_proxy": "google.com", + }); + expectDirect("http://www.google.com", { + "http_proxy": "www.proxy.com:8080", + "no_proxy": ".com", + }); + expectDirect("http://www.google.com", { + "http_proxy": "www.proxy.com:8080", + "no_proxy": ",, , www.google.edu,,.com ", }); expectDirect("http://www.google.edu", { "http_proxy": "www.proxy.com:8080", - "no_proxy": ",, , www.google.edu,,.com " + "no_proxy": ",, , www.google.edu,,.com ", }); expectDirect("http://www.google.com", {"https_proxy": "www.proxy.com:8080"}); - expect("PROXY www.proxy.com:8080", "http://[::ffff:1]", - {"http_proxy": "www.proxy.com:8080", "no_proxy": "["}); - expect("PROXY www.proxy.com:8080", "http://[::ffff:1]", - {"http_proxy": "www.proxy.com:8080", "no_proxy": "[]"}); + expect("PROXY www.proxy.com:8080", "http://[::ffff:1]", { + "http_proxy": "www.proxy.com:8080", + "no_proxy": "[", + }); + expect("PROXY www.proxy.com:8080", "http://[::ffff:1]", { + "http_proxy": "www.proxy.com:8080", + "no_proxy": "[]", + }); - expectDirect("http://[::ffff:1]", - {"http_proxy": "www.proxy.com:8080", "no_proxy": "[::ffff:1]"}); expectDirect("http://[::ffff:1]", { "http_proxy": "www.proxy.com:8080", - "no_proxy": ",, , www.google.edu,,[::ffff:1] " + "no_proxy": "[::ffff:1]", + }); + expectDirect("http://[::ffff:1]", { + "http_proxy": "www.proxy.com:8080", + "no_proxy": ",, , www.google.edu,,[::ffff:1] ", }); } diff --git a/tests/standalone/io/http_proxy_test.dart b/tests/standalone/io/http_proxy_test.dart index 93d07b4a25a..3287a7012a4 100644 --- a/tests/standalone/io/http_proxy_test.dart +++ b/tests/standalone/io/http_proxy_test.dart @@ -18,8 +18,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); final SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); final SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -38,10 +40,10 @@ class Server { ? HttpServer.bindSecure("localhost", 0, serverContext) : HttpServer.bind("localhost", 0)) .then((s) { - server = s; - server.listen(requestHandler); - return this; - }); + server = s; + server.listen(requestHandler); + return this; + }); } void requestHandler(HttpRequest request) { @@ -49,12 +51,16 @@ class Server { requestCount++; // Check whether a proxy or direct connection is expected. bool direct = directRequestPaths.fold( - false, (prev, path) => prev ? prev : path == request.uri.path); + false, + (prev, path) => prev ? prev : path == request.uri.path, + ); if (!secure && !direct && proxyHops > 0) { Expect.isNotNull(request.headers[HttpHeaders.viaHeader]); Expect.equals(1, request.headers[HttpHeaders.viaHeader]!.length); - Expect.equals(proxyHops, - request.headers[HttpHeaders.viaHeader]![0].split(",").length); + Expect.equals( + proxyHops, + request.headers[HttpHeaders.viaHeader]![0].split(",").length, + ); } else { Expect.isNull(request.headers[HttpHeaders.viaHeader]); } @@ -81,8 +87,11 @@ class Server { int get port => server.port; } -Future setupServer(int proxyHops, - {List directRequestPaths = const [], secure = false}) { +Future setupServer( + int proxyHops, { + List directRequestPaths = const [], + secure = false, +}) { Server server = new Server(proxyHops, directRequestPaths, secure); return server.start(); } @@ -115,8 +124,10 @@ class ProxyServer { basicAuthenticationRequired(request) { request.fold(null, (x, y) {}).then((_) { var response = request.response; - response.headers - .set(HttpHeaders.proxyAuthenticateHeader, "Basic, realm=$realm"); + response.headers.set( + HttpHeaders.proxyAuthenticateHeader, + "Basic, realm=$realm", + ); response.statusCode = HttpStatus.proxyAuthenticationRequired; response.close(); }); @@ -157,8 +168,10 @@ class ProxyServer { } return; } else { - Expect.equals(1, - request.headers[HttpHeaders.proxyAuthorizationHeader]!.length); + Expect.equals( + 1, + request.headers[HttpHeaders.proxyAuthorizationHeader]!.length, + ); String authorization = request.headers[HttpHeaders.proxyAuthorizationHeader]![0]; if (authScheme == "Basic") { @@ -170,8 +183,10 @@ class ProxyServer { return; } } else { - HeaderValue header = - HeaderValue.parse(authorization, parameterSeparator: ","); + HeaderValue header = HeaderValue.parse( + authorization, + parameterSeparator: ",", + ); Expect.equals("Digest", header.value); var uri = header.parameters["uri"]; var qop = header.parameters["qop"]; @@ -203,13 +218,17 @@ class ProxyServer { digest = md5.convert("$ha1:${nonce}:$ha2".codeUnits); } else { digest = md5.convert( - "$ha1:${nonce}:${nc}:${cnonce}:${qop}:$ha2".codeUnits); + "$ha1:${nonce}:${nc}:${cnonce}:${qop}:$ha2".codeUnits, + ); } Expect.equals( - hex.encode(digest.bytes), header.parameters["response"]); + hex.encode(digest.bytes), + header.parameters["response"], + ); // Add a bogus Proxy-Authentication-Info for testing. - var info = 'rspauth="77180d1ab3d6c9de084766977790f482", ' + var info = + 'rspauth="77180d1ab3d6c9de084766977790f482", ' 'cnonce="8f971178", ' 'nc=000002c74, ' 'qop=auth'; @@ -231,27 +250,30 @@ class ProxyServer { client .openUrl(request.method, request.uri) .then((HttpClientRequest clientRequest) { - // Forward all headers. - request.headers.forEach((String name, List values) { - values.forEach((String value) { - if (name != "content-length" && name != "via") { - clientRequest.headers.add(name, value); - } + // Forward all headers. + request.headers.forEach((String name, List values) { + values.forEach((String value) { + if (name != "content-length" && name != "via") { + clientRequest.headers.add(name, value); + } + }); + }); + // Special handling of Content-Length and Via. + clientRequest.contentLength = request.contentLength; + List? via = request.headers[HttpHeaders.viaHeader]; + String viaPrefix = via == null ? "" : "${via[0]}, "; + clientRequest.headers.add( + HttpHeaders.viaHeader, + "${viaPrefix}1.1 localhost:$port", + ); + // Copy all content. + return request.cast>().pipe(clientRequest); + }) + .then((clientResponse) { + (clientResponse as HttpClientResponse).cast>().pipe( + request.response, + ); }); - }); - // Special handling of Content-Length and Via. - clientRequest.contentLength = request.contentLength; - List? via = request.headers[HttpHeaders.viaHeader]; - String viaPrefix = via == null ? "" : "${via[0]}, "; - clientRequest.headers - .add(HttpHeaders.viaHeader, "${viaPrefix}1.1 localhost:$port"); - // Copy all content. - return request.cast>().pipe(clientRequest); - }).then((clientResponse) { - (clientResponse as HttpClientResponse) - .cast>() - .pipe(request.response); - }); } }); }); @@ -276,23 +298,23 @@ testInvalidProxy() { client.findProxy = (Uri uri) => ""; Future.value( - client.getUrl(Uri.parse("http://www.google.com/test"))) - .catchError((error) {}, test: (e) => e is HttpException); + client.getUrl(Uri.parse("http://www.google.com/test")), + ).catchError((error) {}, test: (e) => e is HttpException); client.findProxy = (Uri uri) => "XXX"; Future.value( - client.getUrl(Uri.parse("http://www.google.com/test"))) - .catchError((error) {}, test: (e) => e is HttpException); + client.getUrl(Uri.parse("http://www.google.com/test")), + ).catchError((error) {}, test: (e) => e is HttpException); client.findProxy = (Uri uri) => "PROXY www.google.com"; Future.value( - client.getUrl(Uri.parse("http://www.google.com/test"))) - .catchError((error) {}, test: (e) => e is HttpException); + client.getUrl(Uri.parse("http://www.google.com/test")), + ).catchError((error) {}, test: (e) => e is HttpException); client.findProxy = (Uri uri) => "PROXY www.google.com:http"; Future.value( - client.getUrl(Uri.parse("http://www.google.com/test"))) - .catchError((error) {}, test: (e) => e is HttpException); + client.getUrl(Uri.parse("http://www.google.com/test")), + ).catchError((error) {}, test: (e) => e is HttpException); } int testDirectDoneCount = 0; @@ -306,7 +328,7 @@ void testDirectProxy() { " DIRECT ; ", ";DIRECT", " ; DIRECT ", - ";;DIRECT;;" + ";;DIRECT;;", ]; client.findProxy = (Uri uri) { @@ -318,20 +340,24 @@ void testDirectProxy() { client .getUrl(Uri.parse("http://localhost:${server.port}/$i")) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.contentLength = content.length; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - testDirectDoneCount++; - if (testDirectDoneCount == proxy.length) { - Expect.equals(proxy.length, server.requestCount); - server.shutdown(); - client.close(); - } - }); - }); + String content = "$i$i$i"; + clientRequest.contentLength = content.length; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + testDirectDoneCount++; + if (testDirectDoneCount == proxy.length) { + Expect.equals(proxy.length, server.requestCount); + server.shutdown(); + client.close(); + } + }, + ); + }); } }); } @@ -340,8 +366,9 @@ int testProxyDoneCount = 0; void testProxy() { setupProxyServer().then((proxyServer) { setupServer(1, directRequestPaths: ["/4"]).then((server) { - setupServer(1, directRequestPaths: ["/4"], secure: true) - .then((secureServer) { + setupServer(1, directRequestPaths: ["/4"], secure: true).then(( + secureServer, + ) { HttpClient client = new HttpClient(context: clientContext); List proxy; @@ -353,7 +380,7 @@ void testProxy() { "" " PROXY localhost:${proxyServer.port}", "DIRECT", - "PROXY localhost:${proxyServer.port}; DIRECT" + "PROXY localhost:${proxyServer.port}; DIRECT", ]; } else { proxy = [ @@ -363,7 +390,7 @@ void testProxy() { "PROXY hede.hule.hest:8080; PROXY hede.hule.hest:8181;" " PROXY localhost:${proxyServer.port}", "PROXY hede.hule.hest:8080; PROXY hede.hule.hest:8181; DIRECT", - "PROXY localhost:${proxyServer.port}; DIRECT" + "PROXY localhost:${proxyServer.port}; DIRECT", ]; } client.findProxy = (Uri uri) { @@ -381,22 +408,26 @@ void testProxy() { client .postUrl(Uri.parse(url)) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - testProxyDoneCount++; - if (testProxyDoneCount == proxy.length * 2) { - Expect.equals(proxy.length, server.requestCount); - Expect.equals(proxy.length, secureServer.requestCount); - proxyServer.shutdown(); - server.shutdown(); - secureServer.shutdown(); - client.close(); - } - }); - }); + String content = "$i$i$i"; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + testProxyDoneCount++; + if (testProxyDoneCount == proxy.length * 2) { + Expect.equals(proxy.length, server.requestCount); + Expect.equals(proxy.length, secureServer.requestCount); + proxyServer.shutdown(); + server.shutdown(); + secureServer.shutdown(); + client.close(); + } + }, + ); + }); } test(false); @@ -412,8 +443,8 @@ void testProxyChain() { // Setup two proxy servers having the first using the second as its proxy. setupProxyServer().then((proxyServer1) { setupProxyServer().then((proxyServer2) { - proxyServer1.client.findProxy = - (_) => "PROXY localhost:${proxyServer2.port}"; + proxyServer1.client.findProxy = (_) => + "PROXY localhost:${proxyServer2.port}"; setupServer(2, directRequestPaths: ["/4"]).then((server) { HttpClient client = new HttpClient(context: clientContext); @@ -426,7 +457,7 @@ void testProxyChain() { "PROXY localhost:${proxyServer1.port}", "PROXY localhost:${proxyServer1.port}", "DIRECT", - "PROXY localhost:${proxyServer1.port}; DIRECT" + "PROXY localhost:${proxyServer1.port}; DIRECT", ]; } else { proxy = [ @@ -436,7 +467,7 @@ void testProxyChain() { "PROXY hede.hule.hest:8080; PROXY hede.hule.hest:8181;" " PROXY localhost:${proxyServer1.port}", "PROXY hede.hule.hest:8080; PROXY hede.hule.hest:8181; DIRECT", - "PROXY localhost:${proxyServer1.port}; DIRECT" + "PROXY localhost:${proxyServer1.port}; DIRECT", ]; } @@ -450,22 +481,26 @@ void testProxyChain() { client .getUrl(Uri.parse("http://localhost:${server.port}/$i")) .then((HttpClientRequest clientRequest) { - String content = "$i$i$i"; - clientRequest.contentLength = content.length; - clientRequest.write(content); - return clientRequest.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - testProxyChainDoneCount++; - if (testProxyChainDoneCount == proxy.length) { - Expect.equals(proxy.length, server.requestCount); - proxyServer1.shutdown(); - proxyServer2.shutdown(); - server.shutdown(); - client.close(); - } - }); - }); + String content = "$i$i$i"; + clientRequest.contentLength = content.length; + clientRequest.write(content); + return clientRequest.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + testProxyChainDoneCount++; + if (testProxyChainDoneCount == proxy.length) { + Expect.equals(proxy.length, server.requestCount); + proxyServer1.shutdown(); + proxyServer2.shutdown(); + server.shutdown(); + client.close(); + } + }, + ); + }); } }); }); diff --git a/tests/standalone/io/http_read_test.dart b/tests/standalone/io/http_read_test.dart index 584a7e1aab9..8bed87d6795 100644 --- a/tests/standalone/io/http_read_test.dart +++ b/tests/standalone/io/http_read_test.dart @@ -28,7 +28,7 @@ class IsolatedHttpServer { // Send chunked encoding message to the server. port.send([ new IsolatedHttpServerCommand.chunkedEncoding(), - _statusPort.sendPort + _statusPort.sendPort, ]); } @@ -47,8 +47,10 @@ class IsolatedHttpServer { void shutdown() { // Send server stop message to the server. - _serverPort - .send([new IsolatedHttpServerCommand.stop(), _statusPort.sendPort]); + _serverPort.send([ + new IsolatedHttpServerCommand.stop(), + _statusPort.sendPort, + ]); _statusPort.close(); } @@ -173,29 +175,35 @@ void testRead(bool chunkedEncoding) { int count = 0; HttpClient httpClient = new HttpClient(); void sendRequest() { - httpClient.post("127.0.0.1", port, "/echo").then((request) { - if (chunkedEncoding) { - request.write(data.substring(0, 10)); - request.write(data.substring(10, data.length)); - } else { - request.contentLength = data.length; - request.add(data.codeUnits); - } - return request.close(); - }).then((response) { - Expect.equals(HttpStatus.ok, response.statusCode); - List body = []; - response.listen(body.addAll, onDone: () { - Expect.equals(data, new String.fromCharCodes(body)); - count++; - if (count < kMessageCount) { - sendRequest(); - } else { - httpClient.close(); - server.shutdown(); - } - }); - }); + httpClient + .post("127.0.0.1", port, "/echo") + .then((request) { + if (chunkedEncoding) { + request.write(data.substring(0, 10)); + request.write(data.substring(10, data.length)); + } else { + request.contentLength = data.length; + request.add(data.codeUnits); + } + return request.close(); + }) + .then((response) { + Expect.equals(HttpStatus.ok, response.statusCode); + List body = []; + response.listen( + body.addAll, + onDone: () { + Expect.equals(data, new String.fromCharCodes(body)); + count++; + if (count < kMessageCount) { + sendRequest(); + } else { + httpClient.close(); + server.shutdown(); + } + }, + ); + }); } sendRequest(); diff --git a/tests/standalone/io/http_redirect_test.dart b/tests/standalone/io/http_redirect_test.dart index 3df5e072793..c223c06ff1d 100644 --- a/tests/standalone/io/http_redirect_test.dart +++ b/tests/standalone/io/http_redirect_test.dart @@ -13,7 +13,9 @@ Future setupServer({Uri? targetServer}) { HttpServer.bind("127.0.0.1", 0).then((server) { var handlers = new Map(); addRequestHandler( - String path, void handler(HttpRequest request, HttpResponse response)) { + String path, + void handler(HttpRequest request, HttpResponse response), + ) { handlers[path] = handler; } @@ -21,34 +23,48 @@ Future setupServer({Uri? targetServer}) { if (handlers.containsKey(request.uri.path)) { handlers[request.uri.path]!(request, request.response); } else { - request.listen((_) {}, onDone: () { - request.response.statusCode = 404; - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.statusCode = 404; + request.response.close(); + }, + ); } }); void addRedirectHandler(int number, int statusCode) { - addRequestHandler("/$number", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/$number", ( + HttpRequest request, + HttpResponse response, + ) { response.redirect( - Uri.parse("http://127.0.0.1:${server.port}/${number + 1}")); + Uri.parse("http://127.0.0.1:${server.port}/${number + 1}"), + ); }); } // Setup simple redirect. - addRequestHandler("/redirect", - (HttpRequest request, HttpResponse response) { - response.redirect(Uri.parse("http://127.0.0.1:${server.port}/location"), - status: HttpStatus.movedPermanently); + addRequestHandler("/redirect", ( + HttpRequest request, + HttpResponse response, + ) { + response.redirect( + Uri.parse("http://127.0.0.1:${server.port}/location"), + status: HttpStatus.movedPermanently, + ); }); - addRequestHandler("/location", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/location", ( + HttpRequest request, + HttpResponse response, + ) { response.close(); }); - addRequestHandler("/redirect-no-location", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/redirect-no-location", ( + HttpRequest request, + HttpResponse response, + ) { response ..statusCode = HttpStatus.movedPermanently ..reasonPhrase = "Moved Permanently" @@ -56,55 +72,73 @@ Future setupServer({Uri? targetServer}) { }); // Setup redirects with relative url. - addRequestHandler("/redirectUrl", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/redirectUrl", ( + HttpRequest request, + HttpResponse response, + ) { response.headers.set(HttpHeaders.locationHeader, "/some/relativeUrl"); response.statusCode = HttpStatus.movedPermanently; response.close(); }); - addRequestHandler("/some/redirectUrl", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/some/redirectUrl", ( + HttpRequest request, + HttpResponse response, + ) { response.headers.set(HttpHeaders.locationHeader, "relativeUrl"); response.statusCode = HttpStatus.movedPermanently; response.close(); }); - addRequestHandler("/some/relativeUrl", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/some/relativeUrl", ( + HttpRequest request, + HttpResponse response, + ) { response.close(); }); - addRequestHandler("/some/relativeToAbsolute", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/some/relativeToAbsolute", ( + HttpRequest request, + HttpResponse response, + ) { response.redirect(Uri.parse("xxx"), status: HttpStatus.seeOther); }); - addRequestHandler("/redirectUrl2", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/redirectUrl2", ( + HttpRequest request, + HttpResponse response, + ) { response.headers.set(HttpHeaders.locationHeader, "location"); response.statusCode = HttpStatus.movedPermanently; response.close(); }); - addRequestHandler("/redirectUrl3", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/redirectUrl3", ( + HttpRequest request, + HttpResponse response, + ) { response.headers.set(HttpHeaders.locationHeader, "./location"); response.statusCode = HttpStatus.movedPermanently; response.close(); }); - addRequestHandler("/redirectUrl4", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/redirectUrl4", ( + HttpRequest request, + HttpResponse response, + ) { response.headers.set(HttpHeaders.locationHeader, "./a/b/../../location"); response.statusCode = HttpStatus.movedPermanently; response.close(); }); - addRequestHandler("/redirectUrl5", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/redirectUrl5", ( + HttpRequest request, + HttpResponse response, + ) { response.headers.set( - HttpHeaders.locationHeader, "//127.0.0.1:${server.port}/location"); + HttpHeaders.locationHeader, + "//127.0.0.1:${server.port}/location", + ); response.statusCode = HttpStatus.movedPermanently; response.close(); }); @@ -122,14 +156,18 @@ Future setupServer({Uri? targetServer}) { // Setup redirect loop. addRequestHandler("/A", (HttpRequest request, HttpResponse response) { - response.headers - .set(HttpHeaders.locationHeader, "http://127.0.0.1:${server.port}/B"); + response.headers.set( + HttpHeaders.locationHeader, + "http://127.0.0.1:${server.port}/B", + ); response.statusCode = HttpStatus.movedPermanently; response.close(); }); addRequestHandler("/B", (HttpRequest request, HttpResponse response) { - response.headers - .set(HttpHeaders.locationHeader, "http://127.0.0.1:${server.port}/A"); + response.headers.set( + HttpHeaders.locationHeader, + "http://127.0.0.1:${server.port}/A", + ); response.statusCode = HttpStatus.movedTemporarily; response.close(); }); @@ -137,28 +175,40 @@ Future setupServer({Uri? targetServer}) { // Setup redirect checking headers. addRequestHandler("/src", (HttpRequest request, HttpResponse response) { Expect.equals("value", request.headers.value("X-Request-Header")); - Expect.isNotNull(request.headers.value("Authorization"), - "expected 'Authorization' header to be set"); + Expect.isNotNull( + request.headers.value("Authorization"), + "expected 'Authorization' header to be set", + ); response.headers.set( - HttpHeaders.locationHeader, "http://127.0.0.1:${server.port}/target"); + HttpHeaders.locationHeader, + "http://127.0.0.1:${server.port}/target", + ); response.statusCode = HttpStatus.movedPermanently; response.close(); }); addRequestHandler("/target", (HttpRequest request, HttpResponse response) { Expect.equals("value", request.headers.value("X-Request-Header")); - Expect.isNotNull(request.headers.value("Authorization"), - "expected 'Authorization' header to be set"); + Expect.isNotNull( + request.headers.value("Authorization"), + "expected 'Authorization' header to be set", + ); response.close(); }); if (targetServer != null) { - addRequestHandler("/src-crossdomain", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/src-crossdomain", ( + HttpRequest request, + HttpResponse response, + ) { Expect.equals("value", request.headers.value("X-Request-Header")); - Expect.isNotNull(request.headers.value("Authorization"), - "expected 'Authorization' header to be set"); - response.headers - .set(HttpHeaders.locationHeader, targetServer.toString()); + Expect.isNotNull( + request.headers.value("Authorization"), + "expected 'Authorization' header to be set", + ); + response.headers.set( + HttpHeaders.locationHeader, + targetServer.toString(), + ); response.statusCode = HttpStatus.movedPermanently; response.close(); }); @@ -167,38 +217,54 @@ Future setupServer({Uri? targetServer}) { // Setup redirect for 301 where POST should not redirect. addRequestHandler("/301src", (HttpRequest request, HttpResponse response) { Expect.equals("POST", request.method); - request.listen((_) {}, onDone: () { - response.headers.set(HttpHeaders.locationHeader, - "http://127.0.0.1:${server.port}/301target"); - response.statusCode = HttpStatus.movedPermanently; - response.close(); - }); + request.listen( + (_) {}, + onDone: () { + response.headers.set( + HttpHeaders.locationHeader, + "http://127.0.0.1:${server.port}/301target", + ); + response.statusCode = HttpStatus.movedPermanently; + response.close(); + }, + ); }); - addRequestHandler("/301target", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/301target", ( + HttpRequest request, + HttpResponse response, + ) { Expect.fail("Redirect of POST should not happen"); }); // Setup redirect for 303 where POST should turn into GET. addRequestHandler("/303src", (HttpRequest request, HttpResponse response) { - request.listen((_) {}, onDone: () { - Expect.equals("POST", request.method); - response.headers.set(HttpHeaders.locationHeader, - "http://127.0.0.1:${server.port}/303target"); - response.statusCode = HttpStatus.seeOther; - response.close(); - }); + request.listen( + (_) {}, + onDone: () { + Expect.equals("POST", request.method); + response.headers.set( + HttpHeaders.locationHeader, + "http://127.0.0.1:${server.port}/303target", + ); + response.statusCode = HttpStatus.seeOther; + response.close(); + }, + ); }); - addRequestHandler("/303target", - (HttpRequest request, HttpResponse response) { + addRequestHandler("/303target", ( + HttpRequest request, + HttpResponse response, + ) { Expect.equals("GET", request.method); response.close(); }); // Setup redirect where we close the connection. addRequestHandler("/closing", (HttpRequest request, HttpResponse response) { - response.headers - .set(HttpHeaders.locationHeader, "http://127.0.0.1:${server.port}/"); + response.headers.set( + HttpHeaders.locationHeader, + "http://127.0.0.1:${server.port}/", + ); response.statusCode = HttpStatus.found; response.persistentConnection = false; response.close(); @@ -216,21 +282,28 @@ Future setupTargetServer() { HttpServer.bind("127.0.0.1", 0).then((server) { var handlers = new Map(); addRequestHandler( - String path, void handler(HttpRequest request, HttpResponse response)) { + String path, + void handler(HttpRequest request, HttpResponse response), + ) { handlers[path] = handler; } server.listen((HttpRequest request) { if (request.uri.path == "/target") { Expect.equals("value", request.headers.value("X-Request-Header")); - Expect.isNull(request.headers.value("Authorization"), - "expected 'Authorization' header to be removed on redirect"); + Expect.isNull( + request.headers.value("Authorization"), + "expected 'Authorization' header to be removed on redirect", + ); request.response.close(); } else { - request.listen((_) {}, onDone: () { - request.response.statusCode = 404; - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.statusCode = 404; + request.response.close(); + }, + ); } }); @@ -256,27 +329,30 @@ void testManualRedirect() { int redirectCount = 0; handleResponse(HttpClientResponse response) { - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - redirectCount++; - if (redirectCount < 10) { - Expect.isTrue(response.isRedirect); - checkRedirects(redirectCount, response); - response.redirect().then(handleResponse); - } else { - Expect.equals(HttpStatus.notFound, response.statusCode); - server.close(); - client.close(); - } - }); + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + redirectCount++; + if (redirectCount < 10) { + Expect.isTrue(response.isRedirect); + checkRedirects(redirectCount, response); + response.redirect().then(handleResponse); + } else { + Expect.equals(HttpStatus.notFound, response.statusCode); + server.close(); + client.close(); + } + }, + ); } client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/1")) .then((HttpClientRequest request) { - request.followRedirects = false; - return request.close(); - }).then(handleResponse); + request.followRedirects = false; + return request.close(); + }) + .then(handleResponse); }); } @@ -287,28 +363,31 @@ void testManualRedirectWithHeaders() { int redirectCount = 0; handleResponse(HttpClientResponse response) { - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - redirectCount++; - if (redirectCount < 2) { - Expect.isTrue(response.isRedirect); - response.redirect().then(handleResponse); - } else { - Expect.equals(HttpStatus.ok, response.statusCode); - server.close(); - client.close(); - } - }); + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + redirectCount++; + if (redirectCount < 2) { + Expect.isTrue(response.isRedirect); + response.redirect().then(handleResponse); + } else { + Expect.equals(HttpStatus.ok, response.statusCode); + server.close(); + client.close(); + } + }, + ); } client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/src")) .then((HttpClientRequest request) { - request.followRedirects = false; - request.headers.add("X-Request-Header", "value"); - request.headers.add("Authorization", "Basic ..."); - return request.close(); - }).then(handleResponse); + request.followRedirects = false; + request.headers.add("X-Request-Header", "value"); + request.headers.add("Authorization", "Basic ..."); + return request.close(); + }) + .then(handleResponse); }); } @@ -319,15 +398,18 @@ void testAutoRedirect() { client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/redirect")) .then((HttpClientRequest request) { - return request.close(); - }).then((HttpClientResponse response) { - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - Expect.equals(1, response.redirects.length); - server.close(); - client.close(); - }); - }); + return request.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + Expect.equals(1, response.redirects.length); + server.close(); + client.close(); + }, + ); + }); }); } @@ -336,7 +418,8 @@ Future testAutoRedirectNoLocationHeader() async { HttpClient client = new HttpClient(); final request = await client.getUrl( - Uri.parse("http://127.0.0.1:${server.port}/redirect-no-location")); + Uri.parse("http://127.0.0.1:${server.port}/redirect-no-location"), + ); try { final response = await request.close(); @@ -354,21 +437,25 @@ void testAutoRedirectZeroMaxRedirects() { client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/redirect")) .then((HttpClientRequest request) { - request - ..followRedirects = true - ..maxRedirects = 0; + request + ..followRedirects = true + ..maxRedirects = 0; - return request.close(); - }).then((HttpClientResponse response) { - response.drain(); - Expect.fail("Response data not expected"); - }, onError: (error) { - final httpException = error as HttpException; - Expect.equals(httpException.message, "Redirect limit exceeded"); - Expect.equals(httpException.uri, null); - server.close(); - client.close(); - }); + return request.close(); + }) + .then( + (HttpClientResponse response) { + response.drain(); + Expect.fail("Response data not expected"); + }, + onError: (error) { + final httpException = error as HttpException; + Expect.equals(httpException.message, "Redirect limit exceeded"); + Expect.equals(httpException.uri, null); + server.close(); + client.close(); + }, + ); }); } @@ -379,17 +466,20 @@ void testAutoRedirectWithHeaders() { client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/src")) .then((HttpClientRequest request) { - request.headers.add("X-Request-Header", "value"); - request.headers.add("Authorization", "Basic ..."); - return request.close(); - }).then((HttpClientResponse response) { - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - Expect.equals(1, response.redirects.length); - server.close(); - client.close(); - }); - }); + request.headers.add("X-Request-Header", "value"); + request.headers.add("Authorization", "Basic ..."); + return request.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + Expect.equals(1, response.redirects.length); + server.close(); + client.close(); + }, + ); + }); }); } @@ -398,113 +488,202 @@ void testShouldCopyHeadersOnRedirect() { final fnName = Symbol("shouldCopyHeaderOnRedirect"); shouldCopyHeaderOnRedirect( - String headerKey, Uri originalUrl, Uri redirectUri) => - clientClass.invoke( - fnName, [headerKey, originalUrl, redirectUri]).reflectee as bool; + String headerKey, + Uri originalUrl, + Uri redirectUri, + ) => + clientClass.invoke(fnName, [ + headerKey, + originalUrl, + redirectUri, + ]).reflectee + as bool; checkShouldCopyHeader( - String headerKey, String originalUrl, String redirectUri, bool expected) { + String headerKey, + String originalUrl, + String redirectUri, + bool expected, + ) { if (shouldCopyHeaderOnRedirect( - headerKey, Uri.parse(originalUrl), Uri.parse(redirectUri)) != + headerKey, + Uri.parse(originalUrl), + Uri.parse(redirectUri), + ) != expected) { Expect.fail( - "shouldCopyHeaderOnRedirect($headerKey, $originalUrl, $redirectUri) => ${!expected}"); + "shouldCopyHeaderOnRedirect($headerKey, $originalUrl, $redirectUri) => ${!expected}", + ); } } // Redirect on localhost. checkShouldCopyHeader( - "authorization", "http://localhost", "http://localhost/foo", true); + "authorization", + "http://localhost", + "http://localhost/foo", + true, + ); checkShouldCopyHeader( - "cat", "http://localhost", "http://localhost/foo", true); + "cat", + "http://localhost", + "http://localhost/foo", + true, + ); // Redirect to same IP address. - checkShouldCopyHeader("authorization", "http://192.168.20.20", - "http://192.168.20.20/foo", true); checkShouldCopyHeader( - "cat", "http://192.168.20.20", "http://192.168.20.20/foo", true); + "authorization", + "http://192.168.20.20", + "http://192.168.20.20/foo", + true, + ); + checkShouldCopyHeader( + "cat", + "http://192.168.20.20", + "http://192.168.20.20/foo", + true, + ); // Redirect to different IP address. checkShouldCopyHeader( - "authorization", "http://192.168.20.20", "http://192.168.20.99", false); + "authorization", + "http://192.168.20.20", + "http://192.168.20.99", + false, + ); checkShouldCopyHeader( - "cat", "http://192.168.20.20", "http://192.168.20.99", true); + "cat", + "http://192.168.20.20", + "http://192.168.20.99", + true, + ); // Redirect to same domain. checkShouldCopyHeader( - "authorization", "http://foo.com", "http://foo.com/foo", true); + "authorization", + "http://foo.com", + "http://foo.com/foo", + true, + ); checkShouldCopyHeader("cat", "http://foo.com", "http://foo.com/foo", true); // Redirect to same domain with explicit ports. checkShouldCopyHeader( - "authorization", "http://foo.com", "http://foo.com:80/foo", true); + "authorization", + "http://foo.com", + "http://foo.com:80/foo", + true, + ); checkShouldCopyHeader("cat", "http://foo.com", "http://foo.com:80/foo", true); // Redirect to subdomain. checkShouldCopyHeader( - "authorization", "https://foo.com", "https://www.foo.com", true); + "authorization", + "https://foo.com", + "https://www.foo.com", + true, + ); checkShouldCopyHeader("cat", "https://foo.com", "https://www.foo.com", true); // Redirect to different domain. checkShouldCopyHeader( - "authorization", "https://foo.com", "https://wwwfoo.com", false); + "authorization", + "https://foo.com", + "https://wwwfoo.com", + false, + ); checkShouldCopyHeader("cat", "https://foo.com", "https://wwwfoo.com", true); // Redirect to different port. checkShouldCopyHeader( - "authorization", "http://foo.com", "http://foo.com:81", false); + "authorization", + "http://foo.com", + "http://foo.com:81", + false, + ); checkShouldCopyHeader("cat", "http://foo.com", "http://foo.com:81", true); // Redirect from secure to insecure. checkShouldCopyHeader( - "authorization", "https://foo.com", "http://foo.com", false); + "authorization", + "https://foo.com", + "http://foo.com", + false, + ); checkShouldCopyHeader("cat", "https://foo.com", "http://foo.com", true); // Redirect from secure to insecure, same port. checkShouldCopyHeader( - "authorization", "https://foo.com:8888", "http://foo.com:8888", false); + "authorization", + "https://foo.com:8888", + "http://foo.com:8888", + false, + ); checkShouldCopyHeader( - "cat", "https://foo.com:8888", "http://foo.com:8888", true); + "cat", + "https://foo.com:8888", + "http://foo.com:8888", + true, + ); // Redirect from insecure to secure. checkShouldCopyHeader( - "authorization", "http://foo.com", "https://foo.com", false); + "authorization", + "http://foo.com", + "https://foo.com", + false, + ); checkShouldCopyHeader("cat", "http://foo.com", "https://foo.com", true); // Redirect to subdomain, different port. checkShouldCopyHeader( - "authorization", "https://foo.com:80", "https://www.foo.com:81", false); + "authorization", + "https://foo.com:80", + "https://www.foo.com:81", + false, + ); checkShouldCopyHeader( - "cat", "https://foo.com:80", "https://www.foo.com:81", true); + "cat", + "https://foo.com:80", + "https://www.foo.com:81", + true, + ); // Different header casting: checkShouldCopyHeader( - "AuThOrIzAtiOn", "https://foo.com", "https://bar.com", false); + "AuThOrIzAtiOn", + "https://foo.com", + "https://bar.com", + false, + ); } void testCrossDomainAutoRedirectWithHeaders() { setupTargetServer().then((targetServer) { setupServer( - targetServer: - Uri.parse("http://127.0.0.1:${targetServer.port}/target")) - .then((server) { + targetServer: Uri.parse("http://127.0.0.1:${targetServer.port}/target"), + ).then((server) { HttpClient client = new HttpClient(); client .getUrl(Uri.parse("http://127.0.0.1:${server.port}/src-crossdomain")) .then((HttpClientRequest request) { - request.headers.add("X-Request-Header", "value"); - request.headers.add("Authorization", "Basic ..."); - return request.close(); - }).then((HttpClientResponse response) { - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - Expect.equals(1, response.redirects.length); - targetServer.close(); - server.close(); - client.close(); - }); - }); + request.headers.add("X-Request-Header", "value"); + request.headers.add("Authorization", "Basic ..."); + return request.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + Expect.equals(1, response.redirects.length); + targetServer.close(); + server.close(); + client.close(); + }, + ); + }); }); }); } @@ -516,16 +695,19 @@ void testAutoRedirect301POST() { client .postUrl(Uri.parse("http://127.0.0.1:${server.port}/301src")) .then((HttpClientRequest request) { - return request.close(); - }).then((HttpClientResponse response) { - Expect.equals(HttpStatus.movedPermanently, response.statusCode); - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - Expect.equals(0, response.redirects.length); - server.close(); - client.close(); - }); - }); + return request.close(); + }) + .then((HttpClientResponse response) { + Expect.equals(HttpStatus.movedPermanently, response.statusCode); + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + Expect.equals(0, response.redirects.length); + server.close(); + client.close(); + }, + ); + }); }); } @@ -536,16 +718,19 @@ void testAutoRedirect303POST() { client .postUrl(Uri.parse("http://127.0.0.1:${server.port}/303src")) .then((HttpClientRequest request) { - return request.close(); - }).then((HttpClientResponse response) { - Expect.equals(HttpStatus.ok, response.statusCode); - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - Expect.equals(1, response.redirects.length); - server.close(); - client.close(); - }); - }); + return request.close(); + }) + .then((HttpClientResponse response) { + Expect.equals(HttpStatus.ok, response.statusCode); + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + Expect.equals(1, response.redirects.length); + server.close(); + client.close(); + }, + ); + }); }); } @@ -553,10 +738,11 @@ void testAutoRedirectLimit() { setupServer().then((server) { HttpClient client = new HttpClient(); - Future.value(client - .getUrl(Uri.parse("http://127.0.0.1:${server.port}/1")) - .then((HttpClientRequest request) => request.close())) - .catchError((error) { + Future.value( + client + .getUrl(Uri.parse("http://127.0.0.1:${server.port}/1")) + .then((HttpClientRequest request) => request.close()), + ).catchError((error) { Expect.equals(5, error.redirects.length); server.close(); client.close(); @@ -569,10 +755,11 @@ void testRedirectLoop() { HttpClient client = new HttpClient(); int redirectCount = 0; - Future.value(client - .getUrl(Uri.parse("http://127.0.0.1:${server.port}/A")) - .then((HttpClientRequest request) => request.close())) - .catchError((error) { + Future.value( + client + .getUrl(Uri.parse("http://127.0.0.1:${server.port}/A")) + .then((HttpClientRequest request) => request.close()), + ).catchError((error) { Expect.equals(2, error.redirects.length); server.close(); client.close(); @@ -588,12 +775,15 @@ void testRedirectClosingConnection() { .getUrl(Uri.parse("http://127.0.0.1:${server.port}/closing")) .then((request) => request.close()) .then((response) { - response.listen((_) {}, onDone: () { - Expect.equals(1, response.redirects.length); - server.close(); - client.close(); - }); - }); + response.listen( + (_) {}, + onDone: () { + Expect.equals(1, response.redirects.length); + server.close(); + client.close(); + }, + ); + }); }); } @@ -607,13 +797,16 @@ void testRedirectRelativeUrl() { .getUrl(Uri.parse("http://127.0.0.1:${server.port}$path")) .then((request) => request.close()) .then((response) { - response.listen((_) {}, onDone: () { - Expect.equals(HttpStatus.ok, response.statusCode); - Expect.equals(1, response.redirects.length); - server.close(); - client.close(); - }); - }); + response.listen( + (_) {}, + onDone: () { + Expect.equals(HttpStatus.ok, response.statusCode); + Expect.equals(1, response.redirects.length); + server.close(); + client.close(); + }, + ); + }); }); } @@ -631,23 +824,27 @@ void testRedirectRelativeToAbsolute() { int redirectCount = 0; handleResponse(HttpClientResponse response) { - response.listen((_) => Expect.fail("Response data not expected"), - onDone: () { - Expect.equals(HttpStatus.seeOther, response.statusCode); - Expect.equals("xxx", response.headers["Location"]![0]); - Expect.isTrue(response.isRedirect); - server.close(); - client.close(); - }); + response.listen( + (_) => Expect.fail("Response data not expected"), + onDone: () { + Expect.equals(HttpStatus.seeOther, response.statusCode); + Expect.equals("xxx", response.headers["Location"]![0]); + Expect.isTrue(response.isRedirect); + server.close(); + client.close(); + }, + ); } client - .getUrl(Uri.parse( - "http://127.0.0.1:${server.port}/some/relativeToAbsolute")) + .getUrl( + Uri.parse("http://127.0.0.1:${server.port}/some/relativeToAbsolute"), + ) .then((HttpClientRequest request) { - request.followRedirects = false; - return request.close(); - }).then(handleResponse); + request.followRedirects = false; + return request.close(); + }) + .then(handleResponse); }); } diff --git a/tests/standalone/io/http_requested_uri_test.dart b/tests/standalone/io/http_requested_uri_test.dart index a94b32f7c35..ce6cb16cce5 100644 --- a/tests/standalone/io/http_requested_uri_test.dart +++ b/tests/standalone/io/http_requested_uri_test.dart @@ -55,12 +55,14 @@ void testAbsoluteUriInRequest() { socket.write("Host: google.com\r\n"); socket.write("Connection: close\r\n"); socket.write("\r\n"); - socket.flush().then((_) => socket.drain().then((_) { - Expect.equals(Uri.http("google.com", "/"), requestedUri); - socket.close(); - server.close(); - asyncEnd(); - })); + socket.flush().then( + (_) => socket.drain().then((_) { + Expect.equals(Uri.http("google.com", "/"), requestedUri); + socket.close(); + server.close(); + asyncEnd(); + }), + ); }); }); } diff --git a/tests/standalone/io/http_response_deadline_test.dart b/tests/standalone/io/http_response_deadline_test.dart index 18ee4909469..5fcf438fa4d 100644 --- a/tests/standalone/io/http_response_deadline_test.dart +++ b/tests/standalone/io/http_response_deadline_test.dart @@ -22,10 +22,12 @@ void testSimpleDeadline(int connections) { var futures = []; var client = new HttpClient(); for (int i = 0; i < connections; i++) { - futures.add(client - .get('localhost', server.port, '/') - .then((request) => request.close()) - .then((response) => response.drain())); + futures.add( + client + .get('localhost', server.port, '/') + .then((request) => request.close()) + .then((response) => response.drain()), + ); } Future.wait(futures).then((_) => server.close()); }); @@ -42,15 +44,20 @@ void testExceedDeadline(int connections) { var futures = []; var client = new HttpClient(); for (int i = 0; i < connections; i++) { - futures.add(client - .get('localhost', server.port, '/') - .then((request) => request.close()) - .then((response) => response.drain()) - .then((_) { - Expect.fail("Expected error"); - }, onError: (e) { - // Expect error. - })); + futures.add( + client + .get('localhost', server.port, '/') + .then((request) => request.close()) + .then((response) => response.drain()) + .then( + (_) { + Expect.fail("Expected error"); + }, + onError: (e) { + // Expect error. + }, + ), + ); } Future.wait(futures).then((_) => server.close()); }); @@ -74,16 +81,21 @@ void testDeadlineAndDetach(int connections) { var futures = []; var client = new HttpClient(); for (int i = 0; i < connections; i++) { - futures.add(client - .get('localhost', server.port, '/') - .then((request) => request.close()) - .then((response) { - return response - .fold(new BytesBuilder(), (b, d) => b..add(d)) - .then((builder) { - Expect.equals('stuff', new String.fromCharCodes(builder.takeBytes())); - }); - })); + futures.add( + client + .get('localhost', server.port, '/') + .then((request) => request.close()) + .then((response) { + return response + .fold(new BytesBuilder(), (b, d) => b..add(d)) + .then((builder) { + Expect.equals( + 'stuff', + new String.fromCharCodes(builder.takeBytes()), + ); + }); + }), + ); } Future.wait(futures).then((_) => server.close()); }); diff --git a/tests/standalone/io/http_reuse_server_port_test.dart b/tests/standalone/io/http_reuse_server_port_test.dart index afdbc3ee832..da1b6a2d442 100644 --- a/tests/standalone/io/http_reuse_server_port_test.dart +++ b/tests/standalone/io/http_reuse_server_port_test.dart @@ -26,16 +26,18 @@ Future runServer(int port, int connections, bool clean) { } }); - 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((_) { + 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)); diff --git a/tests/standalone/io/http_server_close_response_after_error_test.dart b/tests/standalone/io/http_server_close_response_after_error_test.dart index eb45423a420..ae0b7cf3d2f 100644 --- a/tests/standalone/io/http_server_close_response_after_error_test.dart +++ b/tests/standalone/io/http_server_close_response_after_error_test.dart @@ -16,19 +16,23 @@ const CLIENT_SCRIPT = "http_server_close_response_after_error_client.dart"; void main() { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { - request.listen(null, onError: (e) {}, onDone: () { - request.response.close(); - }); + request.listen( + null, + onError: (e) {}, + onDone: () { + request.response.close(); + }, + ); }); Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..addAll([ - Platform.script.resolve(CLIENT_SCRIPT).toString(), - server.port.toString() - ])) - .then((result) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..addAll([ + Platform.script.resolve(CLIENT_SCRIPT).toString(), + server.port.toString(), + ]), + ).then((result) { if (result.exitCode != 0) throw "Bad exit code"; server.close(); }); diff --git a/tests/standalone/io/http_server_early_client_close2_test.dart b/tests/standalone/io/http_server_early_client_close2_test.dart index 1a84dfd2960..846676dedee 100644 --- a/tests/standalone/io/http_server_early_client_close2_test.dart +++ b/tests/standalone/io/http_server_early_client_close2_test.dart @@ -16,11 +16,11 @@ main() { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { String name = Platform.script.toFilePath(); - new File(name) - .openRead() - .cast>() - .pipe(request.response) - .catchError((e) {/* ignore */}); + new File( + name, + ).openRead().cast>().pipe(request.response).catchError((e) { + /* ignore */ + }); }); var count = 0; diff --git a/tests/standalone/io/http_server_early_client_close_test.dart b/tests/standalone/io/http_server_early_client_close_test.dart index bc1403ab965..6e0d18c2d70 100644 --- a/tests/standalone/io/http_server_early_client_close_test.dart +++ b/tests/standalone/io/http_server_early_client_close_test.dart @@ -36,25 +36,32 @@ class EarlyCloseTest { bool calledOnDone = false; ReceivePort port = new ReceivePort(); var requestCompleter = new Completer(); - server.listen((request) { - Expect.isTrue(expectRequest); - Expect.isFalse(calledOnError); - Expect.isFalse(calledOnRequest, "onRequest called multiple times"); - calledOnRequest = true; - request.listen((_) {}, onDone: () { - requestCompleter.complete(); - }, onError: (error) { + server.listen( + (request) { + Expect.isTrue(expectRequest); Expect.isFalse(calledOnError); - Expect.equals(exception, error.message); - calledOnError = true; - if (exception != null) port.close(); - }); - }, onDone: () { - Expect.equals(expectRequest, calledOnRequest); - calledOnDone = true; - if (exception == null) port.close(); - c.complete(null); - }); + Expect.isFalse(calledOnRequest, "onRequest called multiple times"); + calledOnRequest = true; + request.listen( + (_) {}, + onDone: () { + requestCompleter.complete(); + }, + onError: (error) { + Expect.isFalse(calledOnError); + Expect.equals(exception, error.message); + calledOnError = true; + if (exception != null) port.close(); + }, + ); + }, + onDone: () { + Expect.equals(expectRequest, calledOnRequest); + calledOnDone = true; + if (exception == null) port.close(); + c.complete(null); + }, + ); List? d; if (data is List) d = data; @@ -88,10 +95,16 @@ void testEarlyClose1() { add("GET / HTTP/1.1\r\n"); // Close while sending content - add("GET / HTTP/1.1\r\nContent-Length: 100\r\n\r\n", - "Connection closed while receiving data", true); - add("GET / HTTP/1.1\r\nContent-Length: 100\r\n\r\n1", - "Connection closed while receiving data", true); + add( + "GET / HTTP/1.1\r\nContent-Length: 100\r\n\r\n", + "Connection closed while receiving data", + true, + ); + add( + "GET / HTTP/1.1\r\nContent-Length: 100\r\n\r\n1", + "Connection closed while receiving data", + true, + ); void runTest(Iterator it) { if (it.moveNext()) { @@ -108,11 +121,11 @@ testEarlyClose2() { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { String name = Platform.script.toFilePath(); - new File(name) - .openRead() - .cast>() - .pipe(request.response) - .catchError((e) {/* ignore */}); + new File( + name, + ).openRead().cast>().pipe(request.response).catchError((e) { + /* ignore */ + }); }); var count = 0; @@ -140,11 +153,14 @@ void testEarlyClose3() { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { var subscription; - subscription = request.listen((_) {}, onError: (error) { - // subscription.cancel should not trigger an error. - subscription.cancel(); - server.close(); - }); + subscription = request.listen( + (_) {}, + onError: (error) { + // subscription.cancel should not trigger an error. + subscription.cancel(); + server.close(); + }, + ); }); Socket.connect("127.0.0.1", server.port).then((socket) { socket.write("GET / HTTP/1.1\r\n"); diff --git a/tests/standalone/io/http_server_idle_timeout_test.dart b/tests/standalone/io/http_server_idle_timeout_test.dart index 247bb6fcce2..44e95748ceb 100644 --- a/tests/standalone/io/http_server_idle_timeout_test.dart +++ b/tests/standalone/io/http_server_idle_timeout_test.dart @@ -23,10 +23,13 @@ void testTimeoutAfterRequest() { Socket.connect("127.0.0.1", server.port).then((socket) { var data = "GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n"; socket.write(data); - socket.listen(null, onDone: () { - socket.close(); - server.close(); - }); + socket.listen( + null, + onDone: () { + socket.close(); + server.close(); + }, + ); }); }); } @@ -38,10 +41,13 @@ void testTimeoutBeforeRequest() { server.listen((request) => request.response.close()); Socket.connect("127.0.0.1", server.port).then((socket) { - socket.listen(null, onDone: () { - socket.close(); - server.close(); - }); + socket.listen( + null, + onDone: () { + socket.close(); + server.close(); + }, + ); }); }); } diff --git a/tests/standalone/io/http_server_response_test.dart b/tests/standalone/io/http_server_response_test.dart index 8858c1cd747..ad8e10bbdc0 100644 --- a/tests/standalone/io/http_server_response_test.dart +++ b/tests/standalone/io/http_server_response_test.dart @@ -16,10 +16,14 @@ import "dart:typed_data"; // Platform.script may refer to a AOT or JIT snapshot, which are significantly // larger. File scriptSource = new File( - Platform.script.resolve("http_server_response_test.dart").toFilePath()); + Platform.script.resolve("http_server_response_test.dart").toFilePath(), +); -void testServerRequest(void handler(server, request), - {int? bytes, bool closeClient = false}) { +void testServerRequest( + void handler(server, request), { + int? bytes, + bool closeClient = false, +}) { HttpServer.bind("127.0.0.1", 0).then((server) { server.defaultResponseHeaders.clear(); server.listen((request) { @@ -34,24 +38,29 @@ void testServerRequest(void handler(server, request), .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - int received = 0; - var subscription; - subscription = response.listen((data) { - if (closeClient) { - subscription.cancel(); + int received = 0; + var subscription; + subscription = response.listen( + (data) { + if (closeClient) { + subscription.cancel(); + client.close(); + } else { + received += data.length; + } + }, + onDone: () { + if (bytes != null) Expect.equals(received, bytes); + client.close(); + }, + onError: (error) { + Expect.isTrue(error is HttpException); + }, + ); + }) + .catchError((error) { client.close(); - } else { - received += data.length; - } - }, onDone: () { - if (bytes != null) Expect.equals(received, bytes); - client.close(); - }, onError: (error) { - Expect.isTrue(error is HttpException); - }); - }).catchError((error) { - client.close(); - }, test: (e) => e is HttpException); + }, test: (e) => e is HttpException); }); } @@ -65,11 +74,9 @@ void testResponseDone() { }); testServerRequest((server, request) { - new File("__nonexistent_file_") - .openRead() - .cast>() - .pipe(request.response) - .catchError((e) { + new File( + "__nonexistent_file_", + ).openRead().cast>().pipe(request.response).catchError((e) { server.close(); }); }); @@ -116,16 +123,14 @@ void testResponseAddStream() { request.response .addStream(new File("__nonexistent_file_").openRead()) .catchError((e) { - server.close(); - }); + server.close(); + }); }); testServerRequest((server, request) { - new File("__nonexistent_file_") - .openRead() - .cast>() - .pipe(request.response) - .catchError((e) { + new File( + "__nonexistent_file_", + ).openRead().cast>().pipe(request.response).catchError((e) { server.close(); }); }); @@ -254,16 +259,19 @@ void testIgnoreRequestData() { }); var client = new HttpClient(); - client.get("127.0.0.1", server.port, "/").then((request) { - request.contentLength = 1024 * 1024; - request.add(new Uint8List(1024 * 1024)); - return request.close(); - }).then((response) { - response.fold(0, (s, b) => s + b.length).then((bytes) { - Expect.equals(8, bytes); - server.close(); - }); - }); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + request.contentLength = 1024 * 1024; + request.add(new Uint8List(1024 * 1024)); + return request.close(); + }) + .then((response) { + response.fold(0, (s, b) => s + b.length).then((bytes) { + Expect.equals(8, bytes); + server.close(); + }); + }); }); } diff --git a/tests/standalone/io/http_server_test.dart b/tests/standalone/io/http_server_test.dart index 80c16a23080..39fbd8dd5a4 100644 --- a/tests/standalone/io/http_server_test.dart +++ b/tests/standalone/io/http_server_test.dart @@ -11,8 +11,9 @@ import "package:expect/expect.dart"; void testDefaultResponseHeaders() { checkDefaultHeaders(headers) { - Expect.listEquals( - headers[HttpHeaders.contentTypeHeader], ['text/plain; charset=utf-8']); + Expect.listEquals(headers[HttpHeaders.contentTypeHeader], [ + 'text/plain; charset=utf-8', + ]); Expect.listEquals(headers['X-Frame-Options'], ['SAMEORIGIN']); Expect.listEquals(headers['X-Content-Type-Options'], ['nosniff']); Expect.listEquals(headers['X-XSS-Protection'], ['1; mode=block']); @@ -38,7 +39,8 @@ void testDefaultResponseHeaders() { if (clearHeaders) server.defaultResponseHeaders.clear(); if (defaultHeaders != null) { defaultHeaders.forEach( - (name, value) => server.defaultResponseHeaders.add(name, value)); + (name, value) => server.defaultResponseHeaders.add(name, value), + ); } checker(server.defaultResponseHeaders); server.listen((request) { @@ -50,10 +52,10 @@ void testDefaultResponseHeaders() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - checker(response.headers); - server.close(); - client.close(); - }); + checker(response.headers); + server.close(); + client.close(); + }); }); } @@ -76,13 +78,16 @@ void testDefaultResponseHeadersContentType() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.fold>([], (a, b) => a..addAll(b)).then((body) { - Expect.listEquals(body, responseBody); - }).whenComplete(() { - server.close(); - client.close(); - }); - }); + response + .fold>([], (a, b) => a..addAll(b)) + .then((body) { + Expect.listEquals(body, responseBody); + }) + .whenComplete(() { + server.close(); + client.close(); + }); + }); }); } @@ -98,18 +103,25 @@ void testListenOn() { Expect.equals(socket.port, server.port); HttpClient client = new HttpClient(); - client.get("127.0.0.1", socket.port, "/").then((request) { - return request.close(); - }).then((response) { - response.listen((_) {}, onDone: () { - client.close(); - onDone(); - }); - }).catchError((e, trace) { - String msg = "Unexpected error in Http Client: $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + client + .get("127.0.0.1", socket.port, "/") + .then((request) { + return request.close(); + }) + .then((response) { + response.listen( + (_) {}, + onDone: () { + client.close(); + onDone(); + }, + ); + }) + .catchError((e, trace) { + String msg = "Unexpected error in Http Client: $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }); } // Test two connection after each other. @@ -159,52 +171,61 @@ void testHttpServerZone() { void testHttpServerZoneError() { asyncStart(); Expect.equals(Zone.root, Zone.current); - runZonedGuarded(() { - Expect.notEquals(Zone.root, Zone.current); - HttpServer.bind("127.0.0.1", 0).then((server) { + runZonedGuarded( + () { Expect.notEquals(Zone.root, Zone.current); - server.listen((request) { + HttpServer.bind("127.0.0.1", 0).then((server) { Expect.notEquals(Zone.root, Zone.current); - request.listen((_) {}, onError: (error) { + server.listen((request) { Expect.notEquals(Zone.root, Zone.current); - server.close(); - throw error; + request.listen( + (_) {}, + onError: (error) { + Expect.notEquals(Zone.root, Zone.current); + server.close(); + throw error; + }, + ); + }); + Socket.connect("127.0.0.1", server.port).then((socket) { + socket.write('GET / HTTP/1.1\r\nContent-Length: 100\r\n\r\n'); + socket.write('some body'); + socket.close(); + socket.listen(null); }); }); - Socket.connect("127.0.0.1", server.port).then((socket) { - socket.write('GET / HTTP/1.1\r\nContent-Length: 100\r\n\r\n'); - socket.write('some body'); - socket.close(); - socket.listen(null); - }); - }); - }, (e, s) { - asyncEnd(); - }); + }, + (e, s) { + asyncEnd(); + }, + ); } void testHttpServerClientClose() { HttpServer.bind("127.0.0.1", 0).then((server) { - runZonedGuarded(() { - server.listen((request) { - request.response.bufferOutput = false; - request.response.add(new Uint8List(64 * 1024)); - new Timer(const Duration(milliseconds: 100), () { - request.response.close().then((_) { - server.close(); + runZonedGuarded( + () { + server.listen((request) { + request.response.bufferOutput = false; + request.response.add(new Uint8List(64 * 1024)); + new Timer(const Duration(milliseconds: 100), () { + request.response.close().then((_) { + server.close(); + }); }); }); - }); - }, (e, s) { - Expect.fail("Unexpected error: $e(${e.hashCode})\n$s"); - }); + }, + (e, s) { + Expect.fail("Unexpected error: $e(${e.hashCode})\n$s"); + }, + ); var client = new HttpClient(); client .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.listen((_) {}).cancel(); - }); + response.listen((_) {}).cancel(); + }); }); } diff --git a/tests/standalone/io/http_session_test.dart b/tests/standalone/io/http_session_test.dart index 48587a40130..7845983e6b8 100644 --- a/tests/standalone/io/http_session_test.dart +++ b/tests/standalone/io/http_session_test.dart @@ -21,16 +21,22 @@ String getSessionId(List cookies) { return id!; } -Future connectGetSession(HttpClient client, int port, - [String? session]) { - return client.get("127.0.0.1", port, "/").then((request) { - if (session != null) { - request.cookies.add(new Cookie(SESSION_ID, session)); - } - return request.close(); - }).then((response) { - return response.fold(getSessionId(response.cookies), (v, _) => v); - }); +Future connectGetSession( + HttpClient client, + int port, [ + String? session, +]) { + return client + .get("127.0.0.1", port, "/") + .then((request) { + if (session != null) { + request.cookies.add(new Cookie(SESSION_ID, session)); + } + return request.close(); + }) + .then((response) { + return response.fold(getSessionId(response.cookies), (v, _) => v); + }); } void testSessions(int sessionCount) { @@ -44,15 +50,19 @@ void testSessions(int sessionCount) { var futures = []; for (int i = 0; i < sessionCount; i++) { - futures.add(connectGetSession(client, server.port).then((session) { - Expect.isNotNull(session); - Expect.isTrue(sessions.contains(session)); - return connectGetSession(client, server.port, session).then((session2) { - Expect.equals(session2, session); - Expect.isTrue(sessions.contains(session2)); - return session2; - }); - })); + futures.add( + connectGetSession(client, server.port).then((session) { + Expect.isNotNull(session); + Expect.isTrue(sessions.contains(session)); + return connectGetSession(client, server.port, session).then(( + session2, + ) { + Expect.equals(session2, session); + Expect.isTrue(sessions.contains(session2)); + return session2; + }); + }), + ); } Future.wait(futures).then((clientSessions) { Expect.equals(sessions.length, sessionCount); @@ -85,11 +95,12 @@ void testTimeout(int sessionCount) { Future.wait(timeouts).then((_) { futures = []; for (var id in clientSessions) { - futures - .add(connectGetSession(client, server.port, id).then((session) { - Expect.isNotNull(session); - Expect.notEquals(id, session); - })); + futures.add( + connectGetSession(client, server.port, id).then((session) { + Expect.isNotNull(session); + Expect.notEquals(id, session); + }), + ); } Future.wait(futures).then((_) { server.close(); @@ -127,23 +138,32 @@ void testSessionsData() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.listen((_) {}, onDone: () { - var id = getSessionId(response.cookies); - Expect.isNotNull(id); - client.get("127.0.0.1", server.port, "/").then((request) { - request.cookies.add(new Cookie(SESSION_ID, id)); - return request.close(); - }).then((response) { - response.listen((_) {}, onDone: () { - Expect.isTrue(firstHit); - Expect.isTrue(secondHit); - Expect.equals(id, getSessionId(response.cookies)); - server.close(); - client.close(); - }); + response.listen( + (_) {}, + onDone: () { + var id = getSessionId(response.cookies); + Expect.isNotNull(id); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + request.cookies.add(new Cookie(SESSION_ID, id)); + return request.close(); + }) + .then((response) { + response.listen( + (_) {}, + onDone: () { + Expect.isTrue(firstHit); + Expect.isTrue(secondHit); + Expect.equals(id, getSessionId(response.cookies)); + server.close(); + client.close(); + }, + ); + }); + }, + ); }); - }); - }); }); } @@ -170,22 +190,31 @@ void testSessionsDestroy() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.listen((_) {}, onDone: () { - var id = getSessionId(response.cookies); - Expect.isNotNull(id); - client.get("127.0.0.1", server.port, "/").then((request) { - request.cookies.add(new Cookie(SESSION_ID, id)); - return request.close(); - }).then((response) { - response.listen((_) {}, onDone: () { - Expect.isTrue(firstHit); - Expect.notEquals(id, getSessionId(response.cookies)); - server.close(); - client.close(); - }); + response.listen( + (_) {}, + onDone: () { + var id = getSessionId(response.cookies); + Expect.isNotNull(id); + client + .get("127.0.0.1", server.port, "/") + .then((request) { + request.cookies.add(new Cookie(SESSION_ID, id)); + return request.close(); + }) + .then((response) { + response.listen( + (_) {}, + onDone: () { + Expect.isTrue(firstHit); + Expect.notEquals(id, getSessionId(response.cookies)); + server.close(); + client.close(); + }, + ); + }); + }, + ); }); - }); - }); }); } diff --git a/tests/standalone/io/http_shutdown_test.dart b/tests/standalone/io/http_shutdown_test.dart index 68fcbde12f2..b59ad942b03 100644 --- a/tests/standalone/io/http_shutdown_test.dart +++ b/tests/standalone/io/http_shutdown_test.dart @@ -25,14 +25,17 @@ void test1(int totalConnections) { .get("127.0.0.1", server.port, "/") .then((HttpClientRequest request) => request.close()) .then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - count++; - if (count == totalConnections) { - client.close(); - server.close(); - } - }); - }); + response.listen( + (_) {}, + onDone: () { + count++; + if (count == totalConnections) { + client.close(); + server.close(); + } + }, + ); + }); } }); } @@ -51,27 +54,33 @@ void test2(int totalConnections, int outputStreamWrites) { client .get("127.0.0.1", server.port, "/") .then((HttpClientRequest request) { - request.contentLength = -1; - for (int i = 0; i < outputStreamWrites; i++) { - request.write("Hello, world!"); - } - request.done.catchError((_) {}); - return request.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - count++; - if (count == totalConnections) { - client.close(force: true); - server.close(); - } - }, onError: (e) {} /* ignore */); - }).catchError((error) { - count++; - if (count == totalConnections) { - client.close(); - server.close(); - } - }); + request.contentLength = -1; + for (int i = 0; i < outputStreamWrites; i++) { + request.write("Hello, world!"); + } + request.done.catchError((_) {}); + return request.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + count++; + if (count == totalConnections) { + client.close(force: true); + server.close(); + } + }, + onError: (e) {} /* ignore */, + ); + }) + .catchError((error) { + count++; + if (count == totalConnections) { + client.close(); + server.close(); + } + }); } }); } @@ -80,10 +89,13 @@ void test3(int totalConnections) { // Server which responds when request body has been received. HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((HttpRequest request) { - request.listen((_) {}, onDone: () { - request.response.write("!dlrow ,olleH"); - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.write("!dlrow ,olleH"); + request.response.close(); + }, + ); }); int count = 0; @@ -92,18 +104,22 @@ void test3(int totalConnections) { client .get("127.0.0.1", server.port, "/") .then((HttpClientRequest request) { - request.contentLength = -1; - request.write("Hello, world!"); - return request.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - count++; - if (count == totalConnections) { - client.close(); - server.close(); - } - }); - }); + request.contentLength = -1; + request.write("Hello, world!"); + return request.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + count++; + if (count == totalConnections) { + client.close(); + server.close(); + } + }, + ); + }); } }); } @@ -111,15 +127,18 @@ void test3(int totalConnections) { void test4() { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((var request) { - request.listen((_) {}, onDone: () { - new Timer.periodic(new Duration(milliseconds: 100), (timer) { - if (server.connectionsInfo().total == 0) { - server.close(); - timer.cancel(); - } - }); - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + new Timer.periodic(new Duration(milliseconds: 100), (timer) { + if (server.connectionsInfo().total == 0) { + server.close(); + timer.cancel(); + } + }); + request.response.close(); + }, + ); }); var client = new HttpClient(); @@ -127,20 +146,27 @@ void test4() { .get("127.0.0.1", server.port, "/") .then((request) => request.close()) .then((response) { - response.listen((_) {}, onDone: () { - client.close(); - }); - }); + response.listen( + (_) {}, + onDone: () { + client.close(); + }, + ); + }); }); } void test5(int totalConnections) { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { - request.listen((_) {}, onDone: () { - request.response.close(); - request.response.done.catchError((e) {}); - }, onError: (error) {}); + request.listen( + (_) {}, + onDone: () { + request.response.close(); + request.response.done.catchError((e) {}); + }, + onError: (error) {}, + ); }, onError: (error) {}); // Create a number of client requests and keep then active. Then @@ -160,8 +186,10 @@ void test5(int totalConnections) { return request.close(); }) .then((response) {}) - .catchError((e) {}, - test: (e) => e is HttpException || e is SocketException); + .catchError( + (e) {}, + test: (e) => e is HttpException || e is SocketException, + ); } bool clientClosed = false; new Timer.periodic(new Duration(milliseconds: 100), (timer) { diff --git a/tests/standalone/io/http_stream_close_test.dart b/tests/standalone/io/http_stream_close_test.dart index 06b95727817..e65f4405015 100644 --- a/tests/standalone/io/http_stream_close_test.dart +++ b/tests/standalone/io/http_stream_close_test.dart @@ -21,31 +21,38 @@ main() { } server.listen((request) { - request.listen((_) {}, onDone: () { - request.response.done.then((_) { - serverOnClosed = true; - checkDone(); - }); - request.response.write("hello!"); - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.done.then((_) { + serverOnClosed = true; + checkDone(); + }); + request.response.write("hello!"); + request.response.close(); + }, + ); }); client .postUrl(Uri.parse("http://127.0.0.1:${server.port}")) .then((request) { - request.contentLength = "hello!".length; - request.done.then((_) { - clientOnClosed = true; - checkDone(); - }); - request.write("hello!"); - return request.close(); - }).then((response) { - response.listen((_) {}, onDone: () { - requestOnClosed = true; - checkDone(); - }); - }); + request.contentLength = "hello!".length; + request.done.then((_) { + clientOnClosed = true; + checkDone(); + }); + request.write("hello!"); + return request.close(); + }) + .then((response) { + response.listen( + (_) {}, + onDone: () { + requestOnClosed = true; + checkDone(); + }, + ); + }); }); } diff --git a/tests/standalone/io/https_bad_certificate_test.dart b/tests/standalone/io/https_bad_certificate_test.dart index 96b014407d4..953a97ed006 100644 --- a/tests/standalone/io/https_bad_certificate_test.dart +++ b/tests/standalone/io/https_bad_certificate_test.dart @@ -19,8 +19,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); class CustomException {} @@ -28,9 +30,12 @@ main() async { var HOST = (await InternetAddress.lookup(HOST_NAME)).first; var server = await HttpServer.bindSecure(HOST, 0, serverContext, backlog: 5); server.listen((request) { - request.listen((_) {}, onDone: () { - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.close(); + }, + ); }); SecurityContext goodContext = new SecurityContext() @@ -54,7 +59,11 @@ main() async { } Future runClient( - int port, SecurityContext context, callbackReturns, result) async { + int port, + SecurityContext context, + callbackReturns, + result, +) async { HttpClient client = new HttpClient(context: context); client.badCertificateCallback = (X509Certificate certificate, host, port) { Expect.isTrue(certificate.subject.contains('rootauthority')); @@ -71,8 +80,10 @@ Future runClient( } catch (error) { Expect.notEquals(result, 'pass'); if (result == 'fail') { - Expect.isTrue(error is HandshakeException || - (callbackReturns is! bool && error is TypeError)); + Expect.isTrue( + error is HandshakeException || + (callbackReturns is! bool && error is TypeError), + ); } else if (result == 'throw') { Expect.isTrue(error is CustomException); } else { diff --git a/tests/standalone/io/https_client_certificate_test.dart b/tests/standalone/io/https_client_certificate_test.dart index 4fb9fdf9d22..758af2482c8 100644 --- a/tests/standalone/io/https_client_certificate_test.dart +++ b/tests/standalone/io/https_client_certificate_test.dart @@ -19,26 +19,30 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart') - ..setTrustedCertificates( - localFile('certificates/client_authority.pem'), + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', ) - ..setClientAuthorities( - localFile('certificates/client_authority.pem'), - ); + ..setTrustedCertificates(localFile('certificates/client_authority.pem')) + ..setClientAuthorities(localFile('certificates/client_authority.pem')); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')) ..useCertificateChain(localFile('certificates/client1.pem')) - ..usePrivateKey(localFile('certificates/client1_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/client1_key.pem'), + password: 'dartdart', + ); void main() { asyncStart(); - HttpServer.bindSecure(HOST_NAME, 0, serverContext, - backlog: 5, requestClientCertificate: true) - .then((server) { + HttpServer.bindSecure( + HOST_NAME, + 0, + serverContext, + backlog: 5, + requestClientCertificate: true, + ).then((server) { server.listen((HttpRequest request) { Expect.isNotNull(request.certificate); Expect.equals('/CN=user1', request.certificate!.subject); @@ -51,16 +55,22 @@ void main() { .getUrl(Uri.parse("https://$HOST_NAME:${server.port}/")) .then((request) => request.close()) .then((response) { - Expect.equals('/CN=localhost', response.certificate!.subject); - Expect.equals('/CN=intermediateauthority', response.certificate!.issuer); - return response - .fold>([], (message, data) => message..addAll(data)); - }).then((message) { - String received = new String.fromCharCodes(message); - Expect.equals(received, "Hello"); - client.close(); - server.close(); - asyncEnd(); - }); + Expect.equals('/CN=localhost', response.certificate!.subject); + Expect.equals( + '/CN=intermediateauthority', + response.certificate!.issuer, + ); + return response.fold>( + [], + (message, data) => message..addAll(data), + ); + }) + .then((message) { + String received = new String.fromCharCodes(message); + Expect.equals(received, "Hello"); + client.close(); + server.close(); + asyncEnd(); + }); }); } diff --git a/tests/standalone/io/https_client_exception_test.dart b/tests/standalone/io/https_client_exception_test.dart index 9db17be4295..d4497a05310 100644 --- a/tests/standalone/io/https_client_exception_test.dart +++ b/tests/standalone/io/https_client_exception_test.dart @@ -13,10 +13,11 @@ void testBadHostName() { client .getUrl(Uri.parse("https://some.bad.host.name.7654321/")) .then((HttpClientRequest request) { - Expect.fail("Should not open a request on bad hostname"); - }).catchError((error) { - asyncEnd(); // Should throw an error on bad hostname. - }); + Expect.fail("Should not open a request on bad hostname"); + }) + .catchError((error) { + asyncEnd(); // Should throw an error on bad hostname. + }); } void main() { diff --git a/tests/standalone/io/https_connection_closed_during_handshake_test.dart b/tests/standalone/io/https_connection_closed_during_handshake_test.dart index cc2e5575cf9..cd94ddc89b3 100644 --- a/tests/standalone/io/https_connection_closed_during_handshake_test.dart +++ b/tests/standalone/io/https_connection_closed_during_handshake_test.dart @@ -20,24 +20,30 @@ String getFilename(String path) => Platform.script.resolve(path).toFilePath(); final SecurityContext serverSecurityContext = () { final context = SecurityContext(); - context - .usePrivateKeyBytes(File(getFilename('localhost.key')).readAsBytesSync()); + context.usePrivateKeyBytes( + File(getFilename('localhost.key')).readAsBytesSync(), + ); context.useCertificateChainBytes( - File(getFilename('localhost.crt')).readAsBytesSync()); + File(getFilename('localhost.crt')).readAsBytesSync(), + ); return context; }(); final SecurityContext clientSecurityContext = () { final context = SecurityContext(withTrustedRoots: true); context.setTrustedCertificatesBytes( - File(getFilename('localhost.crt')).readAsBytesSync()); + File(getFilename('localhost.crt')).readAsBytesSync(), + ); return context; }(); void main(List args) async { if (args.length >= 1 && args[0] == 'server') { - final server = - await SecureServerSocket.bind('localhost', 0, serverSecurityContext); + final server = await SecureServerSocket.bind( + 'localhost', + 0, + serverSecurityContext, + ); print('ok ${server.port}'); server.listen((socket) { print('server: got connection'); @@ -53,19 +59,18 @@ void main(List args) async { final serverProcess = await Process.start(Platform.executable, [ ...Platform.executableArguments, Platform.script.toFilePath(), - 'server' + 'server', ]); final serverPortCompleter = Completer(); - serverProcess.stdout - .transform(utf8.decoder) - .transform(LineSplitter()) - .listen((line) { - print('server stdout: $line'); - if (line.startsWith('ok')) { - serverPortCompleter.complete(int.parse(line.substring('ok'.length))); - } - }); + serverProcess.stdout.transform(utf8.decoder).transform(LineSplitter()).listen( + (line) { + print('server stdout: $line'); + if (line.startsWith('ok')) { + serverPortCompleter.complete(int.parse(line.substring('ok'.length))); + } + }, + ); serverProcess.stderr .transform(utf8.decoder) .transform(LineSplitter()) @@ -74,17 +79,23 @@ void main(List args) async { int port = await serverPortCompleter.future; final errorCompleter = Completer(); - await runZoned(() async { - var socket = await SecureSocket.connect('localhost', port, - context: clientSecurityContext); - socket.write([1, 2, 3]); - }, onError: (e) async { - // Even if server disconnects during later parts of handshake, since - // TLS v1.3 client might not notice it until attempt to communicate with - // the server. - print('thrownException: $e'); - errorCompleter.complete(e); - }); + await runZoned( + () async { + var socket = await SecureSocket.connect( + 'localhost', + port, + context: clientSecurityContext, + ); + socket.write([1, 2, 3]); + }, + onError: (e) async { + // Even if server disconnects during later parts of handshake, since + // TLS v1.3 client might not notice it until attempt to communicate with + // the server. + print('thrownException: $e'); + errorCompleter.complete(e); + }, + ); Expect.isTrue((await errorCompleter.future) is SocketException); await serverProcess.kill(); diff --git a/tests/standalone/io/https_server_test.dart b/tests/standalone/io/https_server_test.dart index 6c46d921a73..d12a52bb387 100644 --- a/tests/standalone/io/https_server_test.dart +++ b/tests/standalone/io/https_server_test.dart @@ -18,8 +18,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -29,10 +31,13 @@ void testListenOn() { HttpServer.bindSecure(HOST, 0, serverContext, backlog: 5).then((server) { ReceivePort serverPort = new ReceivePort(); server.listen((HttpRequest request) { - request.listen((_) {}, onDone: () { - request.response.close(); - serverPort.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.close(); + serverPort.close(); + }, + ); }); HttpClient client = new HttpClient(context: clientContext); @@ -40,20 +45,25 @@ void testListenOn() { client .getUrl(Uri.parse("https://${HOST.host}:${server.port}/")) .then((HttpClientRequest request) { - return request.close(); - }).then((HttpClientResponse response) { - response.listen((_) {}, onDone: () { - client.close(); - clientPort.close(); - server.close(); - Expect.throws(() => server.port); - onDone(); - }); - }).catchError((e, trace) { - String msg = "Unexpected error in Https client: $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + return request.close(); + }) + .then((HttpClientResponse response) { + response.listen( + (_) {}, + onDone: () { + client.close(); + clientPort.close(); + server.close(); + Expect.throws(() => server.port); + onDone(); + }, + ); + }) + .catchError((e, trace) { + String msg = "Unexpected error in Https client: $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }); }); } @@ -67,11 +77,11 @@ void testEarlyClientClose() { HttpServer.bindSecure(HOST, 0, serverContext).then((server) { server.listen((request) { String name = Platform.script.toFilePath(); - new File(name) - .openRead() - .cast>() - .pipe(request.response) - .catchError((e) {/* ignore */}); + new File( + name, + ).openRead().cast>().pipe(request.response).catchError((e) { + /* ignore */ + }); }); var count = 0; diff --git a/tests/standalone/io/https_unauthorized_client.dart b/tests/standalone/io/https_unauthorized_client.dart index 6b7e8f6a74c..a291c47ec57 100644 --- a/tests/standalone/io/https_unauthorized_client.dart +++ b/tests/standalone/io/https_unauthorized_client.dart @@ -28,15 +28,24 @@ Future runClients(int port) { var testFutures = []; for (int i = 0; i < 20; ++i) { - testFutures.add(client.getUrl(Uri.parse('https://$HOST_NAME:$port/')).then( - (HttpClientRequest request) { - expect(false, "Request succeeded"); - }, onError: (e) { - // Remove ArgumentError once null default context is supported. - expect( - e is HandshakeException || e is SocketException || e is ArgumentError, - "Error is wrong type: $e"); - })); + testFutures.add( + client + .getUrl(Uri.parse('https://$HOST_NAME:$port/')) + .then( + (HttpClientRequest request) { + expect(false, "Request succeeded"); + }, + onError: (e) { + // Remove ArgumentError once null default context is supported. + expect( + e is HandshakeException || + e is SocketException || + e is ArgumentError, + "Error is wrong type: $e", + ); + }, + ), + ); } return Future.wait(testFutures); } diff --git a/tests/standalone/io/https_unauthorized_test.dart b/tests/standalone/io/https_unauthorized_test.dart index ea172bed615..968d93b10c1 100644 --- a/tests/standalone/io/https_unauthorized_test.dart +++ b/tests/standalone/io/https_unauthorized_test.dart @@ -24,22 +24,34 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext untrustedServerContext = new SecurityContext() ..useCertificateChain(localFile('certificates/untrusted_server_chain.pem')) - ..usePrivateKey(localFile('certificates/untrusted_server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/untrusted_server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); Future runServer() { - return HttpServer.bindSecure(HOST_NAME, 0, untrustedServerContext, backlog: 5) - .then((server) { - server.listen((HttpRequest request) { - request.listen((_) {}, onDone: () { - request.response.close(); - }); - }, onError: (e) { - if (e is! HandshakeException) throw e; - }); + return HttpServer.bindSecure( + HOST_NAME, + 0, + untrustedServerContext, + backlog: 5, + ).then((server) { + server.listen( + (HttpRequest request) { + request.listen( + (_) {}, + onDone: () { + request.response.close(); + }, + ); + }, + onError: (e) { + if (e is! HandshakeException) throw e; + }, + ); return server; }); } @@ -48,11 +60,11 @@ void main() { var clientScript = localFile('https_unauthorized_client.dart'); Future clientProcess(int port) { return Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..addAll([clientScript, port.toString()])) - .then((ProcessResult result) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..addAll([clientScript, port.toString()]), + ).then((ProcessResult result) { if (result.exitCode != 0 || !result.stdout.contains('SUCCESS')) { print("Client failed"); print(" stdout:"); diff --git a/tests/standalone/io/internet_address_test.dart b/tests/standalone/io/internet_address_test.dart index 306affcf179..467fd22086f 100644 --- a/tests/standalone/io/internet_address_test.dart +++ b/tests/standalone/io/internet_address_test.dart @@ -21,8 +21,24 @@ void testDefaultAddresses() { Expect.equals(InternetAddressType.IPv6, loopback6.type); Expect.equals("::1", loopback6.host); Expect.equals("::1", loopback6.address); - Expect.listEquals( - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], loopback6.rawAddress); + Expect.listEquals([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ], loopback6.rawAddress); var any4 = InternetAddress.anyIPv4; Expect.isNotNull(any4); @@ -125,16 +141,24 @@ void testTryParse() { void testEquality() { Expect.equals( - new InternetAddress("127.0.0.1"), new InternetAddress("127.0.0.1")); + new InternetAddress("127.0.0.1"), + new InternetAddress("127.0.0.1"), + ); Expect.equals(new InternetAddress("127.0.0.1"), InternetAddress.loopbackIPv4); Expect.equals(new InternetAddress("::1"), new InternetAddress("::1")); Expect.equals(new InternetAddress("::1"), InternetAddress.loopbackIPv6); - Expect.equals(new InternetAddress("1:2:3:4:5:6:7:8"), - new InternetAddress("1:2:3:4:5:6:7:8")); Expect.equals( - new InternetAddress("1::2"), new InternetAddress("1:0:0:0:0:0:0:2")); - Expect.equals(new InternetAddress("::FFFF:0:0:16.32.48.64"), - new InternetAddress("::FFFF:0:0:1020:3040")); + new InternetAddress("1:2:3:4:5:6:7:8"), + new InternetAddress("1:2:3:4:5:6:7:8"), + ); + Expect.equals( + new InternetAddress("1::2"), + new InternetAddress("1:0:0:0:0:0:0:2"), + ); + Expect.equals( + new InternetAddress("::FFFF:0:0:16.32.48.64"), + new InternetAddress("::FFFF:0:0:1020:3040"), + ); var set = new Set(); set.add(new InternetAddress("127.0.0.1")); @@ -191,8 +215,24 @@ void testRawAddress() { } void testRawAddressIPv6() { - Uint8List addr = - Uint8List.fromList([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + Uint8List addr = Uint8List.fromList([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); var address = InternetAddress.fromRawAddress(addr); Expect.equals('::1', address.address); Expect.equals(address.address, address.host); @@ -202,8 +242,10 @@ void testRawAddressIPv6() { void testRawPath() { var name = 'test_raw_path'; Uint8List path = Uint8List.fromList(utf8.encode(name)); - var address = - InternetAddress.fromRawAddress(path, type: InternetAddressType.unix); + var address = InternetAddress.fromRawAddress( + path, + type: InternetAddressType.unix, + ); Expect.equals(name, address.address); Expect.equals(address.address, address.host); Expect.equals(InternetAddressType.unix, address.type); diff --git a/tests/standalone/io/io_override_test.dart b/tests/standalone/io/io_override_test.dart index 25cc8ba07c7..3a6f26d3a3e 100644 --- a/tests/standalone/io/io_override_test.dart +++ b/tests/standalone/io/io_override_test.dart @@ -36,12 +36,14 @@ class DirectoryMock extends FileSystemEntity implements Directory { Future rename(String newPath) => throw ""; Directory renameSync(String newPath) => throw ""; Directory get absolute => throw ""; - Stream list( - {bool recursive = false, bool followLinks = true}) => - throw ""; - List listSync( - {bool recursive = false, bool followLinks = true}) => - throw ""; + Stream list({ + bool recursive = false, + bool followLinks = true, + }) => throw ""; + List listSync({ + bool recursive = false, + bool followLinks = true, + }) => throw ""; } class FileMock extends FileSystemEntity implements File { @@ -74,29 +76,38 @@ class FileMock extends FileSystemEntity implements File { Future open({FileMode mode = FileMode.read}) => throw ""; RandomAccessFile openSync({FileMode mode = FileMode.read}) => throw ""; Stream> openRead([int? start, int? end]) => throw ""; - IOSink openWrite( - {FileMode mode = FileMode.write, Encoding encoding = utf8}) => - throw ""; + IOSink openWrite({ + FileMode mode = FileMode.write, + Encoding encoding = utf8, + }) => throw ""; Future readAsBytes() => throw ""; Uint8List readAsBytesSync() => throw ""; Future readAsString({Encoding encoding = utf8}) => throw ""; String readAsStringSync({Encoding encoding = utf8}) => throw ""; Future> readAsLines({Encoding encoding = utf8}) => throw ""; List readAsLinesSync({Encoding encoding = utf8}) => throw ""; - Future writeAsBytes(List bytes, - {FileMode mode = FileMode.write, bool flush = false}) => - throw ""; - void writeAsBytesSync(List bytes, - {FileMode mode = FileMode.write, bool flush = false}) {} - Future writeAsString(String contents, - {FileMode mode = FileMode.write, - Encoding encoding = utf8, - bool flush = false}) => - throw ""; - void writeAsStringSync(String contents, - {FileMode mode = FileMode.write, - Encoding encoding = utf8, - bool flush = false}) {} + Future writeAsBytes( + List bytes, { + FileMode mode = FileMode.write, + bool flush = false, + }) => throw ""; + void writeAsBytesSync( + List bytes, { + FileMode mode = FileMode.write, + bool flush = false, + }) {} + Future writeAsString( + String contents, { + FileMode mode = FileMode.write, + Encoding encoding = utf8, + bool flush = false, + }) => throw ""; + void writeAsStringSync( + String contents, { + FileMode mode = FileMode.write, + Encoding encoding = utf8, + bool flush = false, + }) {} } class FileStatMock implements FileStat { @@ -138,8 +149,10 @@ final _mockFileSystemEvent = new Stream.empty(); class FileSystemWatcherMock { static Stream watch( - String path, int events, bool recursive) => - _mockFileSystemEvent; + String path, + int events, + bool recursive, + ) => _mockFileSystemEvent; static bool watchSupported() => false; } @@ -166,18 +179,32 @@ class LinkMock extends FileSystemEntity implements Link { String targetSync() => throw ""; } -Future socketConnect(dynamic host, int port, - {dynamic sourceAddress, int sourcePort = 0, Duration? timeout}) async { +Future socketConnect( + dynamic host, + int port, { + dynamic sourceAddress, + int sourcePort = 0, + Duration? timeout, +}) async { throw ""; } -Future> socketStartConnect(dynamic host, int port, - {dynamic sourceAddress, int sourcePort = 0}) async { +Future> socketStartConnect( + dynamic host, + int port, { + dynamic sourceAddress, + int sourcePort = 0, +}) async { throw ""; } -Future serverSocketBind(dynamic address, int port, - {int backlog = 0, bool v6Only = false, bool shared = false}) async { +Future serverSocketBind( + dynamic address, + int port, { + int backlog = 0, + bool v6Only = false, + bool shared = false, +}) async { throw ""; } @@ -189,11 +216,16 @@ class StdinMock extends Stream> implements Stdin { bool get supportsAnsiEscapes => throw ""; int readByteSync() => throw ""; - String readLineSync( - {Encoding encoding = systemEncoding, bool retainNewlines = false}) => - throw ""; - StreamSubscription> listen(void onData(List event)?, - {Function? onError, void onDone()?, bool? cancelOnError}) { + String readLineSync({ + Encoding encoding = systemEncoding, + bool retainNewlines = false, + }) => throw ""; + StreamSubscription> listen( + void onData(List event)?, { + Function? onError, + void onDone()?, + bool? cancelOnError, + }) { throw ""; } } @@ -227,12 +259,18 @@ Future ioOverridesRunTest() async { Expect.isFalse(await FileSystemEntity.identical("file", "file")); Expect.isFalse(FileSystemEntity.identicalSync("file", "file")); Expect.equals( - await FileSystemEntity.type("file"), FileSystemEntityType.file); + await FileSystemEntity.type("file"), + FileSystemEntityType.file, + ); Expect.equals( - FileSystemEntity.typeSync("file"), FileSystemEntityType.file); + FileSystemEntity.typeSync("file"), + FileSystemEntityType.file, + ); Expect.isFalse(FileSystemEntity.isWatchSupported); Expect.identical( - _mockFileSystemEvent, new Directory("directory").watch()); + _mockFileSystemEvent, + new Directory("directory").watch(), + ); Expect.isTrue(new Link("link") is LinkMock); asyncExpectThrows(Socket.connect(null, 0)); asyncExpectThrows(Socket.startConnect(null, 0)); @@ -298,7 +336,9 @@ class EmptyOverride extends IOOverrides {} void emptyIOOverride() { IOOverrides.runWithIOOverrides( () => Expect.equals( - FileSystemEntity.typeSync('/'), FileSystemEntityType.directory), + FileSystemEntity.typeSync('/'), + FileSystemEntityType.directory, + ), EmptyOverride(), ); } diff --git a/tests/standalone/io/io_sink_test.dart b/tests/standalone/io/io_sink_test.dart index 53c8cd1c0d5..e2ec45df5ea 100644 --- a/tests/standalone/io/io_sink_test.dart +++ b/tests/standalone/io/io_sink_test.dart @@ -15,8 +15,11 @@ class TestConsumer implements StreamConsumer> { int expectedAddStreamCount; bool expectClose; - TestConsumer(this.expected, - {this.expectClose = true, this.expectedAddStreamCount = -1}) { + TestConsumer( + this.expected, { + this.expectClose = true, + this.expectedAddStreamCount = -1, + }) { if (expectClose) asyncStart(); } diff --git a/tests/standalone/io/issue_35112_test.dart b/tests/standalone/io/issue_35112_test.dart index 1d53f1e0194..33dbee898fc 100644 --- a/tests/standalone/io/issue_35112_test.dart +++ b/tests/standalone/io/issue_35112_test.dart @@ -31,7 +31,9 @@ main() async { }); ; FileSystemEvent? event = await eventCompleter.future; - Expect.isNull(event, - "No event should be triggered or .contentChanged should equal false"); + Expect.isNull( + event, + "No event should be triggered or .contentChanged should equal false", + ); }); } diff --git a/tests/standalone/io/issue_46436_test.dart b/tests/standalone/io/issue_46436_test.dart index bbc5800a135..c55f89bbe3b 100644 --- a/tests/standalone/io/issue_46436_test.dart +++ b/tests/standalone/io/issue_46436_test.dart @@ -18,14 +18,19 @@ ClassMirror findWindowsCodePageEncoder() { } final classes = dartIo.declarations.values - .where((d) => - d is ClassMirror && - d.simpleName.toString().contains('"_WindowsCodePageEncoder"')) + .where( + (d) => + d is ClassMirror && + d.simpleName.toString().contains('"_WindowsCodePageEncoder"'), + ) .map((d) => d as ClassMirror) .toList(); Expect.equals( - 1, classes.length, "Expected exactly one _WindowsCodePageEncoder"); + 1, + classes.length, + "Expected exactly one _WindowsCodePageEncoder", + ); return classes[0]; } @@ -34,11 +39,15 @@ test() { final encoder = winCodePageEncoder.newInstance(Symbol(""), List.empty()); try { encoder.invoke(Symbol("convert"), List.of(["test"])); - Expect.isTrue(Platform.isWindows, - "expected UnsupportedError on ${Platform.operatingSystem}"); + Expect.isTrue( + Platform.isWindows, + "expected UnsupportedError on ${Platform.operatingSystem}", + ); } on UnsupportedError catch (e) { Expect.isFalse( - Platform.isWindows, "unexpected UnsupportedError on Windows: $e"); + Platform.isWindows, + "unexpected UnsupportedError on Windows: $e", + ); } } diff --git a/tests/standalone/io/link_async_test.dart b/tests/standalone/io/link_async_test.dart index a4da09784ed..8cd08345303 100644 --- a/tests/standalone/io/link_async_test.dart +++ b/tests/standalone/io/link_async_test.dart @@ -21,17 +21,19 @@ class FutureExpect { static Future listEquals(expected, Future result) => result.then((value) => Expect.listEquals(expected, value)); static Future throws(Future result) => result.then((value) { - throw new ExpectException( - "FutureExpect.throws received $value instead of an exception"); - }, onError: (_) => null); + throw new ExpectException( + "FutureExpect.throws received $value instead of an exception", + ); + }, onError: (_) => null); } Future testCreate() { return Directory.systemTemp.createTemp('dart_link_async').then((baseDir) { if (isRelative(baseDir.path)) { Expect.fail( - 'Link tests expect absolute paths to system temporary directories. ' - 'A relative path in TMPDIR gives relative paths to them.'); + 'Link tests expect absolute paths to system temporary directories. ' + 'A relative path in TMPDIR gives relative paths to them.', + ); } String base = baseDir.path; String link = join(base, 'link'); @@ -39,14 +41,30 @@ Future testCreate() { return new Directory(target) .create() .then((_) => new Link(link).create(target)) - .then((_) => FutureExpect.equals( - FileSystemEntityType.directory, FileSystemEntity.type(link))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.directory, FileSystemEntity.type(target))) - .then((_) => FutureExpect.equals(FileSystemEntityType.link, - FileSystemEntity.type(link, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.directory, - FileSystemEntity.type(target, followLinks: false))) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(link), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(target), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.link, + FileSystemEntity.type(link, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(target, followLinks: false), + ), + ) .then((_) => FutureExpect.isTrue(FileSystemEntity.isLink(link))) .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(target))) .then((_) => FutureExpect.isTrue(new Directory(link).exists())) @@ -56,64 +74,159 @@ Future testCreate() { .then((_) => FutureExpect.equals(target, new Link(link).target())) .then((_) => FutureExpect.throws(new Link(target).target())) .then((_) { - String createdThroughLink = join(base, 'link', 'createdThroughLink'); - String createdDirectly = join(base, 'target', 'createdDirectly'); - String createdFile = join(base, 'link', 'createdFile'); - return new Directory(createdThroughLink) - .create() - .then((_) => new Directory(createdDirectly).create()) - .then((_) => new File(createdFile).create()) - .then((_) => - FutureExpect.isTrue(new Directory(createdThroughLink).exists())) - .then((_) => - FutureExpect.isTrue(new Directory(createdDirectly).exists())) - .then((_) => FutureExpect.isTrue( - new Directory(join(base, 'link', 'createdDirectly')).exists())) - .then((_) => FutureExpect.isTrue( - new Directory(join(base, 'target', 'createdThroughLink')) - .exists())) - .then((_) => FutureExpect.equals(FileSystemEntityType.directory, - FileSystemEntity.type(createdThroughLink, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.directory, - FileSystemEntity.type(createdDirectly, followLinks: false))) - - // Test FileSystemEntity.identical on files, directories, and links, - // reached by different paths. - .then( - (_) => FutureExpect.isTrue(FileSystemEntity.identical(createdDirectly, createdDirectly))) - .then((_) => FutureExpect.isFalse(FileSystemEntity.identical(createdDirectly, createdThroughLink))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.identical(createdDirectly, join(base, 'link', 'createdDirectly')))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.identical(createdThroughLink, join(base, 'target', 'createdThroughLink')))) - .then((_) => FutureExpect.isFalse(FileSystemEntity.identical(target, link))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.identical(link, link))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.identical(target, target))) - .then((_) => new Link(link).target()) - .then((linkTarget) => FutureExpect.isTrue(FileSystemEntity.identical(target, linkTarget))) - .then((_) => new File(".").resolveSymbolicLinks()) - .then((fullCurrentDir) => FutureExpect.isTrue(FileSystemEntity.identical(".", fullCurrentDir))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.identical(createdFile, createdFile))) - .then((_) => FutureExpect.isFalse(FileSystemEntity.identical(createdFile, createdDirectly))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.identical(createdFile, join(base, 'link', 'createdFile')))) - .then((_) => FutureExpect.throws(FileSystemEntity.identical(createdFile, join(base, 'link', 'does_not_exist')))) - .then((_) => testDirectoryListing(base, baseDir)) - .then((_) => new Directory(target).delete(recursive: true)) - .then((_) { - var futures = []; - for (bool recursive in [true, false]) { - for (bool followLinks in [true, false]) { - var result = baseDir.listSync( - recursive: recursive, followLinks: followLinks); - Expect.equals(1, result.length); - Expect.isTrue(result[0] is Link); - futures.add(FutureExpect.isTrue(baseDir - .list(recursive: recursive, followLinks: followLinks) - .single - .then((element) => element is Link))); - } - } - return Future.wait(futures); - }).then((_) => baseDir.delete(recursive: true)); - }); + String createdThroughLink = join(base, 'link', 'createdThroughLink'); + String createdDirectly = join(base, 'target', 'createdDirectly'); + String createdFile = join(base, 'link', 'createdFile'); + return new Directory(createdThroughLink) + .create() + .then((_) => new Directory(createdDirectly).create()) + .then((_) => new File(createdFile).create()) + .then( + (_) => FutureExpect.isTrue( + new Directory(createdThroughLink).exists(), + ), + ) + .then( + (_) => FutureExpect.isTrue( + new Directory(createdDirectly).exists(), + ), + ) + .then( + (_) => FutureExpect.isTrue( + new Directory(join(base, 'link', 'createdDirectly')).exists(), + ), + ) + .then( + (_) => FutureExpect.isTrue( + new Directory( + join(base, 'target', 'createdThroughLink'), + ).exists(), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(createdThroughLink, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(createdDirectly, followLinks: false), + ), + ) + // Test FileSystemEntity.identical on files, directories, and links, + // reached by different paths. + .then( + (_) => FutureExpect.isTrue( + FileSystemEntity.identical(createdDirectly, createdDirectly), + ), + ) + .then( + (_) => FutureExpect.isFalse( + FileSystemEntity.identical( + createdDirectly, + createdThroughLink, + ), + ), + ) + .then( + (_) => FutureExpect.isTrue( + FileSystemEntity.identical( + createdDirectly, + join(base, 'link', 'createdDirectly'), + ), + ), + ) + .then( + (_) => FutureExpect.isTrue( + FileSystemEntity.identical( + createdThroughLink, + join(base, 'target', 'createdThroughLink'), + ), + ), + ) + .then( + (_) => FutureExpect.isFalse( + FileSystemEntity.identical(target, link), + ), + ) + .then( + (_) => + FutureExpect.isTrue(FileSystemEntity.identical(link, link)), + ) + .then( + (_) => FutureExpect.isTrue( + FileSystemEntity.identical(target, target), + ), + ) + .then((_) => new Link(link).target()) + .then( + (linkTarget) => FutureExpect.isTrue( + FileSystemEntity.identical(target, linkTarget), + ), + ) + .then((_) => new File(".").resolveSymbolicLinks()) + .then( + (fullCurrentDir) => FutureExpect.isTrue( + FileSystemEntity.identical(".", fullCurrentDir), + ), + ) + .then( + (_) => FutureExpect.isTrue( + FileSystemEntity.identical(createdFile, createdFile), + ), + ) + .then( + (_) => FutureExpect.isFalse( + FileSystemEntity.identical(createdFile, createdDirectly), + ), + ) + .then( + (_) => FutureExpect.isTrue( + FileSystemEntity.identical( + createdFile, + join(base, 'link', 'createdFile'), + ), + ), + ) + .then( + (_) => FutureExpect.throws( + FileSystemEntity.identical( + createdFile, + join(base, 'link', 'does_not_exist'), + ), + ), + ) + .then((_) => testDirectoryListing(base, baseDir)) + .then((_) => new Directory(target).delete(recursive: true)) + .then((_) { + var futures = []; + for (bool recursive in [true, false]) { + for (bool followLinks in [true, false]) { + var result = baseDir.listSync( + recursive: recursive, + followLinks: followLinks, + ); + Expect.equals(1, result.length); + Expect.isTrue(result[0] is Link); + futures.add( + FutureExpect.isTrue( + baseDir + .list( + recursive: recursive, + followLinks: followLinks, + ) + .single + .then((element) => element is Link), + ), + ); + } + } + return Future.wait(futures); + }) + .then((_) => baseDir.delete(recursive: true)); + }); }); } @@ -121,56 +234,78 @@ Future testCreateLoopingLink(_) { return Directory.systemTemp .createTemp('dart_link_async') .then((dir) => dir.path) - .then((String base) => new Directory(join(base, 'a', 'b', 'c')) - .create(recursive: true) - .then((_) => new Link(join(base, 'a', 'b', 'c', 'd')) - .create(join(base, 'a', 'b'))) - .then((_) => - new Link(join(base, 'a', 'b', 'c', 'e')).create(join(base, 'a'))) - .then((_) => new Directory(join(base, 'a')) - .list(recursive: true, followLinks: false) - .last) - // This directory listing must terminate, even though it contains loops. - .then((_) => new Directory(join(base, 'a')) - .list(recursive: true, followLinks: true) - .last) - // This directory listing must terminate, even though it contains loops. - .then((_) => new Directory(join(base, 'a', 'b', 'c')) - .list(recursive: true, followLinks: true) - .last) - .then((_) => new Directory(base).delete(recursive: true)) - .then((_) => FutureExpect.isFalse(new Directory(base).exists()))); + .then( + (String base) => new Directory(join(base, 'a', 'b', 'c')) + .create(recursive: true) + .then( + (_) => new Link( + join(base, 'a', 'b', 'c', 'd'), + ).create(join(base, 'a', 'b')), + ) + .then( + (_) => new Link( + join(base, 'a', 'b', 'c', 'e'), + ).create(join(base, 'a')), + ) + .then( + (_) => new Directory( + join(base, 'a'), + ).list(recursive: true, followLinks: false).last, + ) + // This directory listing must terminate, even though it contains loops. + .then( + (_) => new Directory( + join(base, 'a'), + ).list(recursive: true, followLinks: true).last, + ) + // This directory listing must terminate, even though it contains loops. + .then( + (_) => new Directory( + join(base, 'a', 'b', 'c'), + ).list(recursive: true, followLinks: true).last, + ) + .then((_) => new Directory(base).delete(recursive: true)) + .then((_) => FutureExpect.isFalse(new Directory(base).exists())), + ); } Future testRename(_) { Future testRename(String base, String target) { late Link link1; late Link link2; - return new Link(join(base, 'c')).create(target).then((link) { - link1 = link; - Expect.isTrue(link1.existsSync()); - return link1.rename(join(base, 'd')); - }).then((link) { - link2 = link; - Expect.isFalse(link1.existsSync()); - Expect.isTrue(link2.existsSync()); - return link2.delete(); - }).then((_) => Expect.isFalse(link2.existsSync())); + return new Link(join(base, 'c')) + .create(target) + .then((link) { + link1 = link; + Expect.isTrue(link1.existsSync()); + return link1.rename(join(base, 'd')); + }) + .then((link) { + link2 = link; + Expect.isFalse(link1.existsSync()); + Expect.isTrue(link2.existsSync()); + return link2.delete(); + }) + .then((_) => Expect.isFalse(link2.existsSync())); } Future testUpdate(String base, String target1, String target2) { late Link link1; - return new Link(join(base, 'c')).create(target1).then((link) { - link1 = link; - Expect.isTrue(link1.existsSync()); - return link1.update(target2); - }).then((Link link) { - Expect.isTrue(link1.existsSync()); - Expect.isTrue(link.existsSync()); - return FutureExpect.equals(target2, link.target()) - .then((_) => FutureExpect.equals(target2, link1.target())) - .then((_) => link.delete()); - }).then((_) => Expect.isFalse(link1.existsSync())); + return new Link(join(base, 'c')) + .create(target1) + .then((link) { + link1 = link; + Expect.isTrue(link1.existsSync()); + return link1.update(target2); + }) + .then((Link link) { + Expect.isTrue(link1.existsSync()); + Expect.isTrue(link.existsSync()); + return FutureExpect.equals(target2, link.target()) + .then((_) => FutureExpect.equals(target2, link1.target())) + .then((_) => link.delete()); + }) + .then((_) => Expect.isFalse(link1.existsSync())); } return Directory.systemTemp.createTemp('dart_link_async').then((baseDir) { @@ -221,22 +356,26 @@ Future testDirectoryListing(String base, Directory baseDir) { for (bool recursive in [true, false]) { for (bool followLinks in [true, false]) { Map expected = makeExpected(recursive, followLinks); - for (var x - in baseDir.listSync(recursive: recursive, followLinks: followLinks)) { + for (var x in baseDir.listSync( + recursive: recursive, + followLinks: followLinks, + )) { checkEntity(x, expected); } for (var v in expected.values) { Expect.equals('Found', v); } expected = makeExpected(recursive, followLinks); - futures.add(baseDir - .list(recursive: recursive, followLinks: followLinks) - .forEach((entity) => checkEntity(entity, expected)) - .then((_) { - for (var v in expected.values) { - Expect.equals('Found', v); - } - })); + futures.add( + baseDir + .list(recursive: recursive, followLinks: followLinks) + .forEach((entity) => checkEntity(entity, expected)) + .then((_) { + for (var v in expected.values) { + Expect.equals('Found', v); + } + }), + ); } } return Future.wait(futures); @@ -246,9 +385,9 @@ Future checkExists(String filePath) => new File(filePath).exists().then(Expect.isTrue); Future testRelativeLinks(_) { - return Directory.systemTemp - .createTemp('dart_link_async') - .then((tempDirectory) { + return Directory.systemTemp.createTemp('dart_link_async').then(( + tempDirectory, + ) { String temp = tempDirectory.path; String oldWorkingDirectory = Directory.current.path; // Make directories and files to test links. @@ -264,9 +403,13 @@ Future testRelativeLinks(_) { .then((_) => Directory.current = 'dir1') .then((_) => new Link(join('..', 'link0_1')).create('dir1')) .then( - (_) => new Link(join('dir2', 'link2_1')).create(join(temp, 'dir1'))) - .then((_) => new Link(join(temp, 'dir1', 'dir2', 'link2_0')) - .create(join('..', '..'))) + (_) => new Link(join('dir2', 'link2_1')).create(join(temp, 'dir1')), + ) + .then( + (_) => new Link( + join(temp, 'dir1', 'dir2', 'link2_0'), + ).create(join('..', '..')), + ) // Test that the links go to the right targets. .then((_) => checkExists(join('..', 'link0_1', 'file1'))) .then((_) => checkExists(join('..', 'link0_2', 'file2'))) @@ -281,13 +424,16 @@ Future testRelativeLinks(_) { } Future testRelativeLinkToDirectoryNotRelativeToCurrentWorkingDirectory( - _) async { + _, +) async { final tempDirectory = await Directory.systemTemp.createTemp('dart_link'); - final dir2 = await Directory(join(tempDirectory.path, 'dir1', 'dir2')) - .create(recursive: true); + final dir2 = await Directory( + join(tempDirectory.path, 'dir1', 'dir2'), + ).create(recursive: true); - final link = - await Link(join(tempDirectory.path, 'link')).create(join('dir1', 'dir2')); + final link = await Link( + join(tempDirectory.path, 'link'), + ).create(join('dir1', 'dir2')); String resolvedDir2Path = await link.resolveSymbolicLinks(); Expect.isTrue(await FileSystemEntity.identical(dir2.path, resolvedDir2Path)); @@ -300,11 +446,15 @@ Future testBrokenLinkType(_) async { String link = join(base, 'link'); await Link(link).create('does not exist'); - Expect.equals(FileSystemEntityType.link, - await FileSystemEntity.type(link, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + await FileSystemEntity.type(link, followLinks: false), + ); - Expect.equals(FileSystemEntityType.notFound, - await FileSystemEntity.type(link, followLinks: true)); + Expect.equals( + FileSystemEntityType.notFound, + await FileSystemEntity.type(link, followLinks: true), + ); } Future testTopLevelLink(_) async { diff --git a/tests/standalone/io/link_test.dart b/tests/standalone/io/link_test.dart index 3a340f90248..460705fea6c 100644 --- a/tests/standalone/io/link_test.dart +++ b/tests/standalone/io/link_test.dart @@ -15,21 +15,30 @@ testCreateSync() { String base = Directory.systemTemp.createTempSync('dart_link').path; if (isRelative(base)) { Expect.fail( - 'Link tests expect absolute paths to system temporary directories. ' - 'A relative path in TMPDIR gives relative paths to them.'); + 'Link tests expect absolute paths to system temporary directories. ' + 'A relative path in TMPDIR gives relative paths to them.', + ); } String link = join(base, 'link'); String target = join(base, 'target'); new Directory(target).createSync(); new Link(link).createSync(target); Expect.equals( - FileSystemEntityType.directory, FileSystemEntity.typeSync(link)); + FileSystemEntityType.directory, + FileSystemEntity.typeSync(link), + ); Expect.equals( - FileSystemEntityType.directory, FileSystemEntity.typeSync(target)); - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(link, followLinks: false)); - Expect.equals(FileSystemEntityType.directory, - FileSystemEntity.typeSync(target, followLinks: false)); + FileSystemEntityType.directory, + FileSystemEntity.typeSync(target), + ); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(link, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(target, followLinks: false), + ); Expect.isTrue(FileSystemEntity.isLinkSync(link)); Expect.isFalse(FileSystemEntity.isLinkSync(target)); Expect.isTrue(new Directory(link).existsSync()); @@ -46,30 +55,47 @@ testCreateSync() { Expect.isTrue(new Directory(createdThroughLink).existsSync()); Expect.isTrue(new Directory(createdDirectly).existsSync()); Expect.isTrue( - new Directory(join(base, 'link', 'createdDirectly')).existsSync()); + new Directory(join(base, 'link', 'createdDirectly')).existsSync(), + ); Expect.isTrue( - new Directory(join(base, 'target', 'createdThroughLink')).existsSync()); - Expect.equals(FileSystemEntityType.directory, - FileSystemEntity.typeSync(createdThroughLink, followLinks: false)); - Expect.equals(FileSystemEntityType.directory, - FileSystemEntity.typeSync(createdDirectly, followLinks: false)); + new Directory(join(base, 'target', 'createdThroughLink')).existsSync(), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(createdThroughLink, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(createdDirectly, followLinks: false), + ); // Test FileSystemEntity.identical on files, directories, and links, // reached by different paths. Expect.isTrue( - FileSystemEntity.identicalSync(createdDirectly, createdDirectly)); + FileSystemEntity.identicalSync(createdDirectly, createdDirectly), + ); Expect.isFalse( - FileSystemEntity.identicalSync(createdDirectly, createdThroughLink)); - Expect.isTrue(FileSystemEntity.identicalSync( - createdDirectly, join(base, 'link', 'createdDirectly'))); - Expect.isTrue(FileSystemEntity.identicalSync( - createdThroughLink, join(base, 'target', 'createdThroughLink'))); + FileSystemEntity.identicalSync(createdDirectly, createdThroughLink), + ); + Expect.isTrue( + FileSystemEntity.identicalSync( + createdDirectly, + join(base, 'link', 'createdDirectly'), + ), + ); + Expect.isTrue( + FileSystemEntity.identicalSync( + createdThroughLink, + join(base, 'target', 'createdThroughLink'), + ), + ); Expect.isFalse(FileSystemEntity.identicalSync(target, link)); Expect.isTrue(FileSystemEntity.identicalSync(link, link)); Expect.isTrue(FileSystemEntity.identicalSync(target, target)); Expect.isTrue( - FileSystemEntity.identicalSync(target, new Link(link).targetSync())); + FileSystemEntity.identicalSync(target, new Link(link).targetSync()), + ); String absolutePath = new File(".").resolveSymbolicLinksSync(); Expect.isTrue(FileSystemEntity.identicalSync(".", absolutePath)); @@ -77,10 +103,18 @@ testCreateSync() { new File(createdFile).createSync(); Expect.isTrue(FileSystemEntity.identicalSync(createdFile, createdFile)); Expect.isFalse(FileSystemEntity.identicalSync(createdFile, createdDirectly)); - Expect.isTrue(FileSystemEntity.identicalSync( - createdFile, join(base, 'link', 'createdFile'))); - Expect.throws(() => FileSystemEntity.identicalSync( - createdFile, join(base, 'link', 'does_not_exist'))); + Expect.isTrue( + FileSystemEntity.identicalSync( + createdFile, + join(base, 'link', 'createdFile'), + ), + ); + Expect.throws( + () => FileSystemEntity.identicalSync( + createdFile, + join(base, 'link', 'does_not_exist'), + ), + ); var baseDir = new Directory(base); @@ -112,8 +146,10 @@ testCreateSync() { for (bool recursive in [true, false]) { for (bool followLinks in [true, false]) { Map expected = makeExpected(recursive, followLinks); - for (var x - in baseDir.listSync(recursive: recursive, followLinks: followLinks)) { + for (var x in baseDir.listSync( + recursive: recursive, + followLinks: followLinks, + )) { checkEntity(x, expected); } for (var v in expected.values) { @@ -124,23 +160,29 @@ testCreateSync() { // a future that completes when done. var f = new Completer(); futures.add(f.future); - baseDir.list(recursive: recursive, followLinks: followLinks).listen( - (entity) { - checkEntity(entity, expected); - }, onDone: () { - for (var v in expected.values) { - Expect.equals('Found', v); - } - f.complete(null); - }); + baseDir + .list(recursive: recursive, followLinks: followLinks) + .listen( + (entity) { + checkEntity(entity, expected); + }, + onDone: () { + for (var v in expected.values) { + Expect.equals('Found', v); + } + f.complete(null); + }, + ); } } Future.wait(futures).then((_) { new Directory(target).deleteSync(recursive: true); for (bool recursive in [true, false]) { for (bool followLinks in [true, false]) { - var result = - baseDir.listSync(recursive: recursive, followLinks: followLinks); + var result = baseDir.listSync( + recursive: recursive, + followLinks: followLinks, + ); Expect.equals(1, result.length); Expect.isTrue(result[0] is Link); } @@ -155,27 +197,37 @@ testCreateLoopingLink() { String base = Directory.systemTemp.createTempSync('dart_link').path; new Directory(join(base, 'a', 'b', 'c')) .create(recursive: true) - .then((_) => - new Link(join(base, 'a', 'b', 'c', 'd')).create(join(base, 'a', 'b'))) - .then((_) => - new Link(join(base, 'a', 'b', 'c', 'e')).create(join(base, 'a'))) - .then((_) => new Directory(join(base, 'a')) - .list(recursive: true, followLinks: false) - .last) - .then((_) => - // This directory listing must terminate, even though it contains loops. - new Directory(join(base, 'a')) - .list(recursive: true, followLinks: true) - .last) - .then((_) => - // This directory listing must terminate, even though it contains loops. - new Directory(join(base, 'a', 'b', 'c')) - .list(recursive: true, followLinks: true) - .last) + .then( + (_) => new Link( + join(base, 'a', 'b', 'c', 'd'), + ).create(join(base, 'a', 'b')), + ) + .then( + (_) => new Link(join(base, 'a', 'b', 'c', 'e')).create(join(base, 'a')), + ) + .then( + (_) => new Directory( + join(base, 'a'), + ).list(recursive: true, followLinks: false).last, + ) + .then( + (_) => + // This directory listing must terminate, even though it contains loops. + new Directory( + join(base, 'a'), + ).list(recursive: true, followLinks: true).last, + ) + .then( + (_) => + // This directory listing must terminate, even though it contains loops. + new Directory( + join(base, 'a', 'b', 'c'), + ).list(recursive: true, followLinks: true).last, + ) .whenComplete(() { - new Directory(base).deleteSync(recursive: true); - asyncEnd(); - }); + new Directory(base).deleteSync(recursive: true); + asyncEnd(); + }); } testRenameSync() { @@ -207,8 +259,10 @@ testRenameSync() { try { Link renamed = link.renameSync(target); if (isDirectory) { - Expect.fail('Renaming a link to the name of an existing directory ' + - 'should fail'); + Expect.fail( + 'Renaming a link to the name of an existing directory ' + + 'should fail', + ); } Expect.isTrue(renamed.existsSync()); renamed.deleteSync(); @@ -216,8 +270,9 @@ testRenameSync() { if (isDirectory) { return; } - Expect.fail('Renaming a link to the name of an existing file should ' + - 'not fail'); + Expect.fail( + 'Renaming a link to the name of an existing file should ' + 'not fail', + ); } } @@ -239,9 +294,11 @@ testRenameSync() { void testLinkErrorSync() { Expect.throws( - () => new Link('some-dir-that-does-not exist/some link file/bla/fisk') - .createSync('bla bla bla/b lalal/blfir/sdfred/es'), - (e) => e is PathNotFoundException); + () => new Link( + 'some-dir-that-does-not exist/some link file/bla/fisk', + ).createSync('bla bla bla/b lalal/blfir/sdfred/es'), + (e) => e is PathNotFoundException, + ); } checkExists(String filePath) => Expect.isTrue(new File(filePath).existsSync()); @@ -333,11 +390,15 @@ testBrokenLinkTypeSync() { String link = join(base, 'link'); Link(link).createSync('does not exist'); - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(link, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(link, followLinks: false), + ); - Expect.equals(FileSystemEntityType.notFound, - FileSystemEntity.typeSync(link, followLinks: true)); + Expect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.typeSync(link, followLinks: true), + ); } void testTopLevelLinkSync() { diff --git a/tests/standalone/io/link_uri_test.dart b/tests/standalone/io/link_uri_test.dart index fe781900a52..884d3d99ef3 100644 --- a/tests/standalone/io/link_uri_test.dart +++ b/tests/standalone/io/link_uri_test.dart @@ -35,11 +35,14 @@ void testFromUri() { void testFromUriUnsupported() { Expect.throwsUnsupportedError( - () => new Link.fromUri(Uri.parse('http://localhost:8080/index.html'))); + () => new Link.fromUri(Uri.parse('http://localhost:8080/index.html')), + ); Expect.throwsUnsupportedError( - () => new Link.fromUri(Uri.parse('ftp://localhost/tmp/xxx'))); + () => new Link.fromUri(Uri.parse('ftp://localhost/tmp/xxx')), + ); Expect.throwsUnsupportedError( - () => new Link.fromUri(Uri.parse('name#fragment'))); + () => new Link.fromUri(Uri.parse('name#fragment')), + ); } void main() { diff --git a/tests/standalone/io/named_pipe_operations_test.dart b/tests/standalone/io/named_pipe_operations_test.dart index f9ee7723066..269a4373410 100644 --- a/tests/standalone/io/named_pipe_operations_test.dart +++ b/tests/standalone/io/named_pipe_operations_test.dart @@ -17,12 +17,13 @@ startProcess(Directory dir, String fname, String script, String result) async { file.writeAsString(script); StringBuffer output = new StringBuffer(); Process process = await Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--sound-null-safety') - ..add('--verbosity=warning') - ..add(file.path)); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--sound-null-safety') + ..add('--verbosity=warning') + ..add(file.path), + ); bool stdinWriteFailed = false; process.stdout.transform(utf8.decoder).listen(output.write); process.stderr.transform(utf8.decoder).listen((data) { @@ -58,7 +59,8 @@ main() async { Directory directory = Directory.systemTemp.createTempSync('named_pipe'); - final String delScript = ''' + final String delScript = + ''' import "dart:io"; main() { try { @@ -72,7 +74,8 @@ main() async { } '''; - final String renameScript = ''' + final String renameScript = + ''' import "dart:io"; main() { try { @@ -86,7 +89,8 @@ main() async { } '''; - final String copyScript = ''' + final String copyScript = + ''' import "dart:io"; main() { try { @@ -110,7 +114,11 @@ main() async { await startProcess(directory, 'delscript', delScript, "Cannot delete file"); await startProcess( - directory, 'renamescript', renameScript, "Cannot rename file"); + directory, + 'renamescript', + renameScript, + "Cannot rename file", + ); await startProcess(directory, 'copyscript', copyScript, "Cannot copy file"); directory.deleteSync(recursive: true); diff --git a/tests/standalone/io/named_pipe_script_test.dart b/tests/standalone/io/named_pipe_script_test.dart index 9ea46756498..41dd1029560 100644 --- a/tests/standalone/io/named_pipe_script_test.dart +++ b/tests/standalone/io/named_pipe_script_test.dart @@ -35,12 +35,13 @@ main() async { StringBuffer output = new StringBuffer(); Process process = await Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--sound-null-safety') - ..add('--verbosity=warning') - ..add(stdinPipePath)); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--sound-null-safety') + ..add('--verbosity=warning') + ..add(stdinPipePath), + ); bool stdinWriteFailed = false; process.stdout.transform(utf8.decoder).listen(output.write); process.stderr.transform(utf8.decoder).listen((data) { diff --git a/tests/standalone/io/named_pipe_type_test.dart b/tests/standalone/io/named_pipe_type_test.dart index 0b31a421e62..7d8d5e869b1 100644 --- a/tests/standalone/io/named_pipe_type_test.dart +++ b/tests/standalone/io/named_pipe_type_test.dart @@ -21,7 +21,8 @@ main() async { Directory dir = Directory.systemTemp.createTempSync('named_pipe'); final String stdinPipePath = '/dev/fd/0'; - final String script = ''' + final String script = + ''' import "dart:io"; main() { FileStat fileStat = FileStat.statSync("$stdinPipePath"); diff --git a/tests/standalone/io/namespace_test.dart b/tests/standalone/io/namespace_test.dart index f460b04089e..3a29f0e0526 100644 --- a/tests/standalone/io/namespace_test.dart +++ b/tests/standalone/io/namespace_test.dart @@ -196,7 +196,7 @@ void setupTest() { args.addAll([ "--namespace=${namespace.path}", Platform.script.toFilePath(), - "--run" + "--run", ]); var pr = Process.runSync(Platform.executable, args); if (pr.exitCode != 0) { diff --git a/tests/standalone/io/non_utf8_directory_test.dart b/tests/standalone/io/non_utf8_directory_test.dart index 0dea9aa3f00..c9167154b99 100644 --- a/tests/standalone/io/non_utf8_directory_test.dart +++ b/tests/standalone/io/non_utf8_directory_test.dart @@ -13,8 +13,9 @@ Future main() async { var syncDir; test('Non-UTF8 Directory Listing', () async { - final tmp = - await Directory.systemTemp.createTemp('non_utf8_directory_test_async'); + final tmp = await Directory.systemTemp.createTemp( + 'non_utf8_directory_test_async', + ); try { final rawPath = new Uint8List.fromList([182]); asyncDir = new Directory.fromRawPath(rawPath); @@ -51,8 +52,9 @@ Future main() async { }); test('Non-UTF8 Directory Sync Listing', () { - final tmp = - Directory.systemTemp.createTempSync('non_utf8_directory_test_sync'); + final tmp = Directory.systemTemp.createTempSync( + 'non_utf8_directory_test_sync', + ); try { final rawPath = new Uint8List.fromList([182]); syncDir = new Directory.fromRawPath(rawPath); diff --git a/tests/standalone/io/non_utf8_file_test.dart b/tests/standalone/io/non_utf8_file_test.dart index 4ea6ed4705f..50354d170e2 100644 --- a/tests/standalone/io/non_utf8_file_test.dart +++ b/tests/standalone/io/non_utf8_file_test.dart @@ -13,8 +13,9 @@ Future main() async { var syncFile; test('Non-UTF8 Filename', () async { - final tmp = - await Directory.systemTemp.createTemp('non_utf8_file_test_async'); + final tmp = await Directory.systemTemp.createTemp( + 'non_utf8_file_test_async', + ); try { final rawPath = new Uint8List.fromList([182]); asyncFile = new File.fromRawPath(rawPath); diff --git a/tests/standalone/io/non_utf8_link_test.dart b/tests/standalone/io/non_utf8_link_test.dart index aadd30a1184..ee581656815 100644 --- a/tests/standalone/io/non_utf8_link_test.dart +++ b/tests/standalone/io/non_utf8_link_test.dart @@ -16,13 +16,16 @@ Future main() async { const dirName = 'foobar'; test('Non-UTF8 Link', () async { - Directory tmp = - await Directory.systemTemp.createTemp('non_utf8_link_test_async'); + Directory tmp = await Directory.systemTemp.createTemp( + 'non_utf8_link_test_async', + ); try { tmp = new Directory(await tmp.resolveSymbolicLinks()); final path = join(tmp.path, dirName); - final rawPath = - utf8.encode(path).sublist(0, path.length - dirName.length).toList(); + final rawPath = utf8 + .encode(path) + .sublist(0, path.length - dirName.length) + .toList(); rawPath.add(47); rawPath.add(182); @@ -74,13 +77,16 @@ Future main() async { }); test('Non-UTF8 Link Sync', () { - Directory tmp = - Directory.systemTemp.createTempSync('non_utf8_link_test_sync'); + Directory tmp = Directory.systemTemp.createTempSync( + 'non_utf8_link_test_sync', + ); try { tmp = new Directory(tmp.resolveSymbolicLinksSync()); final path = join(tmp.path, dirName); - final rawPath = - utf8.encode(path).sublist(0, path.length - dirName.length).toList(); + final rawPath = utf8 + .encode(path) + .sublist(0, path.length - dirName.length) + .toList(); rawPath.add(47); // '/' rawPath.add(182); // invalid UTF-8 character. diff --git a/tests/standalone/io/parent_test.dart b/tests/standalone/io/parent_test.dart index 763517610c9..eec39b858fc 100644 --- a/tests/standalone/io/parent_test.dart +++ b/tests/standalone/io/parent_test.dart @@ -51,7 +51,9 @@ testPosixCases() { Expect.equals('dir/subdir', FileSystemEntity.parentOf('dir/subdir/file')); Expect.equals('dir//subdir', FileSystemEntity.parentOf('dir//subdir//file/')); Expect.equals( - 'dir/sub.dir', FileSystemEntity.parentOf('dir/sub.dir/fi le///')); + 'dir/sub.dir', + FileSystemEntity.parentOf('dir/sub.dir/fi le///'), + ); Expect.equals('dir/..', FileSystemEntity.parentOf('dir/../file/')); Expect.equals('dir/..', FileSystemEntity.parentOf('dir/../..')); Expect.equals('.', FileSystemEntity.parentOf('./..')); @@ -70,12 +72,18 @@ testWindowsCases() { // FileSystemEntity.isAbsolute returns false for 'C:'. Expect.equals(r'.', FileSystemEntity.parentOf(r'C:')); - Expect.equals(r'\\server\share\dir', - FileSystemEntity.parentOf(r'\\server\share\dir\file')); - Expect.equals(r'\\server\share\dir', - FileSystemEntity.parentOf(r'\\server\share\dir\file\')); Expect.equals( - r'\\server\share', FileSystemEntity.parentOf(r'\\server\share\file')); + r'\\server\share\dir', + FileSystemEntity.parentOf(r'\\server\share\dir\file'), + ); + Expect.equals( + r'\\server\share\dir', + FileSystemEntity.parentOf(r'\\server\share\dir\file\'), + ); + Expect.equals( + r'\\server\share', + FileSystemEntity.parentOf(r'\\server\share\file'), + ); Expect.equals(r'\\server\', FileSystemEntity.parentOf(r'\\server\share')); Expect.equals(r'\\server\', FileSystemEntity.parentOf(r'\\server\share\')); Expect.equals(r'\\server\', FileSystemEntity.parentOf(r'\\server\')); @@ -95,7 +103,9 @@ testWindowsCases() { Expect.equals(r'dir', FileSystemEntity.parentOf(r'dir/file/')); Expect.equals(r'dir\subdir', FileSystemEntity.parentOf(r'dir\subdir\file')); Expect.equals( - r'dir\sub.dir', FileSystemEntity.parentOf(r'dir\sub.dir\fi le')); + r'dir\sub.dir', + FileSystemEntity.parentOf(r'dir\sub.dir\fi le'), + ); } Future createTempDirectories() { @@ -115,5 +125,7 @@ testPath(String path) { Expect.equals(tempDirectory, new File(join(tempDirectory, path)).parent.path); Expect.equals(tempDirectory, new Link(join(tempDirectory, path)).parent.path); Expect.equals( - tempDirectory, new Directory(join(tempDirectory, path)).parent.path); + tempDirectory, + new Directory(join(tempDirectory, path)).parent.path, + ); } diff --git a/tests/standalone/io/platform_locale_name_test.dart b/tests/standalone/io/platform_locale_name_test.dart index 2cd23f5815a..80019a29468 100644 --- a/tests/standalone/io/platform_locale_name_test.dart +++ b/tests/standalone/io/platform_locale_name_test.dart @@ -16,7 +16,8 @@ main() { var localePattern = RegExp(r"([A-Za-z]{2,4}([_-][A-Za-z]{2})?)|(C\.)"); var localeName = Platform.localeName; Expect.isNotNull( - localePattern.matchAsPrefix(localeName), - "Platform.localeName: ${localeName} does not match " - "${localePattern.pattern}"); + localePattern.matchAsPrefix(localeName), + "Platform.localeName: ${localeName} does not match " + "${localePattern.pattern}", + ); } diff --git a/tests/standalone/io/platform_test.dart b/tests/standalone/io/platform_test.dart index 7e4c6355359..08904d15c04 100644 --- a/tests/standalone/io/platform_test.dart +++ b/tests/standalone/io/platform_test.dart @@ -25,7 +25,8 @@ test() { Expect.isTrue(Platform.numberOfProcessors > 0); var os = Platform.operatingSystem; Expect.isTrue( - os == "android" || os == "linux" || os == "macos" || os == "windows"); + os == "android" || os == "linux" || os == "macos" || os == "windows", + ); Expect.equals(Platform.isLinux, Platform.operatingSystem == "linux"); Expect.equals(Platform.isMacOS, Platform.operatingSystem == "macos"); Expect.equals(Platform.isWindows, Platform.operatingSystem == "windows"); @@ -58,8 +59,9 @@ test() { var oldDir = Directory.current; Directory.current = Directory.current.parent; if (isRunningFromSource()) { - Expect.isTrue(Platform.script.path - .endsWith('tests/standalone/io/platform_test.dart')); + Expect.isTrue( + Platform.script.path.endsWith('tests/standalone/io/platform_test.dart'), + ); Expect.isTrue(Platform.script.toFilePath().startsWith(oldDir.path)); } } @@ -68,7 +70,7 @@ void f(reply) { reply.send({ "Platform.executable": Platform.executable, "Platform.script": Platform.script, - "Platform.executableArguments": Platform.executableArguments + "Platform.executableArguments": Platform.executableArguments, }); } @@ -85,10 +87,13 @@ testIsolate() { Expect.equals("file", uri.scheme); if (isRunningFromSource()) { Expect.isTrue( - uri.path.endsWith('tests/standalone/io/platform_test.dart')); + uri.path.endsWith('tests/standalone/io/platform_test.dart'), + ); } Expect.listEquals( - Platform.executableArguments, results["Platform.executableArguments"]); + Platform.executableArguments, + results["Platform.executableArguments"], + ); asyncEnd(); }); } @@ -142,8 +147,11 @@ testVersion() { checkValidVersion('1.9.0-edge'); checkValidVersion('1.9.0-edge.r41234'); // Check stripping of additional information. - checkValidVersion(stripAdditionalInfo( - '1.9.0-dev.1.2 (Wed Feb 25 02:22:19 2015) on "linux_ia32"')); + checkValidVersion( + stripAdditionalInfo( + '1.9.0-dev.1.2 (Wed Feb 25 02:22:19 2015) on "linux_ia32"', + ), + ); // Reject some invalid versions. checkInvalidVersion('1.9'); checkInvalidVersion('..'); diff --git a/tests/standalone/io/print_sync_test.dart b/tests/standalone/io/print_sync_test.dart index 976ea87bab7..2c34cb30788 100644 --- a/tests/standalone/io/print_sync_test.dart +++ b/tests/standalone/io/print_sync_test.dart @@ -12,13 +12,12 @@ import "package:expect/expect.dart"; void main() { asyncStart(); Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add( - Platform.script.resolve('print_sync_script.dart').toFilePath())) - .then((out) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(Platform.script.resolve('print_sync_script.dart').toFilePath()), + ).then((out) { asyncEnd(); Expect.equals(1002, out.stdout.split('\n').length); }); diff --git a/tests/standalone/io/print_test.dart b/tests/standalone/io/print_test.dart index 40a5715154b..c17ba05d3f1 100644 --- a/tests/standalone/io/print_test.dart +++ b/tests/standalone/io/print_test.dart @@ -19,17 +19,19 @@ final nl = Platform.isWindows ? [13, 10] : [10]; /// the commands stdout as a list of bytes. List runTest(String command) { final result = Process.runSync( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(Platform.script.resolve('print_test_script.dart').toFilePath()) - ..add(command), - stdoutEncoding: null); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(Platform.script.resolve('print_test_script.dart').toFilePath()) + ..add(command), + stdoutEncoding: null, + ); if (result.exitCode != 0) { throw AssertionError( - 'unexpected exit code for command $command: ${result.stderr}'); + 'unexpected exit code for command $command: ${result.stderr}', + ); } return result.stdout; } @@ -57,7 +59,9 @@ void testStringCarriageReturnLinefeeds() { // Notice on Windows this will result in `\r\n` => `\r\r\n' final expected = [108, 49, 13, ...nl, 108, 50, 13, ...nl, 108, 51, 13, ...nl]; Expect.listEquals( - expected, runTest("string-internal-carriagereturn-linefeeds")); + expected, + runTest("string-internal-carriagereturn-linefeeds"), + ); } void testObjectInternalLineEnding() { diff --git a/tests/standalone/io/process_check_arguments_script.dart b/tests/standalone/io/process_check_arguments_script.dart index 4c19479fc71..1560ffbff4e 100644 --- a/tests/standalone/io/process_check_arguments_script.dart +++ b/tests/standalone/io/process_check_arguments_script.dart @@ -23,7 +23,8 @@ class Expect { main(List arguments) { Expect.isTrue( - Platform.script.path.endsWith('process_check_arguments_script.dart')); + Platform.script.path.endsWith('process_check_arguments_script.dart'), + ); var expected_num_args = int.parse(arguments[0]); var contains_quote = int.parse(arguments[1]); Expect.equals(expected_num_args, arguments.length); diff --git a/tests/standalone/io/process_check_arguments_test.dart b/tests/standalone/io/process_check_arguments_test.dart index 9922dc14ddc..35c353300d1 100644 --- a/tests/standalone/io/process_check_arguments_test.dart +++ b/tests/standalone/io/process_check_arguments_test.dart @@ -7,8 +7,12 @@ import "dart:io"; import "process_test_util.dart"; test(args) { - var future = Process.start(Platform.executable, - []..addAll(Platform.executableArguments)..addAll(args)); + var future = Process.start( + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..addAll(args), + ); future.then((process) { process.exitCode.then((exitCode) { Expect.equals(0, exitCode); @@ -21,11 +25,13 @@ test(args) { main() { // Get the Dart script file which checks arguments. - var scriptFile = - new File("tests/standalone/io/process_check_arguments_script.dart"); + var scriptFile = new File( + "tests/standalone/io/process_check_arguments_script.dart", + ); if (!scriptFile.existsSync()) { - scriptFile = - new File("../tests/standalone/io/process_check_arguments_script.dart"); + scriptFile = new File( + "../tests/standalone/io/process_check_arguments_script.dart", + ); } test([scriptFile.path, '3', '0', 'a']); test([scriptFile.path, '3', '0', 'a b']); diff --git a/tests/standalone/io/process_detached_test.dart b/tests/standalone/io/process_detached_test.dart index 4fd26ff7803..db3118df604 100644 --- a/tests/standalone/io/process_detached_test.dart +++ b/tests/standalone/io/process_detached_test.dart @@ -14,72 +14,89 @@ import "package:expect/expect.dart"; void test() { asyncStart(); - var script = - Platform.script.resolve('process_detached_script.dart').toFilePath(); + var script = Platform.script + .resolve('process_detached_script.dart') + .toFilePath(); var future = Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(script), - mode: ProcessStartMode.detached); - future.then((process) { - Expect.isNotNull(process.pid); - Expect.isTrue(process.pid is int); - Expect.throwsStateError(() => process.exitCode); - Expect.throwsStateError(() => process.stderr); - Expect.throwsStateError(() => process.stdin); - Expect.throwsStateError(() => process.stdout); - Expect.isTrue(process.kill()); - }).whenComplete(() { - asyncEnd(); - }); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(script), + mode: ProcessStartMode.detached, + ); + future + .then((process) { + Expect.isNotNull(process.pid); + Expect.isTrue(process.pid is int); + Expect.throwsStateError(() => process.exitCode); + Expect.throwsStateError(() => process.stderr); + Expect.throwsStateError(() => process.stdin); + Expect.throwsStateError(() => process.stdout); + Expect.isTrue(process.kill()); + }) + .whenComplete(() { + asyncEnd(); + }); } void testWithStdio() { asyncStart(); - var script = - Platform.script.resolve('process_detached_script.dart').toFilePath(); + var script = Platform.script + .resolve('process_detached_script.dart') + .toFilePath(); var future = Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..addAll([script, 'echo']), - mode: ProcessStartMode.detachedWithStdio); - future.then((process) { - Expect.isNotNull(process.pid); - Expect.isTrue(process.pid is int); - Expect.throwsStateError(() => process.exitCode); - var message = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - process.stdin.add(message); - process.stdin.flush().then((_) => process.stdin.close()); - var f1 = process.stdout.fold>([], (p, e) => p..addAll(e)); - var f2 = process.stderr.fold>([], (p, e) => p..addAll(e)); - return Future.wait([f1, f2]).then((values) { - Expect.listEquals(values[0] as List, message); - Expect.listEquals(values[1] as List, message); - }).whenComplete(() { - Expect.isTrue(process.kill()); - }); - }).whenComplete(() { - asyncEnd(); - }); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..addAll([script, 'echo']), + mode: ProcessStartMode.detachedWithStdio, + ); + future + .then((process) { + Expect.isNotNull(process.pid); + Expect.isTrue(process.pid is int); + Expect.throwsStateError(() => process.exitCode); + var message = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + process.stdin.add(message); + process.stdin.flush().then((_) => process.stdin.close()); + var f1 = process.stdout.fold>([], (p, e) => p..addAll(e)); + var f2 = process.stderr.fold>([], (p, e) => p..addAll(e)); + return Future.wait([f1, f2]) + .then((values) { + Expect.listEquals(values[0] as List, message); + Expect.listEquals(values[1] as List, message); + }) + .whenComplete(() { + Expect.isTrue(process.kill()); + }); + }) + .whenComplete(() { + asyncEnd(); + }); } void testFailure() { asyncStart(); Directory.systemTemp.createTemp('dart_detached_process').then((temp) { - var future = - Process.start(temp.path, ['a', 'b'], mode: ProcessStartMode.detached); - future.then((process) { - Expect.fail('Starting process from invalid executable succeeded'); - }, onError: (e) { - Expect.isTrue(e is ProcessException); - }).whenComplete(() { - temp.deleteSync(); - asyncEnd(); - }); + var future = Process.start(temp.path, [ + 'a', + 'b', + ], mode: ProcessStartMode.detached); + future + .then( + (process) { + Expect.fail('Starting process from invalid executable succeeded'); + }, + onError: (e) { + Expect.isTrue(e is ProcessException); + }, + ) + .whenComplete(() { + temp.deleteSync(); + asyncEnd(); + }); }); } diff --git a/tests/standalone/io/process_environment_test.dart b/tests/standalone/io/process_environment_test.dart index 190a104bb8a..3c414ba5969 100644 --- a/tests/standalone/io/process_environment_test.dart +++ b/tests/standalone/io/process_environment_test.dart @@ -10,24 +10,30 @@ import "package:expect/expect.dart"; import "process_test_util.dart"; runEnvironmentProcess( - Map environment, name, includeParent, callback) { + Map environment, + name, + includeParent, + callback, +) { var dartExecutable = Platform.executable; var printEnv = 'tests/standalone/io/print_env.dart'; if (!new File(printEnv).existsSync()) { printEnv = '../$printEnv'; } Process.run( - dartExecutable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..addAll([printEnv, name]), - environment: environment, - includeParentEnvironment: includeParent) - .then((result) { + dartExecutable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..addAll([printEnv, name]), + environment: environment, + includeParentEnvironment: includeParent, + ).then((result) { if (result.exitCode != 0) { - print('print_env.dart subprocess failed ' - 'with exit code ${result.exitCode}'); + print( + 'print_env.dart subprocess failed ' + 'with exit code ${result.exitCode}', + ); print('stdout:'); print(result.stdout); print('stderr:'); diff --git a/tests/standalone/io/process_exit_test.dart b/tests/standalone/io/process_exit_test.dart index c42c50c7397..ed797f022fa 100644 --- a/tests/standalone/io/process_exit_test.dart +++ b/tests/standalone/io/process_exit_test.dart @@ -11,8 +11,12 @@ import "package:expect/expect.dart"; import "process_test_util.dart"; testExit() { - var future = - Process.start(getProcessTestFileName(), const ["0", "0", "99", "0"]); + var future = Process.start(getProcessTestFileName(), const [ + "0", + "0", + "99", + "0", + ]); future.then((process) { process.exitCode.then((int exitCode) { Expect.equals(exitCode, 99); @@ -23,8 +27,9 @@ testExit() { } testExitRun() { - Process.run(getProcessTestFileName(), const ["0", "0", "99", "0"]) - .then((result) { + Process.run(getProcessTestFileName(), const ["0", "0", "99", "0"]).then(( + result, + ) { Expect.equals(result.exitCode, 99); Expect.equals(result.stdout, ''); Expect.equals(result.stderr, ''); diff --git a/tests/standalone/io/process_inherit_stdio_script.dart b/tests/standalone/io/process_inherit_stdio_script.dart index e6cd26fb78c..dac9b06af00 100644 --- a/tests/standalone/io/process_inherit_stdio_script.dart +++ b/tests/standalone/io/process_inherit_stdio_script.dart @@ -15,14 +15,16 @@ void main(List args) { return; } asyncStart(); - var script = - Platform.script.resolve('process_inherit_stdio_script.dart').toFilePath(); + var script = Platform.script + .resolve('process_inherit_stdio_script.dart') + .toFilePath(); var future = Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..addAll([script, "--child", "foo"]), - mode: ProcessStartMode.inheritStdio); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..addAll([script, "--child", "foo"]), + mode: ProcessStartMode.inheritStdio, + ); future.then((process) { process.exitCode.then((c) { asyncEnd(); diff --git a/tests/standalone/io/process_inherit_stdio_test.dart b/tests/standalone/io/process_inherit_stdio_test.dart index e9ee9f3e524..a3f905077e7 100644 --- a/tests/standalone/io/process_inherit_stdio_test.dart +++ b/tests/standalone/io/process_inherit_stdio_test.dart @@ -20,21 +20,28 @@ main() { // process_inherit_stdio_script.dart spawns a process in inheritStdio mode // that prints to its stdout. Since that child process inherits the stdout // of the process spawned here, we should see it. - var script = - Platform.script.resolve('process_inherit_stdio_script.dart').toFilePath(); + var script = Platform.script + .resolve('process_inherit_stdio_script.dart') + .toFilePath(); var future = Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..addAll([script, "foo"])); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..addAll([script, "foo"]), + ); Completer s = new Completer(); future.then((process) { StringBuffer buf = new StringBuffer(); - process.stdout.transform(utf8.decoder).listen((data) { - buf.write(data); - }, onDone: () { - s.complete(buf.toString()); - }); + process.stdout + .transform(utf8.decoder) + .listen( + (data) { + buf.write(data); + }, + onDone: () { + s.complete(buf.toString()); + }, + ); }); s.future.then((String result) { Expect.isTrue(result.contains("foo")); diff --git a/tests/standalone/io/process_non_ascii_test.dart b/tests/standalone/io/process_non_ascii_test.dart index 3d2911cc9e3..72972a76d4c 100644 --- a/tests/standalone/io/process_non_ascii_test.dart +++ b/tests/standalone/io/process_non_ascii_test.dart @@ -29,12 +29,13 @@ main() { // Note: we prevent this child process from using Crashpad handler because // this introduces an issue with deleting the temporary directory. Process.run( - executable, - [] - ..addAll(Platform.executableArguments) - ..add(script), - workingDirectory: nonAsciiDir.path, - environment: {'DART_CRASHPAD_HANDLER': ''}).then((result) { + executable, + [] + ..addAll(Platform.executableArguments) + ..add(script), + workingDirectory: nonAsciiDir.path, + environment: {'DART_CRASHPAD_HANDLER': ''}, + ).then((result) { if (result.exitCode != 0) { print('exitCode:\n${result.exitCode}'); print('stdout:\n${result.stdout}'); diff --git a/tests/standalone/io/process_run_test.dart b/tests/standalone/io/process_run_test.dart index c2295704631..9ec2fdc69ee 100644 --- a/tests/standalone/io/process_run_test.dart +++ b/tests/standalone/io/process_run_test.dart @@ -10,19 +10,30 @@ import "package:path/path.dart" as path; import "process_test_util.dart"; void testProcessRunBinaryOutput() { - var result = Process.runSync( - getProcessTestFileName(), const ["0", "0", "0", "0"], - stdoutEncoding: null); + var result = Process.runSync(getProcessTestFileName(), const [ + "0", + "0", + "0", + "0", + ], stdoutEncoding: null); Expect.isTrue(result.stdout is List); Expect.isTrue(result.stderr is String); - result = Process.runSync(getProcessTestFileName(), const ["0", "0", "0", "0"], - stderrEncoding: null); + result = Process.runSync(getProcessTestFileName(), const [ + "0", + "0", + "0", + "0", + ], stderrEncoding: null); Expect.isTrue(result.stdout is String); Expect.isTrue(result.stderr is List); - result = Process.runSync(getProcessTestFileName(), const ["0", "0", "0", "0"], - stdoutEncoding: null, stderrEncoding: null); + result = Process.runSync( + getProcessTestFileName(), + const ["0", "0", "0", "0"], + stdoutEncoding: null, + stderrEncoding: null, + ); Expect.isTrue(result.stdout is List); Expect.isTrue(result.stderr is List); } @@ -35,8 +46,12 @@ void testProcessPathWithSpace() { File(path.join(dir.path, 'path')).createSync(); var innerDir = Directory(path.join(dir.path, 'path with space')); innerDir.createSync(); - processTest = processTest.copySync(path.join( - innerDir.path, 'process_run_test${getPlatformExecutableExtension()}')); + processTest = processTest.copySync( + path.join( + innerDir.path, + 'process_run_test${getPlatformExecutableExtension()}', + ), + ); // It will run executables without throwing exception. var result = Process.runSync(processTest.path, []); // Kill the isolate because next test reuse the exe file. diff --git a/tests/standalone/io/process_segfault_test.dart b/tests/standalone/io/process_segfault_test.dart index 9fe0ede97b3..d379062bca4 100644 --- a/tests/standalone/io/process_segfault_test.dart +++ b/tests/standalone/io/process_segfault_test.dart @@ -11,8 +11,12 @@ import "package:expect/expect.dart"; import "process_test_util.dart"; testExit() { - var future = - Process.start(getProcessTestFileName(), const ["0", "0", "1", "1"]); + var future = Process.start(getProcessTestFileName(), const [ + "0", + "0", + "1", + "1", + ]); future.then((process) { process.exitCode.then((int exitCode) { Expect.isTrue(exitCode != 0); @@ -23,8 +27,9 @@ testExit() { } testExitRun() { - Process.run(getProcessTestFileName(), const ["0", "0", "1", "1"]) - .then((result) { + Process.run(getProcessTestFileName(), const ["0", "0", "1", "1"]).then(( + result, + ) { Expect.isTrue(result.exitCode != 0); Expect.equals(result.stdout, ''); Expect.equals(result.stderr, ''); diff --git a/tests/standalone/io/process_set_exit_code_test.dart b/tests/standalone/io/process_set_exit_code_test.dart index b67d56cd90d..230ca370b6c 100644 --- a/tests/standalone/io/process_set_exit_code_test.dart +++ b/tests/standalone/io/process_set_exit_code_test.dart @@ -14,15 +14,16 @@ import "package:path/path.dart"; main() { var executable = Platform.executable; - var exitCodeScript = - Platform.script.resolve('process_set_exit_code_script.dart').toFilePath(); + var exitCodeScript = Platform.script + .resolve('process_set_exit_code_script.dart') + .toFilePath(); Process.run( - executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(exitCodeScript)) - .then((result) { + executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(exitCodeScript), + ).then((result) { Expect.equals("standard out", result.stdout); Expect.equals("standard error", result.stderr); Expect.equals(25, result.exitCode); diff --git a/tests/standalone/io/process_shell_test.dart b/tests/standalone/io/process_shell_test.dart index b1d6e0de706..17371caa54c 100644 --- a/tests/standalone/io/process_shell_test.dart +++ b/tests/standalone/io/process_shell_test.dart @@ -15,14 +15,14 @@ void testRunShell() { asyncStart(); var script = Platform.script.resolve("process_echo_util.dart").toFilePath(); Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(script) - ..addAll(args), - runInShell: true) - .then((process_result) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(script) + ..addAll(args), + runInShell: true, + ).then((process_result) { var result; if (Platform.operatingSystem == "windows") { result = process_result.stdout.split("\r\n"); diff --git a/tests/standalone/io/process_start_exception_test.dart b/tests/standalone/io/process_start_exception_test.dart index 96d150ecedf..5e4c315bb09 100644 --- a/tests/standalone/io/process_start_exception_test.dart +++ b/tests/standalone/io/process_start_exception_test.dart @@ -20,28 +20,32 @@ const ENOENT = 2; testStartError() { Future processFuture = Process.start( - "__path_to_something_that_should_not_exist__", const [], - environment: {"PATH": ""}); + "__path_to_something_that_should_not_exist__", + const [], + environment: {"PATH": ""}, + ); processFuture .then((p) => Expect.fail('got process despite start error')) .catchError((error, stackTrace) { - Expect.isTrue(error is ProcessException); - Expect.equals(ENOENT, error.errorCode, error.toString()); - Expect.notEquals(stackTrace.toString(), ''); - }); + Expect.isTrue(error is ProcessException); + Expect.equals(ENOENT, error.errorCode, error.toString()); + Expect.notEquals(stackTrace.toString(), ''); + }); } testRunError() { Future processFuture = Process.run( - "__path_to_something_that_should_not_exist__", const [], - environment: {"PATH": ""}); + "__path_to_something_that_should_not_exist__", + const [], + environment: {"PATH": ""}, + ); - processFuture - .then((result) => Expect.fail("exit handler called")) - .catchError((error) { - Expect.isTrue(error is ProcessException); - Expect.equals(ENOENT, error.errorCode, error.toString()); - }); + processFuture.then((result) => Expect.fail("exit handler called")).catchError( + (error) { + Expect.isTrue(error is ProcessException); + Expect.equals(ENOENT, error.errorCode, error.toString()); + }, + ); } main() { diff --git a/tests/standalone/io/process_stderr_test.dart b/tests/standalone/io/process_stderr_test.dart index 353f52aed81..9808e6b2c9e 100644 --- a/tests/standalone/io/process_stderr_test.dart +++ b/tests/standalone/io/process_stderr_test.dart @@ -30,9 +30,11 @@ void test(Future future, int expectedExitCode) { void readData(List data) { buffer.addAll(data); - for (int i = received; - i < min(input_data.length, buffer.length) - 1; - i++) { + for ( + int i = received; + i < min(input_data.length, buffer.length) - 1; + i++ + ) { Expect.equals(input_data[i], buffer[i]); } received = buffer.length; @@ -57,7 +59,9 @@ void test(Future future, int expectedExitCode) { main() { // Run the test using the process_test binary. test( - Process.start(getProcessTestFileName(), const ["1", "1", "99", "0"]), 99); + Process.start(getProcessTestFileName(), const ["1", "1", "99", "0"]), + 99, + ); // Run the test using the dart binary with an echo script. // The test runner can be run from either the root or from runtime. @@ -67,11 +71,12 @@ main() { } Expect.isTrue(scriptFile.existsSync()); test( - Process.start(Platform.executable, [ - ...Platform.executableArguments, - "--verbosity=warning", // CFE info/hints pollute the stderr we are trying to test - scriptFile.path, - "1" - ]), - 0); + Process.start(Platform.executable, [ + ...Platform.executableArguments, + "--verbosity=warning", // CFE info/hints pollute the stderr we are trying to test + scriptFile.path, + "1", + ]), + 0, + ); } diff --git a/tests/standalone/io/process_stdin_transform_unsubscribe_script.dart b/tests/standalone/io/process_stdin_transform_unsubscribe_script.dart index 6bb369531c9..1b64a1c9807 100644 --- a/tests/standalone/io/process_stdin_transform_unsubscribe_script.dart +++ b/tests/standalone/io/process_stdin_transform_unsubscribe_script.dart @@ -13,7 +13,7 @@ main() { .transform(utf8.decoder) .transform(new LineSplitter()) .listen((String line) { - // Unsubscribe after the first line. - subscription.cancel(); - }); + // Unsubscribe after the first line. + subscription.cancel(); + }); } diff --git a/tests/standalone/io/process_stdin_transform_unsubscribe_test.dart b/tests/standalone/io/process_stdin_transform_unsubscribe_test.dart index 5d8b6e28a1f..426a4e40c70 100644 --- a/tests/standalone/io/process_stdin_transform_unsubscribe_test.dart +++ b/tests/standalone/io/process_stdin_transform_unsubscribe_test.dart @@ -39,10 +39,12 @@ main() { } Expect.isTrue(scriptFile.existsSync()); test( - Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add(scriptFile.path)), - 0); + Process.start( + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add(scriptFile.path), + ), + 0, + ); } diff --git a/tests/standalone/io/process_stdout_test.dart b/tests/standalone/io/process_stdout_test.dart index 10c27f7f86c..eeabd10d60c 100644 --- a/tests/standalone/io/process_stdout_test.dart +++ b/tests/standalone/io/process_stdout_test.dart @@ -55,7 +55,9 @@ void test(Future future, int expectedExitCode) { main() { // Run the test using the process_test binary. test( - Process.start(getProcessTestFileName(), const ["0", "1", "99", "0"]), 99); + Process.start(getProcessTestFileName(), const ["0", "1", "99", "0"]), + 99, + ); // Run the test using the dart binary with an echo script. // The test runner can be run from either the root or from runtime. @@ -65,10 +67,12 @@ main() { } Expect.isTrue(scriptFile.existsSync()); test( - Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..addAll([scriptFile.path, "0"])), - 0); + Process.start( + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..addAll([scriptFile.path, "0"]), + ), + 0, + ); } diff --git a/tests/standalone/io/process_sync_script.dart b/tests/standalone/io/process_sync_script.dart index e89d1a95d91..e3bed1442f8 100644 --- a/tests/standalone/io/process_sync_script.dart +++ b/tests/standalone/io/process_sync_script.dart @@ -12,10 +12,12 @@ main(List arguments) { var blockCount = int.parse(arguments[0]); var stdoutBlockSize = int.parse(arguments[1]); var stderrBlockSize = int.parse(arguments[2]); - var stdoutBlock = - new String.fromCharCodes(new List.filled(stdoutBlockSize, 65)); - var stderrBlock = - new String.fromCharCodes(new List.filled(stderrBlockSize, 66)); + var stdoutBlock = new String.fromCharCodes( + new List.filled(stdoutBlockSize, 65), + ); + var stderrBlock = new String.fromCharCodes( + new List.filled(stderrBlockSize, 66), + ); for (int i = 0; i < blockCount; i++) { stdout.write(stdoutBlock); stderr.write(stderrBlock); diff --git a/tests/standalone/io/process_sync_test.dart b/tests/standalone/io/process_sync_test.dart index 096a1b95d9a..e320166820f 100644 --- a/tests/standalone/io/process_sync_test.dart +++ b/tests/standalone/io/process_sync_test.dart @@ -8,11 +8,17 @@ import "dart:io"; import "package:expect/expect.dart"; import 'package:path/path.dart'; -test(int blockCount, int stdoutBlockSize, int stderrBlockSize, int exitCode, - [int? nonWindowsExitCode]) { +test( + int blockCount, + int stdoutBlockSize, + int stderrBlockSize, + int exitCode, [ + int? nonWindowsExitCode, +]) { // Get the Dart script file that generates output. var scriptFile = new File( - Platform.script.resolve("process_sync_script.dart").toFilePath()); + Platform.script.resolve("process_sync_script.dart").toFilePath(), + ); var args = [] ..addAll(Platform.executableArguments) ..add('--verbosity=warning') @@ -21,7 +27,7 @@ test(int blockCount, int stdoutBlockSize, int stderrBlockSize, int exitCode, blockCount.toString(), stdoutBlockSize.toString(), stderrBlockSize.toString(), - exitCode.toString() + exitCode.toString(), ]); ProcessResult syncResult = Process.runSync(Platform.executable, args); Expect.equals(blockCount * stdoutBlockSize, syncResult.stdout.length); diff --git a/tests/standalone/io/process_working_directory_test.dart b/tests/standalone/io/process_working_directory_test.dart index 9a3b8ee1f22..ad71660c21a 100644 --- a/tests/standalone/io/process_working_directory_test.dart +++ b/tests/standalone/io/process_working_directory_test.dart @@ -19,39 +19,51 @@ class ProcessWorkingDirectoryTest { } static void testValidDirectory() { - Directory directory = - Directory.systemTemp.createTempSync('dart_process_working_directory'); + Directory directory = Directory.systemTemp.createTempSync( + 'dart_process_working_directory', + ); Expect.isTrue(directory.existsSync()); - Process.start(fullTestFilePath, const ["0", "0", "99", "0"], - workingDirectory: directory.path) + Process.start(fullTestFilePath, const [ + "0", + "0", + "99", + "0", + ], workingDirectory: directory.path) .then((process) { - process.exitCode.then((int exitCode) { - Expect.equals(exitCode, 99); - directory.deleteSync(); - }); - process.stdout.listen((_) {}); - process.stderr.listen((_) {}); - }).catchError((error) { - directory.deleteSync(); - Expect.fail("Couldn't start process"); - }); + process.exitCode.then((int exitCode) { + Expect.equals(exitCode, 99); + directory.deleteSync(); + }); + process.stdout.listen((_) {}); + process.stderr.listen((_) {}); + }) + .catchError((error) { + directory.deleteSync(); + Expect.fail("Couldn't start process"); + }); } static void testInvalidDirectory() { - Directory directory = - Directory.systemTemp.createTempSync('dart_process_working_directory'); + Directory directory = Directory.systemTemp.createTempSync( + 'dart_process_working_directory', + ); Expect.isTrue(directory.existsSync()); - Process.start(fullTestFilePath, const ["0", "0", "99", "0"], - workingDirectory: directory.path + "/subPath") + Process.start(fullTestFilePath, const [ + "0", + "0", + "99", + "0", + ], workingDirectory: directory.path + "/subPath") .then((process) { - Expect.fail("bad process completed"); - directory.deleteSync(); - }).catchError((e) { - Expect.isNotNull(e); - directory.deleteSync(); - }); + Expect.fail("bad process completed"); + directory.deleteSync(); + }) + .catchError((e) { + Expect.isNotNull(e); + directory.deleteSync(); + }); } } diff --git a/tests/standalone/io/raw_datagram_socket_test.dart b/tests/standalone/io/raw_datagram_socket_test.dart index 817f1128e3b..d5af2781a64 100644 --- a/tests/standalone/io/raw_datagram_socket_test.dart +++ b/tests/standalone/io/raw_datagram_socket_test.dart @@ -13,9 +13,10 @@ class FutureExpect { static Future check(Future result, check) => result.then((value) => check(value)); static Future throws(Future result) => result.then((value) { - throw new ExpectException( - "FutureExpect.throws received $value instead of an exception"); - }, onError: (_) => null); + throw new ExpectException( + "FutureExpect.throws received $value instead of an exception", + ); + }, onError: (_) => null); } testDatagramBroadcastOptions() { @@ -70,18 +71,22 @@ testDatagramMulticastOptions() { testDatagramSocketReuseAddress() { test(address, reuseAddress) { asyncStart(); - RawDatagramSocket.bind(address, 0, - reuseAddress: reuseAddress, - reusePort: Platform.isMacOS && reuseAddress) - .then((socket) async { + RawDatagramSocket.bind( + address, + 0, + reuseAddress: reuseAddress, + reusePort: Platform.isMacOS && reuseAddress, + ).then((socket) async { if (reuseAddress) { - RawDatagramSocket.bind(address, socket.port, - reusePort: Platform.isMacOS) - .then((s) => Expect.isTrue(s is RawDatagramSocket)) - .then(asyncSuccess); + RawDatagramSocket.bind( + address, + socket.port, + reusePort: Platform.isMacOS, + ).then((s) => Expect.isTrue(s is RawDatagramSocket)).then(asyncSuccess); } else { - await FutureExpect.throws(RawDatagramSocket.bind(address, socket.port)) - .then(asyncSuccess); + await FutureExpect.throws( + RawDatagramSocket.bind(address, socket.port), + ).then(asyncSuccess); } }); } @@ -123,8 +128,11 @@ testDatagramSocketMulticastIf() { RawSocketOption option; late int idx; if (address.type == InternetAddressType.IPv4) { - option = RawSocketOption(RawSocketOption.levelIPv4, - RawSocketOption.IPv4MulticastInterface, address.rawAddress); + option = RawSocketOption( + RawSocketOption.levelIPv4, + RawSocketOption.IPv4MulticastInterface, + address.rawAddress, + ); } else { if (!NetworkInterface.listSupported) { asyncEnd(); @@ -136,8 +144,11 @@ testDatagramSocketMulticastIf() { return; } idx = interface[0].index; - option = RawSocketOption.fromInt(RawSocketOption.levelIPv6, - RawSocketOption.IPv6MulticastInterface, idx); + option = RawSocketOption.fromInt( + RawSocketOption.levelIPv6, + RawSocketOption.IPv6MulticastInterface, + idx, + ); } socket.setRawOption(option); @@ -148,7 +159,9 @@ testDatagramSocketMulticastIf() { } else { // RawSocketOption.fromInt() will create a Uint8List(4). Expect.equals( - getResult.buffer.asByteData().getUint32(0, Endian.host), idx); + getResult.buffer.asByteData().getUint32(0, Endian.host), + idx, + ); } asyncSuccess(socket); @@ -165,7 +178,7 @@ testBroadcast() { asyncStart(); Future.wait([ RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), - RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false) + RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), ]).then((values) { var broadcastTimer; var sender = values[0]; @@ -186,8 +199,11 @@ testBroadcast() { int sendCount = 0; send(_) { - int bytes = - sender.send(new Uint8List(1), broadcastAddress, receiver.port); + int bytes = sender.send( + new Uint8List(1), + broadcastAddress, + receiver.port, + ); Expect.isTrue(bytes == 0 || bytes == 1); sendCount++; if (!enabled && sendCount == 50) { @@ -212,7 +228,7 @@ testLoopbackMulticast() { asyncStart(); Future.wait([ RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), - RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false) + RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), ]).then((values) { var senderTimer; var sender = values[0]; @@ -242,8 +258,11 @@ testLoopbackMulticast() { int sendCount = 0; send(_) { - int bytes = - sender.send(new Uint8List(1), multicastAddress, receiver.port); + int bytes = sender.send( + new Uint8List(1), + multicastAddress, + receiver.port, + ); Expect.isTrue(bytes == 0 || bytes == 1); sendCount++; if (!enabled && sendCount == 50) { @@ -273,7 +292,7 @@ testLoopbackMulticastError() { asyncStart(); Future.wait([ RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), - RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false) + RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), ]).then((values) { var sender = values[0]; var receiver = values[1]; @@ -298,7 +317,7 @@ testSendReceive(InternetAddress bindAddress, int dataSize) { Future.wait([ RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), - RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false) + RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), ]).then((values) { var sender = values[0]; var receiver = values[1]; @@ -326,8 +345,11 @@ testSendReceive(InternetAddress bindAddress, int dataSize) { void sendData(int seq) { // Send a datagram acknowledging the received sequence. - int bytes = - sender.send(createDataPackage(seq), bindAddress, receiver.port); + int bytes = sender.send( + createDataPackage(seq), + bindAddress, + receiver.port, + ); Expect.isTrue(bytes == 0 || bytes == dataSize); } @@ -338,7 +360,9 @@ testSendReceive(InternetAddress bindAddress, int dataSize) { // Start a "long" timer for more data. ackTimer?.cancel(); ackTimer = new Timer.periodic( - new Duration(milliseconds: 100), (_) => sendAck(address, port)); + new Duration(milliseconds: 100), + (_) => sendAck(address, port), + ); } sender.listen((event) { @@ -406,7 +430,7 @@ void testTooLarge(InternetAddress bindAddress, int dataSize) { asyncStart(); Future.wait([ RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), - RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false) + RawDatagramSocket.bind(bindAddress, 0, reuseAddress: false), ]).then((values) { var sender = values[0]; var receiver = values[1]; @@ -419,32 +443,37 @@ void testTooLarge(InternetAddress bindAddress, int dataSize) { } var data = new Uint8List(dataSize); - sender.listen((event) { - switch (event) { - case RawSocketEvent.write: - final numBytes = sender.send(data, bindAddress, receiver.port); - Expect.isTrue(numBytes == 0 || numBytes == data.length, - "Unexpected send() result: $numBytes"); + sender.listen( + (event) { + switch (event) { + case RawSocketEvent.write: + final numBytes = sender.send(data, bindAddress, receiver.port); + Expect.isTrue( + numBytes == 0 || numBytes == data.length, + "Unexpected send() result: $numBytes", + ); - break; - case RawSocketEvent.closed: - break; - default: - throw "Unexpected event $event"; - } - }, onError: (e) { - sender.close(); - receiver.close(); + break; + case RawSocketEvent.closed: + break; + default: + throw "Unexpected event $event"; + } + }, + onError: (e) { + sender.close(); + receiver.close(); - Expect.type(e); - final osError = (e as SocketException).osError!; - if (Platform.isMacOS) { - Expect.equals(40, osError.errorCode); // EMSGSIZE - } else if (Platform.isWindows) { - Expect.equals(1784, osError.errorCode); // ERROR_INVALID_USER_BUFFER - } else {} - asyncEnd(); - }); + Expect.type(e); + final osError = (e as SocketException).osError!; + if (Platform.isMacOS) { + Expect.equals(40, osError.errorCode); // EMSGSIZE + } else if (Platform.isWindows) { + Expect.equals(1784, osError.errorCode); // ERROR_INVALID_USER_BUFFER + } else {} + asyncEnd(); + }, + ); }); } diff --git a/tests/standalone/io/raw_secure_server_closing_test.dart b/tests/standalone/io/raw_secure_server_closing_test.dart index ebf4e99db93..45b8221d0e1 100644 --- a/tests/standalone/io/raw_secure_server_closing_test.dart +++ b/tests/standalone/io/raw_secure_server_closing_test.dart @@ -21,8 +21,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -32,32 +34,45 @@ void testCloseOneEnd(String toClose) { Completer serverDone = new Completer(); Completer serverEndDone = new Completer(); Completer clientEndDone = new Completer(); - Future.wait([serverDone.future, serverEndDone.future, clientEndDone.future]) - .then((_) { + Future.wait([ + serverDone.future, + serverEndDone.future, + clientEndDone.future, + ]).then((_) { asyncEnd(); }); RawSecureServerSocket.bind(HOST, 0, serverContext).then((server) { - server.listen((serverConnection) { - serverConnection.listen((event) { - if (toClose == "server" || event == RawSocketEvent.readClosed) { - serverConnection.shutdown(SocketDirection.send); - } - }, onDone: () { - serverEndDone.complete(null); - }); - }, onDone: () { - serverDone.complete(null); - }); - RawSecureSocket.connect(HOST, server.port, context: clientContext) - .then((clientConnection) { - clientConnection.listen((event) { - if (toClose == "client" || event == RawSocketEvent.readClosed) { - clientConnection.shutdown(SocketDirection.send); - } - }, onDone: () { - clientEndDone.complete(null); - server.close(); - }); + server.listen( + (serverConnection) { + serverConnection.listen( + (event) { + if (toClose == "server" || event == RawSocketEvent.readClosed) { + serverConnection.shutdown(SocketDirection.send); + } + }, + onDone: () { + serverEndDone.complete(null); + }, + ); + }, + onDone: () { + serverDone.complete(null); + }, + ); + RawSecureSocket.connect(HOST, server.port, context: clientContext).then(( + clientConnection, + ) { + clientConnection.listen( + (event) { + if (toClose == "client" || event == RawSocketEvent.readClosed) { + clientConnection.shutdown(SocketDirection.send); + } + }, + onDone: () { + clientEndDone.complete(null); + server.close(); + }, + ); }); }); } @@ -65,8 +80,11 @@ void testCloseOneEnd(String toClose) { void testCloseBothEnds() { asyncStart(); RawSecureServerSocket.bind(HOST, 0, serverContext).then((server) { - var clientEndFuture = - RawSecureSocket.connect(HOST, server.port, context: clientContext); + var clientEndFuture = RawSecureSocket.connect( + HOST, + server.port, + context: clientContext, + ); server.listen((serverEnd) { clientEndFuture.then((clientEnd) { clientEnd.close(); @@ -85,8 +103,12 @@ testPauseServerSocket() { asyncStart(); - RawSecureServerSocket.bind(HOST, 0, serverContext, backlog: 2 * socketCount) - .then((server) { + RawSecureServerSocket.bind( + HOST, + 0, + serverContext, + backlog: 2 * socketCount, + ).then((server) { Expect.isTrue(server.port > 0); var subscription; subscription = server.listen((connection) { @@ -104,8 +126,9 @@ testPauseServerSocket() { subscription.pause(); var connectCount = 0; for (int i = 0; i < socketCount; i++) { - RawSecureSocket.connect(HOST, server.port, context: clientContext) - .then((connection) { + RawSecureSocket.connect(HOST, server.port, context: clientContext).then(( + connection, + ) { connection.shutdown(SocketDirection.send); }); } @@ -113,10 +136,11 @@ testPauseServerSocket() { subscription.resume(); resumed = true; for (int i = 0; i < socketCount; i++) { - RawSecureSocket.connect(HOST, server.port, context: clientContext) - .then((connection) { - connection.shutdown(SocketDirection.send); - }); + RawSecureSocket.connect(HOST, server.port, context: clientContext).then( + (connection) { + connection.shutdown(SocketDirection.send); + }, + ); } }); }); @@ -144,8 +168,9 @@ testCloseServer() { }); for (int i = 0; i < socketCount; i++) { - RawSecureSocket.connect(HOST, server.port, context: clientContext) - .then((connection) { + RawSecureSocket.connect(HOST, server.port, context: clientContext).then(( + connection, + ) { ends.add(connection); checkDone(); }); diff --git a/tests/standalone/io/raw_secure_server_socket_test.dart b/tests/standalone/io/raw_secure_server_socket_test.dart index a7d3a72adc0..c9f71873cfc 100644 --- a/tests/standalone/io/raw_secure_server_socket_test.dart +++ b/tests/standalone/io/raw_secure_server_socket_test.dart @@ -23,8 +23,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -46,39 +48,45 @@ void testInvalidBind() { // Bind to a unknown DNS name. asyncStart(); print("asyncStart testInvalidBind"); - RawSecureServerSocket.bind("ko.faar.__hest__", 0, serverContext).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - print("asyncEnd testInvalidBind"); - asyncEnd(); - }); + RawSecureServerSocket.bind("ko.faar.__hest__", 0, serverContext) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + print("asyncEnd testInvalidBind"); + asyncEnd(); + }); // Bind to an unavailable IP-address. asyncStart(); print("asyncStart testInvalidBind 2"); - RawSecureServerSocket.bind("8.8.8.8", 0, serverContext).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - print("asyncEnd testInvalidBind 2"); - asyncEnd(); - }); + RawSecureServerSocket.bind("8.8.8.8", 0, serverContext) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + print("asyncEnd testInvalidBind 2"); + asyncEnd(); + }); // Bind to a port already in use. asyncStart(); print("asyncStart testInvalidBind 3"); RawSecureServerSocket.bind(HOST, 0, serverContext).then((s) { - RawSecureServerSocket.bind(HOST, s.port, serverContext).then((t) { - s.close(); - t.close(); - Expect.fail("Multiple listens on same port"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - s.close(); - print("asyncEnd testInvalidBind 3"); - asyncEnd(); - }); + RawSecureServerSocket.bind(HOST, s.port, serverContext) + .then((t) { + s.close(); + t.close(); + Expect.fail("Multiple listens on same port"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + s.close(); + print("asyncEnd testInvalidBind 3"); + asyncEnd(); + }); }); } @@ -86,8 +94,11 @@ void testSimpleConnect() { print("asyncStart testSimpleConnect"); asyncStart(); RawSecureServerSocket.bind(HOST, 0, serverContext).then((server) { - var clientEndFuture = - RawSecureSocket.connect(HOST, server.port, context: clientContext); + var clientEndFuture = RawSecureSocket.connect( + HOST, + server.port, + context: clientContext, + ); server.listen((serverEnd) { clientEndFuture.then((clientEnd) { // TODO(whesse): Shutdown(SEND) not supported on secure sockets. @@ -110,20 +121,27 @@ void testSimpleConnectFail(SecurityContext context, bool cancelOnError) { Future clientEndFuture = RawSecureSocket.connect(HOST, server.port, context: clientContext) .then((clientEnd) { - Expect.fail("No client connection expected."); - }).catchError((error) { - Expect.isTrue(error is SocketException || error is HandshakeException); - }); - server.listen((serverEnd) { - Expect.fail("No server connection expected."); - }, onError: (error) { - Expect.isTrue(error is SocketException || error is HandshakeException); - clientEndFuture.then((_) { - if (!cancelOnError) server.close(); - print("asyncEnd testSimpleConnectFail $counter"); - asyncEnd(); - }); - }, cancelOnError: cancelOnError); + Expect.fail("No client connection expected."); + }) + .catchError((error) { + Expect.isTrue( + error is SocketException || error is HandshakeException, + ); + }); + server.listen( + (serverEnd) { + Expect.fail("No server connection expected."); + }, + onError: (error) { + Expect.isTrue(error is SocketException || error is HandshakeException); + clientEndFuture.then((_) { + if (!cancelOnError) server.close(); + print("asyncEnd testSimpleConnectFail $counter"); + asyncEnd(); + }); + }, + cancelOnError: cancelOnError, + ); }); } @@ -132,8 +150,11 @@ void testServerListenAfterConnect() { asyncStart(); RawSecureServerSocket.bind(HOST, 0, serverContext).then((server) { Expect.isTrue(server.port > 0); - var clientEndFuture = - RawSecureSocket.connect(HOST, server.port, context: clientContext); + var clientEndFuture = RawSecureSocket.connect( + HOST, + server.port, + context: clientContext, + ); new Timer(const Duration(milliseconds: 500), () { server.listen((serverEnd) { clientEndFuture.then((clientEnd) { @@ -178,12 +199,13 @@ void testServerListenAfterConnect() { // server will not happen until the first TLS handshake data has been // received from the client. This argument only takes effect when // handshakeBeforeSecure is true. -void testSimpleReadWrite( - {required bool listenSecure, - required bool connectSecure, - required bool handshakeBeforeSecure, - required bool postponeSecure, - required bool dropReads}) { +void testSimpleReadWrite({ + required bool listenSecure, + required bool connectSecure, + required bool handshakeBeforeSecure, + required bool postponeSecure, + required bool dropReads, +}) { int clientReads = 0; int serverReads = 0; if (handshakeBeforeSecure == true && @@ -191,8 +213,10 @@ void testSimpleReadWrite( Expect.fail("Invalid arguments to testSimpleReadWrite"); } - print("asyncStart testSimpleReadWrite($listenSecure, $connectSecure, " - "$handshakeBeforeSecure, $postponeSecure, $dropReads"); + print( + "asyncStart testSimpleReadWrite($listenSecure, $connectSecure, " + "$handshakeBeforeSecure, $postponeSecure, $dropReads", + ); asyncStart(); const messageSize = 1000; @@ -271,8 +295,11 @@ void testSimpleReadWrite( Expect.isTrue(data[i] is int); Expect.isTrue(data[i] < 256 && data[i] >= 0); } - bytesWritten += - client.write(data, bytesWritten, data.length - bytesWritten); + bytesWritten += client.write( + data, + bytesWritten, + data.length - bytesWritten, + ); if (bytesWritten < data.length) { client.writeEventsEnabled = true; } @@ -318,7 +345,10 @@ void testSimpleReadWrite( Expect.isTrue(bytesRead == 0); Expect.isFalse(socket.writeEventsEnabled); bytesWritten += socket.write( - dataSent, bytesWritten, dataSent.length - bytesWritten); + dataSent, + bytesWritten, + dataSent.length - bytesWritten, + ); if (bytesWritten < dataSent.length) { socket.writeEventsEnabled = true; } @@ -384,8 +414,11 @@ void testSimpleReadWrite( Expect.isTrue(data[i] is int); Expect.isTrue(data[i] < 256 && data[i] >= 0); } - bytesWritten += - client.write(data, bytesWritten, data.length - bytesWritten); + bytesWritten += client.write( + data, + bytesWritten, + data.length - bytesWritten, + ); if (bytesWritten < data.length) { client.writeEventsEnabled = true; } @@ -406,7 +439,8 @@ void testSimpleReadWrite( } Future> runClientHandshake( - RawSocket socket) { + RawSocket socket, + ) { var completer = new Completer>(); int bytesRead = 0; int bytesWritten = 0; @@ -439,7 +473,10 @@ void testSimpleReadWrite( Expect.isTrue(bytesRead == 0); Expect.isFalse(socket.writeEventsEnabled); bytesWritten += socket.write( - dataSent, bytesWritten, dataSent.length - bytesWritten); + dataSent, + bytesWritten, + dataSent.length - bytesWritten, + ); if (bytesWritten < dataSent.length) { socket.writeEventsEnabled = true; } @@ -464,8 +501,11 @@ void testSimpleReadWrite( } else { return RawSocket.connect(HOST, port).then((socket) { return runClientHandshake(socket).then((subscription) { - return RawSecureSocket.secure(socket, - context: clientContext, subscription: subscription); + return RawSecureSocket.secure( + socket, + context: clientContext, + subscription: subscription, + ); }); }); } @@ -481,9 +521,12 @@ void testSimpleReadWrite( }); } else { runServerHandshake(client).then((secure) { - RawSecureSocket.secureServer(client, serverContext, - subscription: secure[0], bufferedData: secure[1]) - .then((client) { + RawSecureSocket.secureServer( + client, + serverContext, + subscription: secure[0], + bufferedData: secure[1], + ).then((client) { runServer(client).then((_) => server.close()); }); }); @@ -492,8 +535,10 @@ void testSimpleReadWrite( connectClient(server.port).then(runClient).then((socket) { socket.close(); - print("asyncEnd testSimpleReadWrite($listenSecure, $connectSecure, " - "$handshakeBeforeSecure, $postponeSecure, $dropReads"); + print( + "asyncEnd testSimpleReadWrite($listenSecure, $connectSecure, " + "$handshakeBeforeSecure, $postponeSecure, $dropReads", + ); asyncEnd(); }); } @@ -507,7 +552,8 @@ void testSimpleReadWrite( testPausedSecuringSubscription(bool pausedServer, bool pausedClient) { print( - "asyncStart testPausedSecuringSubscription $pausedServer $pausedClient"); + "asyncStart testPausedSecuringSubscription $pausedServer $pausedClient", + ); asyncStart(); var clientComplete = new Completer(); RawServerSocket.bind(HOST, 0).then((server) { @@ -521,18 +567,22 @@ testPausedSecuringSubscription(bool pausedServer, bool pausedClient) { server.close(); clientComplete.future.then((_) { client.close(); - print("asyncEnd testPausedSecuringSubscription " - "$pausedServer $pausedClient"); + print( + "asyncEnd testPausedSecuringSubscription " + "$pausedServer $pausedClient", + ); asyncEnd(); }); } try { - Future.value(RawSecureSocket.secureServer( - client, serverContext, - subscription: subscription)) - .catchError((_) {}) - .whenComplete(() { + Future.value( + RawSecureSocket.secureServer( + client, + serverContext, + subscription: subscription, + ), + ).catchError((_) {}).whenComplete(() { if (pausedServer) { Expect.fail("secureServer succeeded with paused subscription"); } @@ -558,9 +608,8 @@ testPausedSecuringSubscription(bool pausedServer, bool pausedClient) { } try { Future.value( - RawSecureSocket.secure(socket, subscription: subscription)) - .catchError((_) {}) - .whenComplete(() { + RawSecureSocket.secure(socket, subscription: subscription), + ).catchError((_) {}).whenComplete(() { if (pausedClient) { Expect.fail("secure succeeded with paused subscription"); } @@ -614,55 +663,63 @@ runTests() { testServerListenAfterConnect(); testSimpleReadWrite( - listenSecure: true, - connectSecure: true, - handshakeBeforeSecure: false, - postponeSecure: false, - dropReads: false); + listenSecure: true, + connectSecure: true, + handshakeBeforeSecure: false, + postponeSecure: false, + dropReads: false, + ); testSimpleReadWrite( - listenSecure: true, - connectSecure: false, - handshakeBeforeSecure: false, - postponeSecure: false, - dropReads: false); + listenSecure: true, + connectSecure: false, + handshakeBeforeSecure: false, + postponeSecure: false, + dropReads: false, + ); testSimpleReadWrite( - listenSecure: false, - connectSecure: true, - handshakeBeforeSecure: false, - postponeSecure: false, - dropReads: false); + listenSecure: false, + connectSecure: true, + handshakeBeforeSecure: false, + postponeSecure: false, + dropReads: false, + ); testSimpleReadWrite( - listenSecure: false, - connectSecure: false, - handshakeBeforeSecure: false, - postponeSecure: false, - dropReads: false); + listenSecure: false, + connectSecure: false, + handshakeBeforeSecure: false, + postponeSecure: false, + dropReads: false, + ); testSimpleReadWrite( - listenSecure: false, - connectSecure: false, - handshakeBeforeSecure: true, - postponeSecure: true, - dropReads: false); + listenSecure: false, + connectSecure: false, + handshakeBeforeSecure: true, + postponeSecure: true, + dropReads: false, + ); testSimpleReadWrite( - listenSecure: false, - connectSecure: false, - handshakeBeforeSecure: true, - postponeSecure: false, - dropReads: false); + listenSecure: false, + connectSecure: false, + handshakeBeforeSecure: true, + postponeSecure: false, + dropReads: false, + ); testSimpleReadWrite( - listenSecure: true, - connectSecure: true, - handshakeBeforeSecure: false, - postponeSecure: false, - dropReads: true); + listenSecure: true, + connectSecure: true, + handshakeBeforeSecure: false, + postponeSecure: false, + dropReads: true, + ); testSimpleReadWrite( - listenSecure: false, - connectSecure: false, - handshakeBeforeSecure: true, - postponeSecure: true, - dropReads: true); + listenSecure: false, + connectSecure: false, + handshakeBeforeSecure: true, + postponeSecure: true, + dropReads: true, + ); testPausedSecuringSubscription(false, false); testPausedSecuringSubscription(true, false); testPausedSecuringSubscription(false, true); diff --git a/tests/standalone/io/raw_secure_socket_pause_test.dart b/tests/standalone/io/raw_secure_socket_pause_test.dart index af43758aa55..33d188aa532 100644 --- a/tests/standalone/io/raw_secure_socket_pause_test.dart +++ b/tests/standalone/io/raw_secure_socket_pause_test.dart @@ -20,23 +20,29 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); Future startServer() { - return HttpServer.bindSecure("localhost", 0, serverContext, backlog: 5) - .then((server) { + return HttpServer.bindSecure("localhost", 0, serverContext, backlog: 5).then(( + server, + ) { server.listen((HttpRequest request) { - request.listen((_) {}, onDone: () { - request.response.contentLength = 100; - for (int i = 0; i < 10; i++) { - request.response.add([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - } - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.contentLength = 100; + for (int i = 0; i < 10; i++) { + request.response.add([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + } + request.response.close(); + }, + ); }); return server; }); @@ -47,8 +53,11 @@ main() async { int written = 0; List body = []; var server = await startServer(); - var socket = await RawSecureSocket.connect("localhost", server.port, - context: clientContext); + var socket = await RawSecureSocket.connect( + "localhost", + server.port, + context: clientContext, + ); late StreamSubscription subscription; bool paused = false; bool readEventsTested = false; @@ -102,9 +111,12 @@ main() async { } } - subscription = socket.listen(handleRawEvent, onError: (e, trace) { - String msg = "onError handler of RawSecureSocket stream hit: $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + subscription = socket.listen( + handleRawEvent, + onError: (e, trace) { + String msg = "onError handler of RawSecureSocket stream hit: $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); } diff --git a/tests/standalone/io/raw_secure_socket_ssl_read_error_test.dart b/tests/standalone/io/raw_secure_socket_ssl_read_error_test.dart index 387a48bcccc..43ed56dd905 100644 --- a/tests/standalone/io/raw_secure_socket_ssl_read_error_test.dart +++ b/tests/standalone/io/raw_secure_socket_ssl_read_error_test.dart @@ -22,8 +22,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -35,8 +37,10 @@ testSslReadError() async { final serverSocket = await RawServerSocket.bind(HOST, 0); serverSocket.forEach((socket) async { final secureSocket = await RawSecureSocket.secureServer( - socket, serverContext, - subscription: socket.listen((event) {})); + socket, + serverContext, + subscription: socket.listen((event) {}), + ); secureSocket.write([1, 2, 3]); // Send content using the original unencrypted connection to provoke a // TtsException in the client. @@ -46,15 +50,20 @@ testSslReadError() async { }); final Socket clientSocket = await Socket.connect(HOST, serverSocket.port); - final secureClientSocket = - await SecureSocket.secure(clientSocket, context: clientContext); - secureClientSocket.listen((data) { - Expect.fail("expected TlsException"); - }, onError: (err) { - Expect.isTrue(err is TlsException, "unexpected error: $err"); - secureClientSocket.close(); - clientSocket.close(); - }); + final secureClientSocket = await SecureSocket.secure( + clientSocket, + context: clientContext, + ); + secureClientSocket.listen( + (data) { + Expect.fail("expected TlsException"); + }, + onError: (err) { + Expect.isTrue(err is TlsException, "unexpected error: $err"); + secureClientSocket.close(); + clientSocket.close(); + }, + ); } main() { diff --git a/tests/standalone/io/raw_secure_socket_test.dart b/tests/standalone/io/raw_secure_socket_test.dart index 59ac86973ed..e39cdc4cf63 100644 --- a/tests/standalone/io/raw_secure_socket_test.dart +++ b/tests/standalone/io/raw_secure_socket_test.dart @@ -20,8 +20,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); final SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); final SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -30,8 +32,12 @@ main() async { List message = "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n".codeUnits; int written = 0; List body = []; - var server = - await HttpServer.bindSecure("localhost", 0, serverContext, backlog: 5); + var server = await HttpServer.bindSecure( + "localhost", + 0, + serverContext, + backlog: 5, + ); server.listen((HttpRequest request) async { await request.drain(); request.response.contentLength = 100; @@ -40,33 +46,39 @@ main() async { } request.response.close(); }); - var socket = await RawSecureSocket.connect("localhost", server.port, - context: clientContext); - socket.listen((RawSocketEvent event) { - switch (event) { - case RawSocketEvent.read: - body.addAll(socket.read()!); - break; - case RawSocketEvent.write: - written += socket.write(message, written, message.length - written); - if (written < message.length) { - socket.writeEventsEnabled = true; - } else { - socket.shutdown(SocketDirection.send); - } - break; - case RawSocketEvent.readClosed: - Expect.isTrue(body.length > 100, "$body\n${body.length}"); - Expect.equals(72, body[0]); - Expect.equals(9, body[body.length - 1]); - server.close(); - break; - default: - throw "Unexpected event $event"; - } - }, onError: (e, trace) { - String msg = "onError handler of RawSecureSocket stream hit $e"; - if (trace != null) msg += "\nStackTrace: $trace"; - Expect.fail(msg); - }); + var socket = await RawSecureSocket.connect( + "localhost", + server.port, + context: clientContext, + ); + socket.listen( + (RawSocketEvent event) { + switch (event) { + case RawSocketEvent.read: + body.addAll(socket.read()!); + break; + case RawSocketEvent.write: + written += socket.write(message, written, message.length - written); + if (written < message.length) { + socket.writeEventsEnabled = true; + } else { + socket.shutdown(SocketDirection.send); + } + break; + case RawSocketEvent.readClosed: + Expect.isTrue(body.length > 100, "$body\n${body.length}"); + Expect.equals(72, body[0]); + Expect.equals(9, body[body.length - 1]); + server.close(); + break; + default: + throw "Unexpected event $event"; + } + }, + onError: (e, trace) { + String msg = "onError handler of RawSecureSocket stream hit $e"; + if (trace != null) msg += "\nStackTrace: $trace"; + Expect.fail(msg); + }, + ); } diff --git a/tests/standalone/io/raw_server_socket_cancel_test.dart b/tests/standalone/io/raw_server_socket_cancel_test.dart index 49da43e58c7..6e6026dec8a 100644 --- a/tests/standalone/io/raw_server_socket_cancel_test.dart +++ b/tests/standalone/io/raw_server_socket_cancel_test.dart @@ -66,41 +66,48 @@ void testCancelResubscribeServerSocket(int socketCount, int backlog) { // Connect a number of sockets. for (int i = 0; i < socketCount; i++) { - RawSocket.connect("127.0.0.1", server.port).then((socket) { - bool done = false; - var subscription; - subscription = socket.listen((event) { - switch (event) { - case RawSocketEvent.read: - Expect.fail("No read event expected"); - break; - case RawSocketEvent.readClosed: - done = true; - doneCount++; - checkDone(); - break; - case RawSocketEvent.write: - // We don't care if this write succeeds, so we don't check - // the return value (number of bytes written). - socket.write([1, 2, 3]); - socket.shutdown(SocketDirection.send); - break; - } - }, onDone: () { - if (!done) { - doneCount++; + RawSocket.connect("127.0.0.1", server.port) + .then((socket) { + bool done = false; + var subscription; + subscription = socket.listen( + (event) { + switch (event) { + case RawSocketEvent.read: + Expect.fail("No read event expected"); + break; + case RawSocketEvent.readClosed: + done = true; + doneCount++; + checkDone(); + break; + case RawSocketEvent.write: + // We don't care if this write succeeds, so we don't check + // the return value (number of bytes written). + socket.write([1, 2, 3]); + socket.shutdown(SocketDirection.send); + break; + } + }, + onDone: () { + if (!done) { + doneCount++; + checkDone(); + } + }, + onError: (e) { + // "Connection reset by peer" errors are handled here. + errorCount++; + checkDone(); + }, + cancelOnError: true, + ); + }) + .catchError((e) { + // "Connection actively refused by host" errors are handled here. + earlyErrorCount++; checkDone(); - } - }, onError: (e) { - // "Connection reset by peer" errors are handled here. - errorCount++; - checkDone(); - }, cancelOnError: true); - }).catchError((e) { - // "Connection actively refused by host" errors are handled here. - earlyErrorCount++; - checkDone(); - }); + }); } }); } diff --git a/tests/standalone/io/raw_socket_cross_process_test.dart b/tests/standalone/io/raw_socket_cross_process_test.dart index 42ef3385c94..c9e42db5a3f 100644 --- a/tests/standalone/io/raw_socket_cross_process_test.dart +++ b/tests/standalone/io/raw_socket_cross_process_test.dart @@ -48,13 +48,13 @@ Future makeServer() { Future runClientProcess(int port) { return Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add(Platform.script.toFilePath()) - ..add('--client') - ..add(port.toString())) - .then((ProcessResult result) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add(Platform.script.toFilePath()) + ..add('--client') + ..add(port.toString()), + ).then((ProcessResult result) { if (result.exitCode != 0 || !result.stdout.contains('SUCCESS')) { print("Client failed, exit code ${result.exitCode}"); print(" stdout:"); diff --git a/tests/standalone/io/raw_socket_test.dart b/tests/standalone/io/raw_socket_test.dart index 4c1d714517e..efa8b07dc2a 100644 --- a/tests/standalone/io/raw_socket_test.dart +++ b/tests/standalone/io/raw_socket_test.dart @@ -31,32 +31,38 @@ void testSimpleBind() { void testInvalidBind() { // Bind to a unknown DNS name. asyncStart(); - RawServerSocket.bind("ko.faar.__hest__", 0).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - asyncEnd(); - }); + RawServerSocket.bind("ko.faar.__hest__", 0) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + asyncEnd(); + }); // Bind to an unavailable IP-address. asyncStart(); - RawServerSocket.bind("8.8.8.8", 0).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - asyncEnd(); - }); + RawServerSocket.bind("8.8.8.8", 0) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + asyncEnd(); + }); // Bind to a port already in use. asyncStart(); RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((s) { - RawServerSocket.bind(InternetAddress.loopbackIPv4, s.port).then((t) { - Expect.fail("Multiple listens on same port"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - s.close(); - asyncEnd(); - }); + RawServerSocket.bind(InternetAddress.loopbackIPv4, s.port) + .then((t) { + Expect.fail("Multiple listens on same port"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + s.close(); + asyncEnd(); + }); }); } @@ -77,17 +83,22 @@ void testSimpleConnect() { void testCancelConnect() { asyncStart(); RawSocket.startConnect(InternetAddress.loopbackIPv4, 0).then( - (ConnectionTask task) { - task.cancel(); - task.socket.then((s) { + (ConnectionTask task) { + task.cancel(); + task.socket.then( + (s) { + Expect.fail("Unreachable"); + }, + onError: (e) { + Expect.isTrue(e is SocketException); + asyncEnd(); + }, + ); + }, + onError: (e) { Expect.fail("Unreachable"); - }, onError: (e) { - Expect.isTrue(e is SocketException); - asyncEnd(); - }); - }, onError: (e) { - Expect.fail("Unreachable"); - }); + }, + ); } void testCloseOneEnd(String toClose) { @@ -95,31 +106,43 @@ void testCloseOneEnd(String toClose) { Completer serverDone = new Completer(); Completer serverEndDone = new Completer(); Completer clientEndDone = new Completer(); - Future.wait([serverDone.future, serverEndDone.future, clientEndDone.future]) - .then((_) { + Future.wait([ + serverDone.future, + serverEndDone.future, + clientEndDone.future, + ]).then((_) { asyncEnd(); }); RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((server) { - server.listen((serverConnection) { - serverConnection.listen((event) { - if (toClose == "server" || event == RawSocketEvent.readClosed) { - serverConnection.shutdown(SocketDirection.send); - } - }, onDone: () { - serverEndDone.complete(null); - }); - }, onDone: () { - serverDone.complete(null); - }); + server.listen( + (serverConnection) { + serverConnection.listen( + (event) { + if (toClose == "server" || event == RawSocketEvent.readClosed) { + serverConnection.shutdown(SocketDirection.send); + } + }, + onDone: () { + serverEndDone.complete(null); + }, + ); + }, + onDone: () { + serverDone.complete(null); + }, + ); RawSocket.connect("127.0.0.1", server.port).then((clientConnection) { - clientConnection.listen((event) { - if (toClose == "client" || event == RawSocketEvent.readClosed) { - clientConnection.shutdown(SocketDirection.send); - } - }, onDone: () { - clientEndDone.complete(null); - server.close(); - }); + clientConnection.listen( + (event) { + if (toClose == "client" || event == RawSocketEvent.readClosed) { + clientConnection.shutdown(SocketDirection.send); + } + }, + onDone: () { + clientEndDone.complete(null); + server.close(); + }, + ); }); }); } @@ -193,8 +216,11 @@ void testSimpleReadWrite({required bool dropReads}) { break; case RawSocketEvent.write: Expect.isFalse(client.writeEventsEnabled); - bytesWritten += - client.write(data, bytesWritten, data.length - bytesWritten); + bytesWritten += client.write( + data, + bytesWritten, + data.length - bytesWritten, + ); if (bytesWritten < data.length) { client.writeEventsEnabled = true; } @@ -221,48 +247,54 @@ void testSimpleReadWrite({required bool dropReads}) { bool closedEventReceived = false; List data = createTestData(); - socket.listen((event) { - switch (event) { - case RawSocketEvent.read: - Expect.isTrue(socket.available() > 0); - if (dropReads) { - if (clientReadCount != 10) { - clientReadCount++; - break; - } else { - clientReadCount = 0; + socket.listen( + (event) { + switch (event) { + case RawSocketEvent.read: + Expect.isTrue(socket.available() > 0); + if (dropReads) { + if (clientReadCount != 10) { + clientReadCount++; + break; + } else { + clientReadCount = 0; + } } - } - var buffer = socket.read()!; - data.setRange(bytesRead, bytesRead + buffer.length, buffer); - bytesRead += buffer.length; - break; - case RawSocketEvent.write: - Expect.isTrue(bytesRead == 0); - Expect.isFalse(socket.writeEventsEnabled); - bytesWritten += - socket.write(data, bytesWritten, data.length - bytesWritten); - if (bytesWritten < data.length) { - socket.writeEventsEnabled = true; - } else { - data = new List.filled(messageSize, 0); - } - break; - case RawSocketEvent.readClosed: - verifyTestData(data); - socket.close(); - break; - case RawSocketEvent.closed: - Expect.isFalse(closedEventReceived); - closedEventReceived = true; - break; - default: - throw "Unexpected event $event"; - } - }, onDone: () { - Expect.isTrue(closedEventReceived); - asyncEnd(); - }); + var buffer = socket.read()!; + data.setRange(bytesRead, bytesRead + buffer.length, buffer); + bytesRead += buffer.length; + break; + case RawSocketEvent.write: + Expect.isTrue(bytesRead == 0); + Expect.isFalse(socket.writeEventsEnabled); + bytesWritten += socket.write( + data, + bytesWritten, + data.length - bytesWritten, + ); + if (bytesWritten < data.length) { + socket.writeEventsEnabled = true; + } else { + data = new List.filled(messageSize, 0); + } + break; + case RawSocketEvent.readClosed: + verifyTestData(data); + socket.close(); + break; + case RawSocketEvent.closed: + Expect.isFalse(closedEventReceived); + closedEventReceived = true; + break; + default: + throw "Unexpected event $event"; + } + }, + onDone: () { + Expect.isTrue(closedEventReceived); + asyncEnd(); + }, + ); }); }); } @@ -330,8 +362,11 @@ void testPauseSocket() { if (pauseResumeCount == loopCount) return; Expect.isFalse(client.writeEventsEnabled); Expect.equals(0, bytesRead); // Checks that reader is paused. - bytesWritten += - client.write(data, bytesWritten, data.length - bytesWritten); + bytesWritten += client.write( + data, + bytesWritten, + data.length - bytesWritten, + ); // Ensure all data is written. When done disable the write // event and resume the receiver. if (bytesWritten == data.length) { @@ -426,34 +461,40 @@ void testSocketZone() { void testSocketZoneError() { asyncStart(); Expect.equals(Zone.root, Zone.current); - runZonedGuarded(() { - Expect.notEquals(Zone.root, Zone.current); - RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((server) { + runZonedGuarded( + () { Expect.notEquals(Zone.root, Zone.current); - server.listen((socket) { + RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((server) { Expect.notEquals(Zone.root, Zone.current); - var timer; - void write() { - socket.write(const [0]); - timer = new Timer(const Duration(milliseconds: 5), write); - } - - write(); - socket.listen((_) {}, onError: (error) { - timer.cancel(); + server.listen((socket) { Expect.notEquals(Zone.root, Zone.current); + var timer; + void write() { + socket.write(const [0]); + timer = new Timer(const Duration(milliseconds: 5), write); + } + + write(); + socket.listen( + (_) {}, + onError: (error) { + timer.cancel(); + Expect.notEquals(Zone.root, Zone.current); + socket.close(); + server.close(); + throw error; + }, + ); + }); + RawSocket.connect("127.0.0.1", server.port).then((socket) { socket.close(); - server.close(); - throw error; }); }); - RawSocket.connect("127.0.0.1", server.port).then((socket) { - socket.close(); - }); - }); - }, (e, s) { - asyncEnd(); - }); + }, + (e, s) { + asyncEnd(); + }, + ); } void testClosedError() { @@ -477,12 +518,15 @@ void testClosedServer() { RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((server) { int port = server.port; server.close().then((_) { - RawSocket.connect(InternetAddress.loopbackIPv4, server.port).then((_) { - Expect.fail('Connecting to the closed server socket should fail'); - }, onError: (e) { - Expect.isTrue(e is SocketException); - asyncEnd(); - }); + RawSocket.connect(InternetAddress.loopbackIPv4, server.port).then( + (_) { + Expect.fail('Connecting to the closed server socket should fail'); + }, + onError: (e) { + Expect.isTrue(e is SocketException); + asyncEnd(); + }, + ); }); }); } diff --git a/tests/standalone/io/raw_socket_typed_data_test.dart b/tests/standalone/io/raw_socket_typed_data_test.dart index 09327f221db..5951480188c 100644 --- a/tests/standalone/io/raw_socket_typed_data_test.dart +++ b/tests/standalone/io/raw_socket_typed_data_test.dart @@ -146,7 +146,10 @@ void testSimpleReadWrite() { Expect.isTrue(bytesRead == messageSize); Expect.isFalse(client.writeEventsEnabled); bytesWritten += client.write( - data[index], bytesWritten, data[index].length - bytesWritten); + data[index], + bytesWritten, + data[index].length - bytesWritten, + ); if (bytesWritten < data[index].length) { client.writeEventsEnabled = true; } else { @@ -189,7 +192,10 @@ void testSimpleReadWrite() { Expect.isTrue(bytesRead == 0); Expect.isFalse(socket.writeEventsEnabled); bytesWritten += socket.write( - data[index], bytesWritten, data[index].length - bytesWritten); + data[index], + bytesWritten, + data[index].length - bytesWritten, + ); if (bytesWritten < data[index].length) { socket.writeEventsEnabled = true; } else { diff --git a/tests/standalone/io/raw_synchronous_socket_test.dart b/tests/standalone/io/raw_synchronous_socket_test.dart index ec2bb3bdb0a..3a6f2bcb884 100644 --- a/tests/standalone/io/raw_synchronous_socket_test.dart +++ b/tests/standalone/io/raw_synchronous_socket_test.dart @@ -15,7 +15,8 @@ const String loopbackIPv4String = "127.0.0.1"; void testArguments() { Expect.throws(() => RawSynchronousSocket.connectSync(null, 0)); Expect.throws( - () => RawSynchronousSocket.connectSync(loopbackIPv4String, 65536)); + () => RawSynchronousSocket.connectSync(loopbackIPv4String, 65536), + ); Expect.throws(() => RawSynchronousSocket.connectSync(loopbackIPv4String, -1)); } @@ -46,8 +47,10 @@ void testInvalidConnect() { void testSimpleConnect() { asyncStart(); RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((server) { - var socket = - RawSynchronousSocket.connectSync(loopbackIPv4String, server.port); + var socket = RawSynchronousSocket.connectSync( + loopbackIPv4String, + server.port, + ); server.listen((serverSocket) { Expect.equals(socket.address, serverSocket.remoteAddress); Expect.equals(socket.port, serverSocket.remotePort); @@ -64,8 +67,10 @@ void testServerListenAfterConnect() { asyncStart(); RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((server) { Expect.isTrue(server.port > 0); - var client = - RawSynchronousSocket.connectSync(loopbackIPv4String, server.port); + var client = RawSynchronousSocket.connectSync( + loopbackIPv4String, + server.port, + ); server.listen((socket) { client.closeSync(); server.close(); @@ -88,7 +93,7 @@ enum EchoServerTypes { // The port used to communicate with an isolate. ISOLATE_SEND_PORT, // The port of the newly created echo server. - SERVER_PORT + SERVER_PORT, } List createTestData() { @@ -121,7 +126,7 @@ Future echoServer(var sendPort) async { ReceivePort receivePort = new ReceivePort(); Map response = { EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort, - EchoServerTypes.SERVER_PORT: server.port + EchoServerTypes.SERVER_PORT: server.port, }; sendPort.send(response); Map limits = await receivePort.first; @@ -131,62 +136,71 @@ Future echoServer(var sendPort) async { int connection_count = limits[EchoServerTypes.CONNECTION_COUNT] ?? 1; int connections = 0; sendPort = limits[EchoServerTypes.ISOLATE_SEND_PORT]; - server.listen((client) { - int bytesRead = 0; - int bytesWritten = 0; - bool closedEventReceived = false; - List data = new List.filled(length, 0); - client.writeEventsEnabled = false; - client.listen((event) { - switch (event) { - case RawSocketEvent.read: - Expect.isTrue(bytesWritten == 0); - Expect.isTrue(client.available() > 0); - var buffer = client.read(client.available())!; - data.setRange(bytesRead, bytesRead + buffer.length, buffer); - bytesRead += buffer.length; - // Once we've read all the data, we can echo it back. Otherwise, - // keep waiting for more bytes. - if (bytesRead >= length) { - verifyTestData(data, start, end); - client.writeEventsEnabled = true; + server.listen( + (client) { + int bytesRead = 0; + int bytesWritten = 0; + bool closedEventReceived = false; + List data = new List.filled(length, 0); + client.writeEventsEnabled = false; + client.listen( + (event) { + switch (event) { + case RawSocketEvent.read: + Expect.isTrue(bytesWritten == 0); + Expect.isTrue(client.available() > 0); + var buffer = client.read(client.available())!; + data.setRange(bytesRead, bytesRead + buffer.length, buffer); + bytesRead += buffer.length; + // Once we've read all the data, we can echo it back. Otherwise, + // keep waiting for more bytes. + if (bytesRead >= length) { + verifyTestData(data, start, end); + client.writeEventsEnabled = true; + } + break; + case RawSocketEvent.write: + Expect.isFalse(client.writeEventsEnabled); + bytesWritten += client.write( + data, + bytesWritten, + data.length - bytesWritten, + ); + if (bytesWritten < length) { + client.writeEventsEnabled = true; + } else if (bytesWritten == length) { + // Close the socket for writing from the server since we're done + // writing to this socket. The connection is closed completely + // after the client closes the socket for reading from the server. + client.shutdown(SocketDirection.send); + } + break; + case RawSocketEvent.readClosed: + client.close(); + break; + case RawSocketEvent.closed: + Expect.isFalse(closedEventReceived); + closedEventReceived = true; + break; + default: + throw "Unexpected event $event"; } - break; - case RawSocketEvent.write: - Expect.isFalse(client.writeEventsEnabled); - bytesWritten += - client.write(data, bytesWritten, data.length - bytesWritten); - if (bytesWritten < length) { - client.writeEventsEnabled = true; - } else if (bytesWritten == length) { - // Close the socket for writing from the server since we're done - // writing to this socket. The connection is closed completely - // after the client closes the socket for reading from the server. - client.shutdown(SocketDirection.send); + }, + onDone: () { + Expect.isTrue(closedEventReceived); + connections++; + if (connections >= connection_count) { + server.close(); } - break; - case RawSocketEvent.readClosed: - client.close(); - break; - case RawSocketEvent.closed: - Expect.isFalse(closedEventReceived); - closedEventReceived = true; - break; - default: - throw "Unexpected event $event"; - } - }, onDone: () { - Expect.isTrue(closedEventReceived); - connections++; - if (connections >= connection_count) { - server.close(); - } - }); - }, onDone: () { - // Let the client know we're shutting down then kill the isolate. - sendPort.send(null); - Isolate.current.kill(); - }); + }, + ); + }, + onDone: () { + // Let the client know we're shutting down then kill the isolate. + sendPort.send(null); + Isolate.current.kill(); + }, + ); }); } @@ -213,13 +227,15 @@ Future testSimpleReadWrite({bool? dropReads}) async { Map limits = { EchoServerTypes.OFFSET_START: 0, EchoServerTypes.OFFSET_END: messageSize, - EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort + EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort, }; sendPort.send(limits); try { var socket = RawSynchronousSocket.connectSync( - loopbackIPv4String, serverInternetPort); + loopbackIPv4String, + serverInternetPort, + ); List data = createTestData(); socket.writeFromSync(data); List result = socket.readSync(data.length)!; @@ -257,13 +273,15 @@ Future testPartialRead() async { Map limits = { EchoServerTypes.OFFSET_START: 0, EchoServerTypes.OFFSET_END: 1000, - EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort + EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort, }; sendPort.send(limits); try { var socket = RawSynchronousSocket.connectSync( - loopbackIPv4String, serverInternetPort); + loopbackIPv4String, + serverInternetPort, + ); int half_length = (data.length / 2).toInt(); // Send the full data list to the server. @@ -315,12 +333,14 @@ Future testPartialWrite() async { Map limits = { EchoServerTypes.OFFSET_START: startOffset, EchoServerTypes.OFFSET_END: endOffset, - EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort + EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort, }; sendPort.send(limits); try { var socket = RawSynchronousSocket.connectSync( - loopbackIPv4String, serverInternetPort); + loopbackIPv4String, + serverInternetPort, + ); List data = createTestData(); // Write a subset of data to the server. @@ -369,40 +389,54 @@ Future testShutdown() async { EchoServerTypes.OFFSET_END: data.length, EchoServerTypes.ISOLATE_SEND_PORT: receivePort.sendPort, // Tell the server to shutdown after 3 sockets disconnect. - EchoServerTypes.CONNECTION_COUNT: 3 + EchoServerTypes.CONNECTION_COUNT: 3, }; sendPort.send(limits); try { var socket = RawSynchronousSocket.connectSync( - loopbackIPv4String, serverInternetPort); + loopbackIPv4String, + serverInternetPort, + ); // Close from both directions. Shouldn't be able to read/write to the // socket. socket.shutdown(SocketDirection.both); Expect.throws( - () => socket.writeFromSync(data), (e) => e is SocketException); + () => socket.writeFromSync(data), + (e) => e is SocketException, + ); Expect.throws( - () => socket.readSync(data.length), (e) => e is SocketException); + () => socket.readSync(data.length), + (e) => e is SocketException, + ); socket.closeSync(); // Close the socket for reading then try and perform a read. This should // cause a SocketException. socket = RawSynchronousSocket.connectSync( - loopbackIPv4String, serverInternetPort); + loopbackIPv4String, + serverInternetPort, + ); socket.shutdown(SocketDirection.receive); // Throws exception when the socket is closed for RECEIVE. Expect.throws( - () => socket.readSync(data.length), (e) => e is SocketException); + () => socket.readSync(data.length), + (e) => e is SocketException, + ); socket.closeSync(); // Close the socket for writing and try to do a write. This should cause an // OSError to be throw as the pipe is closed for writing. socket = RawSynchronousSocket.connectSync( - loopbackIPv4String, serverInternetPort); + loopbackIPv4String, + serverInternetPort, + ); socket.shutdown(SocketDirection.send); Expect.throws( - () => socket.writeFromSync(data), (e) => e is SocketException); + () => socket.writeFromSync(data), + (e) => e is SocketException, + ); socket.closeSync(); } catch (e, stack) { print("Echo test failed in client."); @@ -422,21 +456,26 @@ void testInvalidReadWriteOperations() { RawServerSocket.bind(InternetAddress.loopbackIPv4, 0).then((server) { server.listen((socket) {}); List data = createTestData(); - var socket = - RawSynchronousSocket.connectSync(loopbackIPv4String, server.port); + var socket = RawSynchronousSocket.connectSync( + loopbackIPv4String, + server.port, + ); // Invalid writeFromSync invocations Expect.throwsRangeError(() => socket.writeFromSync(data, data.length + 1)); Expect.throwsRangeError( - () => socket.writeFromSync(data, 0, data.length + 1)); + () => socket.writeFromSync(data, 0, data.length + 1), + ); Expect.throwsRangeError(() => socket.writeFromSync(data, 1, 0)); // Invalid readIntoSync invocations List buffer = new List.filled(10, 0); Expect.throwsRangeError( - () => socket.readIntoSync(buffer, buffer.length + 1)); + () => socket.readIntoSync(buffer, buffer.length + 1), + ); Expect.throwsRangeError( - () => socket.readIntoSync(buffer, 0, buffer.length + 1)); + () => socket.readIntoSync(buffer, 0, buffer.length + 1), + ); Expect.throwsRangeError(() => socket.readIntoSync(buffer, 1, 0)); // Invalid readSync invocation @@ -454,8 +493,10 @@ void testClosedError() { server.listen((socket) { socket.close(); }); - var socket = - RawSynchronousSocket.connectSync(loopbackIPv4String, server.port); + var socket = RawSynchronousSocket.connectSync( + loopbackIPv4String, + server.port, + ); server.close(); socket.closeSync(); Expect.throws(() => socket.remotePort, (e) => e is SocketException); diff --git a/tests/standalone/io/regress_10026_test.dart b/tests/standalone/io/regress_10026_test.dart index f9bd5da66d8..4d8e992050f 100644 --- a/tests/standalone/io/regress_10026_test.dart +++ b/tests/standalone/io/regress_10026_test.dart @@ -17,631 +17,634 @@ void testZLibInflate_regress10026() { .transform(zlib.decoder) .transform(utf8.decoder) .fold(new StringBuffer(), (buffer, s) { - buffer.write(s); - return buffer; - }).then((out) { - Expect.equals(out.toString(), expect); - asyncEnd(); - }); + buffer.write(s); + return buffer; + }) + .then((out) { + Expect.equals(out.toString(), expect); + asyncEnd(); + }); controller.add(data); controller.close(); } // Generated by using 'gzip -c | od -v -tu1 -An -w12' and adding commas. - test([ - 31, - 139, - 8, - 8, - 238, - 42, - 167, - 81, - 0, - 3, - 116, - 101, - 120, - 116, - 46, - 116, - 120, - 116, - 0, - 125, - 84, - 79, - 175, - 147, - 64, - 16, - 63, - 183, - 159, - 98, - 196, - 139, - 38, - 165, - 244, - 249, - 212, - 52, - 20, - 136, - 70, - 77, - 188, - 168, - 7, - 189, - 120, - 156, - 178, - 67, - 153, - 20, - 118, - 113, - 119, - 161, - 109, - 140, - 223, - 221, - 97, - 105, - 251, - 170, - 47, - 154, - 54, - 41, - 51, - 195, - 254, - 254, - 49, - 52, - 123, - 162, - 76, - 233, - 79, - 29, - 65, - 237, - 219, - 166, - 152, - 103, - 151, - 31, - 66, - 85, - 204, - 103, - 153, - 103, - 223, - 80, - 241, - 225, - 136, - 109, - 215, - 16, - 188, - 55, - 45, - 178, - 206, - 146, - 169, - 59, - 151, - 121, - 75, - 30, - 161, - 172, - 209, - 58, - 242, - 121, - 212, - 251, - 42, - 94, - 71, - 144, - 20, - 151, - 73, - 237, - 125, - 23, - 211, - 143, - 158, - 135, - 60, - 122, - 103, - 180, - 39, - 237, - 227, - 145, - 45, - 130, - 114, - 170, - 242, - 200, - 211, - 209, - 39, - 35, - 235, - 230, - 138, - 243, - 8, - 70, - 99, - 75, - 121, - 52, - 48, - 29, - 58, - 99, - 253, - 205, - 225, - 3, - 43, - 95, - 231, - 138, - 6, - 46, - 41, - 14, - 197, - 2, - 88, - 179, - 103, - 108, - 98, - 87, - 98, - 67, - 249, - 221, - 25, - 199, - 249, - 147, - 24, - 24, - 185, - 207, - 148, - 165, - 115, - 145, - 12, - 182, - 70, - 157, - 224, - 231, - 124, - 54, - 219, - 98, - 185, - 223, - 89, - 211, - 107, - 21, - 151, - 166, - 49, - 54, - 133, - 167, - 213, - 74, - 62, - 47, - 54, - 50, - 108, - 209, - 238, - 88, - 167, - 176, - 26, - 139, - 14, - 149, - 98, - 189, - 59, - 87, - 149, - 104, - 137, - 43, - 108, - 185, - 57, - 165, - 16, - 125, - 233, - 72, - 195, - 87, - 212, - 46, - 90, - 64, - 244, - 145, - 154, - 129, - 60, - 151, - 8, - 159, - 169, - 39, - 233, - 92, - 27, - 11, - 120, - 107, - 69, - 227, - 2, - 156, - 220, - 26, - 59, - 178, - 92, - 109, - 36, - 206, - 95, - 243, - 153, - 226, - 33, - 200, - 9, - 102, - 82, - 120, - 189, - 90, - 117, - 199, - 91, - 5, - 175, - 168, - 5, - 236, - 189, - 249, - 67, - 200, - 61, - 181, - 155, - 127, - 88, - 168, - 170, - 48, - 49, - 86, - 145, - 141, - 45, - 42, - 238, - 93, - 10, - 119, - 225, - 126, - 97, - 195, - 180, - 97, - 189, - 95, - 0, - 166, - 3, - 59, - 246, - 164, - 2, - 247, - 229, - 240, - 253, - 250, - 229, - 122, - 29, - 206, - 143, - 137, - 197, - 138, - 74, - 99, - 209, - 179, - 17, - 25, - 218, - 104, - 154, - 32, - 222, - 180, - 164, - 24, - 225, - 89, - 139, - 199, - 248, - 86, - 244, - 243, - 41, - 213, - 75, - 188, - 255, - 17, - 39, - 32, - 87, - 219, - 23, - 223, - 23, - 139, - 15, - 201, - 63, - 180, - 254, - 50, - 19, - 158, - 194, - 67, - 22, - 147, - 183, - 17, - 84, - 190, - 89, - 18, - 158, - 187, - 44, - 116, - 50, - 109, - 244, - 60, - 27, - 21, - 73, - 45, - 132, - 227, - 90, - 212, - 119, - 143, - 150, - 91, - 90, - 50, - 232, - 138, - 111, - 53, - 59, - 80, - 161, - 9, - 114, - 69, - 206, - 227, - 182, - 97, - 87, - 75, - 72, - 222, - 192, - 150, - 160, - 119, - 114, - 89, - 25, - 11, - 220, - 52, - 189, - 243, - 99, - 52, - 3, - 1, - 77, - 112, - 78, - 246, - 80, - 78, - 151, - 125, - 43, - 139, - 234, - 150, - 240, - 221, - 244, - 82, - 74, - 110, - 30, - 52, - 5, - 136, - 16, - 180, - 88, - 97, - 141, - 158, - 64, - 96, - 208, - 237, - 3, - 92, - 71, - 182, - 101, - 231, - 36, - 231, - 145, - 72, - 88, - 192, - 223, - 74, - 209, - 87, - 10, - 121, - 110, - 90, - 1, - 251, - 81, - 222, - 8, - 140, - 3, - 114, - 35, - 34, - 105, - 132, - 17, - 120, - 75, - 59, - 158, - 116, - 25, - 189, - 204, - 146, - 110, - 242, - 149, - 201, - 107, - 105, - 169, - 202, - 163, - 241, - 229, - 76, - 147, - 228, - 112, - 56, - 44, - 25, - 53, - 46, - 141, - 221, - 37, - 19, - 137, - 75, - 92, - 71, - 165, - 44, - 104, - 84, - 124, - 50, - 150, - 132, - 83, - 0, - 219, - 9, - 103, - 41, - 72, - 88, - 4, - 180, - 44, - 9, - 41, - 102, - 201, - 57, - 211, - 100, - 250, - 243, - 248, - 13, - 215, - 32, - 235, - 247, - 84, - 4, - 0, - 0 - ], ''' + test( + [ + 31, + 139, + 8, + 8, + 238, + 42, + 167, + 81, + 0, + 3, + 116, + 101, + 120, + 116, + 46, + 116, + 120, + 116, + 0, + 125, + 84, + 79, + 175, + 147, + 64, + 16, + 63, + 183, + 159, + 98, + 196, + 139, + 38, + 165, + 244, + 249, + 212, + 52, + 20, + 136, + 70, + 77, + 188, + 168, + 7, + 189, + 120, + 156, + 178, + 67, + 153, + 20, + 118, + 113, + 119, + 161, + 109, + 140, + 223, + 221, + 97, + 105, + 251, + 170, + 47, + 154, + 54, + 41, + 51, + 195, + 254, + 254, + 49, + 52, + 123, + 162, + 76, + 233, + 79, + 29, + 65, + 237, + 219, + 166, + 152, + 103, + 151, + 31, + 66, + 85, + 204, + 103, + 153, + 103, + 223, + 80, + 241, + 225, + 136, + 109, + 215, + 16, + 188, + 55, + 45, + 178, + 206, + 146, + 169, + 59, + 151, + 121, + 75, + 30, + 161, + 172, + 209, + 58, + 242, + 121, + 212, + 251, + 42, + 94, + 71, + 144, + 20, + 151, + 73, + 237, + 125, + 23, + 211, + 143, + 158, + 135, + 60, + 122, + 103, + 180, + 39, + 237, + 227, + 145, + 45, + 130, + 114, + 170, + 242, + 200, + 211, + 209, + 39, + 35, + 235, + 230, + 138, + 243, + 8, + 70, + 99, + 75, + 121, + 52, + 48, + 29, + 58, + 99, + 253, + 205, + 225, + 3, + 43, + 95, + 231, + 138, + 6, + 46, + 41, + 14, + 197, + 2, + 88, + 179, + 103, + 108, + 98, + 87, + 98, + 67, + 249, + 221, + 25, + 199, + 249, + 147, + 24, + 24, + 185, + 207, + 148, + 165, + 115, + 145, + 12, + 182, + 70, + 157, + 224, + 231, + 124, + 54, + 219, + 98, + 185, + 223, + 89, + 211, + 107, + 21, + 151, + 166, + 49, + 54, + 133, + 167, + 213, + 74, + 62, + 47, + 54, + 50, + 108, + 209, + 238, + 88, + 167, + 176, + 26, + 139, + 14, + 149, + 98, + 189, + 59, + 87, + 149, + 104, + 137, + 43, + 108, + 185, + 57, + 165, + 16, + 125, + 233, + 72, + 195, + 87, + 212, + 46, + 90, + 64, + 244, + 145, + 154, + 129, + 60, + 151, + 8, + 159, + 169, + 39, + 233, + 92, + 27, + 11, + 120, + 107, + 69, + 227, + 2, + 156, + 220, + 26, + 59, + 178, + 92, + 109, + 36, + 206, + 95, + 243, + 153, + 226, + 33, + 200, + 9, + 102, + 82, + 120, + 189, + 90, + 117, + 199, + 91, + 5, + 175, + 168, + 5, + 236, + 189, + 249, + 67, + 200, + 61, + 181, + 155, + 127, + 88, + 168, + 170, + 48, + 49, + 86, + 145, + 141, + 45, + 42, + 238, + 93, + 10, + 119, + 225, + 126, + 97, + 195, + 180, + 97, + 189, + 95, + 0, + 166, + 3, + 59, + 246, + 164, + 2, + 247, + 229, + 240, + 253, + 250, + 229, + 122, + 29, + 206, + 143, + 137, + 197, + 138, + 74, + 99, + 209, + 179, + 17, + 25, + 218, + 104, + 154, + 32, + 222, + 180, + 164, + 24, + 225, + 89, + 139, + 199, + 248, + 86, + 244, + 243, + 41, + 213, + 75, + 188, + 255, + 17, + 39, + 32, + 87, + 219, + 23, + 223, + 23, + 139, + 15, + 201, + 63, + 180, + 254, + 50, + 19, + 158, + 194, + 67, + 22, + 147, + 183, + 17, + 84, + 190, + 89, + 18, + 158, + 187, + 44, + 116, + 50, + 109, + 244, + 60, + 27, + 21, + 73, + 45, + 132, + 227, + 90, + 212, + 119, + 143, + 150, + 91, + 90, + 50, + 232, + 138, + 111, + 53, + 59, + 80, + 161, + 9, + 114, + 69, + 206, + 227, + 182, + 97, + 87, + 75, + 72, + 222, + 192, + 150, + 160, + 119, + 114, + 89, + 25, + 11, + 220, + 52, + 189, + 243, + 99, + 52, + 3, + 1, + 77, + 112, + 78, + 246, + 80, + 78, + 151, + 125, + 43, + 139, + 234, + 150, + 240, + 221, + 244, + 82, + 74, + 110, + 30, + 52, + 5, + 136, + 16, + 180, + 88, + 97, + 141, + 158, + 64, + 96, + 208, + 237, + 3, + 92, + 71, + 182, + 101, + 231, + 36, + 231, + 145, + 72, + 88, + 192, + 223, + 74, + 209, + 87, + 10, + 121, + 110, + 90, + 1, + 251, + 81, + 222, + 8, + 140, + 3, + 114, + 35, + 34, + 105, + 132, + 17, + 120, + 75, + 59, + 158, + 116, + 25, + 189, + 204, + 146, + 110, + 242, + 149, + 201, + 107, + 105, + 169, + 202, + 163, + 241, + 229, + 76, + 147, + 228, + 112, + 56, + 44, + 25, + 53, + 46, + 141, + 221, + 37, + 19, + 137, + 75, + 92, + 71, + 165, + 44, + 104, + 84, + 124, + 50, + 150, + 132, + 83, + 0, + 219, + 9, + 103, + 41, + 72, + 88, + 4, + 180, + 44, + 9, + 41, + 102, + 201, + 57, + 211, + 100, + 250, + 243, + 248, + 13, + 215, + 32, + 235, + 247, + 84, + 4, + 0, + 0, + ], + ''' @@ -693,7 +696,8 @@ void testZLibInflate_regress10026() { -'''); +''', + ); } void main() { diff --git a/tests/standalone/io/regress_21160_test.dart b/tests/standalone/io/regress_21160_test.dart index ad648239516..47b3800046a 100644 --- a/tests/standalone/io/regress_21160_test.dart +++ b/tests/standalone/io/regress_21160_test.dart @@ -18,15 +18,18 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); // 10 KiB of i%256 data. -Uint8List DATA = - new Uint8List.fromList(new List.generate(10 * 1024, (i) => i % 256)); +Uint8List DATA = new Uint8List.fromList( + new List.generate(10 * 1024, (i) => i % 256), +); Future startServer() { return SecureServerSocket.bind("localhost", 0, serverContext).then((server) { @@ -50,37 +53,44 @@ main() async { ..close(); }); - var socket = await RawSecureSocket.connect("localhost", server.port, - context: clientContext); + var socket = await RawSecureSocket.connect( + "localhost", + server.port, + context: clientContext, + ); List body = []; // Close our end, since we're not sending data. socket.shutdown(SocketDirection.send); - socket.listen((RawSocketEvent event) { - switch (event) { - case RawSocketEvent.read: - // NOTE: We have a very low prime number here. The internal - // ring buffers will not have a size of 3. This means that - // we'll reach the point where we would like to read 1/2 bytes - // at the end and then wrap around and read the next 2/1 bytes. - // [This will ensure we trigger the bug.] - body.addAll(socket.read(3)!); - break; - case RawSocketEvent.write: - break; - case RawSocketEvent.readClosed: - break; - default: - throw "Unexpected event $event"; - } - }, onError: (e, _) { - Expect.fail('Unexpected error: $e'); - }, onDone: () { - Expect.equals(body.length, DATA.length); - for (int i = 0; i < body.length; i++) { - Expect.equals(body[i], DATA[i]); - } - server.close(); - asyncEnd(); - }); + socket.listen( + (RawSocketEvent event) { + switch (event) { + case RawSocketEvent.read: + // NOTE: We have a very low prime number here. The internal + // ring buffers will not have a size of 3. This means that + // we'll reach the point where we would like to read 1/2 bytes + // at the end and then wrap around and read the next 2/1 bytes. + // [This will ensure we trigger the bug.] + body.addAll(socket.read(3)!); + break; + case RawSocketEvent.write: + break; + case RawSocketEvent.readClosed: + break; + default: + throw "Unexpected event $event"; + } + }, + onError: (e, _) { + Expect.fail('Unexpected error: $e'); + }, + onDone: () { + Expect.equals(body.length, DATA.length); + for (int i = 0; i < body.length; i++) { + Expect.equals(body[i], DATA[i]); + } + server.close(); + asyncEnd(); + }, + ); } diff --git a/tests/standalone/io/regress_34885_test.dart b/tests/standalone/io/regress_34885_test.dart index 505c7dc205f..292b8d05d95 100644 --- a/tests/standalone/io/regress_34885_test.dart +++ b/tests/standalone/io/regress_34885_test.dart @@ -26,9 +26,13 @@ main() async { Future f = IOOverrides.runZoned( () async { Expect.equals( - await FileSystemEntity.type("file"), FileSystemEntityType.file); + await FileSystemEntity.type("file"), + FileSystemEntityType.file, + ); Expect.equals( - FileSystemEntity.typeSync("file"), FileSystemEntityType.file); + FileSystemEntity.typeSync("file"), + FileSystemEntityType.file, + ); }, fseGetType: FileSystemEntityMock.getType, fseGetTypeSync: FileSystemEntityMock.getTypeSync, diff --git a/tests/standalone/io/regress_44895.dart b/tests/standalone/io/regress_44895.dart index 38c0110aac9..64dde55d1ce 100644 --- a/tests/standalone/io/regress_44895.dart +++ b/tests/standalone/io/regress_44895.dart @@ -8,10 +8,5 @@ void main() { final client = HttpClient(); client.connectionTimeout = Duration.zero; // Should not throw a type error. - client.openUrl( - 'get', - Uri.parse( - 'https://localhost/', - ), - ); + client.openUrl('get', Uri.parse('https://localhost/')); } diff --git a/tests/standalone/io/regress_50206_test.dart b/tests/standalone/io/regress_50206_test.dart index b00bacc6e52..0fc2d3cf6f6 100644 --- a/tests/standalone/io/regress_50206_test.dart +++ b/tests/standalone/io/regress_50206_test.dart @@ -60,8 +60,11 @@ main() async { var chunks = []; var backing = new Uint8List(chunkSize * chunkCount); for (var i = 0; i < chunkCount; i++) { - var chunk = - new Uint8List.view(backing.buffer, i * chunkSize, chunkSize); + var chunk = new Uint8List.view( + backing.buffer, + i * chunkSize, + chunkSize, + ); chunks.add(chunk); } viewTime = await timeWrite(file, chunks); @@ -73,8 +76,11 @@ main() async { var chunks = []; var backing = new Uint8List(chunkSize * chunkCount); for (var i = 0; i < chunkCount; i++) { - var chunk = new Uint8List.view(backing.buffer, i * chunkSize, chunkSize) - .asUnmodifiableView(); + var chunk = new Uint8List.view( + backing.buffer, + i * chunkSize, + chunkSize, + ).asUnmodifiableView(); chunks.add(chunk); } unmodifiableViewTime = await timeWrite(file, chunks); diff --git a/tests/standalone/io/regress_50904_test.dart b/tests/standalone/io/regress_50904_test.dart index 8c3f31ec09c..82e0fdf7976 100644 --- a/tests/standalone/io/regress_50904_test.dart +++ b/tests/standalone/io/regress_50904_test.dart @@ -17,14 +17,11 @@ Future runTest(int length) async { } final digest = sha1.convert(bytes); - final Process proc = await Process.start( - Platform.executable, - [ - ...Platform.executableArguments, - Platform.script.toFilePath(), - 'receiver', - ], - ); + final Process proc = await Process.start(Platform.executable, [ + ...Platform.executableArguments, + Platform.script.toFilePath(), + 'receiver', + ]); proc.stdin.add(bytes); final result = proc.stdout.transform(utf8.decoder).join(); @@ -44,10 +41,11 @@ void main(List arguments) async { // Read [stdin] and respond with `got(bytes,sha1digest)`. var gotBytes = 0; late Digest digest; - final sha1Sink = sha1 - .startChunkedConversion(ChunkedConversionSink.withCallback((result) { - digest = result.first; - })); + final sha1Sink = sha1.startChunkedConversion( + ChunkedConversionSink.withCallback((result) { + digest = result.first; + }), + ); await stdin.listen((chunk) { gotBytes += chunk.length; diff --git a/tests/standalone/io/regress_56049_test.dart b/tests/standalone/io/regress_56049_test.dart index 1414bd83c83..a874903449d 100644 --- a/tests/standalone/io/regress_56049_test.dart +++ b/tests/standalone/io/regress_56049_test.dart @@ -43,21 +43,28 @@ void verifyEvents(List events, String anotherFilePath) { // [subdirPath] and then overwrite `anotherFilePath` with it. Expect.isTrue(events[0] is FileSystemCreateEvent); Expect.isTrue( - events[1] is FileSystemModifyEvent && events[1].path == events[0].path); + events[1] is FileSystemModifyEvent && events[1].path == events[0].path, + ); Expect.isTrue( - events[2] is FileSystemModifyEvent && events[2].path == events[0].path); - Expect.isTrue(events[3] is FileSystemMoveEvent && - events[3].path == events[0].path && - (events[3] as FileSystemMoveEvent).destination == anotherFilePath); + events[2] is FileSystemModifyEvent && events[2].path == events[0].path, + ); + Expect.isTrue( + events[3] is FileSystemMoveEvent && + events[3].path == events[0].path && + (events[3] as FileSystemMoveEvent).destination == anotherFilePath, + ); // File(anotherFilePath).deleteSync(); Expect.isTrue( - events[4] is FileSystemDeleteEvent && events[4].path == anotherFilePath); + events[4] is FileSystemDeleteEvent && events[4].path == anotherFilePath, + ); // f.renameSync(anotherFilePath); Expect.isTrue( - events[5] is FileSystemCreateEvent && events[5].path == anotherFilePath); + events[5] is FileSystemCreateEvent && events[5].path == anotherFilePath, + ); // File(anotherFilePath).deleteSync(); Expect.isTrue( - events[6] is FileSystemDeleteEvent && events[6].path == anotherFilePath); + events[6] is FileSystemDeleteEvent && events[6].path == anotherFilePath, + ); } // Convert `C:\x\y\z` to `\\localhost\C$\x\y\z`. diff --git a/tests/standalone/io/regress_7191_script.dart b/tests/standalone/io/regress_7191_script.dart index a674febd210..11b2c8e8572 100644 --- a/tests/standalone/io/regress_7191_script.dart +++ b/tests/standalone/io/regress_7191_script.dart @@ -11,8 +11,9 @@ main() { // Start sub-process when receiving data. var subscription; subscription = stdin.listen((data) { - Process.start(Platform.executable, [Platform.script.toFilePath()]) - .then((p) { + Process.start(Platform.executable, [Platform.script.toFilePath()]).then(( + p, + ) { p.stdout.listen((_) {}); p.stderr.listen((_) {}); // When receiving data again, kill sub-process and exit. diff --git a/tests/standalone/io/regress_7191_test.dart b/tests/standalone/io/regress_7191_test.dart index 152756c29b7..56907256d1b 100644 --- a/tests/standalone/io/regress_7191_test.dart +++ b/tests/standalone/io/regress_7191_test.dart @@ -22,15 +22,18 @@ main() { var executable = Platform.executable; var script = Platform.script.resolve('regress_7191_script.dart').toFilePath(); Process.start( - executable, - [] - ..addAll(Platform.executableArguments) - ..add(script)) - .then((process) { + executable, + [] + ..addAll(Platform.executableArguments) + ..add(script), + ).then((process) { process.stdin.add([0]); - process.stdout.listen((_) {}, onDone: () { - process.stdin.add([0]); - }); + process.stdout.listen( + (_) {}, + onDone: () { + process.stdin.add([0]); + }, + ); process.stderr.listen((_) {}); process.exitCode.then((exitCode) { asyncEnd(); diff --git a/tests/standalone/io/regress_7679_test.dart b/tests/standalone/io/regress_7679_test.dart index 720e607e3d8..8c8a0671db1 100644 --- a/tests/standalone/io/regress_7679_test.dart +++ b/tests/standalone/io/regress_7679_test.dart @@ -38,12 +38,13 @@ main() { // Note: we prevent this child process from using Crashpad handler because // this introduces an issue with deleting the temporary directory. Process.run( - executable, - [] - ..addAll(Platform.executableArguments) - ..add('script.dart'), - workingDirectory: temp.path, - environment: {'DART_CRASHPAD_HANDLER': ''}).then((result) { + executable, + [] + ..addAll(Platform.executableArguments) + ..add('script.dart'), + workingDirectory: temp.path, + environment: {'DART_CRASHPAD_HANDLER': ''}, + ).then((result) { temp.deleteSync(recursive: true); Expect.equals(0, result.exitCode); }); diff --git a/tests/standalone/io/regress_8828_test.dart b/tests/standalone/io/regress_8828_test.dart index de9891ddf40..a987f4edead 100644 --- a/tests/standalone/io/regress_8828_test.dart +++ b/tests/standalone/io/regress_8828_test.dart @@ -21,15 +21,23 @@ void main() { }); HttpClient client = new HttpClient(); - client.get("127.0.0.1", server.port, "/").then((HttpClientRequest request) { - return request.close(); - }).then((HttpClientResponse response) { - List body = []; - response.listen(body.addAll, onDone: () { - Expect.equals( - "first line\nsecond line\n", new String.fromCharCodes(body)); - server.close(); - }); - }); + client + .get("127.0.0.1", server.port, "/") + .then((HttpClientRequest request) { + return request.close(); + }) + .then((HttpClientResponse response) { + List body = []; + response.listen( + body.addAll, + onDone: () { + Expect.equals( + "first line\nsecond line\n", + new String.fromCharCodes(body), + ); + server.close(); + }, + ); + }); }); } diff --git a/tests/standalone/io/regress_9194_test.dart b/tests/standalone/io/regress_9194_test.dart index c6ca92f9496..8bfb222a65a 100644 --- a/tests/standalone/io/regress_9194_test.dart +++ b/tests/standalone/io/regress_9194_test.dart @@ -14,12 +14,15 @@ void main() { }); HttpClient client = new HttpClient(); - client.get("127.0.0.1", server.port, "/").then((HttpClientRequest request) { - return request.close(); - }).then((HttpClientResponse response) { - Expect.equals("", response.reasonPhrase); - server.close(); - client.close(); - }); + client + .get("127.0.0.1", server.port, "/") + .then((HttpClientRequest request) { + return request.close(); + }) + .then((HttpClientResponse response) { + Expect.equals("", response.reasonPhrase); + server.close(); + client.close(); + }); }); } diff --git a/tests/standalone/io/resolve_symbolic_links_test.dart b/tests/standalone/io/resolve_symbolic_links_test.dart index 3cded60a07d..5e2ac5decfa 100644 --- a/tests/standalone/io/resolve_symbolic_links_test.dart +++ b/tests/standalone/io/resolve_symbolic_links_test.dart @@ -16,85 +16,126 @@ main() { // All of these tests test that resolveSymbolicLinks gives a path // that points to the same place as the original, and that it removes // all links, .., and . segments, and that it produces an absolute path. - asyncTest(() => testFile( - join(testsDir, 'standalone', 'io', 'resolve_symbolic_links_test.dart'))); - asyncTest(() => testFile(join(testsDir, 'standalone', 'io', '..', 'io', - 'resolve_symbolic_links_test.dart'))); + asyncTest( + () => testFile( + join(testsDir, 'standalone', 'io', 'resolve_symbolic_links_test.dart'), + ), + ); + asyncTest( + () => testFile( + join( + testsDir, + 'standalone', + 'io', + '..', + 'io', + 'resolve_symbolic_links_test.dart', + ), + ), + ); asyncTest(() => testDir(join(testsDir, 'standalone', 'io'))); asyncTest(() => testDir(join(testsDir, 'lib', '..', 'standalone', 'io'))); // Test a relative path. if (Platform.isWindows) { - asyncTest(() => testFile(join('\\\\?\\$testsDir', 'standalone', 'io', - 'resolve_symbolic_links_test.dart'))); + asyncTest( + () => testFile( + join( + '\\\\?\\$testsDir', + 'standalone', + 'io', + 'resolve_symbolic_links_test.dart', + ), + ), + ); asyncTest(() => testDir('\\\\?\\$testsDir')); } - asyncTest(() => Directory.systemTemp - .createTemp('dart_resolve_symbolic_links') - .then((tempDir) { - String temp = tempDir.path; - return makeEntities(temp) - .then((_) => Future.wait([ - testFile(join(temp, 'dir1', 'file1')), - testFile(join(temp, 'link1', 'file2')), - testDir(join(temp, 'dir1', 'dir2', '..', '.', '..', 'dir1')), - testDir(join(temp, 'dir1', 'dir2', '..', '.', '..', 'dir1')), - testLink(join(temp, 'link1')), - testDir('.') - ])) - .then((_) { - if (Platform.isWindows) { - // Windows applies '..' to a link without resolving the link first. - return Future.wait([ - testFile(join( - temp, 'dir1', '..', 'link1', '..', 'dir1', 'dir2', 'file2')), - testDir(join(temp, 'dir1', '..', 'link1', '..', 'dir1')), - testLink(join(temp, 'link1', '..', 'link1')) - ]); - } else { - // Non-Windows platforms resolve the link before adding the '..'. + asyncTest( + () => Directory.systemTemp.createTemp('dart_resolve_symbolic_links').then(( + tempDir, + ) { + String temp = tempDir.path; + return makeEntities(temp) + .then( + (_) => Future.wait([ + testFile(join(temp, 'dir1', 'file1')), + testFile(join(temp, 'link1', 'file2')), + testDir(join(temp, 'dir1', 'dir2', '..', '.', '..', 'dir1')), + testDir(join(temp, 'dir1', 'dir2', '..', '.', '..', 'dir1')), + testLink(join(temp, 'link1')), + testDir('.'), + ]), + ) + .then((_) { + if (Platform.isWindows) { + // Windows applies '..' to a link without resolving the link first. + return Future.wait([ + testFile( + join( + temp, + 'dir1', + '..', + 'link1', + '..', + 'dir1', + 'dir2', + 'file2', + ), + ), + testDir(join(temp, 'dir1', '..', 'link1', '..', 'dir1')), + testLink(join(temp, 'link1', '..', 'link1')), + ]); + } else { + // Non-Windows platforms resolve the link before adding the '..'. + return Future.wait([ + testFile( + join(temp, 'dir1', '..', 'link1', '..', 'dir2', 'file2'), + ), + testDir(join(temp, 'dir1', '..', 'link1', '..', 'dir2')), + testLink(join(temp, 'link1', '..', '..', 'link1')), + ]); + } + }) + .then((_) { + Directory.current = temp; return Future.wait([ testFile( - join(temp, 'dir1', '..', 'link1', '..', 'dir2', 'file2')), - testDir(join(temp, 'dir1', '..', 'link1', '..', 'dir2')), - testLink(join(temp, 'link1', '..', '..', 'link1')) - ]); - } - }).then((_) { - Directory.current = temp; - return Future.wait([ - testFile('dir1/dir2/file2'), // Test forward slashes on Windows too. - testFile('link1/file2'), - testFile(join('dir1', '..', 'dir1', '.', 'file1')), - testDir('.'), - testLink('link1') - ]); - }).then((_) { - Directory.current = 'link1'; - if (Platform.isWindows) { - return Future.wait([ - testFile('file2'), - // Windows applies '..' to a link without resolving the link first. - testFile('..\\dir1\\file1'), - testLink('.'), - testDir('..'), - testLink('..\\link1') - ]); - } else { - return Future.wait([ - testFile('file2'), - // On non-Windows the link is changed to dir1/dir2 before .. happens. - testFile('../dir2/file2'), + 'dir1/dir2/file2', + ), // Test forward slashes on Windows too. + testFile('link1/file2'), + testFile(join('dir1', '..', 'dir1', '.', 'file1')), testDir('.'), - testDir('..'), - testLink('../../link1') + testLink('link1'), ]); - } - }).whenComplete(() { - Directory.current = testsDir; - tempDir.delete(recursive: true); - }); - })); + }) + .then((_) { + Directory.current = 'link1'; + if (Platform.isWindows) { + return Future.wait([ + testFile('file2'), + // Windows applies '..' to a link without resolving the link first. + testFile('..\\dir1\\file1'), + testLink('.'), + testDir('..'), + testLink('..\\link1'), + ]); + } else { + return Future.wait([ + testFile('file2'), + // On non-Windows the link is changed to dir1/dir2 before .. happens. + testFile('../dir2/file2'), + testDir('.'), + testDir('..'), + testLink('../../link1'), + ]); + } + }) + .whenComplete(() { + Directory.current = testsDir; + tempDir.delete(recursive: true); + }); + }), + ); asyncTest(testNonExistantPath); asyncTest(testLinkTargetTypeChangedAfterCreation); @@ -105,8 +146,9 @@ Future makeEntities(String temp) { .create(recursive: true) .then((_) => new File(join(temp, 'dir1', 'dir2', 'file2')).create()) .then((_) => new File(join(temp, 'dir1', 'file1')).create()) - .then((_) => - new Link(join(temp, 'link1')).create(join(temp, 'dir1', 'dir2'))); + .then( + (_) => new Link(join(temp, 'link1')).create(join(temp, 'dir1', 'dir2')), + ); } Future testFile(String name) { @@ -127,8 +169,12 @@ Future testFile(String name) { } Future testDir(String name) { - Expect.isTrue(FileSystemEntity.identicalSync( - name, new Directory(name).resolveSymbolicLinksSync())); + Expect.isTrue( + FileSystemEntity.identicalSync( + name, + new Directory(name).resolveSymbolicLinksSync(), + ), + ); return new Directory(name).resolveSymbolicLinks().then((String resolved) { Expect.isTrue(FileSystemEntity.identicalSync(name, resolved)); Expect.isTrue(isAbsolute(resolved)); @@ -140,10 +186,18 @@ Future testDir(String name) { } Future testLink(String name) { - Expect.isFalse(FileSystemEntity.identicalSync( - name, new Link(name).resolveSymbolicLinksSync())); - Expect.isTrue(FileSystemEntity.identicalSync( - new Link(name).targetSync(), new Link(name).resolveSymbolicLinksSync())); + Expect.isFalse( + FileSystemEntity.identicalSync( + name, + new Link(name).resolveSymbolicLinksSync(), + ), + ); + Expect.isTrue( + FileSystemEntity.identicalSync( + new Link(name).targetSync(), + new Link(name).resolveSymbolicLinksSync(), + ), + ); return new Link(name).resolveSymbolicLinks().then((String resolved) { Expect.isFalse(FileSystemEntity.identicalSync(name, resolved)); Expect.isTrue(isAbsolute(resolved)); @@ -171,25 +225,35 @@ Future testLinkTargetTypeChangedAfterCreation() async { // 2. create a link to that file // 3. replace the file with a directory // 4. attempt to resolve the link - final tmp = - await Directory.systemTemp.createTemp('dart_resolve_symbolic_links'); + final tmp = await Directory.systemTemp.createTemp( + 'dart_resolve_symbolic_links', + ); final tmpPath = tmp.absolute.path; final filePath = join(tmpPath, "file"); final linkPath = join(tmpPath, "link"); await File(filePath).create(); await Link(linkPath).create(filePath); - Expect.isTrue(FileSystemEntity.identicalSync( - filePath, await Directory(linkPath).resolveSymbolicLinks())); + Expect.isTrue( + FileSystemEntity.identicalSync( + filePath, + await Directory(linkPath).resolveSymbolicLinks(), + ), + ); await File(filePath).delete(); await Directory(filePath).create(); if (Platform.isWindows) { await asyncExpectThrows( - Directory(linkPath).resolveSymbolicLinks()); + Directory(linkPath).resolveSymbolicLinks(), + ); } else { - Expect.isTrue(await FileSystemEntity.identical( - filePath, await Directory(linkPath).resolveSymbolicLinks())); + Expect.isTrue( + await FileSystemEntity.identical( + filePath, + await Directory(linkPath).resolveSymbolicLinks(), + ), + ); } } diff --git a/tests/standalone/io/secure_bad_certificate_test.dart b/tests/standalone/io/secure_bad_certificate_test.dart index e00231356ae..10e15b9ce36 100644 --- a/tests/standalone/io/secure_bad_certificate_test.dart +++ b/tests/standalone/io/secure_bad_certificate_test.dart @@ -21,35 +21,51 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext badServerContext = new SecurityContext() ..useCertificateChain(localFile('certificates/bad_server_chain.pem')) - ..usePrivateKey(localFile('certificates/bad_server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/bad_server_key.pem'), + password: 'dartdart', + ); class CustomException {} main() async { var HOST = (await InternetAddress.lookup(HOST_NAME)).first; var server = await SecureServerSocket.bind(HOST_NAME, 0, serverContext); - server.listen((SecureSocket socket) { - socket.listen((_) {}, onDone: () { - socket.close(); - }); - }, onError: (e) { - if (e is! HandshakeException) throw e; - }); + server.listen( + (SecureSocket socket) { + socket.listen( + (_) {}, + onDone: () { + socket.close(); + }, + ); + }, + onError: (e) { + if (e is! HandshakeException) throw e; + }, + ); var badServer = await SecureServerSocket.bind(HOST_NAME, 0, badServerContext); - badServer.listen((SecureSocket socket) { - socket.listen((_) {}, onDone: () { - socket.close(); - }); - }, onError: (e) { - if (e is! HandshakeException) throw e; - }); + badServer.listen( + (SecureSocket socket) { + socket.listen( + (_) {}, + onDone: () { + socket.close(); + }, + ); + }, + onError: (e) { + if (e is! HandshakeException) throw e; + }, + ); SecurityContext goodContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -76,7 +92,11 @@ main() async { } Future runClient( - int port, SecurityContext context, callbackReturns, result) async { + int port, + SecurityContext context, + callbackReturns, + result, +) async { bool badCertificateCallback(X509Certificate certificate) { Expect.isNotNull(certificate.subject); Expect.isNotNull(certificate.issuer); @@ -87,8 +107,12 @@ Future runClient( } try { - var socket = await SecureSocket.connect(HOST_NAME, port, - context: context, onBadCertificate: badCertificateCallback); + var socket = await SecureSocket.connect( + HOST_NAME, + port, + context: context, + onBadCertificate: badCertificateCallback, + ); Expect.equals('pass', result); // Is rethrown below await socket.close(); } catch (error) { diff --git a/tests/standalone/io/secure_client_raw_server_test.dart b/tests/standalone/io/secure_client_raw_server_test.dart index 577add7619c..fe78a7e036e 100644 --- a/tests/standalone/io/secure_client_raw_server_test.dart +++ b/tests/standalone/io/secure_client_raw_server_test.dart @@ -20,8 +20,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -45,7 +47,10 @@ Future startEchoServer() { Expect.isFalse(client.writeEventsEnabled); Expect.isNotNull(dataToWrite); bytesWritten += client.write( - dataToWrite!, bytesWritten, dataToWrite!.length - bytesWritten); + dataToWrite!, + bytesWritten, + dataToWrite!.length - bytesWritten, + ); if (bytesWritten < dataToWrite!.length) { client.writeEventsEnabled = true; } @@ -70,18 +75,22 @@ Future startEchoServer() { Future testClient(server) { Completer success = new Completer(); List chunks = []; - SecureSocket.connect(HOST, server.port, context: clientContext) - .then((socket) { + SecureSocket.connect(HOST, server.port, context: clientContext).then(( + socket, + ) { socket.write("Hello server."); socket.close(); - socket.listen((List data) { - var received = new String.fromCharCodes(data); - chunks.add(received); - }, onDone: () { - String reply = chunks.join(); - Expect.equals("Hello server.", reply); - success.complete(server); - }); + socket.listen( + (List data) { + var received = new String.fromCharCodes(data); + chunks.add(received); + }, + onDone: () { + String reply = chunks.join(); + Expect.equals("Hello server.", reply); + success.complete(server); + }, + ); }); return success.future; } diff --git a/tests/standalone/io/secure_client_server_test.dart b/tests/standalone/io/secure_client_server_test.dart index a88cbae6a4c..277f1562d41 100644 --- a/tests/standalone/io/secure_client_server_test.dart +++ b/tests/standalone/io/secure_client_server_test.dart @@ -22,8 +22,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -31,11 +33,12 @@ SecurityContext clientContext = new SecurityContext() Future startEchoServer() { return SecureServerSocket.bind(HOST, 0, serverContext).then((server) { server.listen((SecureSocket client) { - client.fold>( - [], (message, data) => message..addAll(data)).then((message) { - client.add(message); - client.close(); - }); + client + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + client.add(message); + client.close(); + }); }); return server; }); @@ -43,8 +46,9 @@ Future startEchoServer() { void checkServerCertificate(X509Certificate serverCert) { String serverCertString = serverCert.pem; - String certFile = - new File(localFile('certificates/server_chain.pem')).readAsStringSync(); + String certFile = new File( + localFile('certificates/server_chain.pem'), + ).readAsStringSync(); Expect.isTrue(certFile.contains(serverCertString)); // Computed with: @@ -58,16 +62,18 @@ void checkServerCertificate(X509Certificate serverCert) { } Future testClient(server) { - return SecureSocket.connect(HOST, server.port, context: clientContext) - .then((socket) { + return SecureSocket.connect(HOST, server.port, context: clientContext).then(( + socket, + ) { checkServerCertificate(socket.peerCertificate!); socket.write("Hello server."); socket.close(); - return socket.fold>( - [], (message, data) => message..addAll(data)).then((message) { - Expect.listEquals("Hello server.".codeUnits, message); - return server; - }); + return socket + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + Expect.listEquals("Hello server.".codeUnits, message); + return server; + }); }); } diff --git a/tests/standalone/io/secure_key_log_test.dart b/tests/standalone/io/secure_key_log_test.dart index 1e7ecb0e329..36e2bf3428b 100644 --- a/tests/standalone/io/secure_key_log_test.dart +++ b/tests/standalone/io/secure_key_log_test.dart @@ -22,17 +22,20 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); Future startEchoServer() { return SecureServerSocket.bind(HOST, 0, serverContext).then((server) { server.listen((SecureSocket client) { - client.fold>( - [], (message, data) => message..addAll(data)).then((message) { - client.add(message); - client.close(); - }); + client + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + client.add(message); + client.close(); + }); }); return server; }); @@ -43,10 +46,14 @@ testSuccess(SecureServerSocket server) async { SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); - await SecureSocket.connect(HOST, server.port, context: clientContext, - keyLog: (line) { - log += line; - }).then((socket) { + await SecureSocket.connect( + HOST, + server.port, + context: clientContext, + keyLog: (line) { + log += line; + }, + ).then((socket) { socket.write("Hello server."); socket.close(); return socket.drain().then((value) { @@ -61,11 +68,15 @@ testExceptionInKeyLogFunction(SecureServerSocket server) async { ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); var numCalls = 0; - await SecureSocket.connect(HOST, server.port, context: clientContext, - keyLog: (line) { - ++numCalls; - throw FileSystemException("Something bad happened"); - }).then((socket) { + await SecureSocket.connect( + HOST, + server.port, + context: clientContext, + keyLog: (line) { + ++numCalls; + throw FileSystemException("Something bad happened"); + }, + ).then((socket) { socket.close(); return socket.drain().then((value) { Expect.notEquals(0, numCalls); diff --git a/tests/standalone/io/secure_multiple_client_server_test.dart b/tests/standalone/io/secure_multiple_client_server_test.dart index ca089eefb83..79cac187e24 100644 --- a/tests/standalone/io/secure_multiple_client_server_test.dart +++ b/tests/standalone/io/secure_multiple_client_server_test.dart @@ -23,8 +23,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -33,27 +35,30 @@ Future startServer() { return SecureServerSocket.bind(HOST, 0, serverContext).then((server) { SERVER = server; SERVER.listen((SecureSocket client) { - client.fold>( - [], (message, data) => message..addAll(data)).then((message) { - String received = new String.fromCharCodes(message); - Expect.isTrue(received.contains("Hello from client ")); - String name = received.substring(received.indexOf("client ") + 7); - client.add("Welcome, client $name".codeUnits); - client.close(); - }); + client + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + String received = new String.fromCharCodes(message); + Expect.isTrue(received.contains("Hello from client ")); + String name = received.substring(received.indexOf("client ") + 7); + client.add("Welcome, client $name".codeUnits); + client.close(); + }); }); }); } Future testClient(name) { - return SecureSocket.connect(HOST, SERVER.port, context: clientContext) - .then((socket) { + return SecureSocket.connect(HOST, SERVER.port, context: clientContext).then(( + socket, + ) { socket.add("Hello from client $name".codeUnits); socket.close(); - return socket.fold>( - [], (message, data) => message..addAll(data)).then((message) { - Expect.listEquals("Welcome, client $name".codeUnits, message); - }); + return socket + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + Expect.listEquals("Welcome, client $name".codeUnits, message); + }); }); } diff --git a/tests/standalone/io/secure_server_client_certificate_test.dart b/tests/standalone/io/secure_server_client_certificate_test.dart index d32450cf7d4..26070b844e3 100644 --- a/tests/standalone/io/secure_server_client_certificate_test.dart +++ b/tests/standalone/io/secure_server_client_certificate_test.dart @@ -27,46 +27,65 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext(String certType, String password) => new SecurityContext() - ..useCertificateChain(localFile('certificates/server_chain.$certType'), - password: password) - ..usePrivateKey(localFile('certificates/server_key.$certType'), - password: password) + ..useCertificateChain( + localFile('certificates/server_chain.$certType'), + password: password, + ) + ..usePrivateKey( + localFile('certificates/server_key.$certType'), + password: password, + ) ..setTrustedCertificates( - localFile('certificates/client_authority.$certType'), - password: password) + localFile('certificates/client_authority.$certType'), + password: password, + ) ..setClientAuthorities( - localFile('certificates/client_authority.$certType'), - password: password); + localFile('certificates/client_authority.$certType'), + password: password, + ); SecurityContext clientCertContext(String certType, String password) => new SecurityContext() ..setTrustedCertificates( - localFile('certificates/trusted_certs.$certType'), - password: password) - ..useCertificateChain(localFile('certificates/client1.$certType'), - password: password) - ..usePrivateKey(localFile('certificates/client1_key.$certType'), - password: password); + localFile('certificates/trusted_certs.$certType'), + password: password, + ) + ..useCertificateChain( + localFile('certificates/client1.$certType'), + password: password, + ) + ..usePrivateKey( + localFile('certificates/client1_key.$certType'), + password: password, + ); SecurityContext clientNoCertContext(String certType, String password) => - new SecurityContext() - ..setTrustedCertificates( - localFile('certificates/trusted_certs.$certType'), - password: password); + new SecurityContext()..setTrustedCertificates( + localFile('certificates/trusted_certs.$certType'), + password: password, + ); -Future testClientCertificate( - {required bool required, - required bool sendCert, - required String certType, - required String password}) async { +Future testClientCertificate({ + required bool required, + required bool sendCert, + required String certType, + required String password, +}) async { var server = await SecureServerSocket.bind( - HOST, 0, serverContext(certType, password), - requestClientCertificate: true, requireClientCertificate: required); + HOST, + 0, + serverContext(certType, password), + requestClientCertificate: true, + requireClientCertificate: required, + ); var clientContext = sendCert ? clientCertContext(certType, password) : clientNoCertContext(certType, password); - var clientEndFuture = - SecureSocket.connect(HOST, server.port, context: clientContext); + var clientEndFuture = SecureSocket.connect( + HOST, + server.port, + context: clientContext, + ); if (required && !sendCert) { final serverErrorCompleter = Completer(); server.listen((request) { @@ -77,13 +96,17 @@ Future testClientCertificate( final clientEnd = await clientEndFuture; clientEnd.write([5, 6, 7, 8]); clientEnd.close(); - clientEnd.listen((data) { - Expect.fail('Should not get data through'); - }, onError: (e) { - Expect.isTrue(e is SocketException); - }, onDone: () { - clientDisconnected.complete(); - }); + clientEnd.listen( + (data) { + Expect.fail('Should not get data through'); + }, + onError: (e) { + Expect.isTrue(e is SocketException); + }, + onDone: () { + clientDisconnected.complete(); + }, + ); Expect.isTrue(await serverErrorCompleter.future is HandshakeException); // Client might not report an error, might get just disconnected. await clientDisconnected.future; @@ -113,32 +136,80 @@ main() async { // Test client certificate when host is a DNS name HOST = (await InternetAddress.lookup("localhost")).first; await testClientCertificate( - required: false, sendCert: true, certType: 'pem', password: 'dartdart'); + required: false, + sendCert: true, + certType: 'pem', + password: 'dartdart', + ); await testClientCertificate( - required: true, sendCert: true, certType: 'pem', password: 'dartdart'); + required: true, + sendCert: true, + certType: 'pem', + password: 'dartdart', + ); await testClientCertificate( - required: false, sendCert: false, certType: 'pem', password: 'dartdart'); + required: false, + sendCert: false, + certType: 'pem', + password: 'dartdart', + ); await testClientCertificate( - required: true, sendCert: false, certType: 'pem', password: 'dartdart'); + required: true, + sendCert: false, + certType: 'pem', + password: 'dartdart', + ); await testClientCertificate( - required: false, sendCert: true, certType: 'p12', password: 'dartdart'); + required: false, + sendCert: true, + certType: 'p12', + password: 'dartdart', + ); await testClientCertificate( - required: true, sendCert: true, certType: 'p12', password: 'dartdart'); + required: true, + sendCert: true, + certType: 'p12', + password: 'dartdart', + ); await testClientCertificate( - required: false, sendCert: false, certType: 'p12', password: 'dartdart'); + required: false, + sendCert: false, + certType: 'p12', + password: 'dartdart', + ); await testClientCertificate( - required: true, sendCert: false, certType: 'p12', password: 'dartdart'); + required: true, + sendCert: false, + certType: 'p12', + password: 'dartdart', + ); // Test client certificate when host is an IP address HOST = InternetAddress.loopbackIPv4; await testClientCertificate( - required: false, sendCert: true, certType: 'pem', password: 'dartdart'); + required: false, + sendCert: true, + certType: 'pem', + password: 'dartdart', + ); await testClientCertificate( - required: true, sendCert: true, certType: 'pem', password: 'dartdart'); + required: true, + sendCert: true, + certType: 'pem', + password: 'dartdart', + ); await testClientCertificate( - required: false, sendCert: false, certType: 'pem', password: 'dartdart'); + required: false, + sendCert: false, + certType: 'pem', + password: 'dartdart', + ); await testClientCertificate( - required: true, sendCert: false, certType: 'pem', password: 'dartdart'); + required: true, + sendCert: false, + certType: 'pem', + password: 'dartdart', + ); asyncEnd(); } diff --git a/tests/standalone/io/secure_server_closing_test.dart b/tests/standalone/io/secure_server_closing_test.dart index f40a9882daa..d4023db9666 100644 --- a/tests/standalone/io/secure_server_closing_test.dart +++ b/tests/standalone/io/secure_server_closing_test.dart @@ -22,8 +22,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -33,33 +35,46 @@ void testCloseOneEnd(String toClose) { Completer serverDone = new Completer(); Completer serverEndDone = new Completer(); Completer clientEndDone = new Completer(); - Future.wait([serverDone.future, serverEndDone.future, clientEndDone.future]) - .then((_) { + Future.wait([ + serverDone.future, + serverEndDone.future, + clientEndDone.future, + ]).then((_) { asyncEnd(); }); SecureServerSocket.bind(HOST, 0, serverContext).then((server) { - server.listen((serverConnection) { - serverConnection.listen((data) { - Expect.fail("No data should be received by server"); - }, onDone: () { - serverConnection.close(); - serverEndDone.complete(null); - server.close(); - }); - if (toClose == "server") { - serverConnection.close(); - } - }, onDone: () { - serverDone.complete(null); - }); - SecureSocket.connect(HOST, server.port, context: clientContext) - .then((clientConnection) { - clientConnection.listen((data) { - Expect.fail("No data should be received by client"); - }, onDone: () { - clientConnection.close(); - clientEndDone.complete(null); - }); + server.listen( + (serverConnection) { + serverConnection.listen( + (data) { + Expect.fail("No data should be received by server"); + }, + onDone: () { + serverConnection.close(); + serverEndDone.complete(null); + server.close(); + }, + ); + if (toClose == "server") { + serverConnection.close(); + } + }, + onDone: () { + serverDone.complete(null); + }, + ); + SecureSocket.connect(HOST, server.port, context: clientContext).then(( + clientConnection, + ) { + clientConnection.listen( + (data) { + Expect.fail("No data should be received by client"); + }, + onDone: () { + clientConnection.close(); + clientEndDone.complete(null); + }, + ); if (toClose == "client") { clientConnection.close(); } @@ -70,8 +85,11 @@ void testCloseOneEnd(String toClose) { void testCloseBothEnds() { asyncStart(); SecureServerSocket.bind(HOST, 0, serverContext).then((server) { - var clientEndFuture = - SecureSocket.connect(HOST, server.port, context: clientContext); + var clientEndFuture = SecureSocket.connect( + HOST, + server.port, + context: clientContext, + ); server.listen((serverEnd) { clientEndFuture.then((clientEnd) { clientEnd.destroy(); @@ -90,8 +108,12 @@ testPauseServerSocket() { asyncStart(); - SecureServerSocket.bind(HOST, 0, serverContext, backlog: 2 * socketCount) - .then((server) { + SecureServerSocket.bind( + HOST, + 0, + serverContext, + backlog: 2 * socketCount, + ).then((server) { Expect.isTrue(server.port > 0); var subscription; subscription = server.listen((connection) { @@ -108,8 +130,9 @@ testPauseServerSocket() { subscription.pause(); var connectCount = 0; for (int i = 0; i < socketCount; i++) { - SecureSocket.connect(HOST, server.port, context: clientContext) - .then((connection) { + SecureSocket.connect(HOST, server.port, context: clientContext).then(( + connection, + ) { connection.close(); }); } @@ -117,8 +140,9 @@ testPauseServerSocket() { subscription.resume(); resumed = true; for (int i = 0; i < socketCount; i++) { - SecureSocket.connect(HOST, server.port, context: clientContext) - .then((connection) { + SecureSocket.connect(HOST, server.port, context: clientContext).then(( + connection, + ) { connection.close(); }); } @@ -149,8 +173,9 @@ testCloseServer() { }); for (int i = 0; i < socketCount; i++) { - SecureSocket.connect(HOST, server.port, context: clientContext) - .then((connection) { + SecureSocket.connect(HOST, server.port, context: clientContext).then(( + connection, + ) { ends.add(connection); checkDone(); }); diff --git a/tests/standalone/io/secure_server_socket_test.dart b/tests/standalone/io/secure_server_socket_test.dart index 385f23d8f84..0b51ef8746f 100644 --- a/tests/standalone/io/secure_server_socket_test.dart +++ b/tests/standalone/io/secure_server_socket_test.dart @@ -22,8 +22,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -42,40 +44,49 @@ void testInvalidBind() { // Bind to a unknown DNS name. asyncStart(); - SecureServerSocket.bind("ko.faar.__hest__", 0, serverContext).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - asyncEnd(); - }); + SecureServerSocket.bind("ko.faar.__hest__", 0, serverContext) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + asyncEnd(); + }); // Bind to an unavailable IP-address. asyncStart(); - SecureServerSocket.bind("8.8.8.8", 0, serverContext).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - asyncEnd(); - }); + SecureServerSocket.bind("8.8.8.8", 0, serverContext) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + asyncEnd(); + }); // Bind to a port already in use. asyncStart(); SecureServerSocket.bind(HOST, 0, serverContext).then((s) { - SecureServerSocket.bind(HOST, s.port, serverContext).then((t) { - Expect.fail("Multiple listens on same port"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - s.close(); - asyncEnd(); - }); + SecureServerSocket.bind(HOST, s.port, serverContext) + .then((t) { + Expect.fail("Multiple listens on same port"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + s.close(); + asyncEnd(); + }); }); } void testSimpleConnect() { asyncStart(); SecureServerSocket.bind(HOST, 0, serverContext).then((server) { - var clientEndFuture = - SecureSocket.connect(HOST, server.port, context: clientContext); + var clientEndFuture = SecureSocket.connect( + HOST, + server.port, + context: clientContext, + ); server.listen((serverEnd) { clientEndFuture.then((clientEnd) { var x5 = clientEnd.peerCertificate!; @@ -92,35 +103,47 @@ void testSimpleConnect() { }); } -void testSimpleConnectFail(SecurityContext? serverContext, - SecurityContext? clientContext, bool cancelOnError) { +void testSimpleConnectFail( + SecurityContext? serverContext, + SecurityContext? clientContext, + bool cancelOnError, +) { print('$serverContext $clientContext $cancelOnError'); asyncStart(); SecureServerSocket.bind(HOST, 0, serverContext).then((server) { Future clientEndFuture = SecureSocket.connect(HOST, server.port, context: clientContext) .then((clientEnd) { - Expect.fail("No client connection expected."); - }).catchError((error) { - // TODO(whesse): When null context is supported, disallow - // the ArgumentError type here. - Expect.isTrue(error is ArgumentError || - error is HandshakeException || - error is SocketException); - }); - server.listen((serverEnd) { - Expect.fail("No server connection expected."); - }, onError: (error) { - // TODO(whesse): When null context is supported, disallow - // the ArgumentError type here. - Expect.isTrue(error is ArgumentError || - error is HandshakeException || - error is SocketException); - clientEndFuture.then((_) { - if (!cancelOnError) server.close(); - asyncEnd(); - }); - }, cancelOnError: cancelOnError); + Expect.fail("No client connection expected."); + }) + .catchError((error) { + // TODO(whesse): When null context is supported, disallow + // the ArgumentError type here. + Expect.isTrue( + error is ArgumentError || + error is HandshakeException || + error is SocketException, + ); + }); + server.listen( + (serverEnd) { + Expect.fail("No server connection expected."); + }, + onError: (error) { + // TODO(whesse): When null context is supported, disallow + // the ArgumentError type here. + Expect.isTrue( + error is ArgumentError || + error is HandshakeException || + error is SocketException, + ); + clientEndFuture.then((_) { + if (!cancelOnError) server.close(); + asyncEnd(); + }); + }, + cancelOnError: cancelOnError, + ); }); } @@ -128,8 +151,11 @@ void testServerListenAfterConnect() { asyncStart(); SecureServerSocket.bind(HOST, 0, serverContext).then((server) { Expect.isTrue(server.port > 0); - var clientEndFuture = - SecureSocket.connect(HOST, server.port, context: clientContext); + var clientEndFuture = SecureSocket.connect( + HOST, + server.port, + context: clientContext, + ); new Timer(const Duration(milliseconds: 500), () { server.listen((serverEnd) { clientEndFuture.then((clientEnd) { @@ -174,36 +200,43 @@ void testSimpleReadWrite() { int bytesWritten = 0; List data = new List.filled(messageSize, 0); - client.listen((buffer) { - Expect.isTrue(bytesWritten == 0); - data.setRange(bytesRead, bytesRead + buffer.length, buffer); - bytesRead += buffer.length; - if (bytesRead == data.length) { - verifyTestData(data); - client.add(data); - client.close(); - } - }, onDone: () { - server.close(); - }); + client.listen( + (buffer) { + Expect.isTrue(bytesWritten == 0); + data.setRange(bytesRead, bytesRead + buffer.length, buffer); + bytesRead += buffer.length; + if (bytesRead == data.length) { + verifyTestData(data); + client.add(data); + client.close(); + } + }, + onDone: () { + server.close(); + }, + ); }); - SecureSocket.connect(HOST, server.port, context: clientContext) - .then((socket) { + SecureSocket.connect(HOST, server.port, context: clientContext).then(( + socket, + ) { int bytesRead = 0; int bytesWritten = 0; List dataSent = createTestData(); List dataReceived = new List.filled(dataSent.length, 0); socket.add(dataSent); socket.close(); // Can also be delayed. - socket.listen((List buffer) { - dataReceived.setRange(bytesRead, bytesRead + buffer.length, buffer); - bytesRead += buffer.length; - }, onDone: () { - verifyTestData(dataReceived); - socket.close(); - asyncEnd(); - }); + socket.listen( + (List buffer) { + dataReceived.setRange(bytesRead, bytesRead + buffer.length, buffer); + bytesRead += buffer.length; + }, + onDone: () { + verifyTestData(dataReceived); + socket.close(); + asyncEnd(); + }, + ); }); }); } diff --git a/tests/standalone/io/secure_session_resume_test.dart b/tests/standalone/io/secure_session_resume_test.dart index 47d96effec0..564720ffb52 100644 --- a/tests/standalone/io/secure_session_resume_test.dart +++ b/tests/standalone/io/secure_session_resume_test.dart @@ -32,8 +32,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -41,29 +43,32 @@ SecurityContext clientContext = new SecurityContext() Future startServer() { return SecureServerSocket.bind(HOST, 0, serverContext).then((server) { server.listen((SecureSocket client) { - client.fold>( - [], (message, data) => message..addAll(data)).then((message) { - String received = new String.fromCharCodes(message); - Expect.isTrue(received.contains("Hello from client ")); - String name = received.substring(received.indexOf("client ") + 7); - client.write("Welcome, client $name"); - client.close(); - }); + client + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + String received = new String.fromCharCodes(message); + Expect.isTrue(received.contains("Hello from client ")); + String name = received.substring(received.indexOf("client ") + 7); + client.write("Welcome, client $name"); + client.close(); + }); }); return server; }); } Future testClient(server, name) { - return SecureSocket.connect(HOST, server.port, context: clientContext) - .then((socket) { + return SecureSocket.connect(HOST, server.port, context: clientContext).then(( + socket, + ) { socket.write("Hello from client $name"); socket.close(); - return socket.fold>( - [], (message, data) => message..addAll(data)).then((message) { - Expect.listEquals("Welcome, client $name".codeUnits, message); - return server; - }); + return socket + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + Expect.listEquals("Welcome, client $name".codeUnits, message); + return server; + }); }); } @@ -79,11 +84,16 @@ Future runTests() { Duration delay = const Duration(milliseconds: 0); Duration delay_between_connections = const Duration(milliseconds: 300); return startServer() - .then((server) => Future.wait( - ['able', 'baker', 'charlie', 'dozen', 'elapse'].map((name) { + .then( + (server) => Future.wait( + ['able', 'baker', 'charlie', 'dozen', 'elapse'].map((name) { delay += delay_between_connections; - return new Future.delayed(delay, () => server) - .then((server) => testClient(server, name)); - }))) + return new Future.delayed( + delay, + () => server, + ).then((server) => testClient(server, name)); + }), + ), + ) .then((servers) => servers.first.close()); } diff --git a/tests/standalone/io/secure_socket_allow_renegotiation_test.dart b/tests/standalone/io/secure_socket_allow_renegotiation_test.dart index 3e646d9bc6d..4e4eb201c7c 100644 --- a/tests/standalone/io/secure_socket_allow_renegotiation_test.dart +++ b/tests/standalone/io/secure_socket_allow_renegotiation_test.dart @@ -27,17 +27,20 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); Future startEchoServer() { return SecureServerSocket.bind(HOST, 0, serverContext).then((server) { server.listen((SecureSocket client) { - client.fold>( - [], (message, data) => message..addAll(data)).then((message) { - client.add(message); - client.close(); - }); + client + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + client.add(message); + client.close(); + }); }); return server; }); @@ -51,8 +54,9 @@ testSuccess(SecureServerSocket server) async { ..allowLegacyUnsafeRenegotiation = true ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); - await SecureSocket.connect(HOST, server.port, context: clientContext) - .then((socket) async { + await SecureSocket.connect(HOST, server.port, context: clientContext).then(( + socket, + ) async { socket.write("Hello server."); socket.close(); Expect.isTrue(await utf8.decoder.bind(socket).contains("Hello server.")); diff --git a/tests/standalone/io/secure_socket_alpn_test.dart b/tests/standalone/io/secure_socket_alpn_test.dart index 56505ce5294..98a9b7b1d16 100644 --- a/tests/standalone/io/secure_socket_alpn_test.dart +++ b/tests/standalone/io/secure_socket_alpn_test.dart @@ -19,22 +19,29 @@ const String MESSAGE_LENGTH_ERROR = String localFile(path) => Platform.script.resolve(path).toFilePath(); -SecurityContext clientContext() => new SecurityContext() - ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); +SecurityContext clientContext() => + new SecurityContext() + ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); SecurityContext serverContext() => new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); // Tests that client/server with same protocol can securely establish a // connection, negotiate the protocol and can send data to each other. -void testSuccessfulAlpnNegotiationConnection(List clientProtocols, - List serverProtocols, String? selectedProtocol) { +void testSuccessfulAlpnNegotiationConnection( + List clientProtocols, + List serverProtocols, + String? selectedProtocol, +) { asyncStart(); var sContext = serverContext()..setAlpnProtocols(serverProtocols, true); - SecureServerSocket.bind('localhost', 0, sContext) - .then((SecureServerSocket server) { + SecureServerSocket.bind('localhost', 0, sContext).then(( + SecureServerSocket server, + ) { asyncStart(); server.first.then((SecureSocket socket) { Expect.equals(selectedProtocol, socket.selectedProtocol); @@ -48,9 +55,12 @@ void testSuccessfulAlpnNegotiationConnection(List clientProtocols, }); asyncStart(); - SecureSocket.connect('localhost', server.port, - context: clientContext(), supportedProtocols: clientProtocols) - .then((socket) { + SecureSocket.connect( + 'localhost', + server.port, + context: clientContext(), + supportedProtocols: clientProtocols, + ).then((socket) { Expect.equals(selectedProtocol, socket.selectedProtocol); socket ..write('client message') @@ -73,7 +83,9 @@ void testInvalidArgument(List protocols, String errorIncludes) { } void testInvalidArgumentServerContext( - List protocols, String errorIncludes) { + List protocols, + String errorIncludes, +) { Expect.throws(() => serverContext().setAlpnProtocols(protocols, true), (e) { Expect.isTrue(e is ArgumentError); Expect.isTrue(e.toString().contains(errorIncludes)); @@ -82,7 +94,9 @@ void testInvalidArgumentServerContext( } void testInvalidArgumentClientContext( - List protocols, String errorIncludes) { + List protocols, + String errorIncludes, +) { Expect.throws(() => clientContext().setAlpnProtocols(protocols, false), (e) { Expect.isTrue(e is ArgumentError); Expect.isTrue(e.toString().contains(errorIncludes)); @@ -91,32 +105,46 @@ void testInvalidArgumentClientContext( } void testInvalidArgumentClientConnect( - List protocols, String errorIncludes) { + List protocols, + String errorIncludes, +) { asyncStart(); var sContext = serverContext()..setAlpnProtocols(['abc'], true); SecureServerSocket.bind('localhost', 0, sContext).then((server) async { asyncStart(); - server.listen((SecureSocket socket) { - Expect.fail( - "Unexpected connection made to server, with bad client argument"); - }, onError: (e) { - Expect.fail("Unexpected error on server stream: $e"); - }, onDone: () { - asyncEnd(); - }); + server.listen( + (SecureSocket socket) { + Expect.fail( + "Unexpected connection made to server, with bad client argument", + ); + }, + onError: (e) { + Expect.fail("Unexpected error on server stream: $e"); + }, + onDone: () { + asyncEnd(); + }, + ); asyncStart(); - SecureSocket.connect('localhost', server.port, - context: clientContext(), supportedProtocols: protocols) - .then((socket) { - Expect.fail( - "Unexpected connection made from client, with bad client argument"); - }, onError: (e) { - Expect.isTrue(e is ArgumentError); - Expect.isTrue(e.toString().contains(errorIncludes)); - server.close(); - asyncEnd(); - }); + SecureSocket.connect( + 'localhost', + server.port, + context: clientContext(), + supportedProtocols: protocols, + ).then( + (socket) { + Expect.fail( + "Unexpected connection made from client, with bad client argument", + ); + }, + onError: (e) { + Expect.isTrue(e is ArgumentError); + Expect.isTrue(e.toString().contains(errorIncludes)); + server.close(); + asyncEnd(); + }, + ); asyncEnd(); }); } @@ -129,13 +157,17 @@ main() { // This produces a message of (1 << 13) - 2 bytes. 2^12 -1 strings are each // encoded by 1 length byte and 1 ascii byte. - final List manyProtocols = - new Iterable.generate((1 << 12) - 1, (i) => '0').toList(); + final List manyProtocols = new Iterable.generate( + (1 << 12) - 1, + (i) => '0', + ).toList(); // This produces a message of (1 << 13) bytes. 2^12 strings are each // encoded by 1 length byte and 1 ascii byte. - final List tooManyProtocols = - new Iterable.generate((1 << 12), (i) => '0').toList(); + final List tooManyProtocols = new Iterable.generate( + (1 << 12), + (i) => '0', + ).toList(); // Protocols are in order of decreasing priority. The server will select // the first protocol from its list that has a match in the client list. @@ -143,24 +175,39 @@ main() { testSuccessfulAlpnNegotiationConnection(['a'], ['a'], 'a'); testSuccessfulAlpnNegotiationConnection( - [longname255], [longname255], longname255); + [longname255], + [longname255], + longname255, + ); testSuccessfulAlpnNegotiationConnection( - [strangelongname255], [strangelongname255], strangelongname255); + [strangelongname255], + [strangelongname255], + strangelongname255, + ); testSuccessfulAlpnNegotiationConnection(manyProtocols, manyProtocols, '0'); testSuccessfulAlpnNegotiationConnection( - ['a', 'b', 'c'], ['a', 'b', 'c'], 'a'); + ['a', 'b', 'c'], + ['a', 'b', 'c'], + 'a', + ); testSuccessfulAlpnNegotiationConnection(['a', 'b', 'c'], ['c'], 'c'); // Server precedence. testSuccessfulAlpnNegotiationConnection( - ['a', 'b', 'c'], ['c', 'b', 'a'], 'c'); + ['a', 'b', 'c'], + ['c', 'b', 'a'], + 'c', + ); testSuccessfulAlpnNegotiationConnection(['c'], ['a', 'b', 'c'], 'c'); testSuccessfulAlpnNegotiationConnection( - ['s1', 'b', 'e1'], ['s2', 'b', 'e2'], 'b'); + ['s1', 'b', 'e1'], + ['s2', 'b', 'e2'], + 'b', + ); // Test no protocol negotiation support testSuccessfulAlpnNegotiationConnection([], ['a', 'b', 'c'], null); diff --git a/tests/standalone/io/secure_socket_argument_test.dart b/tests/standalone/io/secure_socket_argument_test.dart index 676801e3f28..6b0cbd67fce 100644 --- a/tests/standalone/io/secure_socket_argument_test.dart +++ b/tests/standalone/io/secure_socket_argument_test.dart @@ -10,8 +10,10 @@ const SERVER_ADDRESS = "127.0.0.1"; void testServerSocketArguments() { Expect.throws(() => SecureServerSocket.bind(SERVER_ADDRESS, 65536, null)); Expect.throws(() => SecureServerSocket.bind(SERVER_ADDRESS, -1, null)); - Expect.throws(() => - SecureServerSocket.bind(SERVER_ADDRESS, 0, "not a context" as dynamic)); + Expect.throws( + () => + SecureServerSocket.bind(SERVER_ADDRESS, 0, "not a context" as dynamic), + ); } void main() { diff --git a/tests/standalone/io/secure_socket_error_test.dart b/tests/standalone/io/secure_socket_error_test.dart index fc987f0dd15..5243f7486bf 100644 --- a/tests/standalone/io/secure_socket_error_test.dart +++ b/tests/standalone/io/secure_socket_error_test.dart @@ -19,30 +19,39 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext(String certType, String password) => new SecurityContext() - ..useCertificateChain(localFile('certificates/server_chain.$certType'), - password: password) - ..usePrivateKey(localFile('certificates/server_key.$certType'), - password: password); + ..useCertificateChain( + localFile('certificates/server_chain.$certType'), + password: password, + ) + ..usePrivateKey( + localFile('certificates/server_key.$certType'), + password: password, + ); SecurityContext clientContext(String certType, String password) => - new SecurityContext() - ..setTrustedCertificates( - localFile('certificates/trusted_certs.$certType'), - password: password); + new SecurityContext()..setTrustedCertificates( + localFile('certificates/trusted_certs.$certType'), + password: password, + ); Future startServer(String certType, String password) { return HttpServer.bindSecure( - "localhost", 0, serverContext(certType, password), - backlog: 5) - .then((server) { + "localhost", + 0, + serverContext(certType, password), + backlog: 5, + ).then((server) { server.listen((HttpRequest request) { - request.listen((_) {}, onDone: () { - request.response.contentLength = 100; - for (int i = 0; i < 10; i++) { - request.response.add([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); - } - request.response.close(); - }); + request.listen( + (_) {}, + onDone: () { + request.response.contentLength = 100; + for (int i = 0; i < 10; i++) { + request.response.add([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + } + request.response.close(); + }, + ); }); return server; }); @@ -53,20 +62,26 @@ Future test(String certType, String password) { Completer completer = new Completer(); startServer(certType, password).then((server) { try { - SecureSocket.connect("localhost", server.port, - context: clientContext(certType, 'junkjunk')) - .then((socket) { + SecureSocket.connect( + "localhost", + server.port, + context: clientContext(certType, 'junkjunk'), + ).then((socket) { socket.write("GET / HTTP/1.0\r\nHost: localhost\r\n\r\n"); socket.close(); - socket.listen((List data) { - body.addAll(data); - }, onDone: () { - server.close(); - completer.complete(null); - }, onError: (e, trace) { - server.close(); - completer.complete(null); - }); + socket.listen( + (List data) { + body.addAll(data); + }, + onDone: () { + server.close(); + completer.complete(null); + }, + onError: (e, trace) { + server.close(); + completer.complete(null); + }, + ); }); } catch (e) { Expect.isTrue(e is TlsException); diff --git a/tests/standalone/io/secure_socket_minimum_tls_protocol_version_test.dart b/tests/standalone/io/secure_socket_minimum_tls_protocol_version_test.dart index 50e88bb8758..59e6ea19d65 100644 --- a/tests/standalone/io/secure_socket_minimum_tls_protocol_version_test.dart +++ b/tests/standalone/io/secure_socket_minimum_tls_protocol_version_test.dart @@ -21,17 +21,20 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); Future startEchoServer() { return SecureServerSocket.bind(HOST, 0, serverContext).then((server) { server.listen((SecureSocket client) { - client.fold>( - [], (message, data) => message..addAll(data)).then((message) { - client.add(message); - client.close(); - }); + client + .fold>([], (message, data) => message..addAll(data)) + .then((message) { + client.add(message); + client.close(); + }); }); return server; }); @@ -45,8 +48,9 @@ testVersion(SecureServerSocket server, TlsProtocolVersion tlsVersion) async { ..minimumTlsProtocolVersion = tlsVersion ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); - await SecureSocket.connect(HOST, server.port, context: clientContext) - .then((socket) async { + await SecureSocket.connect(HOST, server.port, context: clientContext).then(( + socket, + ) async { socket.write("Hello server."); socket.close(); Expect.isTrue(await utf8.decoder.bind(socket).contains("Hello server.")); diff --git a/tests/standalone/io/secure_unauthorized_client.dart b/tests/standalone/io/secure_unauthorized_client.dart index 184365b5765..8230b1c4435 100644 --- a/tests/standalone/io/secure_unauthorized_client.dart +++ b/tests/standalone/io/secure_unauthorized_client.dart @@ -31,12 +31,15 @@ Future runClients(int port) { var testFutures = []; for (int i = 0; i < 20; ++i) { testFutures.add( - SecureSocket.connect(HOST_NAME, port, context: clientContext).then( - (SecureSocket socket) { - expect(false); - }, onError: (e) { - expect(e is HandshakeException || e is SocketException); - })); + SecureSocket.connect(HOST_NAME, port, context: clientContext).then( + (SecureSocket socket) { + expect(false); + }, + onError: (e) { + expect(e is HandshakeException || e is SocketException); + }, + ), + ); } return Future.wait(testFutures); } diff --git a/tests/standalone/io/secure_unauthorized_test.dart b/tests/standalone/io/secure_unauthorized_test.dart index c31191a1834..fb67d20ac3f 100644 --- a/tests/standalone/io/secure_unauthorized_test.dart +++ b/tests/standalone/io/secure_unauthorized_test.dart @@ -20,16 +20,22 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/untrusted_server_chain.pem')) - ..usePrivateKey(localFile('certificates/untrusted_server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/untrusted_server_key.pem'), + password: 'dartdart', + ); Future runServer() { - return SecureServerSocket.bind(HOST_NAME, 0, serverContext) - .then((SecureServerSocket server) { + return SecureServerSocket.bind(HOST_NAME, 0, serverContext).then(( + SecureServerSocket server, + ) { server.listen((SecureSocket socket) { - socket.listen((_) {}, onDone: () { - socket.close(); - }); + socket.listen( + (_) {}, + onDone: () { + socket.close(); + }, + ); }, onError: (e) => Expect.isTrue(e is HandshakeException)); return server; }); diff --git a/tests/standalone/io/security_context_no_private_key_test.dart b/tests/standalone/io/security_context_no_private_key_test.dart index f3f8489e3a5..0ddc9db303b 100644 --- a/tests/standalone/io/security_context_no_private_key_test.dart +++ b/tests/standalone/io/security_context_no_private_key_test.dart @@ -11,19 +11,20 @@ import "package:expect/expect.dart"; void main() { // Handcrafted private key with actual value missing(dartbug.com/54719) - Uint8List privateKeyBytes = Uint8List.fromList([ - 0x30, 0x53, 0x02, 0x01, 0x03, 0x30, 0x0b, 0x06, 0x09, 0x2a, 0x86, 0x48, - 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0x30, 0x41, 0x30, 0x31, 0x30, 0x0d, - 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, - 0x00, 0x04, 0x20, 0xfc, 0x85, 0xd5, 0xb6, 0xc7, 0x78, 0x80, 0x96, 0x74, - 0x5b, 0x13, 0xe4, 0x14, 0x79, 0x56, 0x39, 0xd1, 0xa3, 0x1b, 0x0e, 0xf9, - 0x21, 0x22, 0x9a, 0xe8, 0x03, 0x91, 0x98, 0xf4, 0xb6, 0x3d, 0x3f, 0x04, - 0x08, 0x91, 0xc1, 0x65, 0x4e, 0xe5, 0x58, 0x43, 0xf0, 0x02, 0x02, 0x08, - 0x00]); + Uint8List privateKeyBytes = Uint8List.fromList([ + 0x30, 0x53, 0x02, 0x01, 0x03, 0x30, 0x0b, 0x06, 0x09, 0x2a, 0x86, 0x48, + 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0x30, 0x41, 0x30, 0x31, 0x30, 0x0d, + 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, + 0x00, 0x04, 0x20, 0xfc, 0x85, 0xd5, 0xb6, 0xc7, 0x78, 0x80, 0x96, 0x74, + 0x5b, 0x13, 0xe4, 0x14, 0x79, 0x56, 0x39, 0xd1, 0xa3, 0x1b, 0x0e, 0xf9, + 0x21, 0x22, 0x9a, 0xe8, 0x03, 0x91, 0x98, 0xf4, 0xb6, 0x3d, 0x3f, 0x04, + 0x08, 0x91, 0xc1, 0x65, 0x4e, 0xe5, 0x58, 0x43, 0xf0, 0x02, 0x02, 0x08, + 0x00, // + ]); SecurityContext securityContext = SecurityContext(); Expect.throws( - () => securityContext.usePrivateKeyBytes(privateKeyBytes), - (e) => - e is ArgumentError && e.toString().contains("Expected private key")); + () => securityContext.usePrivateKeyBytes(privateKeyBytes), + (e) => e is ArgumentError && e.toString().contains("Expected private key"), + ); } diff --git a/tests/standalone/io/server_socket_close_listen_test.dart b/tests/standalone/io/server_socket_close_listen_test.dart index cc4e5ab2fe7..2ba6747e953 100644 --- a/tests/standalone/io/server_socket_close_listen_test.dart +++ b/tests/standalone/io/server_socket_close_listen_test.dart @@ -16,8 +16,10 @@ void serverSocketCloseListenTest() { Socket.connect("127.0.0.1", server.port).then((socket) { socket.destroy(); server.close(); - server.listen((incoming) => Expect.fail("Unexpected socket"), - onDone: asyncEnd); + server.listen( + (incoming) => Expect.fail("Unexpected socket"), + onDone: asyncEnd, + ); }); }); } diff --git a/tests/standalone/io/server_socket_exception_test.dart b/tests/standalone/io/server_socket_exception_test.dart index 4e1494e0076..5138308747a 100644 --- a/tests/standalone/io/server_socket_exception_test.dart +++ b/tests/standalone/io/server_socket_exception_test.dart @@ -28,9 +28,11 @@ void serverSocketExceptionTest() { Expect.equals(true, !wrongExceptionCaught); // Test invalid host. - ServerSocket.bind("__INVALID_HOST__", 0).then((server) { - Expect.fail('Connection succeeded.'); - }).catchError((e) => Expect.isTrue(e is SocketException)); + ServerSocket.bind("__INVALID_HOST__", 0) + .then((server) { + Expect.fail('Connection succeeded.'); + }) + .catchError((e) => Expect.isTrue(e is SocketException)); }); } diff --git a/tests/standalone/io/shared_socket_test.dart b/tests/standalone/io/shared_socket_test.dart index 39eb4d1ddb1..d53b0597e9e 100644 --- a/tests/standalone/io/shared_socket_test.dart +++ b/tests/standalone/io/shared_socket_test.dart @@ -13,8 +13,10 @@ void main() async { final mainServer = await HttpServer.bind('::1', 0, shared: true); final sharedPort = mainServer.port; - final workers = - List.generate(4, (i) => ServerWorker(i, sharedPort)); + final workers = List.generate( + 4, + (i) => ServerWorker(i, sharedPort), + ); await Future.wait(workers.map((w) => w.start())); mainServer.close(); @@ -48,8 +50,12 @@ class ServerWorker { if (respawn) start(); }); final ready = ReceivePort(); - _isolate = await Isolate.spawn(_main, [workerid, port, ready.sendPort], - errorsAreFatal: true, onExit: onExit.sendPort); + _isolate = await Isolate.spawn( + _main, + [workerid, port, ready.sendPort], + errorsAreFatal: true, + onExit: onExit.sendPort, + ); await ready.first; if (workerid == 0) terminate(); } diff --git a/tests/standalone/io/signals_test.dart b/tests/standalone/io/signals_test.dart index ba54a97aadb..a77679fd0c2 100644 --- a/tests/standalone/io/signals_test.dart +++ b/tests/standalone/io/signals_test.dart @@ -11,22 +11,27 @@ import "dart:convert"; import "package:expect/async_helper.dart"; import "package:expect/expect.dart"; -void testSignals(int usr1Expect, int usr2Expect, - [int? usr1Send, int? usr2Send, bool shouldFail = false]) { +void testSignals( + int usr1Expect, + int usr2Expect, [ + int? usr1Send, + int? usr2Send, + bool shouldFail = false, +]) { if (usr1Send == null) usr1Send = usr1Expect; if (usr2Send == null) usr2Send = usr2Expect; asyncStart(); Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..addAll([ - Platform.script.resolve('signals_test_script.dart').toFilePath(), - usr1Expect.toString(), - usr2Expect.toString() - ])) - .then((process) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..addAll([ + Platform.script.resolve('signals_test_script.dart').toFilePath(), + usr1Expect.toString(), + usr2Expect.toString(), + ]), + ).then((process) { process.stdin.close(); process.stderr.drain(); int v = 0; @@ -52,27 +57,32 @@ void testSignals(int usr1Expect, int usr2Expect, void testSignal(ProcessSignal signal) { asyncStart(); Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..addAll([ - Platform.script.resolve('signal_test_script.dart').toFilePath(), - signal.toString() - ])) - .then((process) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..addAll([ + Platform.script.resolve('signal_test_script.dart').toFilePath(), + signal.toString(), + ]), + ).then((process) { process.stdin.close(); process.stderr.drain(); var output = ""; - process.stdout.transform(utf8.decoder).listen((str) { - output += str; - if (output == 'ready\n') { - process.kill(signal); - } - }, onDone: () { - Expect.equals('ready\n$signal\n', output); - }); + process.stdout + .transform(utf8.decoder) + .listen( + (str) { + output += str; + if (output == 'ready\n') { + process.kill(signal); + } + }, + onDone: () { + Expect.equals('ready\n$signal\n', output); + }, + ); process.exitCode.then((exitCode) { Expect.equals(0, exitCode); asyncEnd(); @@ -84,27 +94,30 @@ void testMultipleSignals(List signals) { for (var signal in signals) { asyncStart(); Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(Platform.script - .resolve('signal_test_script.dart') - .toFilePath()) - ..addAll(signals.map((s) => s.toString()))) - .then((process) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(Platform.script.resolve('signal_test_script.dart').toFilePath()) + ..addAll(signals.map((s) => s.toString())), + ).then((process) { process.stdin.close(); process.stderr.drain(); var output = ""; - process.stdout.transform(utf8.decoder).listen((str) { - output += str; - if (output == 'ready\n') { - process.kill(signal); - } - }, onDone: () { - Expect.equals('ready\n$signal\n', output); - }); + process.stdout + .transform(utf8.decoder) + .listen( + (str) { + output += str; + if (output == 'ready\n') { + process.kill(signal); + } + }, + onDone: () { + Expect.equals('ready\n$signal\n', output); + }, + ); process.exitCode.then((exitCode) { Expect.equals(0, exitCode); asyncEnd(); diff --git a/tests/standalone/io/socket_big_chunk_test.dart b/tests/standalone/io/socket_big_chunk_test.dart index afda97628fa..dc3c5615dc9 100644 --- a/tests/standalone/io/socket_big_chunk_test.dart +++ b/tests/standalone/io/socket_big_chunk_test.dart @@ -23,15 +23,20 @@ Future main() async { }); HttpClient client = new HttpClient(); - HttpClientRequest clientResult = - await client.get('127.0.0.1', server.port, 'foo'); + HttpClientRequest clientResult = await client.get( + '127.0.0.1', + server.port, + 'foo', + ); HttpClientResponse response = await clientResult.close(); print("Client result closed"); int totalLength = 0; await for (List data in response) { totalLength += data.length; - print("Got chunk of size ${data.length}. " - "Total received is now $totalLength."); + print( + "Got chunk of size ${data.length}. " + "Total received is now $totalLength.", + ); } print("Client done."); Expect.equals(data.length, totalLength); diff --git a/tests/standalone/io/socket_bind_test.dart b/tests/standalone/io/socket_bind_test.dart index 0cc540e0df9..6c80f24d1db 100644 --- a/tests/standalone/io/socket_bind_test.dart +++ b/tests/standalone/io/socket_bind_test.dart @@ -13,8 +13,12 @@ Future testBindShared(String host, bool v6Only) async { final socket = await ServerSocket.bind(host, 0, v6Only: v6Only, shared: true); Expect.isTrue(socket.port > 0); - final socket2 = - await ServerSocket.bind(host, socket.port, v6Only: v6Only, shared: true); + final socket2 = await ServerSocket.bind( + host, + socket.port, + v6Only: v6Only, + shared: true, + ); Expect.equals(socket.address.address, socket2.address.address); Expect.equals(socket.port, socket2.port); @@ -27,8 +31,10 @@ Future negTestBindSharedMismatch(String host, bool v6Only) async { final socket = await ServerSocket.bind(host, 0, v6Only: v6Only); Expect.isTrue(socket.port > 0); - await throws(() => ServerSocket.bind(host, socket.port, v6Only: v6Only), - (error) => error is SocketException && '$error'.contains('shared flag')); + await throws( + () => ServerSocket.bind(host, socket.port, v6Only: v6Only), + (error) => error is SocketException && '$error'.contains('shared flag'), + ); await socket.close(); } @@ -37,22 +43,35 @@ Future negTestBindV6OnlyMismatch(String host, bool v6Only) async { Expect.isTrue(socket.port > 0); await throws( - () => ServerSocket.bind(host, socket.port, v6Only: !v6Only, shared: true), - (error) => error is SocketException && '$error'.contains('v6Only flag')); + () => ServerSocket.bind(host, socket.port, v6Only: !v6Only, shared: true), + (error) => error is SocketException && '$error'.contains('v6Only flag'), + ); await socket.close(); } -Future testBindDifferentAddresses(InternetAddress addr1, InternetAddress addr2, - bool addr1V6Only, bool addr2V6Only) async { - var socket = - await ServerSocket.bind(addr1, 0, v6Only: addr1V6Only, shared: false); +Future testBindDifferentAddresses( + InternetAddress addr1, + InternetAddress addr2, + bool addr1V6Only, + bool addr2V6Only, +) async { + var socket = await ServerSocket.bind( + addr1, + 0, + v6Only: addr1V6Only, + shared: false, + ); try { Expect.isTrue(socket.port > 0); - var socket2 = await ServerSocket.bind(addr2, socket.port, - v6Only: addr2V6Only, shared: false); + var socket2 = await ServerSocket.bind( + addr2, + socket.port, + v6Only: addr2V6Only, + shared: false, + ); try { Expect.equals(socket.port, socket2.port); } finally { @@ -65,8 +84,11 @@ Future testBindDifferentAddresses(InternetAddress addr1, InternetAddress addr2, Future testListenCloseListenClose(String host) async { ServerSocket socket = await ServerSocket.bind(host, 0, shared: true); - ServerSocket socket2 = - await ServerSocket.bind(host, socket.port, shared: true); + ServerSocket socket2 = await ServerSocket.bind( + host, + socket.port, + shared: true, + ); var subscription = socket.listen((_) { throw 'error'; @@ -98,11 +120,19 @@ Future testListenCloseListenClose(String host) async { main() async { await retry(() async { await testBindDifferentAddresses( - InternetAddress.anyIPv6, InternetAddress.anyIPv4, true, false); + InternetAddress.anyIPv6, + InternetAddress.anyIPv4, + true, + false, + ); }); await retry(() async { await testBindDifferentAddresses( - InternetAddress.anyIPv4, InternetAddress.anyIPv6, false, true); + InternetAddress.anyIPv4, + InternetAddress.anyIPv6, + false, + true, + ); }); for (var host in ['127.0.0.1', '::1']) { diff --git a/tests/standalone/io/socket_cancel_connect_test.dart b/tests/standalone/io/socket_cancel_connect_test.dart index f3d27c2b143..52be8601cdb 100644 --- a/tests/standalone/io/socket_cancel_connect_test.dart +++ b/tests/standalone/io/socket_cancel_connect_test.dart @@ -17,17 +17,22 @@ void main() { asyncStart(); Duration timeout = new Duration(milliseconds: 20); Socket.startConnect("8.8.8.7", 80).then((task) { - task.socket.timeout(timeout, onTimeout: () { - task.cancel(); - return task.socket; - }); - task.socket.then((socket) { - Expect.fail("Unexpected connection made."); - asyncEnd(); - }).catchError((e) { - print(e); - Expect.isTrue(e is SocketException); - asyncEnd(); - }); + task.socket.timeout( + timeout, + onTimeout: () { + task.cancel(); + return task.socket; + }, + ); + task.socket + .then((socket) { + Expect.fail("Unexpected connection made."); + asyncEnd(); + }) + .catchError((e) { + print(e); + Expect.isTrue(e is SocketException); + asyncEnd(); + }); }); } diff --git a/tests/standalone/io/socket_close_test.dart b/tests/standalone/io/socket_close_test.dart index 00bc1876056..c965287413c 100644 --- a/tests/standalone/io/socket_close_test.dart +++ b/tests/standalone/io/socket_close_test.dart @@ -28,11 +28,11 @@ Future sendReceive(SendPort port, message) { class SocketClose { SocketClose.start(this._mode, this._done) - : _readBytes = 0, - _dataEvents = 0, - _closeEvents = 0, - _errorEvents = 0, - _iterations = 0 { + : _readBytes = 0, + _dataEvents = 0, + _closeEvents = 0, + _errorEvents = 0, + _iterations = 0 { initialize(); } @@ -99,9 +99,11 @@ class SocketClose { } void connectHandler(socket) { - socket.listen(dataHandler, - onDone: () => closeHandler(socket), - onError: (error) => errorHandler(socket)); + socket.listen( + dataHandler, + onDone: () => closeHandler(socket), + onError: (error) => errorHandler(socket), + ); void writeHello() { socket.write("Hello"); diff --git a/tests/standalone/io/socket_connect_dwarf_stacktrace_test.dart b/tests/standalone/io/socket_connect_dwarf_stacktrace_test.dart index baeaf576ced..0ca539822c6 100644 --- a/tests/standalone/io/socket_connect_dwarf_stacktrace_test.dart +++ b/tests/standalone/io/socket_connect_dwarf_stacktrace_test.dart @@ -17,21 +17,26 @@ import "package:native_stack_traces/native_stack_traces.dart"; import "package:path/path.dart" as path; Future> findFrames( - Dwarf dwarf, RegExp re, StackTrace stackTrace) async { - final dwarfed = await Stream.value(stackTrace.toString()) - .transform(const LineSplitter()) - .toList(); - return Stream.fromIterable(dwarfed) - .transform(DwarfStackTraceDecoder(dwarf)) - .where(re.hasMatch) - .toList(); + Dwarf dwarf, + RegExp re, + StackTrace stackTrace, +) async { + final dwarfed = await Stream.value( + stackTrace.toString(), + ).transform(const LineSplitter()).toList(); + return Stream.fromIterable( + dwarfed, + ).transform(DwarfStackTraceDecoder(dwarf)).where(re.hasMatch).toList(); } Future main() async { asyncStart(); - final dwarf = Dwarf.fromFile(path.join( + final dwarf = Dwarf.fromFile( + path.join( Platform.environment['TEST_COMPILATION_DIR']!, - 'socket_connect_debug.so'))!; + 'socket_connect_debug.so', + ), + )!; // Test stacktrace when lookup fails try { await WebSocket.connect('ws://localhost.tld:0/ws'); diff --git a/tests/standalone/io/socket_connect_stream_close_test.dart b/tests/standalone/io/socket_connect_stream_close_test.dart index a018742c2a7..e03735e82fb 100644 --- a/tests/standalone/io/socket_connect_stream_close_test.dart +++ b/tests/standalone/io/socket_connect_stream_close_test.dart @@ -24,15 +24,18 @@ void main() { }); Socket.connect("127.0.0.1", server.port).then((socket) { bool onDoneCalled = false; - socket.listen((_) { - Expect.fail("Unexpected data"); - }, onDone: () { - Expect.isFalse(onDoneCalled); - onDoneCalled = true; - socket.close(); - server.close(); - asyncEnd(); - }); + socket.listen( + (_) { + Expect.fail("Unexpected data"); + }, + onDone: () { + Expect.isFalse(onDoneCalled); + onDoneCalled = true; + socket.close(); + server.close(); + asyncEnd(); + }, + ); }); }); } diff --git a/tests/standalone/io/socket_connect_stream_data_close_cancel_test.dart b/tests/standalone/io/socket_connect_stream_data_close_cancel_test.dart index 0302c251083..450bf832de2 100644 --- a/tests/standalone/io/socket_connect_stream_data_close_cancel_test.dart +++ b/tests/standalone/io/socket_connect_stream_data_close_cancel_test.dart @@ -24,22 +24,29 @@ void testConnectStreamDataCloseCancel(bool useDestroy) { } else { client.close(); } - client.done.then((_) { - if (!useDestroy) client.destroy(); - }).catchError((e) {/* can happen with short writes */}); + client.done + .then((_) { + if (!useDestroy) client.destroy(); + }) + .catchError((e) { + /* can happen with short writes */ + }); }); Socket.connect("127.0.0.1", server.port).then((socket) { List data = []; bool onDoneCalled = false; var subscription; - subscription = socket.listen((_) { - subscription.cancel(); - socket.close(); - server.close(); - asyncEnd(); - }, onDone: () { - Expect.fail("Unexpected pipe completion"); - }); + subscription = socket.listen( + (_) { + subscription.cancel(); + socket.close(); + server.close(); + asyncEnd(); + }, + onDone: () { + Expect.fail("Unexpected pipe completion"); + }, + ); }); }); } diff --git a/tests/standalone/io/socket_connect_stream_data_close_test.dart b/tests/standalone/io/socket_connect_stream_data_close_test.dart index 9ff6bcacf23..7e94a543a09 100644 --- a/tests/standalone/io/socket_connect_stream_data_close_test.dart +++ b/tests/standalone/io/socket_connect_stream_data_close_test.dart @@ -35,15 +35,18 @@ void testConnectStreamDataClose(bool useDestroy) { Socket.connect("127.0.0.1", server.port).then((socket) { List data = []; bool onDoneCalled = false; - socket.listen(data.addAll, onDone: () { - Expect.isFalse(onDoneCalled); - onDoneCalled = true; - if (!useDestroy) Expect.listEquals(sendData, data); - socket.add([0]); - socket.close(); - server.close(); - asyncEnd(); - }); + socket.listen( + data.addAll, + onDone: () { + Expect.isFalse(onDoneCalled); + onDoneCalled = true; + if (!useDestroy) Expect.listEquals(sendData, data); + socket.add([0]); + socket.close(); + server.close(); + asyncEnd(); + }, + ); }); }); } diff --git a/tests/standalone/io/socket_cross_process_test.dart b/tests/standalone/io/socket_cross_process_test.dart index 295f21615b6..ac8dad378a6 100644 --- a/tests/standalone/io/socket_cross_process_test.dart +++ b/tests/standalone/io/socket_cross_process_test.dart @@ -35,13 +35,13 @@ Future makeServer() { Future runClientProcess(int port) { return Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add(Platform.script.toFilePath()) - ..add('--client') - ..add(port.toString())) - .then((ProcessResult result) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add(Platform.script.toFilePath()) + ..add('--client') + ..add(port.toString()), + ).then((ProcessResult result) { if (result.exitCode != 0 || !result.stdout.contains('SUCCESS')) { print("Client failed, exit code ${result.exitCode}"); print(" stdout:"); diff --git a/tests/standalone/io/socket_finalizer_test.dart b/tests/standalone/io/socket_finalizer_test.dart index c6b58858b2b..fb4b83786c6 100644 --- a/tests/standalone/io/socket_finalizer_test.dart +++ b/tests/standalone/io/socket_finalizer_test.dart @@ -26,13 +26,17 @@ main() async { Isolate isolate = await Isolate.spawn(ConnectorIsolate, server.port); Completer completer = new Completer(); server.listen((Socket socket) { - socket.listen((_) {}, onDone: () { - print("Socket closed normally"); - completer.complete(null); - socket.close(); - }, onError: (e) { - Expect.fail("Socket error $e"); - }); + socket.listen( + (_) {}, + onDone: () { + print("Socket closed normally"); + completer.complete(null); + socket.close(); + }, + onError: (e) { + Expect.fail("Socket error $e"); + }, + ); final port = ReceivePort(); port.listen((_) { diff --git a/tests/standalone/io/socket_from_raw_path_test.dart b/tests/standalone/io/socket_from_raw_path_test.dart index 757bf37f513..86ae47e08e2 100644 --- a/tests/standalone/io/socket_from_raw_path_test.dart +++ b/tests/standalone/io/socket_from_raw_path_test.dart @@ -9,8 +9,11 @@ import 'dart:typed_data'; import 'package:expect/expect.dart'; -Future testAddress(Uint8List name, String addr, - {InternetAddressType? type}) async { +Future testAddress( + Uint8List name, + String addr, { + InternetAddressType? type, +}) async { var address = InternetAddress.fromRawAddress(name, type: type); Expect.equals(address.address, addr); var server = await ServerSocket.bind(address, 0); @@ -36,8 +39,10 @@ Future testUnixAddress() async { try { final file = File('${dir.path}/$name'); Uint8List path = Uint8List.fromList(utf8.encode(file.path)); - var address = - InternetAddress.fromRawAddress(path, type: InternetAddressType.unix); + var address = InternetAddress.fromRawAddress( + path, + type: InternetAddressType.unix, + ); Expect.isTrue(address.address.toString().endsWith(name)); // Test socket diff --git a/tests/standalone/io/socket_hang_test.dart b/tests/standalone/io/socket_hang_test.dart index 810d2a1dd35..b3644c517e8 100644 --- a/tests/standalone/io/socket_hang_test.dart +++ b/tests/standalone/io/socket_hang_test.dart @@ -16,8 +16,10 @@ Future main(List args) async { return; } else { // Create child process and keeps writing into stdout. - final p = await Process.start( - Platform.executable, [Platform.script.toFilePath(), 'child']); + final p = await Process.start(Platform.executable, [ + Platform.script.toFilePath(), + 'child', + ]); p.stdout.drain(); p.stderr.drain(); final exitCode = await p.exitCode; diff --git a/tests/standalone/io/socket_info_ipv4_test.dart b/tests/standalone/io/socket_info_ipv4_test.dart index f32db33520f..9d3b8e10ff2 100644 --- a/tests/standalone/io/socket_info_ipv4_test.dart +++ b/tests/standalone/io/socket_info_ipv4_test.dart @@ -17,9 +17,15 @@ void testHostAndPort() { Expect.listEquals(socket.remoteAddress.rawAddress, [127, 0, 0, 1]); Expect.equals(clientSocket.remoteAddress.address, "127.0.0.1"); Expect.equals( - clientSocket.remoteAddress.type, InternetAddressType.IPv4); - Expect.listEquals( - clientSocket.remoteAddress.rawAddress, [127, 0, 0, 1]); + clientSocket.remoteAddress.type, + InternetAddressType.IPv4, + ); + Expect.listEquals(clientSocket.remoteAddress.rawAddress, [ + 127, + 0, + 0, + 1, + ]); socket.destroy(); clientSocket.destroy(); server.close(); diff --git a/tests/standalone/io/socket_info_ipv6_test.dart b/tests/standalone/io/socket_info_ipv6_test.dart index 7c15b7d2daa..abe04bcb625 100644 --- a/tests/standalone/io/socket_info_ipv6_test.dart +++ b/tests/standalone/io/socket_info_ipv6_test.dart @@ -17,13 +17,47 @@ void testHostAndPort() { Expect.equals(clientSocket.remotePort, socket.port); Expect.equals(socket.remoteAddress.address, "::1"); Expect.equals(socket.remoteAddress.type, InternetAddressType.IPv6); - Expect.listEquals(socket.remoteAddress.rawAddress, - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + Expect.listEquals(socket.remoteAddress.rawAddress, [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); Expect.equals(clientSocket.remoteAddress.address, "::1"); Expect.equals( - clientSocket.remoteAddress.type, InternetAddressType.IPv6); - Expect.listEquals(clientSocket.remoteAddress.rawAddress, - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + clientSocket.remoteAddress.type, + InternetAddressType.IPv6, + ); + Expect.listEquals(clientSocket.remoteAddress.rawAddress, [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); socket.destroy(); clientSocket.destroy(); server.close(); @@ -33,8 +67,24 @@ void testHostAndPort() { } Future testRawAddress() async { - var list = - Uint8List.fromList([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]); + var list = Uint8List.fromList([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + ]); var addr = '::1'; var address = InternetAddress.fromRawAddress(list); Expect.equals(address.address, addr); diff --git a/tests/standalone/io/socket_invalid_arguments_test.dart b/tests/standalone/io/socket_invalid_arguments_test.dart index cc679d5d20d..a2647150819 100644 --- a/tests/standalone/io/socket_invalid_arguments_test.dart +++ b/tests/standalone/io/socket_invalid_arguments_test.dart @@ -16,9 +16,10 @@ class NotAnInteger { testSocketCreation(host, port) { asyncStart(); try { - Socket.connect(host, port) - .then((socket) => Expect.fail("Shouldn't get connected")) - .catchError((e) { + Socket.connect( + host, + port, + ).then((socket) => Expect.fail("Shouldn't get connected")).catchError((e) { Expect.isTrue(e is ArgumentError || e is SocketException); asyncEnd(); }); @@ -32,9 +33,11 @@ testServerSocketCreation(address, port, backlog) { asyncStart(); var server; try { - ServerSocket.bind(address, port, backlog: backlog).then((_) { - Expect.fail("ServerSocket bound"); - }).catchError((e) => asyncEnd()); + ServerSocket.bind(address, port, backlog: backlog) + .then((_) { + Expect.fail("ServerSocket bound"); + }) + .catchError((e) => asyncEnd()); } catch (e) { asyncEnd(); } diff --git a/tests/standalone/io/socket_invalid_bind_test.dart b/tests/standalone/io/socket_invalid_bind_test.dart index 514634f08af..31e90b93cae 100644 --- a/tests/standalone/io/socket_invalid_bind_test.dart +++ b/tests/standalone/io/socket_invalid_bind_test.dart @@ -16,31 +16,37 @@ import "package:expect/expect.dart"; void main() { // Bind to a unknown DNS name. asyncStart(); - ServerSocket.bind("ko.faar.__hest__", 0).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - asyncEnd(); - }); + ServerSocket.bind("ko.faar.__hest__", 0) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + asyncEnd(); + }); // Bind to an unavailable IP-address. asyncStart(); - ServerSocket.bind("8.8.8.8", 0).then((_) { - Expect.fail("Failure expected"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - asyncEnd(); - }); + ServerSocket.bind("8.8.8.8", 0) + .then((_) { + Expect.fail("Failure expected"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + asyncEnd(); + }); // Bind to a port already in use. asyncStart(); ServerSocket.bind("127.0.0.1", 0).then((s) { - ServerSocket.bind("127.0.0.1", s.port).then((t) { - Expect.fail("Multiple listens on same port"); - }).catchError((error) { - Expect.isTrue(error is SocketException); - s.close(); - asyncEnd(); - }); + ServerSocket.bind("127.0.0.1", s.port) + .then((t) { + Expect.fail("Multiple listens on same port"); + }) + .catchError((error) { + Expect.isTrue(error is SocketException); + s.close(); + asyncEnd(); + }); }); } diff --git a/tests/standalone/io/socket_local_port_test.dart b/tests/standalone/io/socket_local_port_test.dart index f7251ec3a10..0ab599e3aaf 100644 --- a/tests/standalone/io/socket_local_port_test.dart +++ b/tests/standalone/io/socket_local_port_test.dart @@ -77,7 +77,11 @@ Future testNoCustomPortNoSourceAddressIPv6() async { // Core functionality void testCustomPort( - String host, int port, String sourceAddress, int sourcePort) async { + String host, + int port, + String sourceAddress, + int sourcePort, +) async { var server = await ServerSocket.bind(host, port); server.listen((client) { Expect.equals(server.port, port); @@ -86,14 +90,22 @@ void testCustomPort( client.destroy(); }); - Socket s = await Socket.connect(host, port, - sourceAddress: sourceAddress, sourcePort: sourcePort); + Socket s = await Socket.connect( + host, + port, + sourceAddress: sourceAddress, + sourcePort: sourcePort, + ); s.destroy(); server.close(); } Future testCustomPortNoSourceAddress( - String host, int port, String expectedAddress, int sourcePort) async { + String host, + int port, + String expectedAddress, + int sourcePort, +) async { Completer completer = new Completer(); var server = await ServerSocket.bind(host, port); @@ -133,7 +145,10 @@ Future testNoCustomPort(String host, int port, String sourceAddress) async { } Future testNoCustomPortNoSourceAddress( - String host, int port, String expectedAddress) async { + String host, + int port, + String expectedAddress, +) async { Completer completer = new Completer(); var server = await ServerSocket.bind(host, port); Socket.connect(host, port).then((clientSocket) { diff --git a/tests/standalone/io/socket_many_connections_test.dart b/tests/standalone/io/socket_many_connections_test.dart index 29277029580..f71daa464d2 100644 --- a/tests/standalone/io/socket_many_connections_test.dart +++ b/tests/standalone/io/socket_many_connections_test.dart @@ -16,8 +16,8 @@ const connectionsCount = 200; class SocketManyConnectionsTest { SocketManyConnectionsTest.start() - : _connections = 0, - _sockets = new List.filled(connectionsCount, null) { + : _connections = 0, + _sockets = new List.filled(connectionsCount, null) { initialize(); } diff --git a/tests/standalone/io/socket_sigpipe_test.dart b/tests/standalone/io/socket_sigpipe_test.dart index 61a7e348646..f5fe787ca78 100644 --- a/tests/standalone/io/socket_sigpipe_test.dart +++ b/tests/standalone/io/socket_sigpipe_test.dart @@ -21,54 +21,62 @@ final class Isolate extends Opaque {} abstract class FfiBindings { static final ffiTestFunctions = dlopenPlatformSpecific("ffi_test_functions"); - static final RestoreSIGPIPEHandler = - ffiTestFunctions.lookupFunction( - "RestoreSIGPIPEHandler"); - static final SleepOnAnyOS = ffiTestFunctions.lookupFunction< - Void Function(IntPtr), void Function(int)>("SleepOnAnyOS"); + static final RestoreSIGPIPEHandler = ffiTestFunctions + .lookupFunction( + "RestoreSIGPIPEHandler", + ); + static final SleepOnAnyOS = ffiTestFunctions + .lookupFunction( + "SleepOnAnyOS", + ); } Future main() async { asyncStart(); final server = await Process.start(Platform.executable, [ - p.join(p.dirname(Platform.script.toFilePath()), - "socket_sigpipe_test_server.dart") + p.join( + p.dirname(Platform.script.toFilePath()), + "socket_sigpipe_test_server.dart", + ), ]); final serverPort = Completer(); - server.stdout - .transform(utf8.decoder) - .transform(LineSplitter()) - .listen((line) { + server.stdout.transform(utf8.decoder).transform(LineSplitter()).listen(( + line, + ) { print('server stdout: $line'); if (!serverPort.isCompleted) { serverPort.complete(int.parse(line)); } }); - server.stderr - .transform(utf8.decoder) - .transform(LineSplitter()) - .listen((data) { + server.stderr.transform(utf8.decoder).transform(LineSplitter()).listen(( + data, + ) { print('server stderr: $data'); }); FfiBindings.RestoreSIGPIPEHandler(); - final ws = - await WebSocket.connect('ws://localhost:${await serverPort.future}'); - ws.listen((var data) { - print('Got $data'); - // Sleep to prevent closed socket events coming through and being handled. - // This way websocket stays open and writing into it should trigger SIGPIPE. - // Unless of course we requested SIGPIPE not to be generated on broken socket - // pipe. This is what this test is testing - that the SIGPIPE is not generated - // on broken socket pipe. - ws.add('foo'); - FfiBindings.SleepOnAnyOS(10 /*seconds*/); // give server time to exit - ws.add('baz'); - ws.close(); - }, onDone: () { - asyncEnd(); - }, onError: (e, st) { - Expect.fail('Client websocket failed $e $st'); - }); + final ws = await WebSocket.connect( + 'ws://localhost:${await serverPort.future}', + ); + ws.listen( + (var data) { + print('Got $data'); + // Sleep to prevent closed socket events coming through and being handled. + // This way websocket stays open and writing into it should trigger SIGPIPE. + // Unless of course we requested SIGPIPE not to be generated on broken socket + // pipe. This is what this test is testing - that the SIGPIPE is not generated + // on broken socket pipe. + ws.add('foo'); + FfiBindings.SleepOnAnyOS(10 /*seconds*/); // give server time to exit + ws.add('baz'); + ws.close(); + }, + onDone: () { + asyncEnd(); + }, + onError: (e, st) { + Expect.fail('Client websocket failed $e $st'); + }, + ); } diff --git a/tests/standalone/io/socket_source_address_test.dart b/tests/standalone/io/socket_source_address_test.dart index e8e5b232696..39121b00cd7 100644 --- a/tests/standalone/io/socket_source_address_test.dart +++ b/tests/standalone/io/socket_source_address_test.dart @@ -23,40 +23,52 @@ Future testArguments(connectFunction) async { // Illegal type for sourceAddress. for (sourceAddress in ['www.google.com', 'abc']) { await throws( - () => connectFunction('127.0.0.1', serverIPv4.port, - sourceAddress: sourceAddress), - (e) => e is ArgumentError); + () => connectFunction( + '127.0.0.1', + serverIPv4.port, + sourceAddress: sourceAddress, + ), + (e) => e is ArgumentError, + ); } // Unsupported local address. for (sourceAddress in ['8.8.8.8', new InternetAddress('8.8.8.8')]) { await throws( - () => connectFunction('127.0.0.1', serverIPv4.port, - sourceAddress: sourceAddress), - (e) => - e is SocketException && - e.address == new InternetAddress('8.8.8.8')); + () => connectFunction( + '127.0.0.1', + serverIPv4.port, + sourceAddress: sourceAddress, + ), + (e) => + e is SocketException && e.address == new InternetAddress('8.8.8.8'), + ); } // Address family mismatch for IPv4. for (sourceAddress in [ '::1', InternetAddress.loopbackIPv6, - InternetAddress('sock', type: InternetAddressType.unix) + InternetAddress('sock', type: InternetAddressType.unix), ]) { await throws( - () => connectFunction('127.0.0.1', serverIPv4.port, - sourceAddress: sourceAddress), - (e) => e is SocketException); + () => connectFunction( + '127.0.0.1', + serverIPv4.port, + sourceAddress: sourceAddress, + ), + (e) => e is SocketException, + ); } // Address family mismatch for IPv6. for (sourceAddress in [ '127.0.0.1', InternetAddress.loopbackIPv4, - InternetAddress('sock', type: InternetAddressType.unix) + InternetAddress('sock', type: InternetAddressType.unix), ]) { await throws( - () => connectFunction('::1', serverIPv6.port, - sourceAddress: sourceAddress), - (e) => e is SocketException); + () => + connectFunction('::1', serverIPv6.port, sourceAddress: sourceAddress), + (e) => e is SocketException, + ); } await serverIPv4.close(); @@ -66,7 +78,9 @@ Future testArguments(connectFunction) async { Future testUnixDomainArguments(connectFunction, String socketDir) async { var sourceAddress; final serverUnix = await ServerSocket.bind( - InternetAddress('$socketDir/sock', type: InternetAddressType.unix), 0); + InternetAddress('$socketDir/sock', type: InternetAddressType.unix), + 0, + ); serverUnix.listen((_) { throw 'Unexpected connection from address $sourceAddress'; }); @@ -79,13 +93,15 @@ Future testUnixDomainArguments(connectFunction, String socketDir) async { InternetAddress.loopbackIPv6, ]) { await throws( - () => connectFunction( - InternetAddress("$socketDir/sock", type: InternetAddressType.unix), - serverUnix.port, - sourceAddress: sourceAddress), - (e) => - e is SocketException && - e.toString().contains('Address family not supported')); + () => connectFunction( + InternetAddress("$socketDir/sock", type: InternetAddressType.unix), + serverUnix.port, + sourceAddress: sourceAddress, + ), + (e) => + e is SocketException && + e.toString().contains('Address family not supported'), + ); } await serverUnix.close(); } @@ -95,7 +111,7 @@ var ipV4SourceAddresses = [ InternetAddress.loopbackIPv4, InternetAddress.anyIPv4, '127.0.0.1', - '0.0.0.0' + '0.0.0.0', ]; // IPv6 addresses to use as source address when connecting locally. @@ -103,11 +119,15 @@ var ipV6SourceAddresses = [ InternetAddress.loopbackIPv6, InternetAddress.anyIPv6, '::1', - '::' + '::', ]; -Future testConnect(InternetAddress bindAddress, bool v6Only, - Function connectFunction, Function closeDestroyFunction) async { +Future testConnect( + InternetAddress bindAddress, + bool v6Only, + Function connectFunction, + Function closeDestroyFunction, +) async { var successCount = 0; if (!v6Only) successCount += ipV4SourceAddresses.length; if (bindAddress.type == InternetAddressType.IPv6) { @@ -127,31 +147,45 @@ Future testConnect(InternetAddress bindAddress, bool v6Only, // Connect with IPv4 source addresses. for (var sourceAddress in ipV4SourceAddresses) { if (!v6Only) { - var s = await connectFunction(InternetAddress.loopbackIPv4, server.port, - sourceAddress: sourceAddress); + var s = await connectFunction( + InternetAddress.loopbackIPv4, + server.port, + sourceAddress: sourceAddress, + ); closeDestroyFunction(s); } else { // Cannot use an IPv4 source address to connect to IPv6 if // v6Only is specified. await throws( - () => connectFunction(InternetAddress.loopbackIPv6, server.port, - sourceAddress: sourceAddress), - (e) => e is SocketException); + () => connectFunction( + InternetAddress.loopbackIPv6, + server.port, + sourceAddress: sourceAddress, + ), + (e) => e is SocketException, + ); } } // Connect with IPv6 source addresses. for (var sourceAddress in ipV6SourceAddresses) { if (bindAddress.type == InternetAddressType.IPv6) { - var s = await connectFunction(InternetAddress.loopbackIPv6, server.port, - sourceAddress: sourceAddress); + var s = await connectFunction( + InternetAddress.loopbackIPv6, + server.port, + sourceAddress: sourceAddress, + ); closeDestroyFunction(s); } else { // Cannot use an IPv6 source address to connect to IPv4. await throws( - () => connectFunction(InternetAddress.loopbackIPv4, server.port, - sourceAddress: sourceAddress), - (e) => e is SocketException); + () => connectFunction( + InternetAddress.loopbackIPv4, + server.port, + sourceAddress: sourceAddress, + ), + (e) => e is SocketException, + ); } } @@ -181,26 +215,50 @@ main() async { } await retry(() async { await testConnect( - InternetAddress.anyIPv4, false, RawSocket.connect, (s) => s.close()); + InternetAddress.anyIPv4, + false, + RawSocket.connect, + (s) => s.close(), + ); }); await retry(() async { await testConnect( - InternetAddress.anyIPv4, false, Socket.connect, (s) => s.destroy()); + InternetAddress.anyIPv4, + false, + Socket.connect, + (s) => s.destroy(), + ); }); await retry(() async { await testConnect( - InternetAddress.anyIPv6, false, RawSocket.connect, (s) => s.close()); + InternetAddress.anyIPv6, + false, + RawSocket.connect, + (s) => s.close(), + ); }); await retry(() async { await testConnect( - InternetAddress.anyIPv6, false, Socket.connect, (s) => s.destroy()); + InternetAddress.anyIPv6, + false, + Socket.connect, + (s) => s.destroy(), + ); }); await retry(() async { await testConnect( - InternetAddress.anyIPv6, true, RawSocket.connect, (s) => s.close()); + InternetAddress.anyIPv6, + true, + RawSocket.connect, + (s) => s.close(), + ); }); await retry(() async { await testConnect( - InternetAddress.anyIPv6, true, Socket.connect, (s) => s.destroy()); + InternetAddress.anyIPv6, + true, + Socket.connect, + (s) => s.destroy(), + ); }); } diff --git a/tests/standalone/io/socket_udp_readwrite_test.dart b/tests/standalone/io/socket_udp_readwrite_test.dart index eebadf4e46a..69e51a7e0ac 100644 --- a/tests/standalone/io/socket_udp_readwrite_test.dart +++ b/tests/standalone/io/socket_udp_readwrite_test.dart @@ -14,21 +14,26 @@ main() async { final _socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0); final port = _socket.port; final allDone = Completer() - ..future.whenComplete(() { _socket.close(); }); - _socket.listen((RawSocketEvent event) { - print("event: $event"); - switch (event) { - case RawSocketEvent.read: - _socket.receive(); - break; - case RawSocketEvent.write: - print('received write event $event'); - allDone.complete(true); - break; - } - }, onError: (e) { - Expect.fail('Should be no exceptions, but got $e'); - }); + ..future.whenComplete(() { + _socket.close(); + }); + _socket.listen( + (RawSocketEvent event) { + print("event: $event"); + switch (event) { + case RawSocketEvent.read: + _socket.receive(); + break; + case RawSocketEvent.write: + print('received write event $event'); + allDone.complete(true); + break; + } + }, + onError: (e) { + Expect.fail('Should be no exceptions, but got $e'); + }, + ); for (int i = 0; i < 100; i++) { // Sending data to some non-existent reserved port to trigger diff --git a/tests/standalone/io/socket_upgrade_to_secure_test.dart b/tests/standalone/io/socket_upgrade_to_secure_test.dart index e0aba043621..22eff1690c0 100644 --- a/tests/standalone/io/socket_upgrade_to_secure_test.dart +++ b/tests/standalone/io/socket_upgrade_to_secure_test.dart @@ -22,8 +22,10 @@ List readLocalFile(path) => (new File(localFile(path))).readAsBytesSync(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -49,8 +51,11 @@ SecurityContext clientContext = new SecurityContext() // server will not happen until the first TLS handshake data has been // received from the client. This argument only takes effect when // handshakeBeforeSecure is true. -void test(bool hostnameInConnect, bool handshakeBeforeSecure, - [bool postponeSecure = false]) { +void test( + bool hostnameInConnect, + bool handshakeBeforeSecure, [ + bool postponeSecure = false, +]) { asyncStart(); const messageSize = 1000; @@ -105,14 +110,17 @@ void test(bool hostnameInConnect, bool handshakeBeforeSecure, Future runClient(Socket socket) { Completer completer = new Completer(); var dataReceived = []; - socket.listen((data) { - dataReceived.addAll(data); - }, onDone: () { - Expect.equals(messageSize, dataReceived.length); - verifyTestData(dataReceived); - socket.close(); - completer.complete(null); - }); + socket.listen( + (data) { + dataReceived.addAll(data); + }, + onDone: () { + Expect.equals(messageSize, dataReceived.length); + verifyTestData(dataReceived); + socket.close(); + completer.complete(null); + }, + ); socket.add(createTestData()); return completer.future; } @@ -160,8 +168,11 @@ void test(bool hostnameInConnect, bool handshakeBeforeSecure, if (hostnameInConnect) { future = SecureSocket.secure(socket, context: clientContext); } else { - future = - SecureSocket.secure(socket, host: HOST, context: clientContext); + future = SecureSocket.secure( + socket, + host: HOST, + context: clientContext, + ); } return future.then((SecureSocket secureSocket) { Expect.throws(() { @@ -177,8 +188,11 @@ void test(bool hostnameInConnect, bool handshakeBeforeSecure, if (hostnameInConnect) { future = SecureSocket.secure(socket, context: clientContext); } else { - future = - SecureSocket.secure(socket, host: HOST, context: clientContext); + future = SecureSocket.secure( + socket, + host: HOST, + context: clientContext, + ); } return future.then((secureSocket) { Expect.throws(() { @@ -202,9 +216,11 @@ void test(bool hostnameInConnect, bool handshakeBeforeSecure, }); } else { runServerHandshake(client).then((carryOverData) { - SecureSocket.secureServer(client, serverContext, - bufferedData: carryOverData) - .then((secureClient) { + SecureSocket.secureServer( + client, + serverContext, + bufferedData: carryOverData, + ).then((secureClient) { Expect.throws(() { client.add([0]); }); diff --git a/tests/standalone/io/stdin_sync_test.dart b/tests/standalone/io/stdin_sync_test.dart index afbe255a434..aee141b311b 100644 --- a/tests/standalone/io/stdin_sync_test.dart +++ b/tests/standalone/io/stdin_sync_test.dart @@ -14,13 +14,13 @@ void testReadByte() { void test(String line, List expected) { var script = Platform.script.resolve("stdin_sync_script.dart").toFilePath(); Process.start( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(script) - ..addAll(expected.map(json.encode))) - .then((process) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(script) + ..addAll(expected.map(json.encode)), + ).then((process) { process.stdin.write(line); process.stdin.flush().then((_) => process.stdin.close()); process.stderr @@ -28,15 +28,15 @@ void testReadByte() { .transform(new LineSplitter()) .fold(new StringBuffer(), (b, d) => b..write(d)) .then((data) { - if (data.toString() != '') throw "Bad output: '$data'"; - }); + if (data.toString() != '') throw "Bad output: '$data'"; + }); process.stdout .transform(utf8.decoder) .transform(new LineSplitter()) .fold(new StringBuffer(), (b, d) => b..write(d)) .then((data) { - if (data.toString() != 'true') throw "Bad output: '$data'"; - }); + if (data.toString() != 'true') throw "Bad output: '$data'"; + }); }); } diff --git a/tests/standalone/io/stdio_nonblocking_script.dart b/tests/standalone/io/stdio_nonblocking_script.dart index 99ada55acc8..7fa17b4f7b2 100644 --- a/tests/standalone/io/stdio_nonblocking_script.dart +++ b/tests/standalone/io/stdio_nonblocking_script.dart @@ -28,6 +28,8 @@ void main(List arguments) { stderr.nonBlocking.writeln(new Message('rredts')); test(stdout.nonBlocking); test(stderr.nonBlocking); - Future.wait([stdout.nonBlocking.close(), stderr.nonBlocking.close()]) - .then((_) => exit(1)); + Future.wait([ + stdout.nonBlocking.close(), + stderr.nonBlocking.close(), + ]).then((_) => exit(1)); } diff --git a/tests/standalone/io/stdio_nonblocking_test.dart b/tests/standalone/io/stdio_nonblocking_test.dart index 22d65de047a..ecaa65b2618 100644 --- a/tests/standalone/io/stdio_nonblocking_test.dart +++ b/tests/standalone/io/stdio_nonblocking_test.dart @@ -10,17 +10,18 @@ import "dart:io"; import "package:expect/expect.dart"; void main() { - var script = - Platform.script.resolve("stdio_nonblocking_script.dart").toFilePath(); + var script = Platform.script + .resolve("stdio_nonblocking_script.dart") + .toFilePath(); Process.run( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(script), - stdoutEncoding: ascii, - stderrEncoding: ascii) - .then((result) { + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add(script), + stdoutEncoding: ascii, + stderrEncoding: ascii, + ).then((result) { print(result.stdout); print(result.stderr); Expect.equals(1, result.exitCode); diff --git a/tests/standalone/io/stdout_stderr_test.dart b/tests/standalone/io/stdout_stderr_test.dart index 5dcedc351be..e0f666fa159 100644 --- a/tests/standalone/io/stdout_stderr_test.dart +++ b/tests/standalone/io/stdout_stderr_test.dart @@ -13,21 +13,23 @@ import "dart:io"; /// return the commands stdout as a list of bytes. List runTest(String lineTerminatorMode, String encoding, String command) { final result = Process.runSync( - Platform.executable, - [] - ..addAll(Platform.executableArguments) - ..add('--verbosity=warning') - ..add(Platform.script - .resolve('stdout_stderr_test_script.dart') - .toFilePath()) - ..add('--eol=$lineTerminatorMode') - ..add('--encoding=$encoding') - ..add(command), - stdoutEncoding: null); + Platform.executable, + [] + ..addAll(Platform.executableArguments) + ..add('--verbosity=warning') + ..add( + Platform.script.resolve('stdout_stderr_test_script.dart').toFilePath(), + ) + ..add('--eol=$lineTerminatorMode') + ..add('--encoding=$encoding') + ..add(command), + stdoutEncoding: null, + ); if (result.exitCode != 0) { throw AssertionError( - 'unexpected exit code for command $command: ${result.stderr}'); + 'unexpected exit code for command $command: ${result.stderr}', + ); } return result.stdout; } @@ -93,33 +95,51 @@ void testStringInternalLineFeeds() { final expectedWin = [108, 49, ...winEol, 108, 50, ...winEol, 108, 51]; Expect.listEquals( - expectedPosix, runTest("unix", "ascii", "string-internal-linefeeds")); + expectedPosix, + runTest("unix", "ascii", "string-internal-linefeeds"), + ); Expect.listEquals( - expectedWin, runTest("windows", "ascii", "string-internal-linefeeds")); + expectedWin, + runTest("windows", "ascii", "string-internal-linefeeds"), + ); Expect.listEquals( - expectedPosix, runTest("default", "ascii", "string-internal-linefeeds")); + expectedPosix, + runTest("default", "ascii", "string-internal-linefeeds"), + ); } void testStringCarriageReturns() { // write("l1\rl2\rl3\r") final expected = [108, 49, 13, 108, 50, 13, 108, 51, 13]; Expect.listEquals( - expected, runTest("unix", "ascii", "string-internal-carriagereturns")); + expected, + runTest("unix", "ascii", "string-internal-carriagereturns"), + ); Expect.listEquals( - expected, runTest("windows", "ascii", "string-internal-carriagereturns")); + expected, + runTest("windows", "ascii", "string-internal-carriagereturns"), + ); Expect.listEquals( - expected, runTest("default", "ascii", "string-internal-carriagereturns")); + expected, + runTest("default", "ascii", "string-internal-carriagereturns"), + ); } void testStringCarriageReturnLinefeeds() { // ""l1\r\nl2\r\nl3\r\n"" final expected = [108, 49, ...winEol, 108, 50, ...winEol, 108, 51, ...winEol]; - Expect.listEquals(expected, - runTest("unix", "ascii", "string-internal-carriagereturn-linefeeds")); - Expect.listEquals(expected, - runTest("windows", "ascii", "string-internal-carriagereturn-linefeeds")); - Expect.listEquals(expected, - runTest("default", "ascii", "string-internal-carriagereturn-linefeeds")); + Expect.listEquals( + expected, + runTest("unix", "ascii", "string-internal-carriagereturn-linefeeds"), + ); + Expect.listEquals( + expected, + runTest("windows", "ascii", "string-internal-carriagereturn-linefeeds"), + ); + Expect.listEquals( + expected, + runTest("default", "ascii", "string-internal-carriagereturn-linefeeds"), + ); } void testStringCarriageReturnLinefeedsSeperateWrite() { @@ -127,17 +147,25 @@ void testStringCarriageReturnLinefeedsSeperateWrite() { // write("\nl2"); final expected = [108, 49, ...winEol, 108, 50]; Expect.listEquals( - expected, - runTest( - "unix", "ascii", "string-carriagereturn-linefeed-seperate-write")); + expected, + runTest("unix", "ascii", "string-carriagereturn-linefeed-seperate-write"), + ); Expect.listEquals( - expected, - runTest( - "windows", "ascii", "string-carriagereturn-linefeed-seperate-write")); + expected, + runTest( + "windows", + "ascii", + "string-carriagereturn-linefeed-seperate-write", + ), + ); Expect.listEquals( - expected, - runTest( - "default", "ascii", "string-carriagereturn-linefeed-seperate-write")); + expected, + runTest( + "default", + "ascii", + "string-carriagereturn-linefeed-seperate-write", + ), + ); } void testStringCarriageReturnFollowedByWriteln() { @@ -147,11 +175,17 @@ void testStringCarriageReturnFollowedByWriteln() { final expectedWin = [108, 49, 13, ...winEol]; Expect.listEquals( - expectedPosix, runTest("unix", "ascii", "string-carriagereturn-writeln")); - Expect.listEquals(expectedWin, - runTest("windows", "ascii", "string-carriagereturn-writeln")); - Expect.listEquals(expectedPosix, - runTest("default", "ascii", "string-carriagereturn-writeln")); + expectedPosix, + runTest("unix", "ascii", "string-carriagereturn-writeln"), + ); + Expect.listEquals( + expectedWin, + runTest("windows", "ascii", "string-carriagereturn-writeln"), + ); + Expect.listEquals( + expectedPosix, + runTest("default", "ascii", "string-carriagereturn-writeln"), + ); } void testWriteCharCodeLineFeed() { @@ -161,11 +195,17 @@ void testWriteCharCodeLineFeed() { final expectedWin = [108, 49, ...winEol]; Expect.listEquals( - expectedPosix, runTest("unix", "ascii", "write-char-code-linefeed")); + expectedPosix, + runTest("unix", "ascii", "write-char-code-linefeed"), + ); Expect.listEquals( - expectedWin, runTest("windows", "ascii", "write-char-code-linefeed")); + expectedWin, + runTest("windows", "ascii", "write-char-code-linefeed"), + ); Expect.listEquals( - expectedPosix, runTest("default", "ascii", "write-char-code-linefeed")); + expectedPosix, + runTest("default", "ascii", "write-char-code-linefeed"), + ); } void testWriteCharCodeLineFeedFollowingCarriageReturn() { @@ -174,17 +214,25 @@ void testWriteCharCodeLineFeedFollowingCarriageReturn() { final expected = [108, 49, ...winEol]; Expect.listEquals( - expected, - runTest( - "unix", "ascii", "write-char-code-linefeed-after-carriagereturn")); + expected, + runTest("unix", "ascii", "write-char-code-linefeed-after-carriagereturn"), + ); Expect.listEquals( - expected, - runTest( - "windows", "ascii", "write-char-code-linefeed-after-carriagereturn")); + expected, + runTest( + "windows", + "ascii", + "write-char-code-linefeed-after-carriagereturn", + ), + ); Expect.listEquals( - expected, - runTest( - "default", "ascii", "write-char-code-linefeed-after-carriagereturn")); + expected, + runTest( + "default", + "ascii", + "write-char-code-linefeed-after-carriagereturn", + ), + ); } void testInvalidLineTerminator() { diff --git a/tests/standalone/io/stdout_stderr_test_script.dart b/tests/standalone/io/stdout_stderr_test_script.dart index f8e7558eff2..6c824faeb76 100644 --- a/tests/standalone/io/stdout_stderr_test_script.dart +++ b/tests/standalone/io/stdout_stderr_test_script.dart @@ -37,8 +37,9 @@ main(List arguments) { exit(1); } - stdout.encoding = - Encoding.getByName(arguments[1].replaceFirst("--encoding=", ""))!; + stdout.encoding = Encoding.getByName( + arguments[1].replaceFirst("--encoding=", ""), + )!; switch (arguments.last) { case "byte-list-hello": diff --git a/tests/standalone/io/stream_pipe_test.dart b/tests/standalone/io/stream_pipe_test.dart index fba9d206e0a..d5c23f9d243 100644 --- a/tests/standalone/io/stream_pipe_test.dart +++ b/tests/standalone/io/stream_pipe_test.dart @@ -19,8 +19,13 @@ import "package:expect/expect.dart"; String getDataFilename(String path) => Platform.script.resolve(path).toFilePath(); -bool compareFileContent(String fileName1, String fileName2, - {int file1Offset = 0, int file2Offset = 0, int? count}) { +bool compareFileContent( + String fileName1, + String fileName2, { + int file1Offset = 0, + int file2Offset = 0, + int? count, +}) { var file1 = new File(fileName1).openSync(); var file2 = new File(fileName2).openSync(); var length1 = file1.lengthSync(); @@ -102,7 +107,8 @@ testFileToFilePipe2() { var dstLength = dst.lengthSync(); Expect.equals(srcLength + 1, dstLength); Expect.isTrue( - compareFileContent(srcFileName, dstFileName, count: srcLength)); + compareFileContent(srcFileName, dstFileName, count: srcLength), + ); dst.setPositionSync(srcLength); var data = new List.filled(1, 0); var read2 = dst.readIntoSync(data, 0, 1); @@ -142,9 +148,16 @@ testFileToFilePipe3() { var dstLength = dst.lengthSync(); Expect.equals(srcLength * 2, dstLength); Expect.isTrue( - compareFileContent(srcFileName, dstFileName, count: srcLength)); - Expect.isTrue(compareFileContent(srcFileName, dstFileName, - file2Offset: srcLength, count: srcLength)); + compareFileContent(srcFileName, dstFileName, count: srcLength), + ); + Expect.isTrue( + compareFileContent( + srcFileName, + dstFileName, + file2Offset: srcLength, + count: srcLength, + ), + ); src.closeSync(); dst.closeSync(); dstFile.deleteSync(); diff --git a/tests/standalone/io/system_encoding_test.dart b/tests/standalone/io/system_encoding_test.dart index d78a27ab6d2..bb5217b46d6 100644 --- a/tests/standalone/io/system_encoding_test.dart +++ b/tests/standalone/io/system_encoding_test.dart @@ -38,11 +38,15 @@ main() { // On Windows the default Windows code page cannot encode these // Unicode characters and the ? character is used. Expect.listEquals( - systemEncoding.encode('\u1234\u5678\u9abc'), '???'.codeUnits); + systemEncoding.encode('\u1234\u5678\u9abc'), + '???'.codeUnits, + ); } else { // On all systems except for Windows UTF-8 is used as the system // encoding. - Expect.listEquals(systemEncoding.encode('\u1234\u5678\u9abc'), - utf8.encode('\u1234\u5678\u9abc')); + Expect.listEquals( + systemEncoding.encode('\u1234\u5678\u9abc'), + utf8.encode('\u1234\u5678\u9abc'), + ); } } diff --git a/tests/standalone/io/test_utils.dart b/tests/standalone/io/test_utils.dart index 2e8acfc1d26..b5e93d72632 100644 --- a/tests/standalone/io/test_utils.dart +++ b/tests/standalone/io/test_utils.dart @@ -17,8 +17,10 @@ Future retry(Future fun(), {int maxCount = 10}) async { // trying. return await fun(); } catch (e, stack) { - print("Failed to execute test closure (retry id: ${id}) in attempt $i " - "(${maxCount - i} retries left)."); + print( + "Failed to execute test closure (retry id: ${id}) in attempt $i " + "(${maxCount - i} retries left).", + ); print("Exception: ${e}"); print("Stacktrace: ${stack}"); } diff --git a/tests/standalone/io/unix_socket_regress_46634_test.dart b/tests/standalone/io/unix_socket_regress_46634_test.dart index fca1b2a197e..a414fe78415 100644 --- a/tests/standalone/io/unix_socket_regress_46634_test.dart +++ b/tests/standalone/io/unix_socket_regress_46634_test.dart @@ -13,9 +13,11 @@ void main() async { } final futures = []; for (int i = 0; i < 10; ++i) { - futures.add(withTempDir('unix_socket_test', (Directory dir) async { - await testListenCloseListenClose('${dir.path}'); - })); + futures.add( + withTempDir('unix_socket_test', (Directory dir) async { + await testListenCloseListenClose('${dir.path}'); + }), + ); } await Future.wait(futures); } diff --git a/tests/standalone/io/unix_socket_test.dart b/tests/standalone/io/unix_socket_test.dart index d764d90474b..36478502736 100644 --- a/tests/standalone/io/unix_socket_test.dart +++ b/tests/standalone/io/unix_socket_test.dart @@ -45,12 +45,18 @@ testBindShared(String name) async { // Test relative path var path = name.substring(name.lastIndexOf('/') + 1); - address = InternetAddress('${name}/../${path}/sock', - type: InternetAddressType.unix); + address = InternetAddress( + '${name}/../${path}/sock', + type: InternetAddressType.unix, + ); var socket3 = await ServerSocket.bind(address, 0, shared: true); - Expect.isTrue(FileSystemEntity.identicalSync( - socket.address.address, socket3.address.address)); + Expect.isTrue( + FileSystemEntity.identicalSync( + socket.address.address, + socket3.address.address, + ), + ); Expect.equals(socket.port, socket2.port); await socket.close(); await socket2.close(); @@ -83,8 +89,11 @@ testBind(String name) async { Future testListenCloseListenClose(String name) async { var address = InternetAddress('$name/sock', type: InternetAddressType.unix); ServerSocket socket = await ServerSocket.bind(address, 0, shared: true); - ServerSocket socket2 = - await ServerSocket.bind(address, socket.port, shared: true); + ServerSocket socket2 = await ServerSocket.bind( + address, + socket.port, + shared: true, + ); // The second socket should have kept the OS socket alive. We can therefore // test if it is working correctly. @@ -100,10 +109,13 @@ Future testListenCloseListenClose(String name) async { final client = await Socket.connect(address, socket2.port); List data = []; var completer = Completer(); - client.listen(data.addAll, onDone: () { - Expect.listEquals(sendData, data); - completer.complete(); - }); + client.listen( + data.addAll, + onDone: () { + Expect.listEquals(sendData, data); + completer.complete(); + }, + ); await completer.future; await client.close(); @@ -116,8 +128,10 @@ Future testSourceAddressConnect(String name) async { ServerSocket server = await ServerSocket.bind(address, 0); var completer = Completer(); - var localAddress = - InternetAddress('$name/local', type: InternetAddressType.unix); + var localAddress = InternetAddress( + '$name/local', + type: InternetAddressType.unix, + ); server.listen((Socket socket) async { Expect.equals(socket.address.address, address.address); Expect.equals(socket.remoteAddress.address, localAddress.address); @@ -126,8 +140,11 @@ Future testSourceAddressConnect(String name) async { completer.complete(); }); - Socket client = - await Socket.connect(address, server.port, sourceAddress: localAddress); + Socket client = await Socket.connect( + address, + server.port, + sourceAddress: localAddress, + ); Expect.equals(client.remoteAddress.address, address.address); await completer.future; await client.close(); @@ -139,8 +156,10 @@ Future testAbstractAddress(String uniqueName) async { if (!Platform.isLinux && !Platform.isAndroid) { return; } - var serverAddress = - InternetAddress('@temp.sock.$uniqueName', type: InternetAddressType.unix); + var serverAddress = InternetAddress( + '@temp.sock.$uniqueName', + type: InternetAddressType.unix, + ); ServerSocket server = await ServerSocket.bind(serverAddress, 0); final completer = Completer(); final content = 'random string'; @@ -196,8 +215,10 @@ Future testShortAbstractAddress(String uniqueName) async { .transform(const Utf8Decoder(allowMalformed: true)) .listen(stderr.write) .asFuture(null); - var serverAddress = - InternetAddress(socketAddress, type: InternetAddressType.unix); + var serverAddress = InternetAddress( + socketAddress, + type: InternetAddressType.unix, + ); // The subprocess may take some time to start, so retry setting up the // connection a few times. @@ -218,10 +239,13 @@ Future testShortAbstractAddress(String uniqueName) async { List sendData = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; List data = []; var completer = Completer(); - client.listen(data.addAll, onDone: () { - Expect.listEquals(sendData, data); - completer.complete(); - }); + client.listen( + data.addAll, + onDone: () { + Expect.listEquals(sendData, data); + completer.complete(); + }, + ); client.add(sendData); await client.close(); await completer.future; @@ -272,8 +296,11 @@ Future testSetSockOpt(String name) async { // Get some socket options. for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelTcp, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelTcp, + i, + false, + ); var result = socket.getRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -282,8 +309,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelUdp, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelUdp, + i, + false, + ); var result = socket.getRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -292,8 +322,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelIPv4, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelIPv4, + i, + false, + ); var result = socket.getRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -302,8 +335,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelIPv6, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelIPv6, + i, + false, + ); var result = socket.getRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -312,8 +348,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelSocket, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelSocket, + i, + false, + ); var result = socket.getRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Protocol not available')); @@ -323,7 +362,10 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { RawSocketOption option = RawSocketOption.fromBool( - RawSocketOption.IPv4MulticastInterface, i, false); + RawSocketOption.IPv4MulticastInterface, + i, + false, + ); var result = socket.getRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -333,7 +375,10 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { RawSocketOption option = RawSocketOption.fromBool( - RawSocketOption.IPv6MulticastInterface, i, false); + RawSocketOption.IPv6MulticastInterface, + i, + false, + ); var result = socket.getRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -349,8 +394,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelTcp, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelTcp, + i, + false, + ); var result = socket.setRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -359,8 +407,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelUdp, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelUdp, + i, + false, + ); var result = socket.setRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -369,8 +420,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelIPv4, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelIPv4, + i, + false, + ); var result = socket.setRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -379,8 +433,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelIPv6, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelIPv6, + i, + false, + ); var result = socket.setRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -389,8 +446,11 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { - RawSocketOption option = - RawSocketOption.fromBool(RawSocketOption.levelSocket, i, false); + RawSocketOption option = RawSocketOption.fromBool( + RawSocketOption.levelSocket, + i, + false, + ); var result = socket.setRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Protocol not available')); @@ -400,7 +460,10 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { RawSocketOption option = RawSocketOption.fromBool( - RawSocketOption.IPv4MulticastInterface, i, false); + RawSocketOption.IPv4MulticastInterface, + i, + false, + ); var result = socket.setRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -410,7 +473,10 @@ Future testSetSockOpt(String name) async { for (int i = 0; i < 5; i++) { try { RawSocketOption option = RawSocketOption.fromBool( - RawSocketOption.IPv6MulticastInterface, i, false); + RawSocketOption.IPv6MulticastInterface, + i, + false, + ); var result = socket.setRawOption(option); } catch (e) { Expect.isTrue(e.toString().contains('Operation not supported')); @@ -445,8 +511,10 @@ Future testFileMessage(String tempDirPath) async { final firstMessageReceived = Completer(); final completer = Completer(); - final address = - InternetAddress('$tempDirPath/sock', type: InternetAddressType.unix); + final address = InternetAddress( + '$tempDirPath/sock', + type: InternetAddressType.unix, + ); final server = await RawServerSocket.bind(address, 0, shared: false); server.listen((RawSocket socket) async { @@ -493,8 +561,9 @@ Future testFileMessage(String tempDirPath) async { if (e == RawSocketEvent.write) { randomAccessFile.writeStringSync('Hello, client!\n'); socket.sendMessage([ - SocketControlMessage.fromHandles( - [ResourceHandle.fromFile(randomAccessFile)]) + SocketControlMessage.fromHandles([ + ResourceHandle.fromFile(randomAccessFile), + ]), ], 'Hello'.codeUnits); await firstMessageReceived.future; print('client sent a message'); @@ -507,7 +576,9 @@ Future testFileMessage(String tempDirPath) async { } Expect.equals('abc', String.fromCharCodes(data)); Expect.equals( - 'Hello, client!\nHello, server!\n', file.readAsStringSync()); + 'Hello, client!\nHello, server!\n', + file.readAsStringSync(), + ); socket.close(); completer.complete(true); } @@ -521,8 +592,10 @@ Future testTooLargeControlMessage(String tempDirPath) async { return; } final completer = Completer(); - final address = - InternetAddress('$tempDirPath/sock', type: InternetAddressType.unix); + final address = InternetAddress( + '$tempDirPath/sock', + type: InternetAddressType.unix, + ); final server = await RawServerSocket.bind(address, 0, shared: false); server.listen((RawSocket socket) async { @@ -543,23 +616,27 @@ Future testTooLargeControlMessage(String tempDirPath) async { final socket = await RawSocket.connect(address, 0); runZonedGuarded( - () => socket.listen((e) { - if (e == RawSocketEvent.write) { - randomAccessFile.writeStringSync('Hello, client!\n'); - const int largeHandleCount = 1024; - final manyResourceHandles = List.filled( - largeHandleCount, ResourceHandle.fromFile(randomAccessFile)); - socket.sendMessage([ - SocketControlMessage.fromHandles(manyResourceHandles) - ], 'Hello'.codeUnits); - server.close(); - socket.close(); - } - }), (e, st) { - // print('Got expected unhandled exception $e $st'); - Expect.equals(true, e is SocketException); - completer.complete(true); - }); + () => socket.listen((e) { + if (e == RawSocketEvent.write) { + randomAccessFile.writeStringSync('Hello, client!\n'); + const int largeHandleCount = 1024; + final manyResourceHandles = List.filled( + largeHandleCount, + ResourceHandle.fromFile(randomAccessFile), + ); + socket.sendMessage([ + SocketControlMessage.fromHandles(manyResourceHandles), + ], 'Hello'.codeUnits); + server.close(); + socket.close(); + } + }), + (e, st) { + // print('Got expected unhandled exception $e $st'); + Expect.equals(true, e is SocketException); + completer.complete(true); + }, + ); return completer.future; } @@ -571,8 +648,10 @@ Future testFileMessageWithShortRead(String tempDirPath) async { final completer = Completer(); - final address = - InternetAddress('$tempDirPath/sock', type: InternetAddressType.unix); + final address = InternetAddress( + '$tempDirPath/sock', + type: InternetAddressType.unix, + ); final server = await RawServerSocket.bind(address, 0, shared: false); server.listen((RawSocket socket) async { @@ -580,10 +659,10 @@ Future testFileMessageWithShortRead(String tempDirPath) async { socket.listen((e) { if (e == RawSocketEvent.read) { Expect.throws( - () => socket.readMessage(0), - (e) => - e is ArgumentError && - e.toString().contains('Illegal length 0')); + () => socket.readMessage(0), + (e) => + e is ArgumentError && e.toString().contains('Illegal length 0'), + ); final SocketMessage? message = socket.readMessage(/*count=*/ 1); if (message == null) { return; @@ -623,8 +702,9 @@ Future testFileMessageWithShortRead(String tempDirPath) async { if (e == RawSocketEvent.write) { randomAccessFile.writeStringSync('Hello, client!\n'); socket.sendMessage([ - SocketControlMessage.fromHandles( - [ResourceHandle.fromFile(randomAccessFile)]) + SocketControlMessage.fromHandles([ + ResourceHandle.fromFile(randomAccessFile), + ]), ], 'Hi'.codeUnits); print('client sent a message'); } else if (e == RawSocketEvent.read) { @@ -634,7 +714,9 @@ Future testFileMessageWithShortRead(String tempDirPath) async { } Expect.equals('abc', String.fromCharCodes(data)); Expect.equals( - 'Hello, client!\nHello, server!\n', file.readAsStringSync()); + 'Hello, client!\nHello, server!\n', + file.readAsStringSync(), + ); socket.close(); completer.complete(true); } @@ -645,12 +727,12 @@ Future testFileMessageWithShortRead(String tempDirPath) async { Future createTestServer() async { final server = await RawServerSocket.bind(InternetAddress.loopbackIPv4, 0); - return server - ..listen((client) { - String receivedData = ""; + return server..listen((client) { + String receivedData = ""; - client.writeEventsEnabled = false; - client.listen((event) { + client.writeEventsEnabled = false; + client.listen( + (event) { switch (event) { case RawSocketEvent.read: assert(client.available() > 0); @@ -663,24 +745,29 @@ Future createTestServer() async { break; case RawSocketEvent.closed: Expect.equals( - "Hello, client 1!\nHello, client 2!\nHello, server!\n", - receivedData); + "Hello, client 1!\nHello, client 2!\nHello, server!\n", + receivedData, + ); break; default: throw "Unexpected event $event"; } - }, onError: (e) { + }, + onError: (e) { print("client ERROR $e"); - }); - }); + }, + ); + }); } Future testSocketMessage(String uniqueName) async { if (!Platform.isMacOS && !Platform.isLinux && !Platform.isAndroid) { return; } - final address = - InternetAddress('$uniqueName/sock', type: InternetAddressType.unix); + final address = InternetAddress( + '$uniqueName/sock', + type: InternetAddressType.unix, + ); final server = await RawServerSocket.bind(address, 0, shared: false); server.listen((RawSocket socket) async { @@ -721,8 +808,9 @@ Future testSocketMessage(String uniqueName) async { case RawSocketEvent.write: testSocket.write('Hello, client 1!\n'.codeUnits); socket.sendMessage([ - SocketControlMessage.fromHandles( - [ResourceHandle.fromRawSocket(testSocket)]) + SocketControlMessage.fromHandles([ + ResourceHandle.fromRawSocket(testSocket), + ]), ], 'Hello'.codeUnits); testSocket.write('Hello, client 2!\n'.codeUnits); break; @@ -750,7 +838,7 @@ Future testStdioMessage(String tempDirPath, {bool caller = false}) async { ...Platform.executableArguments, '--verbosity=warning', // CFE info/hints pollute the stderr we are trying to test Platform.script.toFilePath(), - '--start-stdio-message-test' + '--start-stdio-message-test', ]); String processStdout = ""; String processStderr = ""; @@ -767,12 +855,16 @@ Future testStdioMessage(String tempDirPath, {bool caller = false}) async { Expect.equals(0, await process.exitCode); Expect.equals("client sent a message\nHello, server!\n", processStdout); Expect.equals( - "client wrote to stderr\nHello, server too!\n", processStderr); + "client wrote to stderr\nHello, server too!\n", + processStderr, + ); return; } - final address = - InternetAddress('$tempDirPath/sock', type: InternetAddressType.unix); + final address = InternetAddress( + '$tempDirPath/sock', + type: InternetAddressType.unix, + ); final server = await RawServerSocket.bind(address, 0, shared: false); server.listen((RawSocket socket) async { @@ -813,8 +905,8 @@ Future testStdioMessage(String tempDirPath, {bool caller = false}) async { SocketControlMessage.fromHandles([ ResourceHandle.fromStdin(stdin), ResourceHandle.fromStdout(stdout), - ResourceHandle.fromStdout(stderr) - ]) + ResourceHandle.fromStdout(stderr), + ]), ], 'Hello'.codeUnits); stdout.writeln('client sent a message'); stderr.writeln('client wrote to stderr'); @@ -833,8 +925,10 @@ Future testReadPipeMessage(String uniqueName) async { if (!Platform.isMacOS && !Platform.isLinux && !Platform.isAndroid) { return; } - final address = - InternetAddress('$uniqueName/sock', type: InternetAddressType.unix); + final address = InternetAddress( + '$uniqueName/sock', + type: InternetAddressType.unix, + ); final server = await RawServerSocket.bind(address, 0, shared: false); server.listen((RawSocket socket) async { @@ -853,8 +947,10 @@ Future testReadPipeMessage(String uniqueName) async { Expect.isNotNull(handles); Expect.equals(1, handles.length); final receivedPipe = handles[0].toReadPipe(); - Expect.equals('Hello over pipe!', - await receivedPipe.transform(utf8.decoder).join()); + Expect.equals( + 'Hello over pipe!', + await receivedPipe.transform(utf8.decoder).join(), + ); socket.write('server replied'.codeUnits); break; case RawSocketEvent.readClosed: @@ -874,8 +970,9 @@ Future testReadPipeMessage(String uniqueName) async { switch (e) { case RawSocketEvent.write: socket.sendMessage([ - SocketControlMessage.fromHandles( - [ResourceHandle.fromReadPipe(testPipe.read)]) + SocketControlMessage.fromHandles([ + ResourceHandle.fromReadPipe(testPipe.read), + ]), ], 'Hello'.codeUnits); testPipe.write.add('Hello over pipe!'.codeUnits); testPipe.write.close(); @@ -899,8 +996,10 @@ Future testWritePipeMessage(String uniqueName) async { if (!Platform.isMacOS && !Platform.isLinux && !Platform.isAndroid) { return; } - final address = - InternetAddress('$uniqueName/sock', type: InternetAddressType.unix); + final address = InternetAddress( + '$uniqueName/sock', + type: InternetAddressType.unix, + ); final server = await RawServerSocket.bind(address, 0, shared: false); server.listen((RawSocket socket) async { @@ -941,12 +1040,15 @@ Future testWritePipeMessage(String uniqueName) async { switch (e) { case RawSocketEvent.write: socket.sendMessage([ - SocketControlMessage.fromHandles( - [ResourceHandle.fromWritePipe(testPipe.write)]) + SocketControlMessage.fromHandles([ + ResourceHandle.fromWritePipe(testPipe.write), + ]), ], 'Hello'.codeUnits); - Expect.equals('Hello over pipe!', - await testPipe.read.transform(utf8.decoder).join()); + Expect.equals( + 'Hello over pipe!', + await testPipe.read.transform(utf8.decoder).join(), + ); break; case RawSocketEvent.read: final data = socket.read(); @@ -1037,82 +1139,85 @@ Future testFileCopy(String tempDirPath) async { } void main(List args) async { - runZonedGuarded(() async { - if (args.length > 0 && args[0] == '--start-stdio-message-test') { + runZonedGuarded( + () async { + if (args.length > 0 && args[0] == '--start-stdio-message-test') { + await withTempDir('unix_socket_test', (Directory dir) async { + await testStdioMessage('${dir.path}', caller: false); + }); + return; + } await withTempDir('unix_socket_test', (Directory dir) async { - await testStdioMessage('${dir.path}', caller: false); + await testAddress('${dir.path}'); }); - return; - } - await withTempDir('unix_socket_test', (Directory dir) async { - await testAddress('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testBind('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testBindShared('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testListenCloseListenClose('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testSourceAddressConnect('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testAbstractAddress(dir.uri.pathSegments.last); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testExistingFile('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testSetSockOpt('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testHttpServer('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testShortAbstractAddress(dir.uri.pathSegments.last); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testFileMessage('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testFileMessageWithShortRead('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testTooLargeControlMessage('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testSocketMessage('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testStdioMessage('${dir.path}', caller: true); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testReadPipeMessage('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testWritePipeMessage('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testDeleteFile('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testFileStat('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testFileRename('${dir.path}'); - }); - await withTempDir('unix_socket_test', (Directory dir) async { - await testFileCopy('${dir.path}'); - }); - }, (e, st) { - if (Platform.isMacOS || Platform.isLinux || Platform.isAndroid) { - Expect.fail("Unexpected exception $e is thrown:\n$st"); - } else { - Expect.isTrue(e is SocketException); - Expect.isTrue(e.toString().contains('not available')); - } - }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testBind('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testBindShared('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testListenCloseListenClose('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testSourceAddressConnect('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testAbstractAddress(dir.uri.pathSegments.last); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testExistingFile('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testSetSockOpt('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testHttpServer('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testShortAbstractAddress(dir.uri.pathSegments.last); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testFileMessage('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testFileMessageWithShortRead('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testTooLargeControlMessage('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testSocketMessage('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testStdioMessage('${dir.path}', caller: true); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testReadPipeMessage('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testWritePipeMessage('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testDeleteFile('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testFileStat('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testFileRename('${dir.path}'); + }); + await withTempDir('unix_socket_test', (Directory dir) async { + await testFileCopy('${dir.path}'); + }); + }, + (e, st) { + if (Platform.isMacOS || Platform.isLinux || Platform.isAndroid) { + Expect.fail("Unexpected exception $e is thrown:\n$st"); + } else { + Expect.isTrue(e is SocketException); + Expect.isTrue(e.toString().contains('not available')); + } + }, + ); } diff --git a/tests/standalone/io/uri_platform_test.dart b/tests/standalone/io/uri_platform_test.dart index f2d26dc6dc5..c13c475ec6c 100644 --- a/tests/standalone/io/uri_platform_test.dart +++ b/tests/standalone/io/uri_platform_test.dart @@ -32,7 +32,8 @@ main() { Expect.equals("/C:", Uri.parse("file:///C:").toFilePath()); Expect.equals("/C:/", Uri.parse("file:///C:/").toFilePath()); Expect.throwsUnsupportedError( - () => Uri.parse("file://host/a/b").toFilePath()); + () => Uri.parse("file://host/a/b").toFilePath(), + ); Expect.equals("a/b", new Uri.file("a/b").toFilePath()); Expect.equals("a\\b", new Uri.file("a\\b").toFilePath()); @@ -40,9 +41,10 @@ main() { // If the current path is only the root prefix (/ (or c:\), then don't add a // separator at the end. Expect.equals( - Uri.base, - (Directory.current.path.toString() != - path.rootPrefix(Directory.current.path.toString())) - ? new Uri.file(Directory.current.path + Platform.pathSeparator) - : new Uri.file(Directory.current.path)); + Uri.base, + (Directory.current.path.toString() != + path.rootPrefix(Directory.current.path.toString())) + ? new Uri.file(Directory.current.path + Platform.pathSeparator) + : new Uri.file(Directory.current.path), + ); } diff --git a/tests/standalone/io/web_socket_compression_test.dart b/tests/standalone/io/web_socket_compression_test.dart index d1df22950d1..bc4aa5a0eb1 100644 --- a/tests/standalone/io/web_socket_compression_test.dart +++ b/tests/standalone/io/web_socket_compression_test.dart @@ -25,8 +25,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); class SecurityConfiguration { final bool secure; @@ -54,13 +56,14 @@ class SecurityConfiguration { String nonce = base64.encode(nonceData); uri = new Uri( - scheme: uri.isScheme("wss") ? "https" : "http", - userInfo: uri.userInfo, - host: uri.host, - port: uri.port, - path: uri.path, - query: uri.query, - fragment: uri.fragment); + scheme: uri.isScheme("wss") ? "https" : "http", + userInfo: uri.userInfo, + host: uri.host, + port: uri.port, + path: uri.path, + query: uri.query, + fragment: uri.fragment, + ); return _httpClient.openUrl("GET", uri).then((request) { if (uri.userInfo != null && !uri.userInfo.isEmpty) { // If the URL contains user information use that for basic @@ -81,24 +84,30 @@ class SecurityConfiguration { }); } - void testCompressionSupport( - {server = false, client = false, contextTakeover = false}) { + void testCompressionSupport({ + server = false, + client = false, + contextTakeover = false, + }) { asyncStart(); var clientOptions = new CompressionOptions( - enabled: client, - serverNoContextTakeover: contextTakeover, - clientNoContextTakeover: contextTakeover); + enabled: client, + serverNoContextTakeover: contextTakeover, + clientNoContextTakeover: contextTakeover, + ); var serverOptions = new CompressionOptions( - enabled: server, - serverNoContextTakeover: contextTakeover, - clientNoContextTakeover: contextTakeover); + enabled: server, + serverNoContextTakeover: contextTakeover, + clientNoContextTakeover: contextTakeover, + ); createServer().then((server) { server.listen((request) { Expect.isTrue(WebSocketTransformer.isUpgradeRequest(request)); - WebSocketTransformer.upgrade(request, compression: serverOptions) - .then((webSocket) { + WebSocketTransformer.upgrade(request, compression: serverOptions).then(( + webSocket, + ) { webSocket.listen((message) { Expect.equals("Hello World", message); @@ -110,30 +119,34 @@ class SecurityConfiguration { }); var url = '${secure ? "wss" : "ws"}://$HOST_NAME:${server.port}/'; - WebSocket.connect(url, compression: clientOptions).then((websocket) { - var future = websocket.listen((message) { - Expect.equals("Hello World", message); - }).asFuture(); - websocket.add("Hello World"); - return future; - }).then((_) { - server.close(); - asyncEnd(); - }); + WebSocket.connect(url, compression: clientOptions) + .then((websocket) { + var future = websocket.listen((message) { + Expect.equals("Hello World", message); + }).asFuture(); + websocket.add("Hello World"); + return future; + }) + .then((_) { + server.close(); + asyncEnd(); + }); }); } - void testContextSupport( - {CompressionOptions serverOpts = CompressionOptions.compressionDefault, - CompressionOptions clientOpts = CompressionOptions.compressionDefault, - int? messages}) { + void testContextSupport({ + CompressionOptions serverOpts = CompressionOptions.compressionDefault, + CompressionOptions clientOpts = CompressionOptions.compressionDefault, + int? messages, + }) { asyncStart(); createServer().then((server) { server.listen((request) { Expect.isTrue(WebSocketTransformer.isUpgradeRequest(request)); - WebSocketTransformer.upgrade(request, compression: serverOpts) - .then((webSocket) { + WebSocketTransformer.upgrade(request, compression: serverOpts).then(( + webSocket, + ) { webSocket.listen((message) { Expect.equals("Hello World", message); webSocket.add(message); @@ -144,18 +157,21 @@ class SecurityConfiguration { var url = '${secure ? "wss" : "ws"}://$HOST_NAME:${server.port}/'; WebSocket.connect(url, compression: clientOpts).then((websocket) { var i = 1; - websocket.listen((message) { - Expect.equals("Hello World", message); - if (i == messages) { - websocket.close(); - return; - } - websocket.add("Hello World"); - i++; - }, onDone: () { - server.close(); - asyncEnd(); - }); + websocket.listen( + (message) { + Expect.equals("Hello World", message); + if (i == messages) { + websocket.close(); + return; + } + websocket.add("Hello World"); + i++; + }, + onDone: () { + server.close(); + asyncEnd(); + }, + ); websocket.add("Hello World"); }); }); @@ -166,9 +182,13 @@ class SecurityConfiguration { createServer().then((server) { server.listen((request) { Expect.equals( - 'Upgrade', request.headers.value(HttpHeaders.connectionHeader)); + 'Upgrade', + request.headers.value(HttpHeaders.connectionHeader), + ); Expect.equals( - 'websocket', request.headers.value(HttpHeaders.upgradeHeader)); + 'websocket', + request.headers.value(HttpHeaders.upgradeHeader), + ); var key = request.headers.value('Sec-WebSocket-Key'); var digest = sha1.convert("$key$WEB_SOCKET_GUID".codeUnits); @@ -179,42 +199,53 @@ class SecurityConfiguration { ..headers.add(HttpHeaders.upgradeHeader, "websocket") ..headers.add("Sec-WebSocket-Accept", accept) ..headers.add( - "Sec-WebSocket-Extensions", - "permessage-deflate;" - // Test quoted values and space padded = - 'server_max_window_bits="10"; client_max_window_bits = 12' - 'client_no_context_takeover; server_no_context_takeover'); + "Sec-WebSocket-Extensions", + "permessage-deflate;" + // Test quoted values and space padded = + 'server_max_window_bits="10"; client_max_window_bits = 12' + 'client_no_context_takeover; server_no_context_takeover', + ); request.response.contentLength = 0; - request.response.detachSocket().then((socket) { - return new WebSocket.fromUpgradedSocket(socket, serverSide: true); - }).then((websocket) { - websocket.add("Hello"); - websocket.close(); - asyncEnd(); - }); + request.response + .detachSocket() + .then((socket) { + return new WebSocket.fromUpgradedSocket(socket, serverSide: true); + }) + .then((websocket) { + websocket.add("Hello"); + websocket.close(); + asyncEnd(); + }); }); var url = '${secure ? "wss" : "ws"}://$HOST_NAME:${server.port}/'; - WebSocket.connect(url).then((websocket) { - return websocket.listen((message) { - Expect.equals("Hello", message); - websocket.close(); - }).asFuture(); - }).then((_) => server.close()); + WebSocket.connect(url) + .then((websocket) { + return websocket.listen((message) { + Expect.equals("Hello", message); + websocket.close(); + }).asFuture(); + }) + .then((_) => server.close()); }); } - void testReturnHeaders(String headerValue, String expected, - {CompressionOptions serverCompression = - CompressionOptions.compressionDefault}) { + void testReturnHeaders( + String headerValue, + String expected, { + CompressionOptions serverCompression = + CompressionOptions.compressionDefault, + }) { asyncStart(); createServer().then((server) { server.listen((request) { // Stuff Expect.isTrue(WebSocketTransformer.isUpgradeRequest(request)); - WebSocketTransformer.upgrade(request, compression: serverCompression) - .then((webSocket) { + WebSocketTransformer.upgrade( + request, + compression: serverCompression, + ).then((webSocket) { webSocket.listen((message) { Expect.equals("Hello World", message); @@ -225,29 +256,38 @@ class SecurityConfiguration { }); var url = '${secure ? "wss" : "ws"}://$HOST_NAME:${server.port}/'; - createWebsocket(url, headerValue).then((HttpClientResponse response) { - Expect.equals(response.statusCode, HttpStatus.switchingProtocols); - print(response.headers.value('Sec-WebSocket-Extensions')); - Expect.equals( - response.headers.value("Sec-WebSocket-Extensions"), expected); + createWebsocket(url, headerValue) + .then((HttpClientResponse response) { + Expect.equals(response.statusCode, HttpStatus.switchingProtocols); + print(response.headers.value('Sec-WebSocket-Extensions')); + Expect.equals( + response.headers.value("Sec-WebSocket-Extensions"), + expected, + ); - String accept = response.headers.value("Sec-WebSocket-Accept")!; + String accept = response.headers.value("Sec-WebSocket-Accept")!; - var protocol = response.headers.value('Sec-WebSocket-Protocol'); - return response.detachSocket().then((socket) => - new WebSocket.fromUpgradedSocket(socket, - protocol: protocol, serverSide: false)); - }).then((websocket) { - var future = websocket.listen((message) { - Expect.equals("Hello", message); - websocket.close(); - }).asFuture(); - websocket.add("Hello World"); - return future; - }).then((_) { - server.close(); - asyncEnd(); - }); + var protocol = response.headers.value('Sec-WebSocket-Protocol'); + return response.detachSocket().then( + (socket) => new WebSocket.fromUpgradedSocket( + socket, + protocol: protocol, + serverSide: false, + ), + ); + }) + .then((websocket) { + var future = websocket.listen((message) { + Expect.equals("Hello", message); + websocket.close(); + }).asFuture(); + websocket.add("Hello World"); + return future; + }) + .then((_) { + server.close(); + asyncEnd(); + }); }); // End createServer } @@ -255,17 +295,26 @@ class SecurityConfiguration { asyncStart(); createServer().then((server) { server.listen((request) { - var extensionHeader = - request.headers.value('Sec-WebSocket-Extensions')!; + var extensionHeader = request.headers.value( + 'Sec-WebSocket-Extensions', + )!; var hv = HeaderValue.parse(extensionHeader); - Expect.equals(compression.serverNoContextTakeover, - hv.parameters.containsKey('server_no_context_takeover')); - Expect.equals(compression.clientNoContextTakeover, - hv.parameters.containsKey('client_no_context_takeover')); - Expect.equals(compression.serverMaxWindowBits?.toString(), - hv.parameters['server_max_window_bits']); - Expect.equals(compression.clientMaxWindowBits?.toString(), - hv.parameters['client_max_window_bits']); + Expect.equals( + compression.serverNoContextTakeover, + hv.parameters.containsKey('server_no_context_takeover'), + ); + Expect.equals( + compression.clientNoContextTakeover, + hv.parameters.containsKey('client_no_context_takeover'), + ); + Expect.equals( + compression.serverMaxWindowBits?.toString(), + hv.parameters['server_max_window_bits'], + ); + Expect.equals( + compression.clientMaxWindowBits?.toString(), + hv.parameters['client_max_window_bits'], + ); WebSocketTransformer.upgrade(request).then((webSocket) { webSocket.listen((message) { @@ -279,17 +328,19 @@ class SecurityConfiguration { var url = '${secure ? "wss" : "ws"}://$HOST_NAME:${server.port}/'; - WebSocket.connect(url, compression: compression).then((websocket) { - var future = websocket.listen((message) { - Expect.equals('Hello World', message); - websocket.close(); - }).asFuture(); - websocket.add('Hello World'); - return future; - }).then((_) { - server.close(); - asyncEnd(); - }); + WebSocket.connect(url, compression: compression) + .then((websocket) { + var future = websocket.listen((message) { + Expect.equals('Hello World', message); + websocket.close(); + }).asFuture(); + websocket.add('Hello World'); + return future; + }) + .then((_) { + server.close(); + asyncEnd(); + }); }); } @@ -309,67 +360,100 @@ class SecurityConfiguration { // no context takeover on the server. var serverComp = new CompressionOptions(serverNoContextTakeover: true); testContextSupport( - serverOpts: serverComp, clientOpts: serverComp, messages: 5); + serverOpts: serverComp, + clientOpts: serverComp, + messages: 5, + ); // no contexttakeover on the client. var clientComp = new CompressionOptions(clientNoContextTakeover: true); testContextSupport( - serverOpts: clientComp, clientOpts: clientComp, messages: 5); + serverOpts: clientComp, + clientOpts: clientComp, + messages: 5, + ); // no context takeover enabled for both. var compression = new CompressionOptions( - serverNoContextTakeover: true, clientNoContextTakeover: true); + serverNoContextTakeover: true, + clientNoContextTakeover: true, + ); testContextSupport( - serverOpts: compression, clientOpts: compression, messages: 5); + serverOpts: compression, + clientOpts: compression, + messages: 5, + ); // no context take over for opposing configurations. testContextSupport( - serverOpts: serverComp, clientOpts: clientComp, messages: 5); + serverOpts: serverComp, + clientOpts: clientComp, + messages: 5, + ); testContextSupport( - serverOpts: clientComp, clientOpts: serverComp, messages: 5); + serverOpts: clientComp, + clientOpts: serverComp, + messages: 5, + ); testCompressionHeaders(); // Chrome headers - testReturnHeaders('permessage-deflate; client_max_window_bits', - "permessage-deflate; client_max_window_bits=15"); + testReturnHeaders( + 'permessage-deflate; client_max_window_bits', + "permessage-deflate; client_max_window_bits=15", + ); // Firefox headers testReturnHeaders( - 'permessage-deflate', "permessage-deflate; client_max_window_bits=15"); + 'permessage-deflate', + "permessage-deflate; client_max_window_bits=15", + ); // Ensure max_window_bits resize appropriately. testReturnHeaders( - 'permessage-deflate; server_max_window_bits=10', - "permessage-deflate;" - " server_max_window_bits=10;" - " client_max_window_bits=10"); + 'permessage-deflate; server_max_window_bits=10', + "permessage-deflate;" + " server_max_window_bits=10;" + " client_max_window_bits=10", + ); // Don't provider context takeover if requested but not enabled. // Default is not enabled. testReturnHeaders( - 'permessage-deflate; client_max_window_bits;' - 'client_no_context_takeover', - 'permessage-deflate; client_max_window_bits=15'); + 'permessage-deflate; client_max_window_bits;' + 'client_no_context_takeover', + 'permessage-deflate; client_max_window_bits=15', + ); // Enable context Takeover and provide if requested. compression = new CompressionOptions( - clientNoContextTakeover: true, serverNoContextTakeover: true); + clientNoContextTakeover: true, + serverNoContextTakeover: true, + ); testReturnHeaders( - 'permessage-deflate; client_max_window_bits; ' - 'client_no_context_takeover', - 'permessage-deflate; client_no_context_takeover; ' - 'client_max_window_bits=15', - serverCompression: compression); + 'permessage-deflate; client_max_window_bits; ' + 'client_no_context_takeover', + 'permessage-deflate; client_no_context_takeover; ' + 'client_max_window_bits=15', + serverCompression: compression, + ); // Enable context takeover and don't provide if not requested compression = new CompressionOptions( - clientNoContextTakeover: true, serverNoContextTakeover: true); - testReturnHeaders('permessage-deflate; client_max_window_bits; ', - 'permessage-deflate; client_max_window_bits=15', - serverCompression: compression); + clientNoContextTakeover: true, + serverNoContextTakeover: true, + ); + testReturnHeaders( + 'permessage-deflate; client_max_window_bits; ', + 'permessage-deflate; client_max_window_bits=15', + serverCompression: compression, + ); compression = CompressionOptions.compressionDefault; testClientRequestHeaders(compression); compression = new CompressionOptions( - clientNoContextTakeover: true, serverNoContextTakeover: true); + clientNoContextTakeover: true, + serverNoContextTakeover: true, + ); testClientRequestHeaders(compression); compression = new CompressionOptions( - clientNoContextTakeover: true, - serverNoContextTakeover: true, - clientMaxWindowBits: 8, - serverMaxWindowBits: 8); + clientNoContextTakeover: true, + serverNoContextTakeover: true, + clientMaxWindowBits: 8, + serverMaxWindowBits: 8, + ); testClientRequestHeaders(compression); } } diff --git a/tests/standalone/io/web_socket_error_test.dart b/tests/standalone/io/web_socket_error_test.dart index 396f9c98e62..97beba2bb32 100644 --- a/tests/standalone/io/web_socket_error_test.dart +++ b/tests/standalone/io/web_socket_error_test.dart @@ -29,8 +29,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -47,9 +49,10 @@ class SecurityConfiguration { ? HttpServer.bindSecure(HOST_NAME, 0, serverContext, backlog: backlog) : HttpServer.bind(HOST_NAME, 0, backlog: backlog); - Future createClient(int port) => - WebSocket.connect('${secure ? "wss" : "ws"}://$HOST_NAME:$port/', - customClient: secure ? HttpClient(context: clientContext) : null); + Future createClient(int port) => WebSocket.connect( + '${secure ? "wss" : "ws"}://$HOST_NAME:$port/', + customClient: secure ? HttpClient(context: clientContext) : null, + ); void testForceCloseServerEnd(int totalConnections) { createServer().then((server) { @@ -73,14 +76,17 @@ class SecurityConfiguration { for (int i = 0; i < totalConnections; i++) { createClient(server.port).then((webSocket) { webSocket.add("Hello, world!"); - webSocket.listen((message) { - Expect.fail("unexpected message"); - }, onDone: () { - closeCount++; - if (closeCount == totalConnections) { - server.close(); - } - }); + webSocket.listen( + (message) { + Expect.fail("unexpected message"); + }, + onDone: () { + closeCount++; + if (closeCount == totalConnections) { + server.close(); + } + }, + ); }); } }); diff --git a/tests/standalone/io/web_socket_ping_test.dart b/tests/standalone/io/web_socket_ping_test.dart index 87b1a920654..3aeceb2b7a5 100644 --- a/tests/standalone/io/web_socket_ping_test.dart +++ b/tests/standalone/io/web_socket_ping_test.dart @@ -46,14 +46,17 @@ void testPing(int totalConnections) { for (int i = 0; i < totalConnections; i++) { WebSocket.connect('ws://localhost:${server.port}').then((webSocket) { webSocket.pingInterval = const Duration(milliseconds: 100); - webSocket.listen((message) { - Expect.fail("unexpected message"); - }, onDone: () { - closeCount++; - if (closeCount == totalConnections) { - server.close(); - } - }); + webSocket.listen( + (message) { + Expect.fail("unexpected message"); + }, + onDone: () { + closeCount++; + if (closeCount == totalConnections) { + server.close(); + } + }, + ); }); } }); @@ -65,17 +68,25 @@ void testPingCancelledOnClose() { .transform(new WebSocketTransformer()) .listen((webSocket) => webSocket.drain()); - Testing$_WebSocketImpl.connect('ws://localhost:${server.port}', null, null) - .then((webSocket) { + Testing$_WebSocketImpl.connect( + 'ws://localhost:${server.port}', + null, + null, + ).then((webSocket) { Expect.type<_WebSocketImpl>(webSocket); webSocket.pingInterval = const Duration(seconds: 100); - webSocket.listen((message) { - Expect.fail("unexpected message"); - }, onDone: () { - Expect.isFalse((webSocket as _WebSocketImpl).test$_pingTimer?.isActive); - server.close(); - }); + webSocket.listen( + (message) { + Expect.fail("unexpected message"); + }, + onDone: () { + Expect.isFalse( + (webSocket as _WebSocketImpl).test$_pingTimer?.isActive, + ); + server.close(); + }, + ); webSocket.close(); }); diff --git a/tests/standalone/io/web_socket_pipe_test.dart b/tests/standalone/io/web_socket_pipe_test.dart index f061984e07d..8f5a6947061 100644 --- a/tests/standalone/io/web_socket_pipe_test.dart +++ b/tests/standalone/io/web_socket_pipe_test.dart @@ -13,11 +13,12 @@ import "dart:io"; createReverseStringTransformer() { return new StreamTransformer.fromHandlers( - handleData: (data, sink) { - var sb = new StringBuffer(); - for (int i = data.length - 1; i >= 0; i--) sb.write(data[i]); - sink.add(sb.toString()); - }); + handleData: (data, sink) { + var sb = new StringBuffer(); + for (int i = data.length - 1; i >= 0; i--) sb.write(data[i]); + sink.add(sb.toString()); + }, + ); } testPipe({required int messages, required bool transform}) { diff --git a/tests/standalone/io/web_socket_protocol_processor_test.dart b/tests/standalone/io/web_socket_protocol_processor_test.dart index 36b6f157669..6ccb17a9451 100644 --- a/tests/standalone/io/web_socket_protocol_processor_test.dart +++ b/tests/standalone/io/web_socket_protocol_processor_test.dart @@ -17,8 +17,8 @@ import "dart:typed_data"; import "package:expect/async_helper.dart"; import "package:expect/expect.dart"; -typedef _WebSocketProtocolTransformer - = TestingClass$_WebSocketProtocolTransformer; +typedef _WebSocketProtocolTransformer = + TestingClass$_WebSocketProtocolTransformer; class WebSocketFrame { WebSocketFrame(int opcode, List data); @@ -36,8 +36,10 @@ class WebSocketMessageCollector { void Function()? onClosed; - WebSocketMessageCollector(Stream stream, - [List? this.expectedMessage = null]) { + WebSocketMessageCollector( + Stream stream, [ + List? this.expectedMessage = null, + ]) { stream.listen(onMessageData, onDone: onClosed, onError: onError); } @@ -62,8 +64,14 @@ const int FRAME_OPCODE_TEXT = 1; const int FRAME_OPCODE_BINARY = 2; // Function for building a web socket frame. -List createFrame(bool fin, int opcode, int? maskingKey, List data, - int offset, int count) { +List createFrame( + bool fin, + int opcode, + int? maskingKey, + List data, + int offset, + int count, +) { int frameSize = 2; if (count > 125) frameSize += 2; if (count > 65535) frameSize += 6; @@ -97,10 +105,18 @@ void testFullMessages() { var transformer = new _WebSocketProtocolTransformer(); var controller = new StreamController>(sync: true); WebSocketMessageCollector mc = new WebSocketMessageCollector( - controller.stream.transform(transformer), message); + controller.stream.transform(transformer), + message, + ); - List frame = - createFrame(true, opcode, null, message, 0, message.length); + List frame = createFrame( + true, + opcode, + null, + message, + 0, + message.length, + ); // Update the transformer with one big chunk. messageCount++; @@ -157,8 +173,9 @@ void testFragmentedMessages() { // Use the same web socket protocol transformer for all frames. var transformer = new _WebSocketProtocolTransformer(); var controller = new StreamController>(sync: true); - WebSocketMessageCollector mc = - new WebSocketMessageCollector(controller.stream.transform(transformer)); + WebSocketMessageCollector mc = new WebSocketMessageCollector( + controller.stream.transform(transformer), + ); int messageCount = 0; int frameCount = 0; @@ -172,8 +189,14 @@ void testFragmentedMessages() { while (!lastFrame) { int payloadSize = min(fragmentSize, remaining); lastFrame = payloadSize == remaining; - List frame = createFrame(lastFrame, firstFrame ? opcode : 0x00, null, - message, messageIndex, payloadSize); + List frame = createFrame( + lastFrame, + firstFrame ? opcode : 0x00, + null, + message, + messageIndex, + payloadSize, + ); frameCount++; messageIndex += payloadSize; controller.add(frame); @@ -218,12 +241,23 @@ void testUnmaskedMessage() { var transformer = new _WebSocketProtocolTransformer(true); var controller = new StreamController>(sync: true); asyncStart(); - controller.stream.transform(transformer).listen((_) {}, onError: (e) { - asyncEnd(); - }); + controller.stream + .transform(transformer) + .listen( + (_) {}, + onError: (e) { + asyncEnd(); + }, + ); var message = new Uint8List(10); - List frame = - createFrame(true, FRAME_OPCODE_BINARY, null, message, 0, message.length); + List frame = createFrame( + true, + FRAME_OPCODE_BINARY, + null, + message, + 0, + message.length, + ); controller.add(frame); } diff --git a/tests/standalone/io/web_socket_protocol_test.dart b/tests/standalone/io/web_socket_protocol_test.dart index 529feb97f14..aaaf266bb2b 100644 --- a/tests/standalone/io/web_socket_protocol_test.dart +++ b/tests/standalone/io/web_socket_protocol_test.dart @@ -18,8 +18,9 @@ testEmptyProtocol() { websocket.close(); }); }); - WebSocket.connect("ws://127.0.0.1:${server.port}/", protocols: []) - .then((client) { + WebSocket.connect("ws://127.0.0.1:${server.port}/", protocols: []).then(( + client, + ) { Expect.isNull(client.protocol); client.close(); server.close(); @@ -35,14 +36,17 @@ testProtocol(List protocols, String used) { HttpServer.bind("127.0.0.1", 0).then((server) { server.listen((request) { - WebSocketTransformer.upgrade(request, protocolSelector: selector) - .then((websocket) { + WebSocketTransformer.upgrade(request, protocolSelector: selector).then(( + websocket, + ) { Expect.equals(used, websocket.protocol); websocket.close(); }); }); - WebSocket.connect("ws://127.0.0.1:${server.port}/", protocols: protocols) - .then((client) { + WebSocket.connect( + "ws://127.0.0.1:${server.port}/", + protocols: protocols, + ).then((client) { Expect.equals(used, client.protocol); client.close(); server.close(); @@ -59,18 +63,25 @@ testProtocolHandler() { } WebSocketTransformer.upgrade(request, protocolSelector: selector).then( - (websocket) { + (websocket) { + Expect.fail('error expected'); + }, + onError: (error) { + Expect.equals('error', error); + }, + ); + }); + WebSocket.connect( + "ws://127.0.0.1:${server.port}/", + protocols: ["v1.example.com"], + ).then( + (client) { Expect.fail('error expected'); - }, onError: (error) { - Expect.equals('error', error); - }); - }); - WebSocket.connect("ws://127.0.0.1:${server.port}/", - protocols: ["v1.example.com"]).then((client) { - Expect.fail('error expected'); - }, onError: (error) { - server.close(); - }); + }, + onError: (error) { + server.close(); + }, + ); }); // Test returning another protocol. @@ -78,18 +89,25 @@ testProtocolHandler() { server.listen((request) { selector(List receivedProtocols) => "v2.example.com"; WebSocketTransformer.upgrade(request, protocolSelector: selector).then( - (websocket) { + (websocket) { + Expect.fail('error expected'); + }, + onError: (error) { + Expect.isTrue(error is WebSocketException); + }, + ); + }); + WebSocket.connect( + "ws://127.0.0.1:${server.port}/", + protocols: ["v1.example.com"], + ).then( + (client) { Expect.fail('error expected'); - }, onError: (error) { - Expect.isTrue(error is WebSocketException); - }); - }); - WebSocket.connect("ws://127.0.0.1:${server.port}/", - protocols: ["v1.example.com"]).then((client) { - Expect.fail('error expected'); - }, onError: (error) { - server.close(); - }); + }, + onError: (error) { + server.close(); + }, + ); }); } diff --git a/tests/standalone/io/web_socket_test.dart b/tests/standalone/io/web_socket_test.dart index 9397c365e7d..6c1fe2d278f 100644 --- a/tests/standalone/io/web_socket_test.dart +++ b/tests/standalone/io/web_socket_test.dart @@ -28,8 +28,10 @@ String localFile(path) => Platform.script.resolve(path).toFilePath(); SecurityContext serverContext = new SecurityContext() ..useCertificateChain(localFile('certificates/server_chain.pem')) - ..usePrivateKey(localFile('certificates/server_key.pem'), - password: 'dartdart'); + ..usePrivateKey( + localFile('certificates/server_key.pem'), + password: 'dartdart', + ); SecurityContext clientContext = new SecurityContext() ..setTrustedCertificates(localFile('certificates/trusted_certs.pem')); @@ -46,41 +48,57 @@ class SecurityConfiguration { ? HttpServer.bindSecure(HOST_NAME, 0, serverContext, backlog: backlog) : HttpServer.bind(HOST_NAME, 0, backlog: backlog); - Future createClient(int port, - {String? user, - Map? headers, - String? customUserAgent}) => - WebSocket.connect( - '${secure ? "wss" : "ws"}://${user is Null ? "" : "$user@"}$HOST_NAME:$port/', - headers: headers, - customClient: secure - ? (HttpClient(context: clientContext) - ..userAgent = customUserAgent) - : null); + Future createClient( + int port, { + String? user, + Map? headers, + String? customUserAgent, + }) => WebSocket.connect( + '${secure ? "wss" : "ws"}://${user is Null ? "" : "$user@"}$HOST_NAME:$port/', + headers: headers, + customClient: secure + ? (HttpClient(context: clientContext)..userAgent = customUserAgent) + : null, + ); checkCloseStatus(webSocket, closeStatus, closeReason) { Expect.equals( - closeStatus == null ? WebSocketStatus.noStatusReceived : closeStatus, - webSocket.closeCode); + closeStatus == null ? WebSocketStatus.noStatusReceived : closeStatus, + webSocket.closeCode, + ); Expect.equals( - closeReason == null ? "" : closeReason, webSocket.closeReason); + closeReason == null ? "" : closeReason, + webSocket.closeReason, + ); } - void testRequestResponseClientCloses(int totalConnections, int? closeStatus, - String? closeReason, int numberOfMessages) { + void testRequestResponseClientCloses( + int totalConnections, + int? closeStatus, + String? closeReason, + int numberOfMessages, + ) { assert(numberOfMessages >= 1); asyncStart(); createServer().then((server) { - server.transform(new WebSocketTransformer()).listen((webSocket) { - asyncStart(); - webSocket.listen(webSocket.add, onDone: () { - checkCloseStatus(webSocket, closeStatus, closeReason); - asyncEnd(); - }); - }, onDone: () { - asyncEnd(); - }); + server + .transform(new WebSocketTransformer()) + .listen( + (webSocket) { + asyncStart(); + webSocket.listen( + webSocket.add, + onDone: () { + checkCloseStatus(webSocket, closeStatus, closeReason); + asyncEnd(); + }, + ); + }, + onDone: () { + asyncEnd(); + }, + ); int closeCount = 0; String messageText = "Hello, world!"; @@ -88,58 +106,70 @@ class SecurityConfiguration { asyncStart(); createClient(server.port).then((webSocket) { webSocket.add(messageText); - webSocket.listen((message) { - numberOfMessages--; - Expect.equals(messageText, message); + webSocket.listen( + (message) { + numberOfMessages--; + Expect.equals(messageText, message); - if (numberOfMessages > 0) { - webSocket.add(message); - } else { - webSocket.close(closeStatus, closeReason); - } - }, onDone: () { - checkCloseStatus(webSocket, closeStatus, closeReason); - closeCount++; - if (closeCount == totalConnections) { - server.close(); - } - asyncEnd(); - }); + if (numberOfMessages > 0) { + webSocket.add(message); + } else { + webSocket.close(closeStatus, closeReason); + } + }, + onDone: () { + checkCloseStatus(webSocket, closeStatus, closeReason); + closeCount++; + if (closeCount == totalConnections) { + server.close(); + } + asyncEnd(); + }, + ); }); } }); } void testRequestResponseServerCloses( - int totalConnections, int? closeStatus, String? closeReason) { + int totalConnections, + int? closeStatus, + String? closeReason, + ) { createServer().then((server) { int closeCount = 0; server.transform(new WebSocketTransformer()).listen((webSocket) { String messageText = "Hello, world!"; int messageCount = 0; - webSocket.listen((message) { - messageCount++; - if (messageCount < 10) { - Expect.equals(messageText, message); - webSocket.add(message); - } else { - webSocket.close(closeStatus, closeReason); - } - }, onDone: () { - checkCloseStatus(webSocket, closeStatus, closeReason); - closeCount++; - if (closeCount == totalConnections) { - server.close(); - } - }); + webSocket.listen( + (message) { + messageCount++; + if (messageCount < 10) { + Expect.equals(messageText, message); + webSocket.add(message); + } else { + webSocket.close(closeStatus, closeReason); + } + }, + onDone: () { + checkCloseStatus(webSocket, closeStatus, closeReason); + closeCount++; + if (closeCount == totalConnections) { + server.close(); + } + }, + ); webSocket.add(messageText); }); for (int i = 0; i < totalConnections; i++) { createClient(server.port).then((webSocket) { - webSocket.listen(webSocket.add, onDone: () { - checkCloseStatus(webSocket, closeStatus, closeReason); - }); + webSocket.listen( + webSocket.add, + onDone: () { + checkCloseStatus(webSocket, closeStatus, closeReason); + }, + ); }); } }); @@ -273,12 +303,15 @@ class SecurityConfiguration { createServer().then((server) { server.listen((request) { WebSocketTransformer.upgrade(request).then((webSocket) { - webSocket.listen((_) { - Expect.fail("Unexpected message"); - }, onDone: () { - server.close(); - webSocket.close(); - }); + webSocket.listen( + (_) { + Expect.fail("Unexpected message"); + }, + onDone: () { + server.close(); + webSocket.close(); + }, + ); }); }); @@ -309,47 +342,61 @@ class SecurityConfiguration { void testUsePOST() { asyncStart(); createServer().then((server) { - server.transform(new WebSocketTransformer()).listen((webSocket) { - Expect.fail("No connection expected"); - }, onError: (e) { - asyncEnd(); - }); + server + .transform(new WebSocketTransformer()) + .listen( + (webSocket) { + Expect.fail("No connection expected"); + }, + onError: (e) { + asyncEnd(); + }, + ); final client = HttpClient(context: secure ? clientContext : null); client - .postUrl(Uri.parse( - "${secure ? 'https:' : 'http:'}//$HOST_NAME:${server.port}/")) + .postUrl( + Uri.parse( + "${secure ? 'https:' : 'http:'}//$HOST_NAME:${server.port}/", + ), + ) .then((request) => request.close()) .then((response) { - Expect.equals(HttpStatus.badRequest, response.statusCode); - client.close(); - server.close(); - }); + Expect.equals(HttpStatus.badRequest, response.statusCode); + client.close(); + server.close(); + }); }); } void testConnections( - int totalConnections, int closeStatus, String closeReason) { + int totalConnections, + int closeStatus, + String closeReason, + ) { createServer().then((server) { int closeCount = 0; server.transform(new WebSocketTransformer()).listen((webSocket) { String messageText = "Hello, world!"; int messageCount = 0; - webSocket.listen((message) { - messageCount++; - if (messageCount < 10) { - Expect.equals(messageText, message); - webSocket.add(message); - } else { - webSocket.close(closeStatus, closeReason); - } - }, onDone: () { - checkCloseStatus(webSocket, closeStatus, closeReason); - closeCount++; - if (closeCount == totalConnections) { - server.close(); - } - }); + webSocket.listen( + (message) { + messageCount++; + if (messageCount < 10) { + Expect.equals(messageText, message); + webSocket.add(message); + } else { + webSocket.close(closeStatus, closeReason); + } + }, + onDone: () { + checkCloseStatus(webSocket, closeStatus, closeReason); + closeCount++; + if (closeCount == totalConnections) { + server.close(); + } + }, + ); webSocket.add(messageText); }); @@ -364,21 +411,24 @@ class SecurityConfiguration { Expect.isFalse(oncloseCalled); onopenCalled = true; Expect.equals(WebSocket.open, webSocket.readyState); - webSocket.listen((message) { - onmessageCalled++; - Expect.isTrue(onopenCalled); - Expect.isFalse(oncloseCalled); - Expect.equals(WebSocket.open, webSocket.readyState); - webSocket.add(message); - }, onDone: () { - Expect.isTrue(onopenCalled); - Expect.equals(10, onmessageCalled); - Expect.isFalse(oncloseCalled); - oncloseCalled = true; - Expect.equals(3002, webSocket.closeCode); - Expect.equals("Got tired", webSocket.closeReason); - Expect.equals(WebSocket.closed, webSocket.readyState); - }); + webSocket.listen( + (message) { + onmessageCalled++; + Expect.isTrue(onopenCalled); + Expect.isFalse(oncloseCalled); + Expect.equals(WebSocket.open, webSocket.readyState); + webSocket.add(message); + }, + onDone: () { + Expect.isTrue(onopenCalled); + Expect.equals(10, onmessageCalled); + Expect.isFalse(oncloseCalled); + oncloseCalled = true; + Expect.equals(3002, webSocket.closeCode); + Expect.equals("Got tired", webSocket.closeReason); + Expect.equals(WebSocket.closed, webSocket.readyState); + }, + ); }); } @@ -423,13 +473,15 @@ class SecurityConfiguration { }, onDone: completer.complete); }); - futures.add(client - .openUrl("GET", Uri.parse('${baseHttpUrl}')) - .then((request) => request.close()) - .then((response) { - response.listen((_) {}); - Expect.equals(HttpStatus.ok, response.statusCode); - })); + futures.add( + client + .openUrl("GET", Uri.parse('${baseHttpUrl}')) + .then((request) => request.close()) + .then((response) { + response.listen((_) {}); + Expect.equals(HttpStatus.ok, response.statusCode); + }), + ); } Future.wait(futures).then((_) { @@ -445,9 +497,13 @@ class SecurityConfiguration { createServer().then((server) { server.listen((request) { Expect.equals( - 'Upgrade', request.headers.value(HttpHeaders.connectionHeader)); + 'Upgrade', + request.headers.value(HttpHeaders.connectionHeader), + ); Expect.equals( - 'websocket', request.headers.value(HttpHeaders.upgradeHeader)); + 'websocket', + request.headers.value(HttpHeaders.upgradeHeader), + ); var key = request.headers.value('Sec-WebSocket-Key'); var digest = sha1.convert("$key$WEB_SOCKET_GUID".codeUnits); @@ -458,21 +514,26 @@ class SecurityConfiguration { ..headers.add(HttpHeaders.upgradeHeader, "websocket") ..headers.add("Sec-WebSocket-Accept", accept); request.response.contentLength = 0; - request.response.detachSocket().then((socket) { - return new WebSocket.fromUpgradedSocket(socket, serverSide: true); - }).then((websocket) { - websocket.add("Hello"); - websocket.close(); - asyncEnd(); - }); + request.response + .detachSocket() + .then((socket) { + return new WebSocket.fromUpgradedSocket(socket, serverSide: true); + }) + .then((websocket) { + websocket.add("Hello"); + websocket.close(); + asyncEnd(); + }); }); - createClient(server.port).then((websocket) { - return websocket.listen((message) { - Expect.equals("Hello", message); - websocket.close(); - }).asFuture(); - }).then((_) => server.close()); + createClient(server.port) + .then((websocket) { + return websocket.listen((message) { + Expect.equals("Hello", message); + websocket.close(); + }).asFuture(); + }) + .then((_) => server.close()); }); } @@ -495,17 +556,19 @@ class SecurityConfiguration { var headers = { 'My-Header': 'my-value', - 'My-Header-Multiple': ['my-value-1', 'my-value-2'] + 'My-Header-Multiple': ['my-value-1', 'my-value-2'], }; - createClient(server.port, headers: headers).then((websocket) { - return websocket.listen((message) { - Expect.equals("Hello", message); - websocket.close(); - }).asFuture(); - }).then((_) { - server.close(); - asyncEnd(); - }); + createClient(server.port, headers: headers) + .then((websocket) { + return websocket.listen((message) { + Expect.equals("Hello", message); + websocket.close(); + }).asFuture(); + }) + .then((_) { + server.close(); + asyncEnd(); + }); }); } @@ -521,25 +584,31 @@ class SecurityConfiguration { Expect.equals('Basic $auth', request.headers['Authorization']![0]); Expect.equals(1, request.headers['Authorization']!.length); WebSocketTransformer.upgrade(request).then((webSocket) { - webSocket.listen((_) { - throw 'Unexpected'; - }, onDone: () { - asyncEnd(); - }); + webSocket.listen( + (_) { + throw 'Unexpected'; + }, + onDone: () { + asyncEnd(); + }, + ); webSocket.add("Hello"); }); }); - createClient(server.port, user: userInfo).then((websocket) { - return websocket.listen((message) { - Expect.equals("Hello", message); - websocket.close(); - }).asFuture(); - }).then((_) { - return server.close(); - }).whenComplete(() { - asyncEnd(); - }); + createClient(server.port, user: userInfo) + .then((websocket) { + return websocket.listen((message) { + Expect.equals("Hello", message); + websocket.close(); + }).asFuture(); + }) + .then((_) { + return server.close(); + }) + .whenComplete(() { + asyncEnd(); + }); }); } @@ -571,8 +640,9 @@ class SecurityConfiguration { }); // Next line should take no effect on custom user agent value provided WebSocket.userAgent = 'Custom User Agent'; - createClient(server.port, customUserAgent: 'New User Agent') - .then((webSocket) { + createClient(server.port, customUserAgent: 'New User Agent').then(( + webSocket, + ) { webSocket.close(); }); }); diff --git a/tests/standalone/io/web_socket_typed_data_test.dart b/tests/standalone/io/web_socket_typed_data_test.dart index d0934716bf3..69807eed494 100644 --- a/tests/standalone/io/web_socket_typed_data_test.dart +++ b/tests/standalone/io/web_socket_typed_data_test.dart @@ -17,8 +17,10 @@ Future createServer() => HttpServer.bind("127.0.0.1", 0); Future createClient(int port, bool compression) => compression ? WebSocket.connect('ws://127.0.0.1:$port/') - : WebSocket.connect('ws://127.0.0.1:$port/', - compression: CompressionOptions.compressionOff); + : WebSocket.connect( + 'ws://127.0.0.1:$port/', + compression: CompressionOptions.compressionOff, + ); void test(expected, testData, compression) { createServer().then((server) { @@ -26,7 +28,8 @@ void test(expected, testData, compression) { var transformer = compression ? new WebSocketTransformer() : new WebSocketTransformer( - compression: CompressionOptions.compressionOff); + compression: CompressionOptions.compressionOff, + ); server.transform(transformer).listen((webSocket) { webSocket.listen((message) { Expect.listEquals(expected, message); @@ -78,7 +81,8 @@ void testOutOfRangeClient({bool compression = false}) { var transformer = compression ? new WebSocketTransformer() : new WebSocketTransformer( - compression: CompressionOptions.compressionOff); + compression: CompressionOptions.compressionOff, + ); server.transform(transformer).listen((webSocket) { webSocket.listen((message) => Expect.fail("No message expected")); }); @@ -183,7 +187,8 @@ void testOutOfRangeServer({bool compression = false}) { var transformer = compression ? new WebSocketTransformer() : new WebSocketTransformer( - compression: CompressionOptions.compressionOff); + compression: CompressionOptions.compressionOff, + ); server.transform(transformer).listen((webSocket) { webSocket.listen((message) { messageCount++; @@ -197,17 +202,20 @@ void testOutOfRangeServer({bool compression = false}) { Future x(int i) { var completer = new Completer(); createClient(server.port, compression).then((webSocket) { - webSocket.listen((message) => Expect.fail("No message expected"), - onDone: () => completer.complete(true), - onError: (e) => completer.completeError(e)); + webSocket.listen( + (message) => Expect.fail("No message expected"), + onDone: () => completer.complete(true), + onError: (e) => completer.completeError(e), + ); webSocket.add([i]); }); return completer.future; } for (int i = 0; i < testData.length; i++) futures.add(x(i)); - allDone.future - .then((_) => Future.wait(futures).then((_) => server.close())); + allDone.future.then( + (_) => Future.wait(futures).then((_) => server.close()), + ); }); } diff --git a/tests/standalone/io/windows_environment_test.dart b/tests/standalone/io/windows_environment_test.dart index f5fbe556a5f..69f47509a28 100644 --- a/tests/standalone/io/windows_environment_test.dart +++ b/tests/standalone/io/windows_environment_test.dart @@ -22,8 +22,9 @@ echo %1 $vmOptions %2 %1 $vmOptions %2 """); var dart = Platform.executable; - var script = - Platform.script.resolve('windows_environment_script.dart').toFilePath(); + var script = Platform.script + .resolve('windows_environment_script.dart') + .toFilePath(); Process.run('cmd', ['/c', funkyFile.path, dart, script]).then((p) { print('stdout: ${p.stdout}'); print('stderr: ${p.stderr}'); diff --git a/tests/standalone/io/windows_file_system_async_links_test.dart b/tests/standalone/io/windows_file_system_async_links_test.dart index 648111e6365..d0491b7bc90 100644 --- a/tests/standalone/io/windows_file_system_async_links_test.dart +++ b/tests/standalone/io/windows_file_system_async_links_test.dart @@ -18,80 +18,139 @@ class FutureExpect { static Future listEquals(expected, Future result) => result.then((value) => Expect.listEquals(expected, value)); static Future throws(Future result) => result.then((value) { - throw new ExpectException( - "FutureExpect.throws received $value instead of an exception"); - }, onError: (_) => null); + throw new ExpectException( + "FutureExpect.throws received $value instead of an exception", + ); + }, onError: (_) => null); } Future testJunctionTypeDelete() { return Directory.systemTemp .createTemp('dart_windows_file_system_async_links') .then((temp) { - var x = '${temp.path}${Platform.pathSeparator}x'; - var y = '${temp.path}${Platform.pathSeparator}y'; - return new Directory(x) - .create() - .then((_) => new Link(y).create(x)) - .then((_) => FutureExpect.isTrue(new Directory(y).exists())) - .then((_) => FutureExpect.isTrue(new Directory(x).exists())) - .then((_) => FutureExpect.isTrue(FileSystemEntity.isLink(y))) - .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.isDirectory(y))) - .then((_) => FutureExpect.isTrue(FileSystemEntity.isDirectory(x))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.directory, FileSystemEntity.type(y))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.directory, FileSystemEntity.type(x))) - .then((_) => FutureExpect.equals(FileSystemEntityType.link, - FileSystemEntity.type(y, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.directory, - FileSystemEntity.type(x, followLinks: false))) - .then((_) => FutureExpect.equals(x, new Link(y).target())) - - // Test Junction pointing to a missing directory. - .then((_) => new Directory(x).delete()) - .then((_) => FutureExpect.isTrue(new Link(y).exists())) - .then((_) => FutureExpect.isFalse(new Directory(x).exists())) - .then((_) => FutureExpect.isTrue(FileSystemEntity.isLink(y))) - .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) - .then((_) => FutureExpect.isFalse(FileSystemEntity.isDirectory(y))) - .then((_) => FutureExpect.isFalse(FileSystemEntity.isDirectory(x))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.notFound, FileSystemEntity.type(y))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.notFound, FileSystemEntity.type(x))) - .then((_) => FutureExpect.equals(FileSystemEntityType.link, - FileSystemEntity.type(y, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.notFound, - FileSystemEntity.type(x, followLinks: false))) - .then((_) => FutureExpect.equals(x, new Link(y).target())) - - // Delete Junction pointing to a missing directory. - .then((_) => new Link(y).delete()) - .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(y))) - .then((_) => FutureExpect.equals( - FileSystemEntityType.notFound, FileSystemEntity.type(y))) - .then((_) => FutureExpect.throws(new Link(y).target())) - .then((_) => new Directory(x).create()) - .then((_) => new Link(y).create(x)) - .then((_) => FutureExpect.equals(FileSystemEntityType.link, - FileSystemEntity.type(y, followLinks: false))) - .then((_) => FutureExpect.equals(FileSystemEntityType.directory, - FileSystemEntity.type(x, followLinks: false))) - .then((_) => FutureExpect.equals(x, new Link(y).target())) - - // Delete Junction pointing to an existing directory. - .then((_) => new Directory(y).delete()) - .then((_) => FutureExpect.equals( - FileSystemEntityType.notFound, FileSystemEntity.type(y))) - .then((_) => FutureExpect.equals(FileSystemEntityType.notFound, - FileSystemEntity.type(y, followLinks: false))) - .then( - (_) => FutureExpect.equals(FileSystemEntityType.directory, FileSystemEntity.type(x))) - .then((_) => FutureExpect.equals(FileSystemEntityType.directory, FileSystemEntity.type(x, followLinks: false))) - .then((_) => FutureExpect.throws(new Link(y).target())) - .then((_) => temp.delete(recursive: true)); - }); + var x = '${temp.path}${Platform.pathSeparator}x'; + var y = '${temp.path}${Platform.pathSeparator}y'; + return new Directory(x) + .create() + .then((_) => new Link(y).create(x)) + .then((_) => FutureExpect.isTrue(new Directory(y).exists())) + .then((_) => FutureExpect.isTrue(new Directory(x).exists())) + .then((_) => FutureExpect.isTrue(FileSystemEntity.isLink(y))) + .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) + .then((_) => FutureExpect.isTrue(FileSystemEntity.isDirectory(y))) + .then((_) => FutureExpect.isTrue(FileSystemEntity.isDirectory(x))) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(y), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.link, + FileSystemEntity.type(y, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x, followLinks: false), + ), + ) + .then((_) => FutureExpect.equals(x, new Link(y).target())) + // Test Junction pointing to a missing directory. + .then((_) => new Directory(x).delete()) + .then((_) => FutureExpect.isTrue(new Link(y).exists())) + .then((_) => FutureExpect.isFalse(new Directory(x).exists())) + .then((_) => FutureExpect.isTrue(FileSystemEntity.isLink(y))) + .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(x))) + .then((_) => FutureExpect.isFalse(FileSystemEntity.isDirectory(y))) + .then((_) => FutureExpect.isFalse(FileSystemEntity.isDirectory(x))) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(y), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(x), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.link, + FileSystemEntity.type(y, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(x, followLinks: false), + ), + ) + .then((_) => FutureExpect.equals(x, new Link(y).target())) + // Delete Junction pointing to a missing directory. + .then((_) => new Link(y).delete()) + .then((_) => FutureExpect.isFalse(FileSystemEntity.isLink(y))) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(y), + ), + ) + .then((_) => FutureExpect.throws(new Link(y).target())) + .then((_) => new Directory(x).create()) + .then((_) => new Link(y).create(x)) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.link, + FileSystemEntity.type(y, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x, followLinks: false), + ), + ) + .then((_) => FutureExpect.equals(x, new Link(y).target())) + // Delete Junction pointing to an existing directory. + .then((_) => new Directory(y).delete()) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(y), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.type(y, followLinks: false), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x), + ), + ) + .then( + (_) => FutureExpect.equals( + FileSystemEntityType.directory, + FileSystemEntity.type(x, followLinks: false), + ), + ) + .then((_) => FutureExpect.throws(new Link(y).target())) + .then((_) => temp.delete(recursive: true)); + }); } main() { diff --git a/tests/standalone/io/windows_file_system_links_test.dart b/tests/standalone/io/windows_file_system_links_test.dart index 6160e37c0be..1ff4693d2b7 100644 --- a/tests/standalone/io/windows_file_system_links_test.dart +++ b/tests/standalone/io/windows_file_system_links_test.dart @@ -7,8 +7,9 @@ import "dart:io"; import 'package:expect/expect.dart'; testJunctionTypeDelete() { - var temp = - Directory.systemTemp.createTempSync('dart_windows_file_system_links'); + var temp = Directory.systemTemp.createTempSync( + 'dart_windows_file_system_links', + ); var x = '${temp.path}${Platform.pathSeparator}x'; var y = '${temp.path}${Platform.pathSeparator}y'; @@ -22,10 +23,14 @@ testJunctionTypeDelete() { Expect.isTrue(FileSystemEntity.isDirectorySync(x)); Expect.equals(FileSystemEntityType.directory, FileSystemEntity.typeSync(y)); Expect.equals(FileSystemEntityType.directory, FileSystemEntity.typeSync(x)); - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(y, followLinks: false)); - Expect.equals(FileSystemEntityType.directory, - FileSystemEntity.typeSync(x, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(y, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(x, followLinks: false), + ); Expect.equals(x, new Link(y).targetSync()); // Test Junction pointing to a missing directory. @@ -38,10 +43,14 @@ testJunctionTypeDelete() { Expect.isFalse(FileSystemEntity.isDirectorySync(x)); Expect.equals(FileSystemEntityType.notFound, FileSystemEntity.typeSync(y)); Expect.equals(FileSystemEntityType.notFound, FileSystemEntity.typeSync(x)); - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(y, followLinks: false)); - Expect.equals(FileSystemEntityType.notFound, - FileSystemEntity.typeSync(x, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(y, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.notFound, + FileSystemEntity.typeSync(x, followLinks: false), + ); Expect.equals(x, new Link(y).targetSync()); // Delete Junction pointing to a missing directory. @@ -52,22 +61,34 @@ testJunctionTypeDelete() { new Directory(x).createSync(); new Link(y).create(x).then((_) { - Expect.equals(FileSystemEntityType.link, - FileSystemEntity.typeSync(y, followLinks: false)); - Expect.equals(FileSystemEntityType.directory, - FileSystemEntity.typeSync(x, followLinks: false)); + Expect.equals( + FileSystemEntityType.link, + FileSystemEntity.typeSync(y, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(x, followLinks: false), + ); Expect.equals(x, new Link(y).targetSync()); // Delete Junction pointing to an existing directory. new Directory(y).deleteSync(); Expect.equals( - FileSystemEntityType.notFound, FileSystemEntity.typeSync(y)); - Expect.equals(FileSystemEntityType.notFound, - FileSystemEntity.typeSync(y, followLinks: false)); + FileSystemEntityType.notFound, + FileSystemEntity.typeSync(y), + ); Expect.equals( - FileSystemEntityType.directory, FileSystemEntity.typeSync(x)); - Expect.equals(FileSystemEntityType.directory, - FileSystemEntity.typeSync(x, followLinks: false)); + FileSystemEntityType.notFound, + FileSystemEntity.typeSync(y, followLinks: false), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(x), + ); + Expect.equals( + FileSystemEntityType.directory, + FileSystemEntity.typeSync(x, followLinks: false), + ); Expect.throws(() => new Link(y).targetSync()); temp.deleteSync(recursive: true); @@ -76,8 +97,9 @@ testJunctionTypeDelete() { } void testLinkToFile() { - final temp = - Directory.systemTemp.createTempSync('dart_windows_file_system_links'); + final temp = Directory.systemTemp.createTempSync( + 'dart_windows_file_system_links', + ); // Create file File file = new File(temp.path + Platform.pathSeparator + "test-file.tmp"); file.createSync(); @@ -99,8 +121,9 @@ void testLinkToFile() { } void testLinkToDirectory() { - final temp = - Directory.systemTemp.createTempSync('dart_windows_file_system_links'); + final temp = Directory.systemTemp.createTempSync( + 'dart_windows_file_system_links', + ); // Create file Directory dir = Directory(temp.path + Platform.pathSeparator + "test-dir"); dir.createSync(); diff --git a/tests/standalone/io/zlib_test.dart b/tests/standalone/io/zlib_test.dart index 550933d9fcd..52dcad54750 100644 --- a/tests/standalone/io/zlib_test.dart +++ b/tests/standalone/io/zlib_test.dart @@ -15,12 +15,13 @@ void testZLibDeflateEmpty() { controller.stream .transform(new ZLibEncoder(gzip: false, level: 6)) .fold>([], (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((data) { - Expect.listEquals([120, 156, 3, 0, 0, 0, 0, 1], data); - asyncEnd(); - }); + buffer.addAll(data); + return buffer; + }) + .then((data) { + Expect.listEquals([120, 156, 3, 0, 0, 0, 0, 1], data); + asyncEnd(); + }); controller.close(); } @@ -30,13 +31,14 @@ void testZLibDeflateEmptyGzip() { controller.stream .transform(new ZLibEncoder(gzip: true, level: 6)) .fold>([], (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((data) { - Expect.isTrue(data.length > 0); - Expect.listEquals([], new ZLibDecoder().convert(data)); - asyncEnd(); - }); + buffer.addAll(data); + return buffer; + }) + .then((data) { + Expect.isTrue(data.length > 0); + Expect.listEquals([], new ZLibDecoder().convert(data)); + asyncEnd(); + }); controller.close(); } @@ -46,46 +48,13 @@ void testZLibDeflate(List data) { controller.stream .transform(new ZLibEncoder(gzip: false, level: 6)) .fold>([], (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((data) { - Expect.listEquals([ - 120, - 156, - 99, - 96, - 100, - 98, - 102, - 97, - 101, - 99, - 231, - 224, - 4, - 0, - 0, - 175, - 0, - 46 - ], data); - asyncEnd(); - }); - controller.add(data); - controller.close(); -} - -void testZLibDeflateGZip(List data) { - asyncStart(); - var controller = new StreamController>(sync: true); - controller.stream.transform(new ZLibEncoder(gzip: true)).fold>([], - (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((data) { - Expect.equals(30, data.length); - Expect.listEquals( - [ + buffer.addAll(data); + return buffer; + }) + .then((data) { + Expect.listEquals([ + 120, + 156, 99, 96, 100, @@ -98,19 +67,56 @@ void testZLibDeflateGZip(List data) { 224, 4, 0, - 70, - 215, - 108, - 69, - 10, 0, + 175, 0, - 0 - ], - // Skip header, as it can change. - data.sublist(10)); - asyncEnd(); - }); + 46, + ], data); + asyncEnd(); + }); + controller.add(data); + controller.close(); +} + +void testZLibDeflateGZip(List data) { + asyncStart(); + var controller = new StreamController>(sync: true); + controller.stream + .transform(new ZLibEncoder(gzip: true)) + .fold>([], (buffer, data) { + buffer.addAll(data); + return buffer; + }) + .then((data) { + Expect.equals(30, data.length); + Expect.listEquals( + [ + 99, + 96, + 100, + 98, + 102, + 97, + 101, + 99, + 231, + 224, + 4, + 0, + 70, + 215, + 108, + 69, + 10, + 0, + 0, + 0, + ], + // Skip header, as it can change. + data.sublist(10), + ); + asyncEnd(); + }); controller.add(data); controller.close(); } @@ -121,13 +127,26 @@ void testZLibDeflateRaw(List data) { controller.stream .transform(new ZLibEncoder(raw: true, level: 6)) .fold>([], (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((data) { - Expect.listEquals( - [99, 96, 100, 98, 102, 97, 101, 99, 231, 224, 4, 0], data); - asyncEnd(); - }); + buffer.addAll(data); + return buffer; + }) + .then((data) { + Expect.listEquals([ + 99, + 96, + 100, + 98, + 102, + 97, + 101, + 99, + 231, + 224, + 4, + 0, + ], data); + asyncEnd(); + }); controller.add(data); controller.close(); } @@ -136,8 +155,9 @@ void testZLibDeflateInvalidLevel() { [true, false].forEach((gzip) { [-2, -20, 10, 42].forEach((level) { Expect.throwsArgumentError( - () => new ZLibEncoder(gzip: gzip, level: level), - "'level' must be in range -1..9"); + () => new ZLibEncoder(gzip: gzip, level: level), + "'level' must be in range -1..9", + ); }); }); } @@ -156,15 +176,17 @@ void testZLibInflate(List data) { var controller = new StreamController>(sync: true); controller.stream .transform( - new ZLibEncoder(gzip: gzip, level: level, strategy: strategy)) + new ZLibEncoder(gzip: gzip, level: level, strategy: strategy), + ) .transform(new ZLibDecoder()) .fold>([], (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((inflated) { - Expect.listEquals(data, inflated); - asyncEnd(); - }); + buffer.addAll(data); + return buffer; + }) + .then((inflated) { + Expect.listEquals(data, inflated); + asyncEnd(); + }); controller.add(data); controller.close(); }); @@ -180,12 +202,13 @@ void testZLibInflateRaw(List data) { .transform(new ZLibEncoder(raw: true, level: level)) .transform(new ZLibDecoder(raw: true)) .fold>([], (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((inflated) { - Expect.listEquals(data, inflated); - asyncEnd(); - }); + buffer.addAll(data); + return buffer; + }) + .then((inflated) { + Expect.listEquals(data, inflated); + asyncEnd(); + }); controller.add(data); controller.close(); }); @@ -220,12 +243,13 @@ void testZlibInflateWithLargerWindow() { .transform(new ZLibEncoder(gzip: gzip, level: level, windowBits: 8)) .transform(new ZLibDecoder(windowBits: 10)) .fold>([], (buffer, data) { - buffer.addAll(data); - return buffer; - }).then((inflated) { - Expect.listEquals(data, inflated); - asyncEnd(); - }); + buffer.addAll(data); + return buffer; + }) + .then((inflated) { + Expect.listEquals(data, inflated); + asyncEnd(); + }); controller.add(data); controller.close(); }); @@ -242,8 +266,10 @@ void testRoundTripLarge() { ZLibOption.strategyDefault, ]) { final uncompressedData = List.generate(2000000, (i) => i % 256); - final compressedData = - ZLibEncoder(gzip: gzip, strategy: strategy).convert(uncompressedData); + final compressedData = ZLibEncoder( + gzip: gzip, + strategy: strategy, + ).convert(uncompressedData); final decodedData = new ZLibDecoder().convert(compressedData); Expect.listEquals(uncompressedData, decodedData); } @@ -266,7 +292,7 @@ void testConcatenatedBlocksGZip() { /// See RFC-1952. final compressedData = [ ...ZLibEncoder().convert([1, 2, 3]), - ...ZLibEncoder().convert([4, 5, 6]) + ...ZLibEncoder().convert([4, 5, 6]), ]; final decodedData = new ZLibDecoder(gzip: true).convert(compressedData); Expect.listEquals([1, 2, 3, 4, 5, 6], decodedData); @@ -277,7 +303,7 @@ void testConcatenatedBlocksZLib() { // the zlib stream. final compressedData = [ ...ZLibEncoder().convert([1, 2, 3]), - ...ZLibEncoder().convert([4, 5, 6]) + ...ZLibEncoder().convert([4, 5, 6]), ]; final decodedData = new ZLibDecoder(gzip: false).convert(compressedData); Expect.listEquals([1, 2, 3], decodedData); @@ -290,11 +316,12 @@ void testInvalidDataAfterBlockGZip() { ...ZLibEncoder().convert([1, 2, 3]), 1, 2, - 3 + 3, ]; Expect.throwsFormatException( - () => new ZLibDecoder(gzip: true).convert(compressedData)); + () => new ZLibDecoder(gzip: true).convert(compressedData), + ); } void testInvalidDataAfterBlockZLib() { @@ -304,7 +331,7 @@ void testInvalidDataAfterBlockZLib() { ...ZLibEncoder().convert([1, 2, 3]), 1, 2, - 3 + 3, ]; final decodedData = new ZLibDecoder(gzip: false).convert(compressedData); diff --git a/tests/standalone/package/package_isolate_test.dart b/tests/standalone/package/package_isolate_test.dart index 60db5d35ccf..f22f7bb303b 100644 --- a/tests/standalone/package/package_isolate_test.dart +++ b/tests/standalone/package/package_isolate_test.dart @@ -52,9 +52,13 @@ void main() { var replyPort = expectResponse().sendPort; shared.output = 'main'; Isolate.spawnUri( - Uri.parse('test_folder/folder_isolate.dart'), [], replyPort, - packageConfig: Uri.parse( - 'tests/standalone/package/test_folder/.dart_tool/package_config.json')); + Uri.parse('test_folder/folder_isolate.dart'), + [], + replyPort, + packageConfig: Uri.parse( + 'tests/standalone/package/test_folder/.dart_tool/package_config.json', + ), + ); } } diff --git a/tests/standalone/priority_queue_stress_test.dart b/tests/standalone/priority_queue_stress_test.dart index f03db7e87d2..aea612fc4d3 100644 --- a/tests/standalone/priority_queue_stress_test.dart +++ b/tests/standalone/priority_queue_stress_test.dart @@ -284,14 +284,16 @@ void stress(queue) { new StringTypedElement('ff', 'foobar'), new StringTypedElement('dartium', 'barfoo'), new StringTypedElement('chrome', 'hest'), - new StringTypedElement('drt', 'fisk') + new StringTypedElement('drt', 'fisk'), ]; var restricted = [values[0], values[4]]; void addRandom() { - queue.add(values[random.nextInt(values.length)], - new IntPriority(priorities[random.nextInt(priorities.length)])); + queue.add( + values[random.nextInt(values.length)], + new IntPriority(priorities[random.nextInt(priorities.length)]), + ); } var stopwatch = new Stopwatch()..start(); diff --git a/tests/standalone/regress_26031_test.dart b/tests/standalone/regress_26031_test.dart index c8a8e0ac515..41a5a33d809 100644 --- a/tests/standalone/regress_26031_test.dart +++ b/tests/standalone/regress_26031_test.dart @@ -14,7 +14,10 @@ void checkResolvedExecutable(Object reObj) { main() { var exitPort = new ReceivePort(); - Isolate.spawn(checkResolvedExecutable, Platform.resolvedExecutable, - onExit: exitPort.sendPort); + Isolate.spawn( + checkResolvedExecutable, + Platform.resolvedExecutable, + onExit: exitPort.sendPort, + ); exitPort.listen((_) => exitPort.close()); } diff --git a/tests/standalone/regress_41329_absolute_test.dart b/tests/standalone/regress_41329_absolute_test.dart index 5798cbc8939..e0ae5055c41 100644 --- a/tests/standalone/regress_41329_absolute_test.dart +++ b/tests/standalone/regress_41329_absolute_test.dart @@ -19,7 +19,8 @@ Future main() async { // /usr/local/Cellar/dart/2.8.0-dev.20.0/bin/dart -> $DART_SDK/bin/dart Directory.current = a; - final linkLocation = '${d.path}/usr/local/bin/Cellar/dart/2.8.0-dev.20.0/bin/dart'; + final linkLocation = + '${d.path}/usr/local/bin/Cellar/dart/2.8.0-dev.20.0/bin/dart'; final link = Link(linkLocation); link.createSync(exePath, recursive: true); diff --git a/tests/standalone/regress_42092_test.dart b/tests/standalone/regress_42092_test.dart index fc110829c8e..ed90c056330 100644 --- a/tests/standalone/regress_42092_test.dart +++ b/tests/standalone/regress_42092_test.dart @@ -9,12 +9,9 @@ import 'dart:io'; import 'package:expect/expect.dart'; Future main() async { - final process = await Process.start( - Platform.resolvedExecutable, - [ - Platform.script.resolve('regress_42092_script.dart').toString(), - ], - ); + final process = await Process.start(Platform.resolvedExecutable, [ + Platform.script.resolve('regress_42092_script.dart').toString(), + ]); late StreamSubscription sub; int count = 0; sub = process.stdout.transform(Utf8Decoder()).listen((event) { diff --git a/tests/standalone/regress_52691_test.dart b/tests/standalone/regress_52691_test.dart index d11e8c96684..fa83241312d 100644 --- a/tests/standalone/regress_52691_test.dart +++ b/tests/standalone/regress_52691_test.dart @@ -5,6 +5,8 @@ void main() { var re = RegExp(r'[c-'); } on FormatException catch (e, s) { Expect.equals( - "FormatException: Unterminated character class [c-", e.toString()); + "FormatException: Unterminated character class [c-", + e.toString(), + ); } } diff --git a/tests/standalone/typed_array_test.dart b/tests/standalone/typed_array_test.dart index 49bd0e1ae50..cc0cc032906 100644 --- a/tests/standalone/typed_array_test.dart +++ b/tests/standalone/typed_array_test.dart @@ -252,8 +252,10 @@ Float32List float32 = initFloat32(); float32_receiver() { var response = new ReceivePort(); - var remote = - Isolate.spawn(float32_sender, [float32.length, response.sendPort]); + var remote = Isolate.spawn(float32_sender, [ + float32.length, + response.sendPort, + ]); asyncStart(); return response.first.then((a) { Expect.equals(float32.length, a.length); @@ -288,8 +290,10 @@ Float64List float64 = initFloat64(); float64_receiver() { var response = new ReceivePort(); - var remote = - Isolate.spawn(float64_sender, [float64.length, response.sendPort]); + var remote = Isolate.spawn(float64_sender, [ + float64.length, + response.sendPort, + ]); asyncStart(); return response.first.then((a) { Expect.equals(float64.length, a.length); diff --git a/tests/standalone/typed_data_test.dart b/tests/standalone/typed_data_test.dart index 83913b94506..4fd1b262063 100644 --- a/tests/standalone/typed_data_test.dart +++ b/tests/standalone/typed_data_test.dart @@ -84,7 +84,9 @@ void testUnsignedTypedDataRange(bool check_throws) { } void testClampedUnsignedTypedDataRangeHelper( - Uint8ClampedList typed_data, bool check_throws) { + Uint8ClampedList typed_data, + bool check_throws, +) { Uint8ClampedList typed_data; typed_data = new Uint8ClampedList(10); @@ -108,7 +110,9 @@ void testClampedUnsignedTypedDataRangeHelper( void testClampedUnsignedTypedDataRange(bool check_throws) { testClampedUnsignedTypedDataRangeHelper( - new Uint8ClampedList(10), check_throws); + new Uint8ClampedList(10), + check_throws, + ); } void testSetRangeHelper(typed_data) { @@ -298,8 +302,11 @@ void testGetAtIndex(TypedData list, num initial_value) { } } -void testSetAtIndex(TypedDataList list, num initial_value, - [bool use_double = false]) { +void testSetAtIndex( + TypedDataList list, + num initial_value, [ + bool use_double = false, +]) { void validate([reinit = true]) { for (int i = 0; i < list.length; i++) { Expect.equals(initial_value, list[i]); @@ -461,7 +468,7 @@ testCreationFromList() { 0, 128, 256, - 1000000000000000000 + 1000000000000000000, ]; var intLists = []; intLists.add(new Int8List.fromList(intList)); @@ -477,7 +484,7 @@ testCreationFromList() { -123.0, 0.0, 123.0, - 123123123123.123123123 + 123123123123.123123123, ]; var doubleLists = []; doubleLists.add(new Float32List.fromList(doubleList)); diff --git a/tests/standalone/verbose_gc_to_bmu_test.dart b/tests/standalone/verbose_gc_to_bmu_test.dart index 860e5eb09d5..b79889cac45 100644 --- a/tests/standalone/verbose_gc_to_bmu_test.dart +++ b/tests/standalone/verbose_gc_to_bmu_test.dart @@ -15,13 +15,14 @@ import "dart:io"; import "package:path/path.dart"; // Tool script relative to the path of this test. -var toolScript = Uri.parse(Platform.executable) - .resolve("../../runtime/tools/verbose_gc_to_bmu.dart") - .toFilePath(); +var toolScript = Uri.parse( + Platform.executable, +).resolve("../../runtime/tools/verbose_gc_to_bmu.dart").toFilePath(); // Target script relative to this test. -var targetScript = - Platform.script.resolve("verbose_gc_to_bmu_script.dart").toFilePath(); +var targetScript = Platform.script + .resolve("verbose_gc_to_bmu_script.dart") + .toFilePath(); const minOutputLines = 20; void checkExitCode(targetResult) { @@ -33,18 +34,22 @@ void checkExitCode(targetResult) { void main() { // Compute paths for tool and target relative to the path of this script. - var targetResult = - Process.runSync(Platform.executable, ["--verbose_gc", targetScript]); + var targetResult = Process.runSync(Platform.executable, [ + "--verbose_gc", + targetScript, + ]); checkExitCode(targetResult); var gcLog = targetResult.stderr; Process.start(Platform.executable, [toolScript]).then((Process process) { // Feed the GC log of the target to the BMU tool. process.stdin.write(gcLog); process.stdin.close(); - var stdoutStringStream = - process.stdout.transform(utf8.decoder).transform(new LineSplitter()); - var stderrStringStream = - process.stderr.transform(utf8.decoder).transform(new LineSplitter()); + var stdoutStringStream = process.stdout + .transform(utf8.decoder) + .transform(new LineSplitter()); + var stderrStringStream = process.stderr + .transform(utf8.decoder) + .transform(new LineSplitter()); // Wait for 3 future events: stdout and stderr streams closed, and // process terminated. var futures = [];