Get error when reading computed attributes on resources in unit test conditions

Hi!

I’m trying to mock some computed attributes on resources in unit test using command = plan.

The resource gitlab_user_runner has the computed attribute token, which I use as input for other resources. In my unit test I want to mock the return value of the resource.

The main Terraform manifest:

# main.tf
provider "gitlab" {
  base_url = "https://gitlab.com/"
  token    = "secret"
}

resource "gitlab_user_runner" "test_runner" {
  runner_type     = "group_type"
  description     = "test-runner"
  group_id        = 42
  tag_list        = ["test-tag"]
}

Testfile where I want to override the token value on gitlab_user_runner.test_runner

# tests/gitlab.tftest.hcl

mock_provider "gitlab" {}

run "test_mock_token" {
  command = plan
  
  override_resource {
    target = gitlab_user_runner.test_runner
    values = {
      token = "mocked-token"
    }
  }
  
  assert {
    condition     = gitlab_user_runner.test_runner.token == "mocked-token"
    error_message = "tokens not matching"
  }
}

When executing the test, I get the following error:

│ Error: Unknown condition value
│ 
│   on tests/gitlab.tftest.hcl line 12, in run "test_mock_token":
│   12:     condition     = gitlab_user_runner.test_runner.token == "mocked-token"
│ 
│ Condition expression could not be evaluated at this time. This means you have executed a `run` block with `command = plan` and one of the values your condition depended
│ on is not known until after the plan has been applied. Either remove this value from your condition, or execute an `apply` command from this `run` block.
│

When I run the test with command = plan everything works fine. But in this case I just want to have a unit test, without any resources provisioned.

It seems that the mocked values are applied in a later phase. Any ideas how properly mock calculated attributes on resources in unit tests?

Hi @buehlmann, unfortunately I think it is currently not possible to supply mocked values during a plan operation.

I believe the original logic for this behaviour is that it matches the behaviour of most providers. So during the planning stage providers won’t typically provide computed attributes, which are instead generated during the apply stage.

I believe we haven’t received a request for this as a feature yet, as the test and mocking frameworks are still relatively new. You could file this as a feature request: Sign in to GitHub · GitHub. Explaining your use case in there would bring it to the attention of our product team.

Hi @liamcervante
Thanks for your answer. I’ve created a new feature request: Allow mocked values on resources during the planning stage in terraform test · Issue #35851 · hashicorp/terraform · GitHub

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.