diff --git a/aci/aci_test.go b/aci/aci_test.go index c9976e468..145bf2802 100644 --- a/aci/aci_test.go +++ b/aci/aci_test.go @@ -3,7 +3,7 @@ package aci import ( "testing" - "github.com/stretchr/testify/assert" + "gotest.tools/v3/assert" ) func TestGetLinesWritten(t *testing.T) { diff --git a/aci/backend.go b/aci/backend.go index 359d5ef64..a6b872df5 100644 --- a/aci/backend.go +++ b/aci/backend.go @@ -367,7 +367,7 @@ func (cs *aciComposeService) Down(ctx context.Context, opts cli.ProjectOptions) } type aciCloudService struct { - loginService login.AzureLoginService + loginService *login.AzureLoginService } func (cs *aciCloudService) Login(ctx context.Context, params interface{}) error { diff --git a/aci/backend_test.go b/aci/backend_test.go index 5b95ce7df..e6b72765c 100644 --- a/aci/backend_test.go +++ b/aci/backend_test.go @@ -22,55 +22,39 @@ import ( "github.com/docker/api/containers" - "github.com/stretchr/testify/suite" - - . "github.com/onsi/gomega" + "gotest.tools/v3/assert" ) -type BackendSuiteTest struct { - suite.Suite -} - -func (suite *BackendSuiteTest) TestGetContainerName() { +func TestGetContainerName(t *testing.T) { group, container := getGroupAndContainerName("docker1234") - Expect(group).To(Equal("docker1234")) - Expect(container).To(Equal("docker1234")) + assert.Equal(t, group, "docker1234") + assert.Equal(t, container, "docker1234") group, container = getGroupAndContainerName("compose_service1") - Expect(group).To(Equal("compose")) - Expect(container).To(Equal("service1")) + assert.Equal(t, group, "compose") + assert.Equal(t, container, "service1") group, container = getGroupAndContainerName("compose_stack_service1") - Expect(group).To(Equal("compose_stack")) - Expect(container).To(Equal("service1")) + assert.Equal(t, group, "compose_stack") + assert.Equal(t, container, "service1") } -func (suite *BackendSuiteTest) TestErrorMessageDeletingContainerFromComposeApplication() { +func TestErrorMessageDeletingContainerFromComposeApplication(t *testing.T) { service := aciContainerService{} err := service.Delete(context.TODO(), "compose-app_service1", false) - - Expect(err).NotTo(BeNil()) - Expect(err.Error()).To(Equal("cannot delete service \"service1\" from compose application \"compose-app\", you can delete the entire compose app with docker compose down --project-name compose-app")) + assert.Error(t, err, "cannot delete service \"service1\" from compose application \"compose-app\", you can delete the entire compose app with docker compose down --project-name compose-app") } -func (suite *BackendSuiteTest) TestErrorMessageRunSingleContainerNameWithComposeSeparator() { +func TestErrorMessageRunSingleContainerNameWithComposeSeparator(t *testing.T) { service := aciContainerService{} err := service.Run(context.TODO(), containers.ContainerConfig{ID: "container_name"}) - - Expect(err).NotTo(BeNil()) - Expect(err.Error()).To(Equal("invalid container name. ACI container name cannot include \"_\"")) + assert.Error(t, err, "invalid container name. ACI container name cannot include \"_\"") } -func (suite *BackendSuiteTest) TestVerifyCommand() { +func TestVerifyCommand(t *testing.T) { err := verifyExecCommand("command") // Command without an argument - Expect(err).To(BeNil()) + assert.NilError(t, err) err = verifyExecCommand("command argument") // Command with argument - Expect(err).NotTo(BeNil()) - Expect(err.Error()).To(Equal("ACI exec command does not accept arguments to the command. " + - "Only the binary should be specified")) -} - -func TestBackendSuite(t *testing.T) { - RegisterTestingT(t) - suite.Run(t, new(BackendSuiteTest)) + assert.Error(t, err, "ACI exec command does not accept arguments to the command. "+ + "Only the binary should be specified") } diff --git a/aci/context_test.go b/aci/context_test.go index 7da6f876b..1ee90259a 100644 --- a/aci/context_test.go +++ b/aci/context_test.go @@ -25,132 +25,131 @@ import ( "github.com/Azure/go-autorest/autorest/to" "github.com/pkg/errors" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/suite" + "gotest.tools/v3/assert" + "gotest.tools/v3/assert/cmp" "github.com/docker/api/context/store" - - . "github.com/onsi/gomega" ) -type ContextSuiteTest struct { - suite.Suite - mockUserPrompt *mockUserPrompt - mockResourceGroupHeper *MockResourceGroupHelper - contextCreateHelper contextCreateACIHelper +type contextMocks struct { + userPrompt *mockUserPrompt + resourceGroupHelper *MockResourceGroupHelper + contextCreateHelper contextCreateACIHelper } -func (suite *ContextSuiteTest) BeforeTest(suiteName, testName string) { - suite.mockUserPrompt = &mockUserPrompt{} - suite.mockResourceGroupHeper = &MockResourceGroupHelper{} - suite.contextCreateHelper = contextCreateACIHelper{ - suite.mockUserPrompt, - suite.mockResourceGroupHeper, +func testContextMocks() contextMocks { + mockUserPrompt := &mockUserPrompt{} + mockResourceGroupHelper := &MockResourceGroupHelper{} + contextCreateHelper := contextCreateACIHelper{ + mockUserPrompt, + mockResourceGroupHelper, } + return contextMocks{mockUserPrompt, mockResourceGroupHelper, contextCreateHelper} } -func (suite *ContextSuiteTest) TestCreateSpecifiedSubscriptionAndGroup() { +func TestCreateSpecifiedSubscriptionAndGroup(t *testing.T) { ctx := context.TODO() opts := options("1234", "myResourceGroup") - suite.mockResourceGroupHeper.On("GetGroup", ctx, "1234", "myResourceGroup").Return(group("myResourceGroup", "eastus"), nil) + m := testContextMocks() + m.resourceGroupHelper.On("GetGroup", ctx, "1234", "myResourceGroup").Return(group("myResourceGroup", "eastus"), nil) - data, description, err := suite.contextCreateHelper.createContextData(ctx, opts) - - Expect(err).To(BeNil()) - Expect(description).To(Equal("myResourceGroup@eastus")) - Expect(data).To(Equal(aciContext("1234", "myResourceGroup", "eastus"))) + data, description, err := m.contextCreateHelper.createContextData(ctx, opts) + assert.NilError(t, err) + assert.Equal(t, description, "myResourceGroup@eastus") + assert.DeepEqual(t, data, aciContext("1234", "myResourceGroup", "eastus")) } -func (suite *ContextSuiteTest) TestErrorOnNonExistentResourceGroup() { +func TestErrorOnNonExistentResourceGroup(t *testing.T) { ctx := context.TODO() opts := options("1234", "myResourceGroup") notFoundError := errors.New(`Not Found: "myResourceGroup"`) - suite.mockResourceGroupHeper.On("GetGroup", ctx, "1234", "myResourceGroup").Return(resources.Group{}, notFoundError) + m := testContextMocks() + m.resourceGroupHelper.On("GetGroup", ctx, "1234", "myResourceGroup").Return(resources.Group{}, notFoundError) - data, description, err := suite.contextCreateHelper.createContextData(ctx, opts) - - Expect(data).To(BeNil()) - Expect(description).To(Equal("")) - Expect(err.Error()).To(Equal("Could not find resource group \"myResourceGroup\": Not Found: \"myResourceGroup\"")) + data, description, err := m.contextCreateHelper.createContextData(ctx, opts) + assert.Assert(t, cmp.Nil(data)) + assert.Equal(t, description, "") + assert.Error(t, err, "Could not find resource group \"myResourceGroup\": Not Found: \"myResourceGroup\"") } -func (suite *ContextSuiteTest) TestCreateNewResourceGroup() { +func TestCreateNewResourceGroup(t *testing.T) { ctx := context.TODO() opts := options("1234", "") - suite.mockResourceGroupHeper.On("GetGroup", ctx, "1234", "myResourceGroup").Return(group("myResourceGroup", "eastus"), nil) + m := testContextMocks() + m.resourceGroupHelper.On("GetGroup", ctx, "1234", "myResourceGroup").Return(group("myResourceGroup", "eastus"), nil) selectOptions := []string{"create a new resource group", "group1 (eastus)", "group2 (westeurope)"} - suite.mockUserPrompt.On("Select", "Select a resource group", selectOptions).Return(0, nil) - suite.mockResourceGroupHeper.On("CreateOrUpdate", ctx, "1234", mock.AnythingOfType("string"), mock.AnythingOfType("resources.Group")).Return(group("newResourceGroup", "eastus"), nil) - suite.mockResourceGroupHeper.On("ListGroups", ctx, "1234").Return([]resources.Group{ + m.userPrompt.On("Select", "Select a resource group", selectOptions).Return(0, nil) + m.resourceGroupHelper.On("CreateOrUpdate", ctx, "1234", mock.AnythingOfType("string"), mock.AnythingOfType("resources.Group")).Return(group("newResourceGroup", "eastus"), nil) + m.resourceGroupHelper.On("ListGroups", ctx, "1234").Return([]resources.Group{ group("group1", "eastus"), group("group2", "westeurope"), }, nil) - data, description, err := suite.contextCreateHelper.createContextData(ctx, opts) - - Expect(err).To(BeNil()) - Expect(description).To(Equal("newResourceGroup@eastus")) - Expect(data).To(Equal(aciContext("1234", "newResourceGroup", "eastus"))) + data, description, err := m.contextCreateHelper.createContextData(ctx, opts) + assert.NilError(t, err) + assert.Equal(t, description, "newResourceGroup@eastus") + assert.DeepEqual(t, data, aciContext("1234", "newResourceGroup", "eastus")) } -func (suite *ContextSuiteTest) TestSelectExistingResourceGroup() { +func TestSelectExistingResourceGroup(t *testing.T) { ctx := context.TODO() opts := options("1234", "") selectOptions := []string{"create a new resource group", "group1 (eastus)", "group2 (westeurope)"} - suite.mockUserPrompt.On("Select", "Select a resource group", selectOptions).Return(2, nil) - suite.mockResourceGroupHeper.On("ListGroups", ctx, "1234").Return([]resources.Group{ + m := testContextMocks() + m.userPrompt.On("Select", "Select a resource group", selectOptions).Return(2, nil) + m.resourceGroupHelper.On("ListGroups", ctx, "1234").Return([]resources.Group{ group("group1", "eastus"), group("group2", "westeurope"), }, nil) - data, description, err := suite.contextCreateHelper.createContextData(ctx, opts) - - Expect(err).To(BeNil()) - Expect(description).To(Equal("group2@westeurope")) - Expect(data).To(Equal(aciContext("1234", "group2", "westeurope"))) + data, description, err := m.contextCreateHelper.createContextData(ctx, opts) + assert.NilError(t, err) + assert.Equal(t, description, "group2@westeurope") + assert.DeepEqual(t, data, aciContext("1234", "group2", "westeurope")) } -func (suite *ContextSuiteTest) TestSelectSingleSubscriptionIdAndExistingResourceGroup() { +func TestSelectSingleSubscriptionIdAndExistingResourceGroup(t *testing.T) { ctx := context.TODO() opts := options("", "") - suite.mockResourceGroupHeper.On("GetSubscriptionIDs", ctx).Return([]subscription.Model{subModel("123456", "Subscription1")}, nil) + m := testContextMocks() + m.resourceGroupHelper.On("GetSubscriptionIDs", ctx).Return([]subscription.Model{subModel("123456", "Subscription1")}, nil) selectOptions := []string{"create a new resource group", "group1 (eastus)", "group2 (westeurope)"} - suite.mockUserPrompt.On("Select", "Select a resource group", selectOptions).Return(2, nil) - suite.mockResourceGroupHeper.On("ListGroups", ctx, "123456").Return([]resources.Group{ + m.userPrompt.On("Select", "Select a resource group", selectOptions).Return(2, nil) + m.resourceGroupHelper.On("ListGroups", ctx, "123456").Return([]resources.Group{ group("group1", "eastus"), group("group2", "westeurope"), }, nil) - data, description, err := suite.contextCreateHelper.createContextData(ctx, opts) - - Expect(err).To(BeNil()) - Expect(description).To(Equal("group2@westeurope")) - Expect(data).To(Equal(aciContext("123456", "group2", "westeurope"))) + data, description, err := m.contextCreateHelper.createContextData(ctx, opts) + assert.NilError(t, err) + assert.Equal(t, description, "group2@westeurope") + assert.DeepEqual(t, data, aciContext("123456", "group2", "westeurope")) } -func (suite *ContextSuiteTest) TestSelectSubscriptionIdAndExistingResourceGroup() { +func TestSelectSubscriptionIdAndExistingResourceGroup(t *testing.T) { ctx := context.TODO() opts := options("", "") sub1 := subModel("1234", "Subscription1") sub2 := subModel("5678", "Subscription2") - suite.mockResourceGroupHeper.On("GetSubscriptionIDs", ctx).Return([]subscription.Model{sub1, sub2}, nil) + m := testContextMocks() + m.resourceGroupHelper.On("GetSubscriptionIDs", ctx).Return([]subscription.Model{sub1, sub2}, nil) selectOptions := []string{"Subscription1 (1234)", "Subscription2 (5678)"} - suite.mockUserPrompt.On("Select", "Select a subscription ID", selectOptions).Return(1, nil) + m.userPrompt.On("Select", "Select a subscription ID", selectOptions).Return(1, nil) selectOptions = []string{"create a new resource group", "group1 (eastus)", "group2 (westeurope)"} - suite.mockUserPrompt.On("Select", "Select a resource group", selectOptions).Return(2, nil) - suite.mockResourceGroupHeper.On("ListGroups", ctx, "5678").Return([]resources.Group{ + m.userPrompt.On("Select", "Select a resource group", selectOptions).Return(2, nil) + m.resourceGroupHelper.On("ListGroups", ctx, "5678").Return([]resources.Group{ group("group1", "eastus"), group("group2", "westeurope"), }, nil) - data, description, err := suite.contextCreateHelper.createContextData(ctx, opts) - - Expect(err).To(BeNil()) - Expect(description).To(Equal("group2@westeurope")) - Expect(data).To(Equal(aciContext("5678", "group2", "westeurope"))) + data, description, err := m.contextCreateHelper.createContextData(ctx, opts) + assert.NilError(t, err) + assert.Equal(t, description, "group2@westeurope") + assert.DeepEqual(t, data, aciContext("5678", "group2", "westeurope")) } func subModel(subID string, display string) subscription.Model { @@ -183,11 +182,6 @@ func options(subscriptionID string, resourceGroupName string) ContextParams { } } -func TestContextSuite(t *testing.T) { - RegisterTestingT(t) - suite.Run(t, new(ContextSuiteTest)) -} - type mockUserPrompt struct { mock.Mock } diff --git a/aci/convert/container_test.go b/aci/convert/container_test.go index 3512f14c1..947890832 100644 --- a/aci/convert/container_test.go +++ b/aci/convert/container_test.go @@ -21,46 +21,35 @@ import ( "github.com/Azure/go-autorest/autorest/to" "github.com/compose-spec/compose-go/types" + "gotest.tools/v3/assert" "github.com/docker/api/containers" - - . "github.com/onsi/gomega" - "github.com/stretchr/testify/suite" ) -type ContainerConvertTestSuite struct { - suite.Suite -} - -func (suite *ContainerConvertTestSuite) TestConvertContainerEnvironment() { +func TestConvertContainerEnvironment(t *testing.T) { container := containers.ContainerConfig{ ID: "container1", Environment: []string{"key1=value1", "key2", "key3=value3"}, } project, err := ContainerToComposeProject(container) - Expect(err).To(BeNil()) + assert.NilError(t, err) service1 := project.Services[0] - Expect(service1.Name).To(Equal(container.ID)) - Expect(service1.Environment).To(Equal(types.MappingWithEquals{ + assert.Equal(t, service1.Name, container.ID) + assert.DeepEqual(t, service1.Environment, types.MappingWithEquals{ "key1": to.StringPtr("value1"), "key2": nil, "key3": to.StringPtr("value3"), - })) + }) } -func (suite *ContainerConvertTestSuite) TestConvertRestartPolicy() { +func TestConvertRestartPolicy(t *testing.T) { container := containers.ContainerConfig{ ID: "container1", RestartPolicyCondition: "none", } project, err := ContainerToComposeProject(container) - Expect(err).To(BeNil()) + assert.NilError(t, err) service1 := project.Services[0] - Expect(service1.Name).To(Equal(container.ID)) - Expect(service1.Deploy.RestartPolicy.Condition).To(Equal("none")) -} - -func TestContainerConvertTestSuite(t *testing.T) { - RegisterTestingT(t) - suite.Run(t, new(ContainerConvertTestSuite)) + assert.Equal(t, service1.Name, container.ID) + assert.Equal(t, service1.Deploy.RestartPolicy.Condition, "none") } diff --git a/aci/convert/convert_test.go b/aci/convert/convert_test.go index 8b46fd847..cbecf9809 100644 --- a/aci/convert/convert_test.go +++ b/aci/convert/convert_test.go @@ -23,38 +23,29 @@ import ( "github.com/Azure/azure-sdk-for-go/profiles/latest/containerinstance/mgmt/containerinstance" "github.com/Azure/go-autorest/autorest/to" "github.com/compose-spec/compose-go/types" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" "github.com/docker/api/containers" "github.com/docker/api/context/store" - - . "github.com/onsi/gomega" - "github.com/stretchr/testify/require" - "github.com/stretchr/testify/suite" ) -type ConvertTestSuite struct { - suite.Suite - ctx store.AciContext +var convertCtx = store.AciContext{ + SubscriptionID: "subID", + ResourceGroup: "rg", + Location: "eu", } -func (suite *ConvertTestSuite) BeforeTest(suiteName, testName string) { - suite.ctx = store.AciContext{ - SubscriptionID: "subID", - ResourceGroup: "rg", - Location: "eu", - } -} - -func (suite *ConvertTestSuite) TestProjectName() { +func TestProjectName(t *testing.T) { project := types.Project{ Name: "TEST", } - containerGroup, err := ToContainerGroup(suite.ctx, project) - require.NoError(suite.T(), err) - require.Equal(suite.T(), *containerGroup.Name, "test") + containerGroup, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) + assert.Equal(t, *containerGroup.Name, "test") } -func (suite *ConvertTestSuite) TestContainerGroupToContainer() { +func TestContainerGroupToContainer(t *testing.T) { myContainerGroup := containerinstance.ContainerGroup{ ContainerGroupProperties: &containerinstance.ContainerGroupProperties{ IPAddress: &containerinstance.IPAddress{ @@ -108,11 +99,11 @@ func (suite *ConvertTestSuite) TestContainerGroupToContainer() { } container, err := ContainerGroupToContainer("myContainerID", myContainerGroup, myContainer) - Expect(err).To(BeNil()) - Expect(container).To(Equal(expectedContainer)) + assert.NilError(t, err) + assert.DeepEqual(t, container, expectedContainer) } -func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerWithDnsSideCarSide() { +func TestComposeContainerGroupToContainerWithDnsSideCarSide(t *testing.T) { project := types.Project{ Services: []types.ServiceConfig{ { @@ -126,22 +117,22 @@ func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerWithDnsSideCa }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) - Expect(len(*group.Containers)).To(Equal(3)) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) + assert.Assert(t, is.Len(*group.Containers, 3)) - Expect(*(*group.Containers)[0].Name).To(Equal("service1")) - Expect(*(*group.Containers)[1].Name).To(Equal("service2")) - Expect(*(*group.Containers)[2].Name).To(Equal(ComposeDNSSidecarName)) + assert.Equal(t, *(*group.Containers)[0].Name, "service1") + assert.Equal(t, *(*group.Containers)[1].Name, "service2") + assert.Equal(t, *(*group.Containers)[2].Name, ComposeDNSSidecarName) - Expect(*(*group.Containers)[2].Command).To(Equal([]string{"sh", "-c", "echo 127.0.0.1 service1 >> /etc/hosts;echo 127.0.0.1 service2 >> /etc/hosts;sleep infinity"})) + assert.DeepEqual(t, *(*group.Containers)[2].Command, []string{"sh", "-c", "echo 127.0.0.1 service1 >> /etc/hosts;echo 127.0.0.1 service2 >> /etc/hosts;sleep infinity"}) - Expect(*(*group.Containers)[0].Image).To(Equal("image1")) - Expect(*(*group.Containers)[1].Image).To(Equal("image2")) - Expect(*(*group.Containers)[2].Image).To(Equal(dnsSidecarImage)) + assert.Equal(t, *(*group.Containers)[0].Image, "image1") + assert.Equal(t, *(*group.Containers)[1].Image, "image2") + assert.Equal(t, *(*group.Containers)[2].Image, dnsSidecarImage) } -func (suite *ConvertTestSuite) TestComposeSingleContainerGroupToContainerNoDnsSideCarSide() { +func TestComposeSingleContainerGroupToContainerNoDnsSideCarSide(t *testing.T) { project := types.Project{ Services: []types.ServiceConfig{ { @@ -151,15 +142,15 @@ func (suite *ConvertTestSuite) TestComposeSingleContainerGroupToContainerNoDnsSi }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) - Expect(len(*group.Containers)).To(Equal(1)) - Expect(*(*group.Containers)[0].Name).To(Equal("service1")) - Expect(*(*group.Containers)[0].Image).To(Equal("image1")) + assert.Assert(t, is.Len(*group.Containers, 1)) + assert.Equal(t, *(*group.Containers)[0].Name, "service1") + assert.Equal(t, *(*group.Containers)[0].Image, "image1") } -func (suite *ConvertTestSuite) TestComposeSingleContainerGroupToContainerSpecificRestartPolicy() { +func TestComposeSingleContainerGroupToContainerSpecificRestartPolicy(t *testing.T) { project := types.Project{ Services: []types.ServiceConfig{ { @@ -174,15 +165,15 @@ func (suite *ConvertTestSuite) TestComposeSingleContainerGroupToContainerSpecifi }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) - Expect(len(*group.Containers)).To(Equal(1)) - Expect(*(*group.Containers)[0].Name).To(Equal("service1")) - Expect(group.RestartPolicy).To(Equal(containerinstance.OnFailure)) + assert.Assert(t, is.Len(*group.Containers, 1)) + assert.Equal(t, *(*group.Containers)[0].Name, "service1") + assert.Equal(t, group.RestartPolicy, containerinstance.OnFailure) } -func (suite *ConvertTestSuite) TestComposeSingleContainerGroupToContainerDefaultRestartPolicy() { +func TestComposeSingleContainerGroupToContainerDefaultRestartPolicy(t *testing.T) { project := types.Project{ Services: []types.ServiceConfig{ { @@ -192,15 +183,15 @@ func (suite *ConvertTestSuite) TestComposeSingleContainerGroupToContainerDefault }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) - Expect(len(*group.Containers)).To(Equal(1)) - Expect(*(*group.Containers)[0].Name).To(Equal("service1")) - Expect(group.RestartPolicy).To(Equal(containerinstance.Always)) + assert.Assert(t, is.Len(*group.Containers, 1)) + assert.Equal(t, *(*group.Containers)[0].Name, "service1") + assert.Equal(t, group.RestartPolicy, containerinstance.Always) } -func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerMultiplePorts() { +func TestComposeContainerGroupToContainerMultiplePorts(t *testing.T) { project := types.Project{ Services: []types.ServiceConfig{ { @@ -226,29 +217,27 @@ func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerMultiplePorts }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) - Expect(len(*group.Containers)).To(Equal(3)) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) + assert.Assert(t, is.Len(*group.Containers, 3)) container1 := (*group.Containers)[0] - container2 := (*group.Containers)[1] - Expect(*container1.Name).To(Equal("service1")) - Expect(*container1.Image).To(Equal("image1")) - portsC1 := *container1.Ports - Expect(*portsC1[0].Port).To(Equal(int32(80))) + assert.Equal(t, *container1.Name, "service1") + assert.Equal(t, *container1.Image, "image1") + assert.Equal(t, *(*container1.Ports)[0].Port, int32(80)) - Expect(*container2.Name).To(Equal("service2")) - Expect(*container2.Image).To(Equal("image2")) - portsC2 := *container2.Ports - Expect(*portsC2[0].Port).To(Equal(int32(8080))) + container2 := (*group.Containers)[1] + assert.Equal(t, *container2.Name, "service2") + assert.Equal(t, *container2.Image, "image2") + assert.Equal(t, *(*container2.Ports)[0].Port, int32(8080)) groupPorts := *group.IPAddress.Ports - Expect(len(groupPorts)).To(Equal(2)) - Expect(*groupPorts[0].Port).To(Equal(int32(80))) - Expect(*groupPorts[1].Port).To(Equal(int32(8080))) + assert.Assert(t, is.Len(groupPorts, 2)) + assert.Equal(t, *groupPorts[0].Port, int32(80)) + assert.Equal(t, *groupPorts[1].Port, int32(8080)) } -func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerResourceLimits() { +func TestComposeContainerGroupToContainerResourceLimits(t *testing.T) { _0_1Gb := 0.1 * 1024 * 1024 * 1024 project := types.Project{ Services: []types.ServiceConfig{ @@ -267,16 +256,15 @@ func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerResourceLimit }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) - container1 := (*group.Containers)[0] - limits := *container1.Resources.Limits - Expect(*limits.CPU).To(Equal(float64(0.1))) - Expect(*limits.MemoryInGB).To(Equal(float64(0.1))) + limits := *((*group.Containers)[0]).Resources.Limits + assert.Equal(t, *limits.CPU, float64(0.1)) + assert.Equal(t, *limits.MemoryInGB, float64(0.1)) } -func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerResourceLimitsDefaults() { +func TestComposeContainerGroupToContainerResourceLimitsDefaults(t *testing.T) { project := types.Project{ Services: []types.ServiceConfig{ { @@ -294,18 +282,17 @@ func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerResourceLimit }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) - container1 := (*group.Containers)[0] - limits := *container1.Resources.Limits - Expect(*limits.CPU).To(Equal(float64(1))) - Expect(*limits.MemoryInGB).To(Equal(float64(1))) + limits := *((*group.Containers)[0]).Resources.Limits + assert.Equal(t, *limits.CPU, float64(1)) + assert.Equal(t, *limits.MemoryInGB, float64(1)) } -func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerenvVar() { +func TestComposeContainerGroupToContainerenvVar(t *testing.T) { err := os.Setenv("key2", "value2") - Expect(err).To(BeNil()) + assert.NilError(t, err) project := types.Project{ Services: []types.ServiceConfig{ { @@ -319,31 +306,25 @@ func (suite *ConvertTestSuite) TestComposeContainerGroupToContainerenvVar() { }, } - group, err := ToContainerGroup(suite.ctx, project) - Expect(err).To(BeNil()) + group, err := ToContainerGroup(convertCtx, project) + assert.NilError(t, err) - container1 := (*group.Containers)[0] - envVars := *container1.EnvironmentVariables - Expect(len(envVars)).To(Equal(2)) - Expect(envVars).To(ContainElement(containerinstance.EnvironmentVariable{Name: to.StringPtr("key1"), Value: to.StringPtr("value1")})) - Expect(envVars).To(ContainElement(containerinstance.EnvironmentVariable{Name: to.StringPtr("key2"), Value: to.StringPtr("value2")})) + envVars := *((*group.Containers)[0]).EnvironmentVariables + assert.Assert(t, is.Len(envVars, 2)) + assert.Assert(t, is.Contains(envVars, containerinstance.EnvironmentVariable{Name: to.StringPtr("key1"), Value: to.StringPtr("value1")})) + assert.Assert(t, is.Contains(envVars, containerinstance.EnvironmentVariable{Name: to.StringPtr("key2"), Value: to.StringPtr("value2")})) } -func (suite *ConvertTestSuite) TestConvertToAciRestartPolicyCondition() { - Expect(toAciRestartPolicy("none")).To(Equal(containerinstance.Never)) - Expect(toAciRestartPolicy("always")).To(Equal(containerinstance.Always)) - Expect(toAciRestartPolicy("on-failure")).To(Equal(containerinstance.OnFailure)) - Expect(toAciRestartPolicy("on-failure:5")).To(Equal(containerinstance.Always)) +func TestConvertToAciRestartPolicyCondition(t *testing.T) { + assert.Equal(t, toAciRestartPolicy("none"), containerinstance.Never) + assert.Equal(t, toAciRestartPolicy("always"), containerinstance.Always) + assert.Equal(t, toAciRestartPolicy("on-failure"), containerinstance.OnFailure) + assert.Equal(t, toAciRestartPolicy("on-failure:5"), containerinstance.Always) } -func (suite *ConvertTestSuite) TestConvertToDockerRestartPolicyCondition() { - Expect(toContainerRestartPolicy(containerinstance.Never)).To(Equal("none")) - Expect(toContainerRestartPolicy(containerinstance.Always)).To(Equal("any")) - Expect(toContainerRestartPolicy(containerinstance.OnFailure)).To(Equal("on-failure")) - Expect(toContainerRestartPolicy("")).To(Equal("any")) -} - -func TestConvertTestSuite(t *testing.T) { - RegisterTestingT(t) - suite.Run(t, new(ConvertTestSuite)) +func TestConvertToDockerRestartPolicyCondition(t *testing.T) { + assert.Equal(t, toContainerRestartPolicy(containerinstance.Never), "none") + assert.Equal(t, toContainerRestartPolicy(containerinstance.Always), "any") + assert.Equal(t, toContainerRestartPolicy(containerinstance.OnFailure), "on-failure") + assert.Equal(t, toContainerRestartPolicy(""), "any") } diff --git a/aci/convert/ports_test.go b/aci/convert/ports_test.go index 78af6ed6d..60ef948bf 100644 --- a/aci/convert/ports_test.go +++ b/aci/convert/ports_test.go @@ -21,7 +21,7 @@ import ( "github.com/Azure/azure-sdk-for-go/profiles/latest/containerinstance/mgmt/containerinstance" "github.com/Azure/go-autorest/autorest/to" - "github.com/stretchr/testify/assert" + "gotest.tools/v3/assert" "github.com/docker/api/containers" ) @@ -119,7 +119,7 @@ func TestPortConvert(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { ports := ToPorts(testCase.ip, testCase.ports) - assert.Equal(t, testCase.expected, ports) + assert.DeepEqual(t, testCase.expected, ports) }) } } diff --git a/aci/convert/registrycredentials.go b/aci/convert/registry_credentials.go similarity index 100% rename from aci/convert/registrycredentials.go rename to aci/convert/registry_credentials.go diff --git a/aci/convert/registrycredentials_test.go b/aci/convert/registry_credentials_test.go similarity index 96% rename from aci/convert/registrycredentials_test.go rename to aci/convert/registry_credentials_test.go index ee3eaf839..d8a112d6b 100644 --- a/aci/convert/registrycredentials_test.go +++ b/aci/convert/registry_credentials_test.go @@ -26,7 +26,7 @@ import ( cliconfigtypes "github.com/docker/cli/cli/config/types" "github.com/stretchr/testify/mock" "gotest.tools/v3/assert" - "gotest.tools/v3/assert/cmp" + is "gotest.tools/v3/assert/cmp" ) const getAllCredentials = "getAllRegistryCredentials" @@ -144,7 +144,6 @@ func TestNoMoreRegistriesThanImages(t *testing.T) { Password: to.StringPtr("pwd"), }, }) - } func TestHubAndSeveralACRRegistries(t *testing.T) { @@ -161,19 +160,17 @@ func TestHubAndSeveralACRRegistries(t *testing.T) { creds, err := getRegistryCredentials(composeServices("mycontainerregistry1.azurecr.io/privateimg", "someuser/privateImg2", "mycontainerregistry2.azurecr.io/privateimg"), loader) assert.NilError(t, err) - assert.Assert(t, cmp.Contains(creds, containerinstance.ImageRegistryCredential{ + assert.Assert(t, is.Contains(creds, containerinstance.ImageRegistryCredential{ Server: to.StringPtr("mycontainerregistry1.azurecr.io"), Username: to.StringPtr(tokenUsername), Password: to.StringPtr("123456"), })) - - assert.Assert(t, cmp.Contains(creds, containerinstance.ImageRegistryCredential{ + assert.Assert(t, is.Contains(creds, containerinstance.ImageRegistryCredential{ Server: to.StringPtr("mycontainerregistry2.azurecr.io"), Username: to.StringPtr(tokenUsername), Password: to.StringPtr("456789"), })) - - assert.Assert(t, cmp.Contains(creds, containerinstance.ImageRegistryCredential{ + assert.Assert(t, is.Contains(creds, containerinstance.ImageRegistryCredential{ Server: to.StringPtr(dockerHub), Username: to.StringPtr("toto"), Password: to.StringPtr("pwd"), diff --git a/aci/convert/volume_test.go b/aci/convert/volume_test.go index 0426172ea..6a9da4470 100644 --- a/aci/convert/volume_test.go +++ b/aci/convert/volume_test.go @@ -20,7 +20,7 @@ import ( "testing" "github.com/compose-spec/compose-go/types" - "gotest.tools/assert" + "gotest.tools/v3/assert" "github.com/docker/api/errdefs" ) @@ -96,28 +96,28 @@ func TestGetRunVolumes(t *testing.T) { func TestGetRunVolumesMissingFileShare(t *testing.T) { _, _, err := GetRunVolumes([]string{"myuser:mykey@"}) - assert.Equal(t, true, errdefs.IsErrParsingFailed(err)) + assert.Assert(t, errdefs.IsErrParsingFailed(err)) assert.ErrorContains(t, err, "does not include a storage file share") } func TestGetRunVolumesMissingUser(t *testing.T) { _, _, err := GetRunVolumes([]string{":mykey@myshare"}) - assert.Equal(t, true, errdefs.IsErrParsingFailed(err)) + assert.Assert(t, errdefs.IsErrParsingFailed(err)) assert.ErrorContains(t, err, "does not include a storage username") } func TestGetRunVolumesMissingKey(t *testing.T) { _, _, err := GetRunVolumes([]string{"userwithnokey:@myshare"}) - assert.Equal(t, true, errdefs.IsErrParsingFailed(err)) + assert.Assert(t, errdefs.IsErrParsingFailed(err)) assert.ErrorContains(t, err, "does not include a storage key") _, _, err = GetRunVolumes([]string{"userwithnokeytoo@myshare"}) - assert.Equal(t, true, errdefs.IsErrParsingFailed(err)) + assert.Assert(t, errdefs.IsErrParsingFailed(err)) assert.ErrorContains(t, err, "does not include a storage key") } func TestGetRunVolumesNoShare(t *testing.T) { _, _, err := GetRunVolumes([]string{"noshare"}) - assert.Equal(t, true, errdefs.IsErrParsingFailed(err)) + assert.Assert(t, errdefs.IsErrParsingFailed(err)) assert.ErrorContains(t, err, "no share specified") } diff --git a/aci/login/loginHelper.go b/aci/login/helper.go similarity index 100% rename from aci/login/loginHelper.go rename to aci/login/helper.go diff --git a/aci/login/login.go b/aci/login/login.go index 59dd3cd87..5d9ef68a8 100644 --- a/aci/login/login.go +++ b/aci/login/login.go @@ -75,16 +75,16 @@ type AzureLoginService struct { const tokenStoreFilename = "dockerAccessToken.json" // NewAzureLoginService creates a NewAzureLoginService -func NewAzureLoginService() (AzureLoginService, error) { +func NewAzureLoginService() (*AzureLoginService, error) { return newAzureLoginServiceFromPath(GetTokenStorePath(), azureAPIHelper{}) } -func newAzureLoginServiceFromPath(tokenStorePath string, helper apiHelper) (AzureLoginService, error) { +func newAzureLoginServiceFromPath(tokenStorePath string, helper apiHelper) (*AzureLoginService, error) { store, err := newTokenStore(tokenStorePath) if err != nil { - return AzureLoginService{}, err + return nil, err } - return AzureLoginService{ + return &AzureLoginService{ tokenStore: store, apiHelper: helper, }, nil @@ -92,7 +92,7 @@ func newAzureLoginServiceFromPath(tokenStorePath string, helper apiHelper) (Azur // TestLoginFromServicePrincipal login with clientId / clientSecret from a previously created service principal. // The resulting token does not include a refresh token, used for tests only -func (login AzureLoginService) TestLoginFromServicePrincipal(clientID string, clientSecret string, tenantID string) error { +func (login *AzureLoginService) TestLoginFromServicePrincipal(clientID string, clientSecret string, tenantID string) error { // Tried with auth2.NewUsernamePasswordConfig() but could not make this work with username / password, setting this for CI with clientID / clientSecret creds := auth2.NewClientCredentialsConfig(clientID, clientSecret, tenantID) @@ -117,7 +117,7 @@ func (login AzureLoginService) TestLoginFromServicePrincipal(clientID string, cl } // Logout remove azure token data -func (login AzureLoginService) Logout(ctx context.Context) error { +func (login *AzureLoginService) Logout(ctx context.Context) error { err := login.tokenStore.removeData() if os.IsNotExist(err) { return errors.New("No Azure login data to be removed") @@ -126,7 +126,7 @@ func (login AzureLoginService) Logout(ctx context.Context) error { } // Login performs an Azure login through a web browser -func (login AzureLoginService) Login(ctx context.Context, requestedTenantID string) error { +func (login *AzureLoginService) Login(ctx context.Context, requestedTenantID string) error { queryCh := make(chan localResponse, 1) s, err := NewLocalServer(queryCh) if err != nil { @@ -267,7 +267,7 @@ func newAuthorizerFromLoginStorePath(storeTokenPath string) (autorest.Authorizer } // GetValidToken returns an access token. Refresh token if needed -func (login AzureLoginService) GetValidToken() (oauth2.Token, error) { +func (login *AzureLoginService) GetValidToken() (oauth2.Token, error) { loginInfo, err := login.tokenStore.readToken() if err != nil { return oauth2.Token{}, err @@ -288,7 +288,7 @@ func (login AzureLoginService) GetValidToken() (oauth2.Token, error) { return token, nil } -func (login AzureLoginService) refreshToken(currentRefreshToken string, tenantID string) (oauth2.Token, error) { +func (login *AzureLoginService) refreshToken(currentRefreshToken string, tenantID string) (oauth2.Token, error) { data := url.Values{ "grant_type": []string{"refresh_token"}, "client_id": []string{clientID}, diff --git a/aci/login/login_test.go b/aci/login/login_test.go index 5b1b84681..ca39ceeb2 100644 --- a/aci/login/login_test.go +++ b/aci/login/login_test.go @@ -28,48 +28,35 @@ import ( "time" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/suite" + "gotest.tools/v3/assert" "golang.org/x/oauth2" - - . "github.com/onsi/gomega" ) -type LoginSuite struct { - suite.Suite - dir string - mockHelper *MockAzureHelper - azureLogin AzureLoginService -} - -func (suite *LoginSuite) BeforeTest(suiteName, testName string) { +func testLoginService(t *testing.T, m *MockAzureHelper) (*AzureLoginService, error) { dir, err := ioutil.TempDir("", "test_store") - Expect(err).To(BeNil()) - - suite.dir = dir - suite.mockHelper = &MockAzureHelper{} - suite.azureLogin, err = newAzureLoginServiceFromPath(filepath.Join(dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) + if err != nil { + return nil, err + } + t.Cleanup(func() { + _ = os.RemoveAll(dir) + }) + return newAzureLoginServiceFromPath(filepath.Join(dir, tokenStoreFilename), m) } -func (suite *LoginSuite) AfterTest(suiteName, testName string) { - err := os.RemoveAll(suite.dir) - Expect(err).To(BeNil()) -} - -func (suite *LoginSuite) TestRefreshInValidToken() { +func TestRefreshInValidToken(t *testing.T) { data := refreshTokenData("refreshToken") - suite.mockHelper.On("queryToken", data, "123456").Return(azureToken{ + m := &MockAzureHelper{} + m.On("queryToken", data, "123456").Return(azureToken{ RefreshToken: "newRefreshToken", AccessToken: "newAccessToken", ExpiresIn: 3600, Foci: "1", }, nil) - azureLogin, err := newAzureLoginServiceFromPath(filepath.Join(suite.dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) - suite.azureLogin = azureLogin - err = suite.azureLogin.tokenStore.writeLoginInfo(TokenInfo{ + azureLogin, err := testLoginService(t, m) + assert.NilError(t, err) + err = azureLogin.tokenStore.writeLoginInfo(TokenInfo{ TenantID: "123456", Token: oauth2.Token{ AccessToken: "accessToken", @@ -78,27 +65,34 @@ func (suite *LoginSuite) TestRefreshInValidToken() { TokenType: "Bearer", }, }) - Expect(err).To(BeNil()) + assert.NilError(t, err) - token, _ := suite.azureLogin.GetValidToken() + token, _ := azureLogin.GetValidToken() - Expect(token.AccessToken).To(Equal("newAccessToken")) - Expect(token.Expiry).To(BeTemporally(">", time.Now().Add(3500*time.Second))) + assert.Equal(t, token.AccessToken, "newAccessToken") + assert.Assert(t, time.Now().Add(3500*time.Second).Before(token.Expiry)) - storedToken, _ := suite.azureLogin.tokenStore.readToken() - Expect(storedToken.Token.AccessToken).To(Equal("newAccessToken")) - Expect(storedToken.Token.RefreshToken).To(Equal("newRefreshToken")) - Expect(storedToken.Token.Expiry).To(BeTemporally(">", time.Now().Add(3500*time.Second))) + storedToken, _ := azureLogin.tokenStore.readToken() + assert.Equal(t, storedToken.Token.AccessToken, "newAccessToken") + assert.Equal(t, storedToken.Token.RefreshToken, "newRefreshToken") + assert.Assert(t, time.Now().Add(3500*time.Second).Before(storedToken.Token.Expiry)) } -func (suite *LoginSuite) TestClearErrorMessageIfNotAlreadyLoggedIn() { - _, err := newAuthorizerFromLoginStorePath(filepath.Join(suite.dir, tokenStoreFilename)) - Expect(err.Error()).To(ContainSubstring("not logged in to azure, you need to run \"docker login azure\" first")) +func TestClearErrorMessageIfNotAlreadyLoggedIn(t *testing.T) { + dir, err := ioutil.TempDir("", "test_store") + assert.NilError(t, err) + t.Cleanup(func() { + _ = os.RemoveAll(dir) + }) + _, err = newAuthorizerFromLoginStorePath(filepath.Join(dir, tokenStoreFilename)) + assert.ErrorContains(t, err, "not logged in to azure, you need to run \"docker login azure\" first") } -func (suite *LoginSuite) TestDoesNotRefreshValidToken() { +func TestDoesNotRefreshValidToken(t *testing.T) { expiryDate := time.Now().Add(1 * time.Hour) - err := suite.azureLogin.tokenStore.writeLoginInfo(TokenInfo{ + azureLogin, err := testLoginService(t, nil) + assert.NilError(t, err) + err = azureLogin.tokenStore.writeLoginInfo(TokenInfo{ TenantID: "123456", Token: oauth2.Token{ AccessToken: "accessToken", @@ -107,37 +101,37 @@ func (suite *LoginSuite) TestDoesNotRefreshValidToken() { TokenType: "Bearer", }, }) - Expect(err).To(BeNil()) + assert.NilError(t, err) - token, _ := suite.azureLogin.GetValidToken() - - Expect(suite.mockHelper.Calls).To(BeEmpty()) - Expect(token.AccessToken).To(Equal("accessToken")) + token, _ := azureLogin.GetValidToken() + assert.Equal(t, token.AccessToken, "accessToken") } -func (suite *LoginSuite) TestInvalidLogin() { - suite.mockHelper.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { +func TestInvalidLogin(t *testing.T) { + m := &MockAzureHelper{} + m.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { redirectURL := args.Get(0).(string) err := queryKeyValue(redirectURL, "error", "access denied: login failed") - Expect(err).To(BeNil()) + assert.NilError(t, err) }) - azureLogin, err := newAzureLoginServiceFromPath(filepath.Join(suite.dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) + azureLogin, err := testLoginService(t, m) + assert.NilError(t, err) err = azureLogin.Login(context.TODO(), "") - Expect(err.Error()).To(BeEquivalentTo("no login code: login failed")) + assert.Error(t, err, "no login code: login failed") } -func (suite *LoginSuite) TestValidLogin() { +func TestValidLogin(t *testing.T) { var redirectURL string - suite.mockHelper.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { + m := &MockAzureHelper{} + m.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { redirectURL = args.Get(0).(string) err := queryKeyValue(redirectURL, "code", "123456879") - Expect(err).To(BeNil()) + assert.NilError(t, err) }) - suite.mockHelper.On("queryToken", mock.MatchedBy(func(data url.Values) bool { + m.On("queryToken", mock.MatchedBy(func(data url.Values) bool { //Need a matcher here because the value of redirectUrl is not known until executing openAzureLoginPage return reflect.DeepEqual(data, url.Values{ "grant_type": []string{"authorization_code"}, @@ -155,38 +149,39 @@ func (suite *LoginSuite) TestValidLogin() { authBody := `{"value":[{"id":"/tenants/12345a7c-c56d-43e8-9549-dd230ce8a038","tenantId":"12345a7c-c56d-43e8-9549-dd230ce8a038"}]}` - suite.mockHelper.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) + m.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) data := refreshTokenData("firstRefreshToken") - suite.mockHelper.On("queryToken", data, "12345a7c-c56d-43e8-9549-dd230ce8a038").Return(azureToken{ + m.On("queryToken", data, "12345a7c-c56d-43e8-9549-dd230ce8a038").Return(azureToken{ RefreshToken: "newRefreshToken", AccessToken: "newAccessToken", ExpiresIn: 3600, Foci: "1", }, nil) - azureLogin, err := newAzureLoginServiceFromPath(filepath.Join(suite.dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) + azureLogin, err := testLoginService(t, m) + assert.NilError(t, err) err = azureLogin.Login(context.TODO(), "") - Expect(err).To(BeNil()) + assert.NilError(t, err) - loginToken, err := suite.azureLogin.tokenStore.readToken() - Expect(err).To(BeNil()) - Expect(loginToken.Token.AccessToken).To(Equal("newAccessToken")) - Expect(loginToken.Token.RefreshToken).To(Equal("newRefreshToken")) - Expect(loginToken.Token.Expiry).To(BeTemporally(">", time.Now().Add(3500*time.Second))) - Expect(loginToken.TenantID).To(Equal("12345a7c-c56d-43e8-9549-dd230ce8a038")) - Expect(loginToken.Token.Type()).To(Equal("Bearer")) + loginToken, err := azureLogin.tokenStore.readToken() + assert.NilError(t, err) + assert.Equal(t, loginToken.Token.AccessToken, "newAccessToken") + assert.Equal(t, loginToken.Token.RefreshToken, "newRefreshToken") + assert.Assert(t, time.Now().Add(3500*time.Second).Before(loginToken.Token.Expiry)) + assert.Equal(t, loginToken.TenantID, "12345a7c-c56d-43e8-9549-dd230ce8a038") + assert.Equal(t, loginToken.Token.Type(), "Bearer") } -func (suite *LoginSuite) TestValidLoginRequestedTenant() { +func TestValidLoginRequestedTenant(t *testing.T) { var redirectURL string - suite.mockHelper.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { + m := &MockAzureHelper{} + m.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { redirectURL = args.Get(0).(string) err := queryKeyValue(redirectURL, "code", "123456879") - Expect(err).To(BeNil()) + assert.NilError(t, err) }) - suite.mockHelper.On("queryToken", mock.MatchedBy(func(data url.Values) bool { + m.On("queryToken", mock.MatchedBy(func(data url.Values) bool { //Need a matcher here because the value of redirectUrl is not known until executing openAzureLoginPage return reflect.DeepEqual(data, url.Values{ "grant_type": []string{"authorization_code"}, @@ -205,38 +200,39 @@ func (suite *LoginSuite) TestValidLoginRequestedTenant() { authBody := `{"value":[{"id":"/tenants/00000000-c56d-43e8-9549-dd230ce8a038","tenantId":"00000000-c56d-43e8-9549-dd230ce8a038"}, {"id":"/tenants/12345a7c-c56d-43e8-9549-dd230ce8a038","tenantId":"12345a7c-c56d-43e8-9549-dd230ce8a038"}]}` - suite.mockHelper.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) + m.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) data := refreshTokenData("firstRefreshToken") - suite.mockHelper.On("queryToken", data, "12345a7c-c56d-43e8-9549-dd230ce8a038").Return(azureToken{ + m.On("queryToken", data, "12345a7c-c56d-43e8-9549-dd230ce8a038").Return(azureToken{ RefreshToken: "newRefreshToken", AccessToken: "newAccessToken", ExpiresIn: 3600, Foci: "1", }, nil) - azureLogin, err := newAzureLoginServiceFromPath(filepath.Join(suite.dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) + azureLogin, err := testLoginService(t, m) + assert.NilError(t, err) err = azureLogin.Login(context.TODO(), "12345a7c-c56d-43e8-9549-dd230ce8a038") - Expect(err).To(BeNil()) + assert.NilError(t, err) - loginToken, err := suite.azureLogin.tokenStore.readToken() - Expect(err).To(BeNil()) - Expect(loginToken.Token.AccessToken).To(Equal("newAccessToken")) - Expect(loginToken.Token.RefreshToken).To(Equal("newRefreshToken")) - Expect(loginToken.Token.Expiry).To(BeTemporally(">", time.Now().Add(3500*time.Second))) - Expect(loginToken.TenantID).To(Equal("12345a7c-c56d-43e8-9549-dd230ce8a038")) - Expect(loginToken.Token.Type()).To(Equal("Bearer")) + loginToken, err := azureLogin.tokenStore.readToken() + assert.NilError(t, err) + assert.Equal(t, loginToken.Token.AccessToken, "newAccessToken") + assert.Equal(t, loginToken.Token.RefreshToken, "newRefreshToken") + assert.Assert(t, time.Now().Add(3500*time.Second).Before(loginToken.Token.Expiry)) + assert.Equal(t, loginToken.TenantID, "12345a7c-c56d-43e8-9549-dd230ce8a038") + assert.Equal(t, loginToken.Token.Type(), "Bearer") } -func (suite *LoginSuite) TestLoginNoTenant() { +func TestLoginNoTenant(t *testing.T) { var redirectURL string - suite.mockHelper.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { + m := &MockAzureHelper{} + m.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { redirectURL = args.Get(0).(string) err := queryKeyValue(redirectURL, "code", "123456879") - Expect(err).To(BeNil()) + assert.NilError(t, err) }) - suite.mockHelper.On("queryToken", mock.MatchedBy(func(data url.Values) bool { + m.On("queryToken", mock.MatchedBy(func(data url.Values) bool { //Need a matcher here because the value of redirectUrl is not known until executing openAzureLoginPage return reflect.DeepEqual(data, url.Values{ "grant_type": []string{"authorization_code"}, @@ -253,24 +249,25 @@ func (suite *LoginSuite) TestLoginNoTenant() { }, nil) authBody := `{"value":[{"id":"/tenants/12345a7c-c56d-43e8-9549-dd230ce8a038","tenantId":"12345a7c-c56d-43e8-9549-dd230ce8a038"}]}` - suite.mockHelper.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) + m.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) - azureLogin, err := newAzureLoginServiceFromPath(filepath.Join(suite.dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) + azureLogin, err := testLoginService(t, m) + assert.NilError(t, err) err = azureLogin.Login(context.TODO(), "00000000-c56d-43e8-9549-dd230ce8a038") - Expect(err.Error()).To(BeEquivalentTo("could not find requested azure tenant 00000000-c56d-43e8-9549-dd230ce8a038: login failed")) + assert.Error(t, err, "could not find requested azure tenant 00000000-c56d-43e8-9549-dd230ce8a038: login failed") } -func (suite *LoginSuite) TestLoginRequestedTenantNotFound() { +func TestLoginRequestedTenantNotFound(t *testing.T) { var redirectURL string - suite.mockHelper.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { + m := &MockAzureHelper{} + m.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { redirectURL = args.Get(0).(string) err := queryKeyValue(redirectURL, "code", "123456879") - Expect(err).To(BeNil()) + assert.NilError(t, err) }) - suite.mockHelper.On("queryToken", mock.MatchedBy(func(data url.Values) bool { + m.On("queryToken", mock.MatchedBy(func(data url.Values) bool { //Need a matcher here because the value of redirectUrl is not known until executing openAzureLoginPage return reflect.DeepEqual(data, url.Values{ "grant_type": []string{"authorization_code"}, @@ -287,24 +284,25 @@ func (suite *LoginSuite) TestLoginRequestedTenantNotFound() { }, nil) authBody := `{"value":[]}` - suite.mockHelper.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) + m.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 200, nil) - azureLogin, err := newAzureLoginServiceFromPath(filepath.Join(suite.dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) + azureLogin, err := testLoginService(t, m) + assert.NilError(t, err) err = azureLogin.Login(context.TODO(), "") - Expect(err.Error()).To(BeEquivalentTo("could not find azure tenant: login failed")) + assert.Error(t, err, "could not find azure tenant: login failed") } -func (suite *LoginSuite) TestLoginAuthorizationFailed() { +func TestLoginAuthorizationFailed(t *testing.T) { var redirectURL string - suite.mockHelper.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { + m := &MockAzureHelper{} + m.On("openAzureLoginPage", mock.AnythingOfType("string")).Run(func(args mock.Arguments) { redirectURL = args.Get(0).(string) err := queryKeyValue(redirectURL, "code", "123456879") - Expect(err).To(BeNil()) + assert.NilError(t, err) }) - suite.mockHelper.On("queryToken", mock.MatchedBy(func(data url.Values) bool { + m.On("queryToken", mock.MatchedBy(func(data url.Values) bool { //Need a matcher here because the value of redirectUrl is not known until executing openAzureLoginPage return reflect.DeepEqual(data, url.Values{ "grant_type": []string{"authorization_code"}, @@ -322,13 +320,13 @@ func (suite *LoginSuite) TestLoginAuthorizationFailed() { authBody := `[access denied]` - suite.mockHelper.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 400, nil) + m.On("queryAuthorizationAPI", authorizationURL, "Bearer firstAccessToken").Return([]byte(authBody), 400, nil) - azureLogin, err := newAzureLoginServiceFromPath(filepath.Join(suite.dir, tokenStoreFilename), suite.mockHelper) - Expect(err).To(BeNil()) + azureLogin, err := testLoginService(t, m) + assert.NilError(t, err) err = azureLogin.Login(context.TODO(), "") - Expect(err.Error()).To(BeEquivalentTo("unable to login status code 400: [access denied]: login failed")) + assert.Error(t, err, "unable to login status code 400: [access denied]: login failed") } func refreshTokenData(refreshToken string) url.Values { @@ -342,7 +340,9 @@ func refreshTokenData(refreshToken string) url.Values { func queryKeyValue(redirectURL string, key string, value string) error { req, err := http.NewRequest("GET", redirectURL, nil) - Expect(err).To(BeNil()) + if err != nil { + return err + } q := req.URL.Query() q.Add(key, value) req.URL.RawQuery = q.Encode() @@ -351,11 +351,6 @@ func queryKeyValue(redirectURL string, key string, value string) error { return err } -func TestLoginSuite(t *testing.T) { - RegisterTestingT(t) - suite.Run(t, new(LoginSuite)) -} - type MockAzureHelper struct { mock.Mock } diff --git a/aci/login/tokenStore.go b/aci/login/token_store.go similarity index 100% rename from aci/login/tokenStore.go rename to aci/login/token_store.go diff --git a/aci/login/tokenStore_test.go b/aci/login/token_store_test.go similarity index 57% rename from aci/login/tokenStore_test.go rename to aci/login/token_store_test.go index 3e9638c4e..b6d05724c 100644 --- a/aci/login/tokenStore_test.go +++ b/aci/login/token_store_test.go @@ -17,54 +17,43 @@ package login import ( - "errors" "io/ioutil" "os" "path/filepath" "testing" - . "github.com/onsi/gomega" - "github.com/stretchr/testify/suite" + "gotest.tools/v3/assert" ) -type tokenStoreTestSuite struct { - suite.Suite -} - -func (suite *tokenStoreTestSuite) TestCreateStoreFromExistingFolder() { +func TestCreateStoreFromExistingFolder(t *testing.T) { existingDir, err := ioutil.TempDir("", "test_store") - Expect(err).To(BeNil()) + assert.NilError(t, err) storePath := filepath.Join(existingDir, tokenStoreFilename) store, err := newTokenStore(storePath) - Expect(err).To(BeNil()) - Expect((store.filePath)).To(Equal(storePath)) + assert.NilError(t, err) + assert.Equal(t, store.filePath, storePath) } -func (suite *tokenStoreTestSuite) TestCreateStoreFromNonExistingFolder() { +func TestCreateStoreFromNonExistingFolder(t *testing.T) { existingDir, err := ioutil.TempDir("", "test_store") - Expect(err).To(BeNil()) + assert.NilError(t, err) storePath := filepath.Join(existingDir, "new", tokenStoreFilename) store, err := newTokenStore(storePath) - Expect(err).To(BeNil()) - Expect((store.filePath)).To(Equal(storePath)) + assert.NilError(t, err) + assert.Equal(t, store.filePath, storePath) newDir, err := os.Stat(filepath.Join(existingDir, "new")) - Expect(err).To(BeNil()) - Expect(newDir.Mode().IsDir()).To(BeTrue()) + assert.NilError(t, err) + assert.Assert(t, newDir.Mode().IsDir()) } -func (suite *tokenStoreTestSuite) TestErrorIfParentFolderIsAFile() { +func TestErrorIfParentFolderIsAFile(t *testing.T) { existingDir, err := ioutil.TempFile("", "test_store") - Expect(err).To(BeNil()) + assert.NilError(t, err) storePath := filepath.Join(existingDir.Name(), tokenStoreFilename) _, err = newTokenStore(storePath) - Expect(err).To(MatchError(errors.New("cannot use path " + storePath + " ; " + existingDir.Name() + " already exists and is not a directory"))) -} - -func TestTokenStoreSuite(t *testing.T) { - RegisterTestingT(t) - suite.Run(t, new(tokenStoreTestSuite)) + assert.Error(t, err, "cannot use path "+storePath+" ; "+existingDir.Name()+" already exists and is not a directory") } diff --git a/aci/resourcegroup.go b/aci/resource_group.go similarity index 100% rename from aci/resourcegroup.go rename to aci/resource_group.go