Files
opentf/internal/tofu/transform_import_state_test.go
Martin Atkins 32082321bf providers: Interface now requires context.Context arguments
Continuing our work to gradually plumb context.Context to everywhere that
we want to generate OpenTelemetry traces, this completes the call path
for most (but not all) of the gRPC requests to provider plugins, so that
we can add OpenTelemetry trace instrumentation in a future commit.

Unfortunately there are still a few providers.Interface callers left in
functions that don't have context.Context plumbed to them yet, and so
those are temporarily stubbed as context.TODO() here so we can more easily
find and complete them later.

The two gRPC implementations of providers.Interface were previously making
provider requests using a single context.Context established at the time
the provider process was started, but that isn't an appropriate context
to use for per-request concerns like tracing, so that context is now
unused and could potentially be removed in a future commit, but this change
already got pretty large and so I intend to deal with that separately
later.

This now exposes the gRPC provider calls to potential context cancellation
that they would previously observe only indirectly though the Stop method.
Since Stop is primarily used for graceful shutdown of ApplyResourceChange,
the changes here explicitly disconnect the cancellation signal for
ApplyResourceChange in particular, while letting the others get canceled
in the normal way since they are expected to be free of significant
side-effects. In future work we could consider removing Stop from the
internal API entirely and keeping it only as an implementation detail of
the gRPC implementation of this interface, with ApplyResourceChange
directly reacting to context cancellation and sending the gRPC Stop call
itself, but again that's too much change for this already-large commit.

The internal/legacy package currently contains some legacy code preserved
for the benefit of the backends, and unfortunately contains more than is
strictly necessary to support those callers, and so there was some dead
code there that also needed updating. provider_mock.go is removed entirely
because it's just an older copy of the similar file in package tofu. The
few calls to providers in schemas.go are updated to use
context.Background() rather than context.TODO() because we have no
intention of plumbing context.Context into that legacy code, and will
hopefully just delete it wholesale one day.

Signed-off-by: Martin Atkins <mart@degeneration.co.uk>
2025-05-23 08:58:23 -07:00

177 lines
5.0 KiB
Go

// Copyright (c) The OpenTofu Authors
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2023 HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package tofu
import (
"strings"
"testing"
"github.com/opentofu/opentofu/internal/addrs"
"github.com/opentofu/opentofu/internal/configs/configschema"
"github.com/opentofu/opentofu/internal/providers"
"github.com/opentofu/opentofu/internal/states"
"github.com/zclconf/go-cty/cty"
)
func TestGraphNodeImportStateExecute(t *testing.T) {
state := states.NewState()
provider := testProvider("aws")
provider.ImportResourceStateResponse = &providers.ImportResourceStateResponse{
ImportedResources: []providers.ImportedResource{
{
TypeName: "aws_instance",
State: cty.ObjectVal(map[string]cty.Value{
"id": cty.StringVal("bar"),
}),
},
},
}
provider.ConfigureProvider(t.Context(), providers.ConfigureProviderRequest{})
evalCtx := &MockEvalContext{
StateState: state.SyncWrapper(),
ProviderProvider: provider,
}
// Import a new aws_instance.foo, this time with ID=bar. The original
// aws_instance.foo object should be removed from state and replaced with
// the new.
node := graphNodeImportState{
Addr: addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "aws_instance",
Name: "foo",
}.Instance(addrs.NoKey).Absolute(addrs.RootModuleInstance),
ID: "bar",
ResolvedProvider: ResolvedProvider{ProviderConfig: addrs.AbsProviderConfig{
Provider: addrs.NewDefaultProvider("aws"),
Module: addrs.RootModule,
}},
}
diags := node.Execute(t.Context(), evalCtx, walkImport)
if diags.HasErrors() {
t.Fatalf("Unexpected error: %s", diags.Err())
}
if len(node.states) != 1 {
t.Fatalf("Wrong result! Expected one imported resource, got %d", len(node.states))
}
// Verify the ID for good measure
id := node.states[0].State.GetAttr("id")
if !id.RawEquals(cty.StringVal("bar")) {
t.Fatalf("Wrong result! Expected id \"bar\", got %q", id.AsString())
}
}
func TestGraphNodeImportStateSubExecute(t *testing.T) {
state := states.NewState()
provider := testProvider("aws")
provider.ConfigureProvider(t.Context(), providers.ConfigureProviderRequest{})
evalCtx := &MockEvalContext{
StateState: state.SyncWrapper(),
ProviderProvider: provider,
ProviderSchemaSchema: providers.ProviderSchema{
ResourceTypes: map[string]providers.Schema{
"aws_instance": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"id": {
Type: cty.String,
Computed: true,
},
},
},
},
},
},
}
importedResource := providers.ImportedResource{
TypeName: "aws_instance",
State: cty.ObjectVal(map[string]cty.Value{"id": cty.StringVal("bar")}),
}
node := graphNodeImportStateSub{
TargetAddr: addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "aws_instance",
Name: "foo",
}.Instance(addrs.NoKey).Absolute(addrs.RootModuleInstance),
State: importedResource,
ResolvedProvider: ResolvedProvider{ProviderConfig: addrs.AbsProviderConfig{
Provider: addrs.NewDefaultProvider("aws"),
Module: addrs.RootModule,
}},
}
diags := node.Execute(t.Context(), evalCtx, walkImport)
if diags.HasErrors() {
t.Fatalf("Unexpected error: %s", diags.Err())
}
// check for resource in state
actual := strings.TrimSpace(state.String())
expected := `aws_instance.foo:
ID = bar
provider = provider["registry.opentofu.org/hashicorp/aws"]`
if actual != expected {
t.Fatalf("bad state after import: \n%s", actual)
}
}
func TestGraphNodeImportStateSubExecuteNull(t *testing.T) {
state := states.NewState()
provider := testProvider("aws")
provider.ReadResourceFn = func(req providers.ReadResourceRequest) (resp providers.ReadResourceResponse) {
// return null indicating that the requested resource does not exist
resp.NewState = cty.NullVal(cty.Object(map[string]cty.Type{
"id": cty.String,
}))
return resp
}
evalCtx := &MockEvalContext{
StateState: state.SyncWrapper(),
ProviderProvider: provider,
ProviderSchemaSchema: providers.ProviderSchema{
ResourceTypes: map[string]providers.Schema{
"aws_instance": {
Block: &configschema.Block{
Attributes: map[string]*configschema.Attribute{
"id": {
Type: cty.String,
Computed: true,
},
},
},
},
},
},
}
importedResource := providers.ImportedResource{
TypeName: "aws_instance",
State: cty.ObjectVal(map[string]cty.Value{"id": cty.StringVal("bar")}),
}
node := graphNodeImportStateSub{
TargetAddr: addrs.Resource{
Mode: addrs.ManagedResourceMode,
Type: "aws_instance",
Name: "foo",
}.Instance(addrs.NoKey).Absolute(addrs.RootModuleInstance),
State: importedResource,
ResolvedProvider: ResolvedProvider{ProviderConfig: addrs.AbsProviderConfig{
Provider: addrs.NewDefaultProvider("aws"),
Module: addrs.RootModule,
}},
}
diags := node.Execute(t.Context(), evalCtx, walkImport)
if !diags.HasErrors() {
t.Fatal("expected error for non-existent resource")
}
}