dart-lang / sdk

The Dart SDK, including the VM, dart2js, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
9.94k stars 1.53k forks source link

Added exit function to IOOverrides #49888

Open bsutton opened 1 year ago

bsutton commented 1 year ago

Dart 2.18

I write a lot of console apps in dart which often use the 'exit' method.

This is a problem when writing unit tests as a single call to exit will shut down the unit tests.

I experimented with replacing all calls to exit with my on function dcliExit (and use dependency injection during unit testing to tell the call to exit not to actually exit). However, this didn't work as it interfered with the dart static analysis.

e.g.

If (a == null)
{
exit(1);
}

a.something; // generates an error as a code be null

The above code compiles fine as the static analyzer realizes that the call to exit stops the code from running. Replacing the call to exit with dcliExit generates an error as now the analyzer thinks that a could be null.

So the correct solutions, appears to be that exit should be added to the IOOverrides as we will then be able to overload exit in unit tests.

Edit: changed ZoneSpecificaiton to IOOverrides

lrhn commented 1 year ago

The Zone interception functionality is only intended for intercepting asynchronous functionality if dart:async itself. The print interceptor is an exception, and (IMO) it was a mistake. At least it depends on dart:core, which is known to exist on all platforms. The Zone functionality should not be extended to affecting or depending on dart:io functionality, since not all platforms support dart:io.

The dart:io library has its own functionality for overriding things, the IOOverrides class. Controlling exit should probably be done through that instead.

Your typing issue comes from exit having return type Never. Any overloaded functionality you replace the exiting-the-program with must still not return normally. Which means it must throw instead.

bsutton commented 1 year ago

Updated the title and initial description to suggest IOOverrides as suggested by @lrhn

bsutton commented 1 year ago

If some work gets done in this area it would be nice to get #39796 fixed as well as both are blockers for unit testing.