github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/context/remove_test.go (about) 1 package context 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path/filepath" 7 "testing" 8 9 "github.com/docker/cli/cli/config" 10 "github.com/docker/cli/cli/config/configfile" 11 "github.com/docker/cli/cli/context/store" 12 "gotest.tools/v3/assert" 13 ) 14 15 func TestRemove(t *testing.T) { 16 cli, cleanup := makeFakeCli(t) 17 defer cleanup() 18 createTestContextWithKubeAndSwarm(t, cli, "current", "all") 19 createTestContextWithKubeAndSwarm(t, cli, "other", "all") 20 assert.NilError(t, RunRemove(cli, RemoveOptions{}, []string{"other"})) 21 _, err := cli.ContextStore().GetMetadata("current") 22 assert.NilError(t, err) 23 _, err = cli.ContextStore().GetMetadata("other") 24 assert.Check(t, store.IsErrContextDoesNotExist(err)) 25 } 26 27 func TestRemoveNotAContext(t *testing.T) { 28 cli, cleanup := makeFakeCli(t) 29 defer cleanup() 30 createTestContextWithKubeAndSwarm(t, cli, "current", "all") 31 createTestContextWithKubeAndSwarm(t, cli, "other", "all") 32 err := RunRemove(cli, RemoveOptions{}, []string{"not-a-context"}) 33 assert.ErrorContains(t, err, `context "not-a-context" does not exist`) 34 } 35 36 func TestRemoveCurrent(t *testing.T) { 37 cli, cleanup := makeFakeCli(t) 38 defer cleanup() 39 createTestContextWithKubeAndSwarm(t, cli, "current", "all") 40 createTestContextWithKubeAndSwarm(t, cli, "other", "all") 41 cli.SetCurrentContext("current") 42 err := RunRemove(cli, RemoveOptions{}, []string{"current"}) 43 assert.ErrorContains(t, err, "current: context is in use, set -f flag to force remove") 44 } 45 46 func TestRemoveCurrentForce(t *testing.T) { 47 configDir, err := ioutil.TempDir("", t.Name()+"config") 48 assert.NilError(t, err) 49 defer os.RemoveAll(configDir) 50 configFilePath := filepath.Join(configDir, "config.json") 51 testCfg := configfile.New(configFilePath) 52 testCfg.CurrentContext = "current" 53 assert.NilError(t, testCfg.Save()) 54 55 cli, cleanup := makeFakeCli(t, withCliConfig(testCfg)) 56 defer cleanup() 57 createTestContextWithKubeAndSwarm(t, cli, "current", "all") 58 createTestContextWithKubeAndSwarm(t, cli, "other", "all") 59 cli.SetCurrentContext("current") 60 assert.NilError(t, RunRemove(cli, RemoveOptions{Force: true}, []string{"current"})) 61 reloadedConfig, err := config.Load(configDir) 62 assert.NilError(t, err) 63 assert.Equal(t, "", reloadedConfig.CurrentContext) 64 } 65 66 func TestRemoveDefault(t *testing.T) { 67 cli, cleanup := makeFakeCli(t) 68 defer cleanup() 69 createTestContextWithKubeAndSwarm(t, cli, "other", "all") 70 cli.SetCurrentContext("current") 71 err := RunRemove(cli, RemoveOptions{}, []string{"default"}) 72 assert.ErrorContains(t, err, `default: context "default" cannot be removed`) 73 }