github.com/magodo/terraform@v0.11.12-beta1/command/unlock_test.go (about)

     1  package command
     2  
     3  import (
     4  	"os"
     5  	"testing"
     6  
     7  	"github.com/hashicorp/terraform/backend/remote-state/inmem"
     8  	"github.com/hashicorp/terraform/helper/copy"
     9  	"github.com/hashicorp/terraform/terraform"
    10  	"github.com/mitchellh/cli"
    11  )
    12  
    13  // Since we can't unlock a local state file, just test that calling unlock
    14  // doesn't fail.
    15  func TestUnlock(t *testing.T) {
    16  	td := tempDir(t)
    17  	os.MkdirAll(td, 0755)
    18  	defer os.RemoveAll(td)
    19  	defer testChdir(t, td)()
    20  
    21  	// Write the legacy state
    22  	statePath := DefaultStateFilename
    23  	{
    24  		f, err := os.Create(statePath)
    25  		if err != nil {
    26  			t.Fatalf("err: %s", err)
    27  		}
    28  		err = terraform.WriteState(testState(), f)
    29  		f.Close()
    30  		if err != nil {
    31  			t.Fatalf("err: %s", err)
    32  		}
    33  	}
    34  
    35  	p := testProvider()
    36  	ui := new(cli.MockUi)
    37  	c := &UnlockCommand{
    38  		Meta: Meta{
    39  			testingOverrides: metaOverridesForProvider(p),
    40  			Ui:               ui,
    41  		},
    42  	}
    43  
    44  	args := []string{
    45  		"-force",
    46  		"LOCK_ID",
    47  	}
    48  
    49  	if code := c.Run(args); code != 1 {
    50  		t.Fatalf("bad: %d\n%s\n%s", code, ui.OutputWriter.String(), ui.ErrorWriter.String())
    51  	}
    52  }
    53  
    54  // Newly configured backend
    55  func TestUnlock_inmemBackend(t *testing.T) {
    56  	// Create a temporary working directory that is empty
    57  	td := tempDir(t)
    58  	copy.CopyDir(testFixturePath("backend-inmem-locked"), td)
    59  	defer os.RemoveAll(td)
    60  	defer testChdir(t, td)()
    61  	defer inmem.Reset()
    62  
    63  	// init backend
    64  	ui := new(cli.MockUi)
    65  	ci := &InitCommand{
    66  		Meta: Meta{
    67  			Ui: ui,
    68  		},
    69  	}
    70  	if code := ci.Run(nil); code != 0 {
    71  		t.Fatalf("bad: %d\n%s", code, ui.ErrorWriter)
    72  	}
    73  
    74  	ui = new(cli.MockUi)
    75  	c := &UnlockCommand{
    76  		Meta: Meta{
    77  			Ui: ui,
    78  		},
    79  	}
    80  
    81  	// run with the incorrect lock ID
    82  	args := []string{
    83  		"-force",
    84  		"LOCK_ID",
    85  	}
    86  
    87  	if code := c.Run(args); code == 0 {
    88  		t.Fatalf("bad: %d\n%s\n%s", code, ui.OutputWriter.String(), ui.ErrorWriter.String())
    89  	}
    90  
    91  	ui = new(cli.MockUi)
    92  	c = &UnlockCommand{
    93  		Meta: Meta{
    94  			Ui: ui,
    95  		},
    96  	}
    97  
    98  	// lockID set in the test fixture
    99  	args[1] = "2b6a6738-5dd5-50d6-c0ae-f6352977666b"
   100  	if code := c.Run(args); code != 0 {
   101  		t.Fatalf("bad: %d\n%s\n%s", code, ui.OutputWriter.String(), ui.ErrorWriter.String())
   102  	}
   103  
   104  }