github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/pkg/platform/runtime/testhelper/testhelper.go (about)

     1  package testhelper
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  	"testing"
     9  
    10  	"github.com/ActiveState/cli/internal/environment"
    11  	"github.com/ActiveState/cli/pkg/platform/api/buildplanner/response"
    12  	"github.com/ActiveState/cli/pkg/platform/api/headchef/headchef_models"
    13  	"github.com/ActiveState/cli/pkg/platform/api/inventory/inventory_models"
    14  	"github.com/stretchr/testify/require"
    15  )
    16  
    17  func dataPathErr() (string, error) {
    18  	root, err := environment.GetRootPath()
    19  	if err != nil {
    20  		return "", err
    21  	}
    22  	return filepath.Join(root, "pkg", "platform", "runtime", "testhelper", "data"), nil
    23  }
    24  
    25  func dataPath(t *testing.T) string {
    26  	fp, err := dataPathErr()
    27  	require.NoError(t, err)
    28  	return fp
    29  }
    30  
    31  func LoadRecipe(t *testing.T, name string) *inventory_models.Recipe {
    32  	d, err := os.ReadFile(filepath.Join(dataPath(t), "recipes", fmt.Sprintf("%s.json", name)))
    33  	require.NoError(t, err)
    34  
    35  	var recipe inventory_models.Recipe
    36  	err = json.Unmarshal(d, &recipe)
    37  	require.NoError(t, err)
    38  
    39  	return &recipe
    40  }
    41  
    42  func LoadBuildPlan(t *testing.T, name string) *response.ProjectCommitResponse {
    43  	d, err := os.ReadFile(filepath.Join(dataPath(t), "buildplans", fmt.Sprintf("%s.json", name)))
    44  	require.NoError(t, err)
    45  
    46  	var bp response.ProjectCommitResponse
    47  	err = json.Unmarshal(d, &bp)
    48  	require.NoError(t, err)
    49  
    50  	return &bp
    51  }
    52  
    53  func SaveRecipe(name string, m *inventory_models.Recipe) error {
    54  	return save("recipes", name, m)
    55  }
    56  
    57  func save(dir, name string, m interface{}) error {
    58  	dp, err := dataPathErr()
    59  	if err != nil {
    60  		return err
    61  	}
    62  	fn := filepath.Join(dp, dir, fmt.Sprintf("%s.json", name))
    63  
    64  	d, err := json.Marshal(m)
    65  	if err != nil {
    66  		return err
    67  	}
    68  
    69  	return os.WriteFile(fn, d, 0666)
    70  }
    71  
    72  func LoadBuildResponse(t *testing.T, name string) *headchef_models.V1BuildStatusResponse {
    73  	d, err := os.ReadFile(filepath.Join(dataPath(t), "builds", fmt.Sprintf("%s.json", name)))
    74  	require.NoError(t, err)
    75  
    76  	var status headchef_models.V1BuildStatusResponse
    77  	err = json.Unmarshal(d, &status)
    78  	require.NoError(t, err)
    79  
    80  	return &status
    81  }
    82  
    83  func SaveBuildResponse(name string, m *headchef_models.V1BuildStatusResponse) error {
    84  	return save("builds", name, m)
    85  }