From 262bb2e3ded38269f5fd48488dcd1aa51201e6f1 Mon Sep 17 00:00:00 2001 From: Mrinal Wadhwa Date: Wed, 7 Nov 2018 21:54:54 -0800 Subject: [PATCH] feat: add IsReference function to check if a DID is a reference --- did.go | 6 ++++++ did_test.go | 38 ++++++++++++++++++++++++++++++++++++++ example_test.go | 18 ++++++++++++++++++ 3 files changed, 62 insertions(+) diff --git a/did.go b/did.go index 8c08d61..5ad8d7c 100644 --- a/did.go +++ b/did.go @@ -45,6 +45,12 @@ type parser struct { // a step in the parser state machine that returns the next step type parserStep func() parserStep +// IsReference returns true if a DID has a Path or a Fragment +// https://w3c-ccg.github.io/did-spec/#dfn-did-reference +func (d *DID) IsReference() bool { + return (d.Path != "" || len(d.PathSegments) > 0 || d.Fragment != "") +} + // String encodes a DID struct into a valid DID string. func (d *DID) String() string { var buf strings.Builder diff --git a/did_test.go b/did_test.go index 7734369..74f8a84 100644 --- a/did_test.go +++ b/did_test.go @@ -4,6 +4,44 @@ import ( "testing" ) +func TestIsReference(t *testing.T) { + + t.Run("returns false if no Path of Fragment", func(t *testing.T) { + d := &DID{Method: "example", ID: "123"} + if d.IsReference() { + t.Errorf("returned true") + } + }) + + t.Run("returns true if Path", func(t *testing.T) { + d := &DID{Method: "example", ID: "123", Path: "a/b"} + if !d.IsReference() { + t.Errorf("returned false") + } + }) + + t.Run("returns true if PathSegements", func(t *testing.T) { + d := &DID{Method: "example", ID: "123", PathSegments: []string{"a", "b"}} + if !d.IsReference() { + t.Errorf("returned false") + } + }) + + t.Run("returns true if Fragment", func(t *testing.T) { + d := &DID{Method: "example", ID: "123", Fragment: "00000"} + if !d.IsReference() { + t.Errorf("returned false") + } + }) + + t.Run("returns true if Path and Fragment", func(t *testing.T) { + d := &DID{Method: "example", ID: "123", Path: "a/b", Fragment: "00000"} + if !d.IsReference() { + t.Errorf("returned false") + } + }) +} + // nolint func TestString(t *testing.T) { diff --git a/example_test.go b/example_test.go index 98a3993..cec129b 100644 --- a/example_test.go +++ b/example_test.go @@ -55,3 +55,21 @@ func ExampleDID_String_withFragment() { fmt.Println(d) // Output: did:example:q7ckgxeq1lxmra0r#keys-1 } + +func ExampleDID_IsReference_withPath() { + d := &did.DID{Method: "example", ID: "q7ckgxeq1lxmra0r", Path: "a/b"} + fmt.Println(d.IsReference()) + // Output: true +} + +func ExampleDID_IsReference_withFragment() { + d := &did.DID{Method: "example", ID: "q7ckgxeq1lxmra0r", Fragment: "keys-1"} + fmt.Println(d.IsReference()) + // Output: true +} + +func ExampleDID_IsReference_noPathOrFragment() { + d := &did.DID{Method: "example", ID: "q7ckgxeq1lxmra0r"} + fmt.Println(d.IsReference()) + // Output: false +}