Skip to content

Commit c80066b

Browse files
committed
more tests added
1 parent 6510292 commit c80066b

File tree

3 files changed

+72
-11
lines changed

3 files changed

+72
-11
lines changed

epic/resouce_random_name.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,20 @@ func resourceRandomName() *schema.Resource {
4848
}
4949
}
5050

51+
// FOR TESTING ONLY!!
52+
func getDataDirPath() string {
53+
dataDir := os.Getenv("DATA_DIR") // Set to "../data" for go tests
54+
if dataDir == "" {
55+
dataDir = "data" // Default is "data" because that is what is required for users consuming the provider
56+
}
57+
return dataDir
58+
}
59+
5160
func loadNames(mediaType, title string) ([]string, error) {
5261
sanitizedTitle := strings.ReplaceAll(title, " ", "_")
5362
fileName := fmt.Sprintf("%s.json", sanitizedTitle)
54-
filePath := filepath.Join("data", mediaType, fileName)
63+
dataDirPath := filepath.FromSlash(getDataDirPath())
64+
filePath := filepath.Join(dataDirPath, mediaType, fileName)
5565

5666
data, err := os.ReadFile(filePath)
5767
if err != nil {

epic/resource_random_name_test.go

+39
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package epic
22

33
import (
4+
"regexp"
45
"testing"
56

67
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
@@ -9,6 +10,14 @@ import (
910

1011
// Acceptance tests. Set TF_ACC=1 env variable to enable.
1112
func TestAccEpicRandomName_basic(t *testing.T) {
13+
14+
// $env:DATA_DIR = "../data" or export DATA_DIR="../data"
15+
dataDir := getDataDirPath()
16+
17+
if err := LoadAndCacheMediaTypes(dataDir); err != nil {
18+
t.Fatalf("Failed to load media types: %v", err)
19+
}
20+
1221
resource.Test(t, resource.TestCase{
1322
Providers: map[string]*schema.Provider{
1423
"epic": Provider(),
@@ -21,6 +30,14 @@ func TestAccEpicRandomName_basic(t *testing.T) {
2130
resource.TestCheckResourceAttr("epic_random_name.test", "title", "lord of the rings"),
2231
),
2332
},
33+
{
34+
Config: testAccCheckEpicRandomNameConfig_invalidMediaType(),
35+
ExpectError: regexp.MustCompile(`'not_a_real_media' is not a recognized media type`),
36+
},
37+
{
38+
Config: testAccCheckEpicRandomNameConfig_invalidTitle(),
39+
ExpectError: regexp.MustCompile(`'fake_title' is not a valid title for media type 'movie'`),
40+
},
2441
},
2542
})
2643
}
@@ -35,3 +52,25 @@ resource "epic_random_name" "test" {
3552
}
3653
`
3754
}
55+
56+
func testAccCheckEpicRandomNameConfig_invalidMediaType() string {
57+
return `
58+
provider "epic" {}
59+
60+
resource "epic_random_name" "test_invalid_media_type" {
61+
media_type = "not_a_real_media"
62+
title = "lord of the rings"
63+
}
64+
`
65+
}
66+
67+
func testAccCheckEpicRandomNameConfig_invalidTitle() string {
68+
return `
69+
provider "epic" {}
70+
71+
resource "epic_random_name" "test_invalid_title" {
72+
media_type = "movie"
73+
title = "fake_title"
74+
}
75+
`
76+
}

epic/validate_data.go

+22-10
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,10 @@ import (
1111
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
1212
)
1313

14+
// validate_data.go ensures that the map of media_types to titles is cached during the plan.
15+
// I'm not actually sure if this carries over to the apply?
16+
// It also validates that the media_types in the /data directory contain a title provided as an input.
17+
1418
var mediaTypeCache map[string]map[string][]string
1519
var cacheLoaded bool
1620

@@ -23,11 +27,13 @@ type MediaTypeData struct {
2327
// LoadMediaTypes scans the specified dataDir directory, reads each subdirectory as a media type,
2428
// and loads each JSON file in those subdirectories as titles of that media type.
2529
func LoadMediaTypes(dataDir string) (map[string]map[string][]string, error) {
30+
2631
// This map will hold the media type as key and a map of titles with their names as value.
2732
mediaTypes := make(map[string]map[string][]string)
2833

2934
// Read the main data directory.
30-
entries, err := os.ReadDir(dataDir)
35+
dataDirPath := filepath.FromSlash(dataDir)
36+
entries, err := os.ReadDir(dataDirPath)
3137
if err != nil {
3238
return nil, fmt.Errorf("failed to read data directory: %v", err)
3339
}
@@ -36,7 +42,7 @@ func LoadMediaTypes(dataDir string) (map[string]map[string][]string, error) {
3642
for _, entry := range entries {
3743
if entry.IsDir() {
3844
mediaType := entry.Name()
39-
mediaPath := filepath.Join(dataDir, mediaType)
45+
mediaPath := filepath.Join(dataDirPath, mediaType)
4046
mediaTypeMap := make(map[string][]string)
4147

4248
// Read files within the media type directory.
@@ -59,6 +65,7 @@ func LoadMediaTypes(dataDir string) (map[string]map[string][]string, error) {
5965
}
6066

6167
// Use the title from the JSON or the filename without extension as a fallback.
68+
// I actually don't know if this will cause unexpected outcomes for users? We shall see.
6269
title := mediaData.Title
6370
if title == "" {
6471
title = strings.TrimSuffix(file.Name(), ".json")
@@ -79,6 +86,7 @@ func LoadMediaTypes(dataDir string) (map[string]map[string][]string, error) {
7986
return mediaTypes, nil
8087
}
8188

89+
// Function to load media_type to title mapping from cache if the cache is not considered loaded already.
8290
func LoadAndCacheMediaTypes(dataDir string) error {
8391
if !cacheLoaded {
8492
var err error
@@ -91,35 +99,39 @@ func LoadAndCacheMediaTypes(dataDir string) error {
9199
return nil
92100
}
93101

102+
// Function called by customizeDiff: during resource creation
94103
func customValidateMediaTypeAndTitle(ctx context.Context, diff *schema.ResourceDiff, v interface{}) error {
95104
mediaType := diff.Get("media_type").(string)
96105
title := diff.Get("title").(string)
97106

98-
if !isValidMediaTypeAndTitle(mediaType, title) {
99-
return fmt.Errorf("'%s' is not a valid title for media type '%s'", title, mediaType)
107+
isValid, errMsg := isValidMediaTypeAndTitle(mediaType, title)
108+
if !isValid {
109+
return fmt.Errorf(errMsg)
100110
}
101111

102112
return nil
103113
}
104114

105-
func isValidMediaTypeAndTitle(mediaType, title string) bool {
115+
// Function to validate that the user provided media_type and title are valid or not
116+
func isValidMediaTypeAndTitle(mediaType, title string) (bool, string) {
106117
if !cacheLoaded {
107118
if err := LoadAndCacheMediaTypes("data"); err != nil {
108-
fmt.Printf("Error loading media types: %v\n", err)
109-
return false
119+
return false, fmt.Sprintf("error loading media types: %v", err)
110120
}
111121
}
112122

123+
// Check if the media_type is valid
113124
titlesMap, ok := mediaTypeCache[mediaType]
114125
if !ok {
115-
return false
126+
return false, fmt.Sprintf("'%s' is not a recognized media type", mediaType)
116127
}
117128

129+
// Check if the title is valid for the given media_type
118130
for t := range titlesMap {
119131
if strings.EqualFold(t, title) {
120-
return true
132+
return true, ""
121133
}
122134
}
123135

124-
return false
136+
return false, fmt.Sprintf("'%s' is not a valid title for media type '%s'", title, mediaType)
125137
}

0 commit comments

Comments
 (0)