riverqueue / river

Fast and reliable background jobs in Go
https://riverqueue.com
Mozilla Public License 2.0
3.34k stars 89 forks source link

Cannot test work that inserts jobs using `river.ClientFromContext` #512

Closed rgalanakis closed 2 weeks ago

rgalanakis commented 1 month ago

If I use river.ClientFromContext() within a job, and test it using the Work method (as docs suggest), I cannot insert the client into the context. Could be solved by adding a river.ContextWithClient helper, exposing ctxKey, etc.

bgentry commented 1 month ago

I actually just encountered this yesterday! Rather than expose a setter for the context value or key, I’m trying to build a test helper that executes a single job. I think this can be a huge improvement for testability.

Are you testing with a job row that you’ve actually inserted, or just a simulated job struct you’ve constructed yourself?

bgentry commented 1 month ago

Should be resolved by https://github.com/riverqueue/river/pull/514 in the next release, thanks for the report!

rgalanakis commented 1 month ago

I think your comment refers to #511, not this issue.

Yeah, a test helper sounds great.

I am testing with a simulated worker struct, like:

w := scheduled_sync_worker.New(scheduled_sync_worker.Input{})
Expect(w.Work(ctx, &river.Job[scheduled_sync_worker.Args]{JobRow: &rivertype.JobRow{ID: 5}, Args: scheduled_sync_worker.Args{}})).To(Succeed())
bgentry commented 1 month ago

D’oh, yes, sorry 😆 I have some details to work out with this test helper but I think that’s gotta be the real answer here.

For a workaround, maybe define a helper function that falls back to extracting the client from an alternate context key you only use in tests. Not ideal though.

rgalanakis commented 1 month ago

Yup, that is what I ended up doing, not a huge problem but would be nice to avoid critical paths that are different when running unit tests, as you already know :)

staugaard commented 3 weeks ago

I'm pretty sure this was accidentally closed.

bgentry commented 3 weeks ago

@staugaard you're right, it’s actually https://github.com/riverqueue/river/pull/526 which provides a fix for this issue.