Home > Mobile >  temporal: when testing, how do I pass context into workflows and activities?
temporal: when testing, how do I pass context into workflows and activities?

Time:10-18

I'm writing an integration test for a temporal workflow and using the golang sdk. My workflow has an activity which includes the following code:

   stackEnv, ok := ctx.Value("stackEnv").(*StackEnv)
    if !ok {
        return nil, errors.New("stackEnv not configured")
    }

In my test I create a TestWorkflowEnvironment and run my workflow with s.env.ExecuteWorkflow(EntityCreateWorkflow, wfParams). However I get an error in my test that stackEnv not configured because the context.Context the activity is running with in the test environment does not have stackEnv set on it. How do I specify a custom context to my TestWorkflowEnvironment?

CodePudding user response:

Use the TestWorkflowEnvironment.SetWorkerOptions() API.

In production code, the context parameter is specified on the worker that executes workflows, e.g.:

    ctx := context.WithValue(context.Background(), "stackEnv", stackEnv)

    worker.New(stackEnv.Temporal, string(taskQueueName), worker.Options{
        BackgroundActivityContext: ctx,
    })

In the WorkflowTestEnvironment, a worker is simulated. We can specify options to it with SetWorkerOptions(), e.g.:

    ctx := context.WithValue(context.Background(), "stackEnv", StackEnv)

    s.env.SetWorkerOptions(worker.Options{
        BackgroundActivityContext: ctx,
    })

(where s.env is the temporal testsuite.TestWorkflowEnvironment)

CodePudding user response:

Patrick's answer is absolutely correct.

I would also recommend looking into implementing activities as members of a structure. This way passing dependencies to them doesn't require messing with context.

See the greetings sample that uses this technique.

  • Related