Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions cmd/jq_validation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package cmd

import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"

"github.com/stretchr/testify/require"
)

// newCountingSchedulingRuleServer answers the scheduling-rule create endpoint
// with 201 and counts every POST it receives.
func newCountingSchedulingRuleServer(t *testing.T) (*httptest.Server, *int64) {
t.Helper()
var posts int64
mux := http.NewServeMux()
mux.HandleFunc("/platform/automation/v1/scheduling-rules", func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
atomic.AddInt64(&posts, 1)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, _ = w.Write([]byte(`{"id":"r1","title":"t"}`))
})
srv := httptest.NewServer(mux)
t.Cleanup(srv.Close)
return srv, &posts
}

// runCreateSchedulingRule runs `create scheduling-rule -f <file> --agent --jq <filter>`
// end to end, so the root's PersistentPreRunE runs as it does on the CLI.
func runCreateSchedulingRule(t *testing.T, srvURL, filter string) (int, string, string) {
t.Helper()
clearAgentEnvVars(t)
t.Cleanup(func() { restorePristineTree(context.Background()) })

ruleFile := filepath.Join(t.TempDir(), "rule.yaml")
require.NoError(t, os.WriteFile(ruleFile, []byte("title: t\nruleType: rrule\nrrule:\n freq: WEEKLY\n"), 0o600))

var stdout, stderr bytes.Buffer
code := Run([]string{"create", "scheduling-rule", "-f", ruleFile, "--agent", "--jq", filter}, RunOptions{
Session: &Session{EnvironmentURL: srvURL, Token: "t", SafetyLevel: "readwrite-all", MinStability: "experimental"},
Stdout: &stdout,
Stderr: &stderr,
})
return code, stdout.String(), stderr.String()
}

// TestInvalidJQRejectedBeforeMutation covers #815: a --jq filter that does not
// compile must fail before the command sends its request, so a caller that
// reads the error and retries does not create a duplicate.
func TestInvalidJQRejectedBeforeMutation(t *testing.T) {
srv, posts := newCountingSchedulingRuleServer(t)

code, stdout, stderr := runCreateSchedulingRule(t, srv.URL, ".[")

require.Zero(t, atomic.LoadInt64(posts), "an invalid --jq filter must not let the POST through")
require.Equal(t, 1, code, "stderr: %s", stderr)

var env struct {
OK bool `json:"ok"`
Error struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal([]byte(strings.TrimSpace(stdout)), &env), "stdout: %s", stdout)
require.False(t, env.OK)
require.Equal(t, "validation_error", env.Error.Code)
require.True(t, strings.HasPrefix(env.Error.Message, "invalid --jq filter: "), "message: %q", env.Error.Message)
}

// TestValidJQStillAppliedAfterMutation: a filter that compiles passes the
// early check, the request goes out once, and the filter shapes the result.
func TestValidJQStillAppliedAfterMutation(t *testing.T) {
srv, posts := newCountingSchedulingRuleServer(t)

code, stdout, stderr := runCreateSchedulingRule(t, srv.URL, ".id")

require.Equal(t, 0, code, "stdout: %s\nstderr: %s", stdout, stderr)
require.Equal(t, int64(1), atomic.LoadInt64(posts))

var env struct {
OK bool `json:"ok"`
Result any `json:"result"`
}
require.NoError(t, json.Unmarshal([]byte(strings.TrimSpace(stdout)), &env), "stdout: %s", stdout)
require.True(t, env.OK)
require.Equal(t, "r1", env.Result)
}

func TestValidateGlobalFlags_RejectsInvalidJQ(t *testing.T) {
origJQ := jqFilter(context.Background())
t.Cleanup(func() { gFlags.jqFilter = origJQ })

gFlags.jqFilter = ".["
err := validateGlobalFlags(context.Background())
require.Error(t, err)
require.Contains(t, err.Error(), "invalid --jq filter")
}
11 changes: 10 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,19 @@ SLOs, queries, and other Dynatrace platform capabilities.`,
}

// validateGlobalFlags enforces cross-command constraints for root persistent flags.
//
// A --jq filter is compiled here, before the command body runs: the printer
// would otherwise find a syntax error only after a mutating command had sent
// its request, and a caller reading the non-zero exit would retry a change
// that already happened (#815).
func validateGlobalFlags(ctx context.Context) error {
if jqFilter(ctx) == "" {
filter := jqFilter(ctx)
if filter == "" {
return nil
}
if _, err := output.CompileJQ(filter); err != nil {
return err
}

setOutputFormat(ctx, output.NormalizeJQOutputFormat(outputFormat(ctx)))
return nil
Expand Down
Loading