|
| 1 | +// Copyright (c) HashiCorp, Inc. |
| 2 | +// SPDX-License-Identifier: BUSL-1.1 |
| 3 | + |
| 4 | +package local |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "testing" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/hashicorp/terraform/internal/backend/backendrun" |
| 12 | + "github.com/hashicorp/terraform/internal/configs/configschema" |
| 13 | + "github.com/hashicorp/terraform/internal/providers" |
| 14 | +) |
| 15 | + |
| 16 | +func TestLocal_applyStopEarly(t *testing.T) { |
| 17 | + b := TestLocal(t) |
| 18 | + |
| 19 | + schema := applyFixtureSchema() |
| 20 | + schema.DataSources = map[string]providers.Schema{ |
| 21 | + "test_data": { |
| 22 | + Body: &configschema.Block{}, |
| 23 | + }, |
| 24 | + } |
| 25 | + |
| 26 | + // Create a provider that blocks on ReadDataSource |
| 27 | + p := TestLocalProvider(t, b, "test", schema) |
| 28 | + |
| 29 | + // We need to make sure ReadDataSource is called and blocks |
| 30 | + readCalled := make(chan struct{}) |
| 31 | + block := make(chan struct{}) |
| 32 | + |
| 33 | + // Override the ReadDataSourceFn |
| 34 | + p.ReadDataSourceFn = func(req providers.ReadDataSourceRequest) providers.ReadDataSourceResponse { |
| 35 | + close(readCalled) |
| 36 | + <-block |
| 37 | + return providers.ReadDataSourceResponse{ |
| 38 | + State: req.Config, |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + op, configCleanup, done := testOperationApply(t, "./testdata/apply-stop") |
| 43 | + defer configCleanup() |
| 44 | + |
| 45 | + // Create a context that we can cancel |
| 46 | + ctx, cancel := context.WithCancel(context.Background()) |
| 47 | + |
| 48 | + // Cancel immediately to simulate "early" interrupt |
| 49 | + cancel() |
| 50 | + |
| 51 | + run, err := b.Operation(ctx, op) |
| 52 | + if err != nil { |
| 53 | + t.Fatalf("bad: %s", err) |
| 54 | + } |
| 55 | + |
| 56 | + // Wait for result |
| 57 | + doneCh := make(chan struct{}) |
| 58 | + go func() { |
| 59 | + <-run.Done() |
| 60 | + close(doneCh) |
| 61 | + }() |
| 62 | + |
| 63 | + select { |
| 64 | + case <-doneCh: |
| 65 | + // Success (it returned) |
| 66 | + case <-readCalled: |
| 67 | + // It reached the provider! This means it didn't stop early. |
| 68 | + close(block) // Unblock to cleanup |
| 69 | + t.Fatal("Operation reached provider despite early cancellation") |
| 70 | + case <-time.After(5 * time.Second): |
| 71 | + t.Fatal("Operation timed out") |
| 72 | + } |
| 73 | + |
| 74 | + if run.Result == backendrun.OperationSuccess { |
| 75 | + t.Fatal("Operation succeeded but should have been cancelled") |
| 76 | + } |
| 77 | + |
| 78 | + if errOutput := done(t).Stderr(); errOutput != "" { |
| 79 | + // We expect some error output due to cancellation, but let's log it just in case |
| 80 | + t.Logf("error output:\n%s", errOutput) |
| 81 | + } |
| 82 | +} |
0 commit comments