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
1 change: 1 addition & 0 deletions cmds/xr/conform.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ func TestTDAll(td *TD) {
td.DependsOn(TestCapabilities)
td.DependsOn(TestRegistryRoot)
td.DependsOn(TestGroups)
td.DependsOn(TestFilter)
td.DependsOn(TestResources)
}

Expand Down
22 changes: 22 additions & 0 deletions cmds/xr/td.go
Original file line number Diff line number Diff line change
Expand Up @@ -736,6 +736,28 @@ func (td *TD) ShouldEqual(exp any, got any, args ...any) {
td.Pass(args...)
}

// HTTPGetJSON records a request subtest and returns nil after a failed check.
// FailFast still stops execution on the first failure.
func (td *TD) HTTPGetJSON(path string) *xrlib.HttpResponse {
nTD := NewTD(td, "GET %s", path)
res, xErr := td.GetRegistry().HttpDo(VerboseCount > 2, "GET", path, nil)
nTD.NoError(xErr, "GET %s", path)
if nTD.Status == FAIL {
return nil
}

nTD.HTTPStatusMustEqual(res, 200, "GET %s", path)
if nTD.Status == FAIL {
return nil
}

nTD.HTTPBodyMustJSON(res, "GET %s", path)
if nTD.Status == FAIL {
return nil
}
return res
}

func (td *TD) HTTPStatusMustEqual(res *xrlib.HttpResponse, exp int, args ...any) {
if res == nil {
td.Fail(args...)
Expand Down
69 changes: 67 additions & 2 deletions cmds/xr/td_registry.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
// "fmt"
"net/url"
"regexp"

"github.com/xregistry/server/cmds/xr/xrlib"
Expand All @@ -23,6 +23,7 @@ func TestRegistry(td *TD) {
td.Run(TestCapabilities)
td.Run(TestRegistryRoot)
td.Run(TestGroups)
td.Run(TestFilter)
td.Run(TestResources)
}

Expand Down Expand Up @@ -56,6 +57,7 @@ func TestCapabilities(td *TD) {

if reg.Capabilities == nil {
td.Skip("No capabilities found - leaving")
td.Skip()
return
}

Expand Down Expand Up @@ -222,7 +224,8 @@ func TestGroups(td *TD) {
MakeURL(reg.GetStuffAsString("self"),
gm.Plural, MustString(gRes.JSON[gm.Singular+"id"])))
gTD.ObjReqMustEq(gRes.JSON, "xid",
MakeURL("/", gm.Plural, MustString(gRes.JSON[gm.Singular+"id"])))
MakeURL("/", gm.Plural,
MustString(gRes.JSON[gm.Singular+"id"])))
gTD.ObjReqMustGe(gRes.JSON, "epoch", 0)
gTD.ObjMayExist(gRes.JSON, "name", "")
gTD.ObjMayExist(gRes.JSON, "description", "")
Expand All @@ -240,6 +243,68 @@ func TestGroups(td *TD) {
reg.SetStuff("groupPaths", groupPaths)
}

func TestFilter(td *TD) {
td.DependsOn(TestCapabilities)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now td.DependsOn() only stops if the dependency fails... I'm wondering if it should stop (with a 'skip' status) if the dependency was skipped. In this case if TestCapabilities is skipped because they don't expose capabilities, then it seems like we should immediate stop this one too and then you can remove the "if reg.Capabilities == nil ..." block below too. Thoughts?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense for a wholly skipped dependency. We'd need to be able to differentiate that from a passing test with some skipped checks before changing DependsOn.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think an optional arg with instructions on what to do would help. For example:

td.DependsOn(TestCapabilities, TD_FAILONFAIL) // the default (today)
td.DependsOn(TestCapabilities, TD_FAILONSKIP) // what I think we need here (fail on skip or worse)
td.DependsOn(TestCapabilities, TD_IGNOREFAIL) // If we're ok with a failed dependency

there may be reasons to have other variants too.

#103

reg := td.GetRegistry()

if reg.Capabilities == nil {
td.Skip("No capabilities found - leaving")
td.Skip()
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think adding a td.Skip() will make TestFilters() report SKIP - you may need to rebase though to get that code.
And in the "leaving" if-statements below too.
Because doesn't it seem like TestFilters should report SKIP rather than PASS if our prereqs aren't met?

}

if !reg.Capabilities.FlagEnabled("filter") {
td.Skip("?filter not supported - leaving")
td.Skip()
return
}

td.DependsOn(TestGroups)

groupPathsAny, ok := reg.GetStuff("groupPaths")
if !ok {
td.Skip("No observable Group Types defined - leaving")
td.Skip()
return
}
groupPaths, ok := groupPathsAny.(map[string]string)
PanicIf(!ok, "reg.stuff.groupPaths != map[string]string")

if len(groupPaths) == 0 {
td.Skip("No observable Group Types defined - leaving")
td.Skip()
return
}

xid, err := ParseXid(groupPaths[SortedKeys(groupPaths)[0]])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

At some point it might be easier to just store the XID in groupPaths instead of the string (ie. let TestGroups do the ParseXid instead of all users of it).

PanicIf(err != nil, "reg.stuff.groupPaths has an invalid XID: %s", err)

gm := reg.Model.Groups[xid.Group]
filterAttr := gm.Singular + "id"
collectionPath := "/" + xid.Group
matchID := xid.GroupID
if matchID == "null" {
matchID = "NULL"
}

matchPath := collectionPath + "?filter=" + filterAttr + "=" +
url.QueryEscape(matchID)
matchRes := td.HTTPGetJSON(matchPath)
if matchRes != nil {
Comment thread
duglin marked this conversation as resolved.
Resolved
td.MustEqual([]string{xid.GroupID}, SortedKeys(matchRes.JSON),
"'GET %s' MUST return exactly group %q", matchPath, xid.GroupID)
td.Must(!IsNil(matchRes.JSON[xid.GroupID]),
"'GET %s' group %q MUST NOT be nil", matchPath, xid.GroupID)
}

absentPath := collectionPath + "?filter=" + filterAttr + "=null"
absentRes := td.HTTPGetJSON(absentPath)
if absentRes != nil {
td.MustEqual(0, len(absentRes.JSON),
"'GET %s' MUST return an empty collection", absentPath)
}
}

func TestResources(td *TD) {
td.DependsOn(TestGroups)
reg := td.GetRegistry()
Expand Down
139 changes: 139 additions & 0 deletions cmds/xr/td_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package main

import (
"bytes"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync/atomic"
"testing"

"github.com/xregistry/server/cmds/xr/xrlib"
Expand Down Expand Up @@ -147,6 +150,142 @@ Pass: 2 Fail: 0 Warn: 0 Skip: 0
XEqual(t, "Stdout", stdout, "")
}

func TestTDHTTPGetJSON(t *testing.T) {
tests := []struct {
name string
code int
body string
status int
}{
{"object", 200, `{"null":{}}`, PASS},
{"empty object", 200, `{}`, PASS},
{"wrong success status", 201, `{}`, FAIL},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the future we may need to allow 201's not just 200's when we're testing creates.
But 202 and 204 are different beasts

{"error with null body", 500, `null`, FAIL},
{"empty body", 200, ``, FAIL},
{"null", 200, `null`, FAIL},
{"array", 200, `[]`, FAIL},
{"string", 200, `"not an object"`, FAIL},
{"malformed", 200, `{"null":`, FAIL},
{"transport", 200, `{}`, FAIL},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(test.code)
_, _ = w.Write([]byte(test.body))
}))
defer server.Close()
if test.name == "transport" {
server.Close()
}

td := newTestTD("HTTP GET")
td.SetRegistry(xrlib.DefineRegistry(server.URL))
const path = "/widgets?filter=widgetid=NULL"
res := td.HTTPGetJSON(path)

XEqual(t, "Root status", td.Status, test.status)
XEqual(t, "Request subtests", len(td.Logs), 1)
requestTD := td.Logs[0].Subtest
XEqual(t, "Request name", requestTD.TestName, "GET "+path)
XEqual(t, "Request status", requestTD.Status, test.status)
if test.status == PASS {
XCheck(t, res != nil, "Expected a JSON response")
XEqual(t, "Response status", res.Code, 200)
XEqual(t, "Response body", string(res.Body), test.body)
XCheck(t, res.JSON != nil, "Expected a JSON object")
} else {
XCheck(t, res == nil, "A failed request must return nil")
}
td.Pass("continued")
XEqual(t, "Final status", td.Status, test.status)
})
}

t.Run("independent requests", func(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
if requests.Add(1) == 1 {
_, _ = w.Write([]byte("null"))
} else {
_, _ = w.Write([]byte("{}"))
}
}))
defer server.Close()

td := newTestTD("HTTP GET")
td.SetRegistry(xrlib.DefineRegistry(server.URL))
first := td.HTTPGetJSON("/widgets?filter=widgetid=NULL")
second := td.HTTPGetJSON("/widgets?filter=widgetid=null")
XCheck(t, first == nil, "The first request must fail")
XCheck(t, second != nil, "The second request must still run")
XEqual(t, "Requests", requests.Load(), int32(2))
XEqual(t, "First status", td.Logs[0].Subtest.Status, FAIL)
XEqual(t, "Second status", td.Logs[1].Subtest.Status, PASS)
})

t.Run("failfast", func(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
_, _ = w.Write([]byte("null"))
}))
defer server.Close()

td := newTestTD("HTTP GET")
td.SetRegistry(xrlib.DefineRegistry(server.URL))
td.Config.FailFast = true
continued := false
td.Run(func(td *TD) {
td.HTTPGetJSON("/widgets?filter=widgetid=NULL")
continued = true
td.HTTPGetJSON("/widgets?filter=widgetid=null")
})
XEqual(t, "Root status", td.Status, FAIL)
XEqual(t, "Requests", requests.Load(), int32(1))
XEqual(t, "Continued", continued, false)
})
}

func TestCapabilitiesMissingResponseStatus(t *testing.T) {
tests := []struct {
name string
code int
body string
status int
}{
{"no capabilities", 200, "null", SKIP},
{"malformed capabilities", 200, "{", FAIL},
{"capabilities HTTP error", 500, "null", FAIL},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
w.WriteHeader(test.code)
_, _ = w.Write([]byte(test.body))
}))
defer server.Close()

root := newTestTD("Capabilities")
root.SetRegistry(xrlib.DefineRegistry(server.URL))
td := root.Run(TestCapabilities)
XEqual(t, "Capabilities status", td.Status, test.status)
XEqual(t, "Requests", requests.Load(), int32(1))
XEqual(t, "Diagnostic",
td.Logs[len(td.Logs)-1].Text,
"No capabilities found - leaving")
})
}
}

func TestRunConformIsolatesOutputAndConfigState(t *testing.T) {
staleRun := NewTD(nil, "stale")
staleRun.Fail("stale failure")
Expand Down
4 changes: 2 additions & 2 deletions cmds/xr/xrlib/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func Debug(args ...any) {

str := fmt.Sprintf(fmtStr, args[1:]...)

log.VPrintf(2, str)
log.VPrintf(2, "%s", str)
/*
fmt.Fprint(os.Stderr, str)
if str[len(str)-1] != '\n' && str[len(str)-1] != '\r' {
Expand Down Expand Up @@ -165,7 +165,7 @@ func HttpDo(debug bool, verb string, url string, headers map[string]string, body
// If we 'think' it's an XRError then return it, else just
// return the raw data
err := json.Unmarshal(httpRes.Body, &xErr)
if (err == nil && xErr.Type == "") || err != nil {
if err != nil || xErr == nil || xErr.Type == "" {
xErr = NewXRError("talking_to_server", url,
"error_detail="+strings.TrimSpace(string(httpRes.Body)))
}
Expand Down
29 changes: 29 additions & 0 deletions cmds/xr/xrlib/utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package xrlib

import (
"io"
"net/http"
"net/http/httptest"
"testing"
)

func TestHttpDoNullErrorBody(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = io.WriteString(w, "null")
}))
defer server.Close()

res, xErr := HttpDo(false, http.MethodGet,
server.URL+"/", nil, nil)
if res == nil || res.Code != http.StatusInternalServerError {
t.Fatalf("unexpected response: %#v", res)
}
if xErr == nil {
t.Fatal("expected a non-nil error")
}
if string(res.Body) != "null" {
t.Fatalf("unexpected response body: %q", res.Body)
}
}
Loading
Loading