Skip to content

Commit

Permalink
GODRIVER-1893 Add primitive.IsValidObjectID function (#592)
Browse files Browse the repository at this point in the history
  • Loading branch information
kachick authored and Divjot Arora committed Mar 2, 2021
1 parent ccdaffc commit b88bb74
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions bson/primitive/objectid.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ func ObjectIDFromHex(s string) (ObjectID, error) {
return oid, nil
}

// IsValidObjectID judges given string format is valid or invalid for ObjectID.
func IsValidObjectID(s string) bool {
_, err := ObjectIDFromHex(s)
if err != nil {
return false
}

return true
}

// MarshalJSON returns the ObjectID as a string
func (id ObjectID) MarshalJSON() ([]byte, error) {
return json.Marshal(id.Hex())
Expand Down
21 changes: 21 additions & 0 deletions bson/primitive/objectid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,27 @@ func TestFromHex_WrongLength(t *testing.T) {
require.Equal(t, ErrInvalidHex, err)
}

func TestIsValidObjectID(t *testing.T) {
testCases := []struct {
givenID string
expected bool
}{
{
givenID: "5ef7fdd91c19e3222b41b839",
expected: true,
},
{
givenID: "5ef7fdd91c19e3222b41b83",
expected: false,
},
}

for _, testcase := range testCases {
got := IsValidObjectID(testcase.givenID)
require.Equal(t, testcase.expected, got)
}
}

func TestTimeStamp(t *testing.T) {
testCases := []struct {
Hex string
Expand Down

0 comments on commit b88bb74

Please sign in to comment.