Skip to content

Commit

Permalink
feat: add IsReference function to check if a DID is a reference
Browse files Browse the repository at this point in the history
  • Loading branch information
mrinalwadhwa committed Nov 8, 2018
1 parent cdf8b26 commit 262bb2e
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
6 changes: 6 additions & 0 deletions did.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions did_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {

Expand Down
18 changes: 18 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 262bb2e

Please sign in to comment.