1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
package unit
import (
"embed"
"encoding/json"
"fmt"
"path/filepath"
"strings"
)
//go:embed fixtures/*.json
var fixtureFiles embed.FS
// TestFixtures manages loading and retrieving test fixtures
type TestFixtures struct {
fixtures map[string]interface{}
}
// NewTestFixtures creates a new TestFixtures instance
func NewTestFixtures() *TestFixtures {
tf := &TestFixtures{}
tf.loadFixtures()
return tf
}
// loadFixtures loads all embedded JSON files
func (tf *TestFixtures) loadFixtures() {
tf.fixtures = make(map[string]interface{})
entries, err := fixtureFiles.ReadDir("fixtures")
if err != nil {
panic(fmt.Sprintf("failed to read embedded fixtures: %v", err))
}
for _, entry := range entries {
if !entry.IsDir() && filepath.Ext(entry.Name()) == ".json" {
// Read the embedded JSON file
data, err := fixtureFiles.ReadFile("fixtures/" + entry.Name())
if err != nil {
panic(fmt.Sprintf("failed to read fixture %s: %v", entry.Name(), err))
}
var jsonData interface{}
if err := json.Unmarshal(data, &jsonData); err != nil {
panic(fmt.Sprintf("failed to unmarshal fixture %s: %v", entry.Name(), err))
}
// Remove ".json" from the file name
fixtureName := strings.TrimSuffix(entry.Name(), ".json")
tf.fixtures[fixtureName] = jsonData
}
}
}
// GetFixture retrieves the fixture data for the given name
func (tf *TestFixtures) GetFixture(name string) (interface{}, error) {
data, ok := tf.fixtures[name]
if !ok {
return nil, fmt.Errorf("fixture not found: %s", name)
}
return data, nil
}
|