gotestingtemporal-workflow

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


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?


Solution

  • 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)