uber-go / fx

A dependency injection based application framework for Go.
https://uber-go.github.io/fx/
MIT License
5.48k stars 283 forks source link

fxtest: Enforceable Timeouts on Lifecycle #1203

Closed JacobOaks closed 1 month ago

JacobOaks commented 1 month ago

In Fx, if starting/stopping the application takes longer than the context's timeout, the fx.App will bail early, regardless of the status of the currently running hooks.

This prevents stalling an application when hooks (accidentally) block forever.

In order to test hook behavior, Fx provides fxtest.Lifecycle to interact with. This Lifecycle is a simple wrapper around the actual fx Lifecycle type, meaning it does not check for timeout and bail early like fx.App does. This is an issue because:

See #1180 for more details.

This PR adds an option that can be passed to fxtest.NewLifecycle to cause it to immediately fail when context expires, similar to fx.App.

lc := fxtest.NewLifecycle(fxtest.EnforceTimeout(true))
lc.Append(fx.StartHook(func() { for {} }))
ctx, _ := context.WithTimeout(context.Background(), time.Second)
err := lc.Start(ctx) // Will return deadline exceeded after a second

This PR doesn't provide a way to test timeouts using RequireStart and RequireStop. However, since those don't take contexts anyways, my assumption is that usage of those APIs represents an intentional decision to not care about timeouts by the test writer.

However, if people feel differently, we can instead do something like expose two new APIs RequireStartWithContext(ctx) and RequireStopWithContext(ctx) or something (names obviously up for discussion).

codecov[bot] commented 1 month ago

Codecov Report

All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 98.51%. Comparing base (abda254) to head (1c5db75).

Additional details and impacted files ```diff @@ Coverage Diff @@ ## master #1203 +/- ## ========================================== - Coverage 98.57% 98.51% -0.06% ========================================== Files 34 34 Lines 2871 2900 +29 ========================================== + Hits 2830 2857 +27 - Misses 35 36 +1 - Partials 6 7 +1 ```

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

JacobOaks commented 1 month ago

lgtm with one minor behavioral improvement suggested

Thank you for all your helpful review @abhinav!