Skip to content

Commit

Permalink
Chore: Optimize environments by name query (#932)
Browse files Browse the repository at this point in the history
* change Environments method to EnvironmentsByName

* rename method to EnvironmentsByName and pass the name qs

* refactor getEnvironmentByName to pass the name parameter to the api client

* adapt tests to the get env by name refactor

* update mocks

* fix test

* fix tests

* changed readme to treat arm as default instead of amd
  • Loading branch information
yaronya authored Aug 14, 2024
1 parent 292562f commit 6e3153f
Show file tree
Hide file tree
Showing 7 changed files with 41 additions and 43 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ resource "env0_template" "example" {
### Run local version of the provider

- Build - `./build.sh`
- Create the plugins folder - `mkdir -p ~/.terraform.d/plugins/terraform.env0.com/local/env0/6.6.6/darwin_amd64` (for M1 processor, replace `amd64` with `arm64`)
- Copy the built binary - `cp ./terraform-provider-env0 ~/.terraform.d/plugins/terraform.env0.com/local/env0/6.6.6/darwin_amd64` (Replace `darwin` with `linux` on Linux)
- Create the plugins folder - `mkdir -p ~/.terraform.d/plugins/terraform.env0.com/local/env0/6.6.6/darwin_arm64` (for Intel processor, replace `arm64` with `amd64`)
- Copy the built binary - `cp ./terraform-provider-env0 ~/.terraform.d/plugins/terraform.env0.com/local/env0/6.6.6/darwin_arm64` (Replace `darwin` with `linux` on Linux)
- Require the local provider in your `main.tf` -

```
Expand Down
2 changes: 1 addition & 1 deletion client/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ type ApiClientInterface interface {
TeamCreate(payload TeamCreatePayload) (Team, error)
TeamUpdate(id string, payload TeamUpdatePayload) (Team, error)
TeamDelete(id string) error
Environments() ([]Environment, error)
EnvironmentsByName(name string) ([]Environment, error)
ProjectEnvironments(projectId string) ([]Environment, error)
Environment(id string) (Environment, error)
EnvironmentCreate(payload EnvironmentCreate) (Environment, error)
Expand Down
12 changes: 6 additions & 6 deletions client/api_client_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions client/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package client
import (
"encoding/json"
"fmt"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

Expand Down Expand Up @@ -213,14 +212,15 @@ func (Environment) getEndpoint() string {
return "/environments"
}

func (client *ApiClient) Environments() ([]Environment, error) {
func (client *ApiClient) EnvironmentsByName(name string) ([]Environment, error) {
organizationId, err := client.OrganizationId()
if err != nil {
return nil, err
}

return getAll(client, map[string]string{
"organizationId": organizationId,
"name": name,
})
}

Expand Down
22 changes: 17 additions & 5 deletions client/environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,17 @@ var _ = Describe("Environment Client", func() {
BeforeEach(func() {
mockOrganizationIdCall(organizationId)
httpCall = mockHttpClient.EXPECT().
Get("/environments", gomock.Any(), gomock.Any()).
Get("/environments", map[string]string{
"limit": "100",
"offset": "0",
"organizationId": organizationId,
"name": mockEnvironment.Name,
}, gomock.Any()).
Do(func(path string, request interface{}, response *[]Environment) {
*response = mockEnvironments
})

environments, err = apiClient.Environments()
environments, err = apiClient.EnvironmentsByName(mockEnvironment.Name)
})

It("Should send GET request", func() {
Expand Down Expand Up @@ -75,6 +80,7 @@ var _ = Describe("Environment Client", func() {
"offset": "0",
"limit": "100",
"organizationId": organizationId,
"name": mockEnvironment.Name,
}, gomock.Any()).
Do(func(path string, request interface{}, response *[]Environment) {
*response = environmentsP1
Expand All @@ -85,12 +91,13 @@ var _ = Describe("Environment Client", func() {
"offset": "100",
"limit": "100",
"organizationId": organizationId,
"name": mockEnvironment.Name,
}, gomock.Any()).
Do(func(path string, request interface{}, response *[]Environment) {
*response = environmentsP2
}).Times(1)

environments, err = apiClient.Environments()
environments, err = apiClient.EnvironmentsByName(mockEnvironment.Name)
})

It("Should return the environments", func() {
Expand Down Expand Up @@ -143,10 +150,15 @@ var _ = Describe("Environment Client", func() {
expectedErr := errors.New("some error")
mockOrganizationIdCall(organizationId)
httpCall = mockHttpClient.EXPECT().
Get("/environments", gomock.Any(), gomock.Any()).
Get("/environments", map[string]string{
"limit": "100",
"offset": "0",
"organizationId": organizationId,
"name": mockEnvironment.Name,
}, gomock.Any()).
Return(expectedErr)

_, err = apiClient.Environments()
_, err = apiClient.EnvironmentsByName(mockEnvironment.Name)
Expect(expectedErr).Should(Equal(err))
})
})
Expand Down
24 changes: 6 additions & 18 deletions env0/data_environment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,6 @@ func TestEnvironmentDataSource(t *testing.T) {
},
}

otherEnvironment := client.Environment{
Id: "other-id",
Name: "other-name",
}

environmentWithSameName := client.Environment{
Id: "other-id",
Name: environment.Name,
Expand Down Expand Up @@ -109,7 +104,7 @@ func TestEnvironmentDataSource(t *testing.T) {

mockListEnvironmentsCall := func(returnValue []client.Environment, tem *client.Template) func(mockFunc *client.MockApiClientInterface) {
return func(mock *client.MockApiClientInterface) {
mock.EXPECT().Environments().AnyTimes().Return(returnValue, nil)
mock.EXPECT().EnvironmentsByName(environment.Name).AnyTimes().Return(returnValue, nil)
if tem != nil {
mock.EXPECT().Template(environment.LatestDeploymentLog.BlueprintId).AnyTimes().Return(*tem, nil)
}
Expand All @@ -126,21 +121,21 @@ func TestEnvironmentDataSource(t *testing.T) {
t.Run("By Name", func(t *testing.T) {
runUnitTest(t,
getValidTestCase(environmentFieldsByName),
mockListEnvironmentsCall([]client.Environment{environment, otherEnvironment}, &template),
mockListEnvironmentsCall([]client.Environment{environment}, &template),
)
})

t.Run("By Name with Archived", func(t *testing.T) {
runUnitTest(t,
getValidTestCase(environmentFieldsByNameWithExclude),
mockListEnvironmentsCall([]client.Environment{environment, archivedEnvironment, otherEnvironment}, &template),
mockListEnvironmentsCall([]client.Environment{environment, archivedEnvironment}, &template),
)
})

t.Run("By Name with Different Project Id", func(t *testing.T) {
runUnitTest(t,
getValidTestCase(environmentFieldByNameWithProjectId),
mockListEnvironmentsCall([]client.Environment{environment, environmentWithSameName, otherEnvironment}, &template),
mockListEnvironmentsCall([]client.Environment{environment, environmentWithSameName}, &template),
)
})

Expand All @@ -154,14 +149,14 @@ func TestEnvironmentDataSource(t *testing.T) {
t.Run("Throw error when by name and more than one environment exists", func(t *testing.T) {
runUnitTest(t,
getErrorTestCase(environmentFieldsByName, "Found multiple environments for name"),
mockListEnvironmentsCall([]client.Environment{environment, environment, otherEnvironment}, nil),
mockListEnvironmentsCall([]client.Environment{environment, environment}, nil),
)
})

t.Run("Throw error when by name and more than one environment exists (archived use-case)", func(t *testing.T) {
runUnitTest(t,
getErrorTestCase(environmentFieldsByName, "Found multiple environments for name"),
mockListEnvironmentsCall([]client.Environment{environment, archivedEnvironment, otherEnvironment}, nil),
mockListEnvironmentsCall([]client.Environment{environment, archivedEnvironment}, nil),
)
})

Expand All @@ -171,11 +166,4 @@ func TestEnvironmentDataSource(t *testing.T) {
mockListEnvironmentsCall([]client.Environment{}, nil),
)
})

t.Run("Throw error when by name and no environments found with that name", func(t *testing.T) {
runUnitTest(t,
getErrorTestCase(environmentFieldsByName, "Could not find an env0 environment with name"),
mockListEnvironmentsCall([]client.Environment{otherEnvironment}, nil),
)
})
}
16 changes: 7 additions & 9 deletions env0/resource_environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -1336,13 +1336,13 @@ func getConfigurationVariableFromSchema(variable map[string]interface{}) client.

func getEnvironmentByName(meta interface{}, name string, projectId string, excludeArchived bool) (client.Environment, diag.Diagnostics) {
apiClient := meta.(client.ApiClientInterface)
environments, err := apiClient.Environments()
environmentsByName, err := apiClient.EnvironmentsByName(name)
if err != nil {
return client.Environment{}, diag.Errorf("Could not get Environment: %v", err)
}

var environmentsByName []client.Environment
for _, candidate := range environments {
var filteredEnvironments []client.Environment
for _, candidate := range environmentsByName {
if excludeArchived && candidate.IsArchived != nil && *candidate.IsArchived {
continue
}
Expand All @@ -1351,20 +1351,18 @@ func getEnvironmentByName(meta interface{}, name string, projectId string, exclu
continue
}

if candidate.Name == name {
environmentsByName = append(environmentsByName, candidate)
}
filteredEnvironments = append(filteredEnvironments, candidate)
}

if len(environmentsByName) > 1 {
if len(filteredEnvironments) > 1 {
return client.Environment{}, diag.Errorf("Found multiple environments for name: %s. Use ID instead or make sure environment names are unique %v", name, environmentsByName)
}

if len(environmentsByName) == 0 {
if len(filteredEnvironments) == 0 {
return client.Environment{}, diag.Errorf("Could not find an env0 environment with name %s", name)
}

return environmentsByName[0], nil
return filteredEnvironments[0], nil
}

func getEnvironmentById(environmentId string, meta interface{}) (client.Environment, diag.Diagnostics) {
Expand Down

0 comments on commit 6e3153f

Please sign in to comment.