Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ linters:
- usetesting # Reports uses of functions with replacement inside the testing package. [auto-fix]
- wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false]
- whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true]
- wsl # Whitespace Linter - Forces you to use empty lines! [fast: true, auto-fix: false]
- zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg` [fast: false, auto-fix: false]

disable:
Expand All @@ -101,7 +102,6 @@ linters:
- nestif # Reports deeply nested if statements [fast: true, auto-fix: false]
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false]
- varnamelen # checks that the length of a variable's name matches its scope [fast: false, auto-fix: false]
- wsl # Whitespace Linter - Forces you to use empty lines! [fast: true, auto-fix: false]

linters-settings:
goconst:
Expand Down
2 changes: 2 additions & 0 deletions internal/acctest/acctest.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type TestTools struct {

func NewTestTools(t *testing.T) *TestTools {
t.Helper()

ctx := context.Background()

folder, err := os.Getwd()
Expand Down Expand Up @@ -142,6 +143,7 @@ func compareJSONBodies(expected, actual map[string]interface{}) bool {
// We do not want to generate new cassettes for each new features
continue
}

if !compareJSONFields(expectedValue, actual[key]) {
return false
}
Expand Down
7 changes: 7 additions & 0 deletions internal/acctest/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@ func CheckResourceIDChanged(resourceName string, resourceID *string) resource.Te
if resourceID == nil || *resourceID == "" {
return errors.New("resourceID was not set")
}

rs, ok := s.RootModule().Resources[resourceName]
if !ok {
return fmt.Errorf("resource was not found: %s", resourceName)
}

if *resourceID == rs.Primary.ID {
return errors.New("resource ID persisted when it should have changed")
}

*resourceID = rs.Primary.ID

return nil
Expand All @@ -39,9 +42,11 @@ func CheckResourceIDPersisted(resourceName string, resourceID *string) resource.
if !ok {
return fmt.Errorf("resource was not found: %s", resourceName)
}

if *resourceID != "" && *resourceID != rs.Primary.ID {
return errors.New("resource ID changed when it should have persisted")
}

*resourceID = rs.Primary.ID

return nil
Expand Down Expand Up @@ -84,10 +89,12 @@ func CheckResourceAttrFunc(name string, key string, test func(string) error) res
if !ok {
return fmt.Errorf("resource not found: %s", name)
}

value, ok := rs.Primary.Attributes[key]
if !ok {
return fmt.Errorf("key not found: %s", key)
}

err := test(value)
if err != nil {
return fmt.Errorf("test for %s %s did not pass test: %s", name, key, err)
Expand Down
1 change: 1 addition & 0 deletions internal/acctest/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func init() {

// check if the test domain is not a Scaleway reserved domain
isReserved := false

for _, reservedDomain := range reservedDomains {
if reservedDomain.MatchString(TestDomain) {
isReserved = true
Expand Down
12 changes: 12 additions & 0 deletions internal/acctest/fixtures.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func CreateFakeIAMManager(tt *TestTools) (*account.Project, *iam.APIKey, FakeSid
iamPolicyName := sdkacctest.RandomWithPrefix("test-acc-scaleway-iam-policy")

projectAPI := account.NewProjectAPI(tt.Meta.ScwClient())

project, err := projectAPI.CreateProject(&account.ProjectAPICreateProjectRequest{
Name: projectName,
})
Expand All @@ -74,13 +75,15 @@ func CreateFakeIAMManager(tt *TestTools) (*account.Project, *iam.APIKey, FakeSid

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return projectAPI.DeleteProject(&account.ProjectAPIDeleteProjectRequest{
ProjectID: project.ID,
})
})

iamAPI := iam.NewAPI(tt.Meta.ScwClient())

iamApplication, err := iamAPI.CreateApplication(&iam.CreateApplicationRequest{
Name: iamApplicationName,
})
Expand All @@ -91,6 +94,7 @@ func CreateFakeIAMManager(tt *TestTools) (*account.Project, *iam.APIKey, FakeSid

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return iamAPI.DeleteApplication(&iam.DeleteApplicationRequest{
ApplicationID: iamApplication.ID,
Expand All @@ -114,6 +118,7 @@ func CreateFakeIAMManager(tt *TestTools) (*account.Project, *iam.APIKey, FakeSid

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return iamAPI.DeletePolicy(&iam.DeletePolicyRequest{
PolicyID: iamPolicy.ID,
Expand All @@ -131,6 +136,7 @@ func CreateFakeIAMManager(tt *TestTools) (*account.Project, *iam.APIKey, FakeSid

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return iamAPI.DeleteAPIKey(&iam.DeleteAPIKeyRequest{
AccessKey: iamAPIKey.AccessKey,
Expand Down Expand Up @@ -163,6 +169,7 @@ func CreateFakeSideProject(tt *TestTools) (*account.Project, *iam.APIKey, FakeSi
iamPolicyName := sdkacctest.RandomWithPrefix("test-acc-scaleway-iam-policy")

projectAPI := account.NewProjectAPI(tt.Meta.ScwClient())

project, err := projectAPI.CreateProject(&account.ProjectAPICreateProjectRequest{
Name: projectName,
})
Expand All @@ -173,13 +180,15 @@ func CreateFakeSideProject(tt *TestTools) (*account.Project, *iam.APIKey, FakeSi

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return projectAPI.DeleteProject(&account.ProjectAPIDeleteProjectRequest{
ProjectID: project.ID,
})
})

iamAPI := iam.NewAPI(tt.Meta.ScwClient())

iamApplication, err := iamAPI.CreateApplication(&iam.CreateApplicationRequest{
Name: iamApplicationName,
})
Expand All @@ -190,6 +199,7 @@ func CreateFakeSideProject(tt *TestTools) (*account.Project, *iam.APIKey, FakeSi

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return iamAPI.DeleteApplication(&iam.DeleteApplicationRequest{
ApplicationID: iamApplication.ID,
Expand All @@ -213,6 +223,7 @@ func CreateFakeSideProject(tt *TestTools) (*account.Project, *iam.APIKey, FakeSi

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return iamAPI.DeletePolicy(&iam.DeletePolicyRequest{
PolicyID: iamPolicy.ID,
Expand All @@ -230,6 +241,7 @@ func CreateFakeSideProject(tt *TestTools) (*account.Project, *iam.APIKey, FakeSi

return nil, nil, nil, err
}

terminateFunctions = append(terminateFunctions, func() error {
return iamAPI.DeleteAPIKey(&iam.DeleteAPIKeyRequest{
AccessKey: iamAPIKey.AccessKey,
Expand Down
3 changes: 3 additions & 0 deletions internal/acctest/sweepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

func Sweep(f func(scwClient *scw.Client) error) error {
ctx := context.Background()

m, err := meta.NewMeta(ctx, &meta.Config{
TerraformVersion: "terraform-tests",
})
Expand All @@ -26,6 +27,7 @@ func SweepZones(zones []scw.Zone, f func(scwClient *scw.Client, zone scw.Zone) e
if err != nil {
return err
}

err = f(client, zone)
if err != nil {
logging.L.Warningf("error running sweepZones, ignoring: %s", err)
Expand All @@ -52,6 +54,7 @@ func SweepRegions(regions []scw.Region, f func(scwClient *scw.Client, region scw
// functions for a given zone
func sharedClientForZone(zone scw.Zone) (*scw.Client, error) {
ctx := context.Background()

m, err := meta.NewMeta(ctx, &meta.Config{
TerraformVersion: "terraform-tests",
ForceZone: zone,
Expand Down
4 changes: 4 additions & 0 deletions internal/acctest/validate_cassettes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,11 @@ func exceptionsCassettesCases() map[string]struct{} {
func getTestFiles() (map[string]struct{}, error) {
filesMap := make(map[string]struct{})
exceptions := exceptionsCassettesCases()

err := filepath.WalkDir("../services", func(path string, _ fs.DirEntry, _ error) error {
isCassette := strings.Contains(path, "cassette")
_, isException := exceptions[path]

if isCassette && !isException {
filesMap[fileNameWithoutExtSuffix(path)] = struct{}{}
}
Expand Down Expand Up @@ -74,6 +76,7 @@ func checkErrorCode(c *cassette.Cassette) error {

func checkErrCodeExcept(i *cassette.Interaction, c *cassette.Cassette, codes ...int) bool {
exceptions := exceptionsCassettesCases()

_, isException := exceptions[c.File]
if isException {
return isException
Expand All @@ -82,6 +85,7 @@ func checkErrCodeExcept(i *cassette.Interaction, c *cassette.Cassette, codes ...
if strings.Contains(i.Response.Body, mnq.AWSErrNonExistentQueue) && i.Response.Code == 400 {
return true
}

if i.Response.Code >= 400 {
for _, httpCode := range codes {
if i.Response.Code == httpCode {
Expand Down
12 changes: 12 additions & 0 deletions internal/acctest/vcr.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ var BodyMatcherIgnore = []string{
// getTestFilePath returns a valid filename path based on the go test name and suffix. (Take care of non fs friendly char)
func getTestFilePath(t *testing.T, pkgFolder string, suffix string) string {
t.Helper()

specialChars := regexp.MustCompile(`[\\?%*:|"<>. ]`)

// Replace nested tests separators.
Expand Down Expand Up @@ -91,6 +92,7 @@ func compareFormBodies(expected, actual url.Values) bool {
// We do not want to generate new cassettes for each new features
continue
}

if !compareJSONFields(expectedValue, actual[key]) {
return false
}
Expand Down Expand Up @@ -125,6 +127,7 @@ func cassetteBodyMatcher(actualRequest *http.Request, cassetteRequest cassette.R
if err != nil {
panic(fmt.Errorf("cassette body matcher: failed to copy actualRequest body: %w", err)) // lintignore: R009
}

actualRawBody, err := io.ReadAll(actualBody)
if err != nil {
panic(fmt.Errorf("cassette body matcher: failed to read actualRequest body: %w", err)) // lintignore: R009
Expand Down Expand Up @@ -186,10 +189,12 @@ func cassetteMatcher(actual *http.Request, expected cassette.Request) bool {
actualURL := actual.URL
actualURLValues := actualURL.Query()
expectedURLValues := expectedURL.Query()

for _, query := range QueryMatcherIgnore {
actualURLValues.Del(query)
expectedURLValues.Del(query)
}

actualURL.RawQuery = actualURLValues.Encode()
expectedURL.RawQuery = expectedURLValues.Encode()

Expand All @@ -199,6 +204,7 @@ func cassetteMatcher(actual *http.Request, expected cassette.Request) bool {
if !strings.HasSuffix(expectedURL.Host, "scw.cloud") {
return false
}

actualS3Host := strings.Split(actualURL.Host, ".")
expectedS3Host := strings.Split(expectedURL.Host, ".")

Expand All @@ -212,6 +218,7 @@ func cassetteMatcher(actual *http.Request, expected cassette.Request) bool {
if strings.Contains(actualBucket, "-") {
actualBucket = actualBucket[:strings.LastIndex(actualBucket, "-")]
}

if strings.Contains(expectedBucket, "-") {
expectedBucket = expectedBucket[:strings.LastIndex(expectedBucket, "-")]
}
Expand All @@ -230,20 +237,24 @@ func cassetteMatcher(actual *http.Request, expected cassette.Request) bool {

func cassetteSensitiveFieldsAnonymizer(i *cassette.Interaction) error {
var jsonBody map[string]interface{}

err := json.Unmarshal([]byte(i.Response.Body), &jsonBody)
if err != nil {
//nolint:nilerr
return nil
}

for key, value := range SensitiveFields {
if _, ok := jsonBody[key]; ok {
jsonBody[key] = value
}
}

anonymizedBody, err := json.Marshal(jsonBody)
if err != nil {
return fmt.Errorf("failed to marshal anonymized body: %w", err)
}

i.Response.Body = string(anonymizedBody)

return nil
Expand All @@ -257,6 +268,7 @@ func cassetteSensitiveFieldsAnonymizer(i *cassette.Interaction) error {
// closed and saved after the requests.
func getHTTPRecoder(t *testing.T, pkgFolder string, update bool) (client *http.Client, cleanup func(), err error) {
t.Helper()

recorderMode := recorder.ModeReplayOnly
if update {
recorderMode = recorder.ModeRecordOnly
Expand Down
2 changes: 2 additions & 0 deletions internal/datasource/schemas.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ func NewRegionalID(idI interface{}, fallBackRegion scw.Region) string {
// source: https://github.com/hashicorp/terraform-provider-google/blob/main/google/tpgresource/datasource_helpers.go
func SchemaFromResourceSchema(rs map[string]*schema.Schema) map[string]*schema.Schema {
ds := make(map[string]*schema.Schema, len(rs))

for k, v := range rs {
dv := &schema.Schema{
Computed: true,
Expand Down Expand Up @@ -69,6 +70,7 @@ func SchemaFromResourceSchema(rs map[string]*schema.Schema) map[string]*schema.S
// Elem of all other types are copied as-is
dv.Elem = v.Elem
}

ds[k] = dv
}

Expand Down
2 changes: 2 additions & 0 deletions internal/datasource/search.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
// It returns the first matching element and an error if either no match is found or multiple matches are found.
func FindExact[T any](slice []T, finder func(T) bool, searchName string) (T, error) { //nolint:ireturn
var found T

var foundFlag bool

for _, elem := range slice {
Expand All @@ -21,6 +22,7 @@ func FindExact[T any](slice []T, finder func(T) bool, searchName string) (T, err

return zero, fmt.Errorf("multiple elements found with the name %s", searchName)
}

found = elem
foundFlag = true
}
Expand Down
1 change: 1 addition & 0 deletions internal/dsf/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func GetStringListsFromState(key string, d *schema.ResourceData) ([]string, []st
for i, v := range oldList.([]interface{}) {
oldListStr[i] = fmt.Sprint(v)
}

for i, v := range newList.([]interface{}) {
newListStr[i] = fmt.Sprint(v)
}
Expand Down
4 changes: 4 additions & 0 deletions internal/dsf/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ func Duration(_, oldValue, newValue string, _ *schema.ResourceData) bool {
if oldValue == newValue {
return true
}

d1, err1 := time.ParseDuration(oldValue)
d2, err2 := time.ParseDuration(newValue)

if err1 != nil || err2 != nil {
return false
}
Expand All @@ -23,8 +25,10 @@ func TimeRFC3339(_, oldValue, newValue string, _ *schema.ResourceData) bool {
if oldValue == newValue {
return true
}

t1, err1 := time.Parse(time.RFC3339, oldValue)
t2, err2 := time.Parse(time.RFC3339, newValue)

if err1 != nil || err2 != nil {
return false
}
Expand Down
2 changes: 2 additions & 0 deletions internal/locality/ids.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ func ExpandID(id interface{}) string {

func ExpandIDs(data interface{}) []string {
expandedIDs := make([]string, 0, len(data.([]interface{})))

for _, s := range data.([]interface{}) {
if s == nil {
s = ""
}

expandedID := ExpandID(s.(string))
expandedIDs = append(expandedIDs, expandedID)
}
Expand Down
Loading
Loading