github.com/verrazzano/verrazzano@v1.7.1/tools/vz/cmd/uninstall/uninstall_test.go (about)

     1  // Copyright (c) 2022, 2024, Oracle and/or its affiliates.
     2  // Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
     3  
     4  package uninstall
     5  
     6  import (
     7  	"context"
     8  	"os"
     9  	"strings"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  	vzconstants "github.com/verrazzano/verrazzano/pkg/constants"
    14  	vzapi "github.com/verrazzano/verrazzano/platform-operator/apis/verrazzano/v1alpha1"
    15  	"github.com/verrazzano/verrazzano/platform-operator/apis/verrazzano/v1beta1"
    16  	"github.com/verrazzano/verrazzano/tools/vz/pkg/constants"
    17  	"github.com/verrazzano/verrazzano/tools/vz/pkg/helpers"
    18  	testhelpers "github.com/verrazzano/verrazzano/tools/vz/test/helpers"
    19  	adminv1 "k8s.io/api/admissionregistration/v1"
    20  	appsv1 "k8s.io/api/apps/v1"
    21  	corev1 "k8s.io/api/core/v1"
    22  	rbacv1 "k8s.io/api/rbac/v1"
    23  	"k8s.io/apimachinery/pkg/api/errors"
    24  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    25  	"k8s.io/apimachinery/pkg/types"
    26  	dynfake "k8s.io/client-go/dynamic/fake"
    27  	ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
    28  	"sigs.k8s.io/controller-runtime/pkg/client/fake"
    29  )
    30  
    31  const (
    32  	testKubeConfig    = "kubeconfig"
    33  	testK8sContext    = "testcontext"
    34  	VzVpoFailureError = "Failed to find the Verrazzano platform operator in namespace verrazzano-install"
    35  	PodNotFoundError  = "Waiting for verrazzano-uninstall-verrazzano, verrazzano-uninstall-verrazzano pod not found in namespace verrazzano-install"
    36  	BugReportNotExist = "cannot find bug report file in current directory"
    37  )
    38  
    39  // TestUninstallCmd
    40  // GIVEN a CLI uninstall command with all defaults
    41  //
    42  //	WHEN I call cmd.Execute for uninstall
    43  //	THEN the CLI uninstall command is successful
    44  func TestUninstallCmd(t *testing.T) {
    45  	deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.4.0"})
    46  	vpo := createVpoPod()
    47  	namespace := createNamespace()
    48  	validatingWebhookConfig := createWebhook()
    49  	clusterRoleBinding := createClusterRoleBinding()
    50  	mcClusterRole := createMCClusterRole()
    51  	registrarClusterRole := createRegistrarClusterRoleForRancher()
    52  	vz := createVz()
    53  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, vpo, vz, namespace, validatingWebhookConfig, clusterRoleBinding, mcClusterRole, registrarClusterRole).Build()
    54  
    55  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
    56  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
    57  	rc.SetClient(c)
    58  	cmd := NewCmdUninstall(rc)
    59  	assert.NotNil(t, cmd)
    60  
    61  	// Suppressing uninstall prompt
    62  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
    63  
    64  	// Run uninstall command, check for the expected status results to be displayed
    65  	err := cmd.Execute()
    66  	assert.NoError(t, err)
    67  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
    68  	assert.Nil(t, err)
    69  	buf, err := os.ReadFile(rc.Out.Name())
    70  	assert.Nil(t, err)
    71  	assert.Equal(t, "", string(errBytes))
    72  	assert.Contains(t, string(buf), "Uninstalling Verrazzano\n")
    73  
    74  	// Ensure resources have been deleted
    75  	ensureResourcesDeleted(t, c)
    76  }
    77  
    78  // TestUninstallCmdUninstallJob
    79  // GIVEN a CLI uninstall command with all defaults and a 1.3.1 version install
    80  //
    81  //	WHEN I call cmd.Execute for uninstall
    82  //	THEN the CLI uninstall command is successful
    83  func TestUninstallCmdUninstallJob(t *testing.T) {
    84  	deployment := createVpoDeployment(nil)
    85  	job := &corev1.Pod{
    86  		ObjectMeta: metav1.ObjectMeta{
    87  			Namespace: vzconstants.VerrazzanoInstallNamespace,
    88  			Name:      constants.VerrazzanoUninstall,
    89  			Labels: map[string]string{
    90  				"job-name": constants.VerrazzanoUninstall + "-verrazzano",
    91  			},
    92  		},
    93  		Status: corev1.PodStatus{
    94  			ContainerStatuses: []corev1.ContainerStatus{
    95  				{
    96  					Ready: true,
    97  				},
    98  			},
    99  		},
   100  	}
   101  	namespace := createNamespace()
   102  	validatingWebhookConfig := createWebhook()
   103  	clusterRoleBinding := createClusterRoleBinding()
   104  	mcClusterRole := createMCClusterRole()
   105  	registrarClusterRole := createRegistrarClusterRoleForRancher()
   106  	vz := createVz()
   107  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, job, vz, namespace, validatingWebhookConfig, clusterRoleBinding, mcClusterRole, registrarClusterRole).Build()
   108  
   109  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   110  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   111  	rc.SetClient(c)
   112  	cmd := NewCmdUninstall(rc)
   113  	assert.NotNil(t, cmd)
   114  
   115  	// Suppressing uninstall prompt
   116  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   117  
   118  	// Run uninstall command, check for the expected status results to be displayed
   119  	err := cmd.Execute()
   120  	assert.NoError(t, err)
   121  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   122  	assert.Nil(t, err)
   123  	buf, err := os.ReadFile(rc.Out.Name())
   124  	assert.Nil(t, err)
   125  	assert.Equal(t, "", string(errBytes))
   126  	assert.Contains(t, string(buf), "Uninstalling Verrazzano\n")
   127  
   128  	// Ensure resources have been deleted
   129  	ensureResourcesDeleted(t, c)
   130  }
   131  
   132  // TestUninstallCmdDefaultTimeout
   133  // GIVEN a CLI uninstall command with all defaults and --timeout=2ms
   134  //
   135  //	WHEN I call cmd.Execute for uninstall
   136  //	THEN the CLI uninstall command times out and a bug-report is generated
   137  func TestUninstallCmdDefaultTimeout(t *testing.T) {
   138  	deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.4.0"})
   139  	vpo := createVpoPod()
   140  	namespace := createNamespace()
   141  	vz := createVz()
   142  	webhook := createWebhook()
   143  	mcClusterRole := createMCClusterRole()
   144  	registrarClusterRole := createRegistrarClusterRoleForRancher()
   145  	crb := createClusterRoleBinding()
   146  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, vpo, vz, namespace, webhook, mcClusterRole, registrarClusterRole, crb).Build()
   147  
   148  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   149  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   150  	rc.SetClient(c)
   151  	rc.SetDynamicClient(dynfake.NewSimpleDynamicClient(helpers.GetScheme()))
   152  	cmd := NewCmdUninstall(rc)
   153  	assert.NotNil(t, cmd)
   154  	tempKubeConfigPath, _ := os.CreateTemp(os.TempDir(), testKubeConfig)
   155  	cmd.Flags().String(constants.GlobalFlagKubeConfig, tempKubeConfigPath.Name(), "")
   156  	cmd.Flags().String(constants.GlobalFlagContext, testK8sContext, "")
   157  	_ = cmd.PersistentFlags().Set(constants.TimeoutFlag, "2ms")
   158  	defer os.RemoveAll(tempKubeConfigPath.Name())
   159  
   160  	// Suppressing uninstall prompt
   161  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   162  
   163  	// Run upgrade command
   164  	err := cmd.Execute()
   165  	assert.Error(t, err)
   166  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   167  	assert.Nil(t, err)
   168  	// This must be less than the 1 second polling delay to pass
   169  	// since the Verrazzano resource gets deleted almost instantaneously
   170  	assert.Equal(t, "Error: Timeout 2ms exceeded waiting for uninstall to complete\n", string(errBytes))
   171  	ensureResourcesNotDeleted(t, c)
   172  	if !helpers.CheckAndRemoveBugReportAndRedactionFileExistsInDir("") {
   173  		t.Fatal(BugReportNotExist)
   174  	}
   175  }
   176  
   177  // TestUninstallCmdDefaultTimeoutNoBugReport
   178  // GIVEN a CLI uninstall command with all defaults, --timeout=2ms, and auto-bug-report=false
   179  //
   180  //	WHEN I call cmd.Execute for uninstall
   181  //	THEN the CLI uninstall command times out and bug-report is not generated
   182  func TestUninstallCmdDefaultTimeoutNoBugReport(t *testing.T) {
   183  	deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.4.0"})
   184  	vpo := createVpoPod()
   185  	namespace := createNamespace()
   186  	vz := createVz()
   187  	webhook := createWebhook()
   188  	mcClusterRole := createMCClusterRole()
   189  	registrarClusterRole := createRegistrarClusterRoleForRancher()
   190  	crb := createClusterRoleBinding()
   191  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, vpo, vz, namespace, webhook, mcClusterRole, registrarClusterRole, crb).Build()
   192  
   193  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   194  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   195  	rc.SetClient(c)
   196  	cmd := NewCmdUninstall(rc)
   197  	assert.NotNil(t, cmd)
   198  	_ = cmd.PersistentFlags().Set(constants.TimeoutFlag, "2ms")
   199  	_ = cmd.PersistentFlags().Set(constants.AutoBugReportFlag, "false")
   200  
   201  	// Suppressing uninstall prompt
   202  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   203  
   204  	// Run upgrade command
   205  	err := cmd.Execute()
   206  	assert.Error(t, err)
   207  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   208  	assert.Nil(t, err)
   209  	// This must be less than the 1 second polling delay to pass
   210  	// since the Verrazzano resource gets deleted almost instantaneously
   211  	assert.Equal(t, "Error: Timeout 2ms exceeded waiting for uninstall to complete\n", string(errBytes))
   212  	ensureResourcesNotDeleted(t, c)
   213  	// Bug Report must not exist
   214  	if helpers.CheckAndRemoveBugReportAndRedactionFileExistsInDir("") {
   215  		t.Fatal("found bug report file in current directory")
   216  	}
   217  }
   218  
   219  // TestUninstallCmdDefaultNoWait
   220  // GIVEN a CLI uninstall command with all defaults and --wait==false
   221  //
   222  //	WHEN I call cmd.Execute for uninstall
   223  //	THEN the CLI uninstall command is successful
   224  func TestUninstallCmdDefaultNoWait(t *testing.T) {
   225  	deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.4.0"})
   226  	vpo := createVpoPod()
   227  	namespace := createNamespace()
   228  	vz := createVz()
   229  	webhook := createWebhook()
   230  	mcClusterRole := createMCClusterRole()
   231  	registrarClusterRole := createRegistrarClusterRoleForRancher()
   232  	crb := createClusterRoleBinding()
   233  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, vpo, vz, namespace, webhook, mcClusterRole, registrarClusterRole, crb).Build()
   234  
   235  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   236  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   237  	rc.SetClient(c)
   238  	cmd := NewCmdUninstall(rc)
   239  	assert.NotNil(t, cmd)
   240  	_ = cmd.PersistentFlags().Set(constants.WaitFlag, "false")
   241  
   242  	// Suppressing uninstall prompt
   243  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   244  
   245  	// Run uninstall command
   246  	err := cmd.Execute()
   247  	assert.NoError(t, err)
   248  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   249  	assert.Nil(t, err)
   250  	assert.Equal(t, "", string(errBytes))
   251  
   252  	ensureResourcesNotDeleted(t, c)
   253  }
   254  
   255  // TestUninstallCmdJsonLogFormat
   256  // GIVEN a CLI uninstall command with defaults and --log-format=json and --wait==false
   257  //
   258  //	WHEN I call cmd.Execute for uninstall
   259  //	THEN the CLI uninstall command is successful
   260  func TestUninstallCmdJsonLogFormat(t *testing.T) {
   261  	deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.4.0"})
   262  	vz := createVz()
   263  	vpo := createVpoPod()
   264  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, vz, vpo).Build()
   265  
   266  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   267  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   268  	rc.SetClient(c)
   269  	cmd := NewCmdUninstall(rc)
   270  	assert.NotNil(t, cmd)
   271  	cmd.PersistentFlags().Set(constants.LogFormatFlag, "json")
   272  	cmd.PersistentFlags().Set(constants.WaitFlag, "false")
   273  
   274  	// Suppressing uninstall prompt
   275  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   276  
   277  	// Run uninstall command
   278  	err := cmd.Execute()
   279  	assert.NoError(t, err)
   280  	assert.NoError(t, err)
   281  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   282  	assert.NoError(t, err)
   283  	assert.Equal(t, "", string(errBytes))
   284  }
   285  
   286  // TestUninstallCmdDefaultNoVPO
   287  // GIVEN a CLI uninstall command with all defaults and no VPO found
   288  //
   289  //	WHEN I call cmd.Execute for uninstall
   290  //	THEN the CLI uninstall command fails and a bug-report is generated
   291  func TestUninstallCmdDefaultNoVPO(t *testing.T) {
   292  	deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.4.0"})
   293  	vz := createVz()
   294  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, vz).Build()
   295  
   296  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   297  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   298  	rc.SetClient(c)
   299  	rc.SetDynamicClient(dynfake.NewSimpleDynamicClient(helpers.GetScheme()))
   300  	cmd := NewCmdUninstall(rc)
   301  	assert.NotNil(t, cmd)
   302  	tempKubeConfigPath, _ := os.CreateTemp(os.TempDir(), testKubeConfig)
   303  	cmd.Flags().String(constants.GlobalFlagKubeConfig, tempKubeConfigPath.Name(), "")
   304  	cmd.Flags().String(constants.GlobalFlagContext, testK8sContext, "")
   305  	defer os.RemoveAll(tempKubeConfigPath.Name())
   306  
   307  	// Suppressing uninstall prompt
   308  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   309  
   310  	// Run uninstall command
   311  	err := cmd.Execute()
   312  	assert.Error(t, err)
   313  	assert.ErrorContains(t, err, VzVpoFailureError)
   314  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   315  	assert.NoError(t, err)
   316  	assert.Contains(t, string(errBytes), VzVpoFailureError)
   317  	if !helpers.CheckAndRemoveBugReportAndRedactionFileExistsInDir("") {
   318  		t.Fatal(BugReportNotExist)
   319  	}
   320  }
   321  
   322  // TestUninstallCmdDefaultNoUninstallJob
   323  // GIVEN a CLI uninstall command with all defaults and no uninstall job pod
   324  //
   325  //	WHEN I call cmd.Execute for uninstall
   326  //	THEN the CLI uninstall command fails and a bug-report is generated
   327  func TestUninstallCmdDefaultNoUninstallJob(t *testing.T) {
   328  	deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.3.0"})
   329  	vz := createVz()
   330  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(deployment, vz).Build()
   331  
   332  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   333  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   334  	rc.SetClient(c)
   335  	rc.SetDynamicClient(dynfake.NewSimpleDynamicClient(helpers.GetScheme()))
   336  	cmd := NewCmdUninstall(rc)
   337  	assert.NotNil(t, cmd)
   338  	cmd.PersistentFlags().Set(constants.LogFormatFlag, "simple")
   339  	tempKubeConfigPath, _ := os.CreateTemp(os.TempDir(), testKubeConfig)
   340  	cmd.Flags().String(constants.GlobalFlagKubeConfig, tempKubeConfigPath.Name(), "")
   341  	cmd.Flags().String(constants.GlobalFlagContext, testK8sContext, "")
   342  
   343  	setWaitRetries(1)
   344  	defer resetWaitRetries()
   345  	defer os.RemoveAll(tempKubeConfigPath.Name())
   346  
   347  	// Suppressing uninstall prompt
   348  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   349  
   350  	// Run uninstall command
   351  	err := cmd.Execute()
   352  	assert.Error(t, err)
   353  	assert.ErrorContains(t, err, PodNotFoundError)
   354  	assert.ErrorContains(t, err, PodNotFoundError)
   355  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   356  	assert.NoError(t, err)
   357  	assert.Contains(t, string(errBytes), PodNotFoundError)
   358  	if !helpers.CheckAndRemoveBugReportAndRedactionFileExistsInDir("") {
   359  		t.Fatal(BugReportNotExist)
   360  	}
   361  }
   362  
   363  // TestUninstallCmdDefaultNoVzResource
   364  // GIVEN a CLI uninstall command with all defaults and no vz resource found
   365  //
   366  //	WHEN I call cmd.Execute for uninstall
   367  //	THEN the CLI uninstall command fails and bug report should not be generated
   368  func TestUninstallCmdDefaultNoVzResource(t *testing.T) {
   369  	c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).Build()
   370  
   371  	rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   372  	defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   373  	rc.SetClient(c)
   374  	rc.SetDynamicClient(dynfake.NewSimpleDynamicClient(helpers.GetScheme()))
   375  	cmd := NewCmdUninstall(rc)
   376  	tempKubeConfigPath, _ := os.CreateTemp(os.TempDir(), testKubeConfig)
   377  	cmd.Flags().String(constants.GlobalFlagKubeConfig, tempKubeConfigPath.Name(), "")
   378  	cmd.Flags().String(constants.GlobalFlagContext, testK8sContext, "")
   379  	assert.NotNil(t, cmd)
   380  
   381  	// Suppressing uninstall prompt
   382  	cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   383  
   384  	// Run uninstall command
   385  	err := cmd.Execute()
   386  	assert.Error(t, err)
   387  	assert.ErrorContains(t, err, "Verrazzano is not installed: Failed to find any Verrazzano resources")
   388  	errBytes, err := os.ReadFile(rc.ErrOut.Name())
   389  	assert.NoError(t, err)
   390  	assert.Contains(t, string(errBytes), "Verrazzano is not installed: Failed to find any Verrazzano resources")
   391  	if helpers.CheckAndRemoveBugReportAndRedactionFileExistsInDir("") {
   392  		t.Fatal(BugReportNotExist)
   393  	}
   394  }
   395  
   396  // TestUninstallWithConfirmUninstallFlag
   397  // Given the "--skip-confirmation or -y" flag the Verrazzano Uninstall prompt will be suppressed
   398  // any other input to the command-line other than Y or y will kill the uninstall process
   399  func TestUninstallWithConfirmUninstallFlag(t *testing.T) {
   400  	type fields struct {
   401  		cmdLineInput  string
   402  		doesUninstall bool
   403  	}
   404  	tests := []struct {
   405  		name   string
   406  		fields fields
   407  	}{
   408  		{"Suppress Uninstall prompt with --skip-confirmation=true", fields{cmdLineInput: "", doesUninstall: true}},
   409  		{"Proceed with Uninstall, Y", fields{cmdLineInput: "Y", doesUninstall: true}},
   410  		{"Proceed with Uninstall, y", fields{cmdLineInput: "y", doesUninstall: true}},
   411  		{"Halt with Uninstall, n", fields{cmdLineInput: "n", doesUninstall: false}},
   412  		{"Garbage input passed on cmdLine", fields{cmdLineInput: "GARBAGE", doesUninstall: false}},
   413  	}
   414  	for _, tt := range tests {
   415  		t.Run(tt.name, func(t *testing.T) {
   416  			deployment := createVpoDeployment(map[string]string{"app.kubernetes.io/version": "1.4.0"})
   417  			vpo := createVpoPod()
   418  			namespace := createNamespace()
   419  			validatingWebhookConfig := createWebhook()
   420  			clusterRoleBinding := createClusterRoleBinding()
   421  			mcClusterRole := createMCClusterRole()
   422  			registrarClusterRole := createRegistrarClusterRoleForRancher()
   423  			vz := createVz()
   424  			c := fake.NewClientBuilder().WithScheme(helpers.NewScheme()).WithObjects(
   425  				deployment, vpo, vz, namespace, validatingWebhookConfig, clusterRoleBinding, mcClusterRole, registrarClusterRole).Build()
   426  
   427  			if tt.fields.cmdLineInput != "" {
   428  				content := []byte(tt.fields.cmdLineInput)
   429  				tempfile, err := os.CreateTemp("", "test-input.txt")
   430  				if err != nil {
   431  					assert.Error(t, err)
   432  				}
   433  				// clean up tempfile
   434  				defer os.Remove(tempfile.Name())
   435  				if _, err := tempfile.Write(content); err != nil {
   436  					assert.Error(t, err)
   437  				}
   438  				if _, err := tempfile.Seek(0, 0); err != nil {
   439  					assert.Error(t, err)
   440  				}
   441  				oldStdin := os.Stdin
   442  				// Restore original Stdin
   443  				defer func() { os.Stdin = oldStdin }()
   444  				os.Stdin = tempfile
   445  			}
   446  
   447  			rc := testhelpers.NewFakeRootCmdContextWithFiles(t)
   448  			defer testhelpers.CleanUpNewFakeRootCmdContextWithFiles(rc)
   449  			rc.IOStreams.In = os.Stdin
   450  			rc.SetClient(c)
   451  			rc.SetDynamicClient(dynfake.NewSimpleDynamicClient(helpers.GetScheme()))
   452  			cmd := NewCmdUninstall(rc)
   453  
   454  			if tt.fields.doesUninstall {
   455  				if strings.Contains(tt.name, "skip-confirmation") {
   456  					// Suppressing uninstall prompt
   457  					cmd.PersistentFlags().Set(ConfirmUninstallFlag, "true")
   458  				}
   459  				err := cmd.Execute()
   460  				assert.NoError(t, err)
   461  				ensureResourcesDeleted(t, c)
   462  			} else if !tt.fields.doesUninstall {
   463  				err := cmd.Execute()
   464  				assert.NoError(t, err)
   465  				ensureResourcesNotDeleted(t, c)
   466  			}
   467  		})
   468  	}
   469  }
   470  
   471  func createNamespace() *corev1.Namespace {
   472  	return &corev1.Namespace{
   473  		TypeMeta: metav1.TypeMeta{},
   474  		ObjectMeta: metav1.ObjectMeta{
   475  			Name: vzconstants.VerrazzanoInstallNamespace,
   476  		},
   477  	}
   478  }
   479  
   480  func createVz() *v1beta1.Verrazzano {
   481  	return &v1beta1.Verrazzano{
   482  		TypeMeta: metav1.TypeMeta{},
   483  		ObjectMeta: metav1.ObjectMeta{
   484  			Namespace: "default",
   485  			Name:      "verrazzano",
   486  		},
   487  	}
   488  }
   489  
   490  func createVpoDeployment(labels map[string]string) *appsv1.Deployment {
   491  	return &appsv1.Deployment{
   492  		ObjectMeta: metav1.ObjectMeta{
   493  			Namespace: vzconstants.VerrazzanoInstallNamespace,
   494  			Name:      constants.VerrazzanoPlatformOperator,
   495  			Labels:    labels,
   496  		},
   497  	}
   498  }
   499  
   500  func createVpoPod() *corev1.Pod {
   501  	return &corev1.Pod{
   502  		ObjectMeta: metav1.ObjectMeta{
   503  			Namespace: vzconstants.VerrazzanoInstallNamespace,
   504  			Name:      constants.VerrazzanoPlatformOperator,
   505  			Labels: map[string]string{
   506  				"app": constants.VerrazzanoPlatformOperator,
   507  			},
   508  		},
   509  	}
   510  }
   511  
   512  func createWebhook() *adminv1.ValidatingWebhookConfiguration {
   513  	return &adminv1.ValidatingWebhookConfiguration{
   514  		TypeMeta: metav1.TypeMeta{},
   515  		ObjectMeta: metav1.ObjectMeta{
   516  			Name: constants.VerrazzanoPlatformOperatorWebhook,
   517  		},
   518  	}
   519  }
   520  
   521  func createClusterRoleBinding() *rbacv1.ClusterRoleBinding {
   522  	return &rbacv1.ClusterRoleBinding{
   523  		TypeMeta: metav1.TypeMeta{},
   524  		ObjectMeta: metav1.ObjectMeta{
   525  			Name: constants.VerrazzanoPlatformOperator,
   526  		},
   527  	}
   528  }
   529  
   530  func createMCClusterRole() *rbacv1.ClusterRole {
   531  	return &rbacv1.ClusterRole{
   532  		TypeMeta: metav1.TypeMeta{},
   533  		ObjectMeta: metav1.ObjectMeta{
   534  			Name: constants.VerrazzanoManagedCluster,
   535  		},
   536  	}
   537  }
   538  
   539  func createRegistrarClusterRoleForRancher() *rbacv1.ClusterRole {
   540  	return &rbacv1.ClusterRole{
   541  		TypeMeta: metav1.TypeMeta{},
   542  		ObjectMeta: metav1.ObjectMeta{
   543  			Name: vzconstants.VerrazzanoClusterRancherName,
   544  		},
   545  	}
   546  }
   547  
   548  func ensureResourcesDeleted(t *testing.T, client ctrlclient.Client) {
   549  	// Expect the Verrazzano resource to be deleted
   550  	v := vzapi.Verrazzano{}
   551  	err := client.Get(context.TODO(), types.NamespacedName{Namespace: "default", Name: "verrazzano"}, &v)
   552  	assert.True(t, errors.IsNotFound(err))
   553  
   554  	// Expect the install namespace to be deleted
   555  	ns := corev1.Namespace{}
   556  	err = client.Get(context.TODO(), types.NamespacedName{Name: vzconstants.VerrazzanoInstallNamespace}, &ns)
   557  	assert.True(t, errors.IsNotFound(err))
   558  
   559  	// Expect the Validating Webhook Configuration to be deleted
   560  	vwc := adminv1.ValidatingWebhookConfiguration{}
   561  	err = client.Get(context.TODO(), types.NamespacedName{Name: constants.VerrazzanoPlatformOperatorWebhook}, &vwc)
   562  	assert.True(t, errors.IsNotFound(err))
   563  
   564  	// Expect the Cluster Role Binding to be deleted
   565  	crb := rbacv1.ClusterRoleBinding{}
   566  	err = client.Get(context.TODO(), types.NamespacedName{Name: constants.VerrazzanoPlatformOperator}, &crb)
   567  	assert.True(t, errors.IsNotFound(err))
   568  
   569  	// Expect the managed cluster Cluster Role to be deleted
   570  	cr := rbacv1.ClusterRole{}
   571  	err = client.Get(context.TODO(), types.NamespacedName{Name: constants.VerrazzanoManagedCluster}, &cr)
   572  	assert.True(t, errors.IsNotFound(err))
   573  
   574  	// Expect the cluster Registrar Cluster Role to be deleted
   575  	cr = rbacv1.ClusterRole{}
   576  	err = client.Get(context.TODO(), types.NamespacedName{Name: vzconstants.VerrazzanoClusterRancherName}, &cr)
   577  	assert.True(t, errors.IsNotFound(err))
   578  }
   579  
   580  func ensureResourcesNotDeleted(t *testing.T, client ctrlclient.Client) {
   581  	// Expect the install namespace not to be deleted
   582  	ns := corev1.Namespace{}
   583  	err := client.Get(context.TODO(), types.NamespacedName{Name: vzconstants.VerrazzanoInstallNamespace}, &ns)
   584  	assert.NoError(t, err)
   585  
   586  	// Expect the Validating Webhook Configuration not to be deleted
   587  	vwc := adminv1.ValidatingWebhookConfiguration{}
   588  	err = client.Get(context.TODO(), types.NamespacedName{Name: constants.VerrazzanoPlatformOperatorWebhook}, &vwc)
   589  	assert.NoError(t, err)
   590  
   591  	// Expect the Cluster Role Binding not to be deleted
   592  	crb := rbacv1.ClusterRoleBinding{}
   593  	err = client.Get(context.TODO(), types.NamespacedName{Name: constants.VerrazzanoPlatformOperator}, &crb)
   594  	assert.NoError(t, err)
   595  
   596  	// Expect the managed cluster Cluster Role not to be deleted
   597  	cr := rbacv1.ClusterRole{}
   598  	err = client.Get(context.TODO(), types.NamespacedName{Name: constants.VerrazzanoManagedCluster}, &cr)
   599  	assert.NoError(t, err)
   600  
   601  	// Expect the cluster Registrar Cluster Role not to be deleted
   602  	cr = rbacv1.ClusterRole{}
   603  	err = client.Get(context.TODO(), types.NamespacedName{Name: vzconstants.VerrazzanoClusterRancherName}, &cr)
   604  	assert.NoError(t, err)
   605  }