github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/test/integration/shared_int_test.go (about)

     1  package integration
     2  
     3  import (
     4  	"encoding/json"
     5  	"os"
     6  	"runtime"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  
    12  	"github.com/ActiveState/cli/internal/locale"
    13  	"github.com/ActiveState/cli/internal/logging"
    14  	"github.com/ActiveState/cli/internal/testhelpers/e2e"
    15  )
    16  
    17  func init() {
    18  	if os.Getenv("VERBOSE") == "true" || os.Getenv("VERBOSE_TESTS") == "true" {
    19  		logging.CurrentHandler().SetVerbose(true)
    20  	}
    21  }
    22  
    23  // AssertValidJSON asserts that the previous command emitted valid JSON and did not attempt to emit
    24  // any non-JSON/structured output.
    25  // This should only be called after a command has executed and all output is available.
    26  func AssertValidJSON(t *testing.T, cp *e2e.SpawnedCmd) {
    27  	output := cp.StrippedSnapshot()
    28  	output = strings.TrimPrefix(output, locale.T("notice_runtime_disabled"))
    29  	if runtime.GOOS != "windows" {
    30  		assert.True(t, json.Valid([]byte(output)), "The command produced invalid JSON/structured output:\n"+output)
    31  	} else {
    32  		// Windows can trim the last byte for some reason.
    33  		assert.True(
    34  			t,
    35  			json.Valid([]byte(output)) || json.Valid([]byte(output+"}")) || json.Valid([]byte(output+"]")),
    36  			"The command produced invalid JSON/structured output:\n"+output,
    37  		)
    38  	}
    39  	if strings.Contains(output, `"errors":[`) {
    40  		assert.NotContains(t, output, `output not supported`, "The command attempted to emit non-JSON/structured output:\n"+output)
    41  	}
    42  }