diff --git a/client.go b/client.go index 3ecf86f..04643c9 100644 --- a/client.go +++ b/client.go @@ -165,6 +165,9 @@ func (c *Client) HTTPClient() *http.Client { // // s := client.String() func (c *Client) String() string { + if c == nil { + return "forge.Client{}" + } tokenState := "unset" if c.HasToken() { tokenState = "set" diff --git a/forge.go b/forge.go index fab6e2e..3c3a976 100644 --- a/forge.go +++ b/forge.go @@ -117,6 +117,12 @@ func (f *Forge) HasToken() bool { return f.client.HasToken() } // // s := f.String() func (f *Forge) String() string { + if f == nil { + return "forge.Forge{}" + } + if f.client == nil { + return "forge.Forge{client=}" + } return "forge.Forge{" + f.client.String() + "}" } diff --git a/resource.go b/resource.go index d2f34f1..712a610 100644 --- a/resource.go +++ b/resource.go @@ -27,6 +27,9 @@ type Resource[T any, C any, U any] struct { // // s := res.String() func (r *Resource[T, C, U]) String() string { + if r == nil { + return "forge.Resource{}" + } return core.Concat( "forge.Resource{path=", strconv.Quote(r.path), diff --git a/stringer_nil_test.go b/stringer_nil_test.go new file mode 100644 index 0000000..8295a68 --- /dev/null +++ b/stringer_nil_test.go @@ -0,0 +1,48 @@ +package forge + +import ( + "fmt" + "testing" +) + +func TestClient_String_NilSafe(t *testing.T) { + var c *Client + want := "forge.Client{}" + if got := c.String(); got != want { + t.Fatalf("got String()=%q, want %q", got, want) + } + if got := fmt.Sprint(c); got != want { + t.Fatalf("got fmt.Sprint=%q, want %q", got, want) + } + if got := fmt.Sprintf("%#v", c); got != want { + t.Fatalf("got GoString=%q, want %q", got, want) + } +} + +func TestForge_String_NilSafe(t *testing.T) { + var f *Forge + want := "forge.Forge{}" + if got := f.String(); got != want { + t.Fatalf("got String()=%q, want %q", got, want) + } + if got := fmt.Sprint(f); got != want { + t.Fatalf("got fmt.Sprint=%q, want %q", got, want) + } + if got := fmt.Sprintf("%#v", f); got != want { + t.Fatalf("got GoString=%q, want %q", got, want) + } +} + +func TestResource_String_NilSafe(t *testing.T) { + var r *Resource[int, struct{}, struct{}] + want := "forge.Resource{}" + if got := r.String(); got != want { + t.Fatalf("got String()=%q, want %q", got, want) + } + if got := fmt.Sprint(r); got != want { + t.Fatalf("got fmt.Sprint=%q, want %q", got, want) + } + if got := fmt.Sprintf("%#v", r); got != want { + t.Fatalf("got GoString=%q, want %q", got, want) + } +}