github.com/cozy/cozy-stack@v0.0.0-20240327093429-939e4a21320e/cmd/cmd_test.go (about)

     1  package cmd
     2  
     3  import (
     4  	"bytes"
     5  	"net/http/httptest"
     6  	"net/url"
     7  	"strings"
     8  	"testing"
     9  	"time"
    10  
    11  	"github.com/cozy/cozy-stack/client"
    12  	"github.com/cozy/cozy-stack/client/request"
    13  	"github.com/cozy/cozy-stack/model/instance/lifecycle"
    14  	"github.com/cozy/cozy-stack/model/stack"
    15  	"github.com/cozy/cozy-stack/pkg/config/config"
    16  	"github.com/cozy/cozy-stack/pkg/consts"
    17  	"github.com/cozy/cozy-stack/tests/testutils"
    18  	"github.com/cozy/cozy-stack/web"
    19  	"github.com/labstack/echo/v4"
    20  	"github.com/stretchr/testify/assert"
    21  	"github.com/stretchr/testify/require"
    22  )
    23  
    24  func TestExecCommand(t *testing.T) {
    25  	if testing.Short() {
    26  		t.Skip("an instance is required for this test: test skipped due to the use of --short flag")
    27  	}
    28  
    29  	config.UseTestFile(t)
    30  
    31  	testutils.NeedCouchdb(t)
    32  
    33  	_, _, err := stack.Start()
    34  	require.NoError(t, err)
    35  
    36  	tempDir := t.TempDir()
    37  
    38  	config.GetConfig().Fs.URL = &url.URL{
    39  		Scheme: "file",
    40  		Host:   "localhost",
    41  		Path:   tempDir,
    42  	}
    43  	server := echo.New()
    44  	require.NoError(t, web.SetupRoutes(server, &stack.Services{}))
    45  
    46  	ts := httptest.NewServer(server)
    47  	t.Cleanup(ts.Close)
    48  
    49  	u, _ := url.Parse(ts.URL)
    50  	domain := strings.ReplaceAll(u.Host, "127.0.0.1", "localhost")
    51  
    52  	_ = lifecycle.Destroy(domain)
    53  	testInstance, err := lifecycle.Create(&lifecycle.Options{
    54  		Domain: domain,
    55  		Locale: "en",
    56  	})
    57  	if err != nil {
    58  		require.NoError(t, err, "Could not create test instance.")
    59  	}
    60  	t.Cleanup(func() { _ = lifecycle.Destroy("test-files") })
    61  
    62  	token, err := testInstance.MakeJWT(consts.CLIAudience, "CLI", consts.Files, "", time.Now())
    63  	if err != nil {
    64  		require.NoError(t, err, "Could not get test instance token.")
    65  	}
    66  
    67  	testClient := &client.Client{
    68  		Domain:     domain,
    69  		Authorizer: &request.BearerAuthorizer{Token: token},
    70  	}
    71  
    72  	buf := new(bytes.Buffer)
    73  	err = execCommand(testClient, "mkdir /hello-test", buf)
    74  	assert.NoError(t, err)
    75  
    76  	buf = new(bytes.Buffer)
    77  	err = execCommand(testClient, "ls /", buf)
    78  	assert.NoError(t, err)
    79  	assert.True(t, bytes.Contains(buf.Bytes(), []byte("hello-test")))
    80  }