Skip to content

Commit

Permalink
Function to check nil Identifier (#97)
Browse files Browse the repository at this point in the history
* Validation function for resource Identifier

* Renamed: Valid -> Nil in order to avoid confusions
  • Loading branch information
amaskalenka authored and Evgeniy-L committed Aug 7, 2018
1 parent 4ff6030 commit 923006b
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
24 changes: 24 additions & 0 deletions rpc/resource/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,27 @@ message MyMessage {

Please give a read to [README](../../gorm/resource/README.md) of `gorm/resource`
package to see how it could be used with gorm and `protoc-gen-gorm` generated code.

# How to check that an Identifier is nil?

In order to check that an identifier is nil use `resource.Nil` function.

```go
package main

import (
"fmt"

"github.com/infobloxopen/atlas-app-toolkit/rpc/resource"
)

func main() {
var id *resource.Identifier

if resource.Nil(id) {
fmt.Println("resource is nil identifier")
}
}
```

See [Unit test](nil_test.go).
17 changes: 17 additions & 0 deletions rpc/resource/nil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package resource

// String method calls proto.CompactTextString which returns "<nil>" string
// in case if passed proto.Message is nil.
// The "<nil>" string is common representation of nil value in Go code. See fmt package.
const pbnil = "<nil>"

// Nil reports whether id is empty identifier or not.
// The id is empty if it is either nil or could be converted to the empty string by its String method.
func Nil(id *Identifier) (ok bool) {
// comparison with pbnil is mostly paranoid check
// should never happen
if id == nil || id.String() == "" || id.String() == pbnil {
return true
}
return
}
29 changes: 29 additions & 0 deletions rpc/resource/nil_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package resource

import "testing"

func TestNil(t *testing.T) {
tcases := []struct {
Identifier *Identifier
Expected bool
}{
{
Identifier: nil,
Expected: true,
},
{
Identifier: &Identifier{},
Expected: true,
},
{
Identifier: &Identifier{ResourceId: "uuid"},
Expected: false,
},
}

for n, tc := range tcases {
if v := Nil(tc.Identifier); v != tc.Expected {
t.Errorf("%d: invalid result %t, expected %t", n, v, tc.Expected)
}
}
}

0 comments on commit 923006b

Please sign in to comment.