From d105adfed6e60a3f6d081ba920f08eedd1f819b3 Mon Sep 17 00:00:00 2001 From: Tit Petric Date: Tue, 5 Feb 2019 12:46:57 +0100 Subject: [PATCH] add(system): resource type and encoding --- system/types/resource.go | 39 +++++++++++++++++++++++++++++++++++ system/types/resource_test.go | 33 +++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 system/types/resource.go create mode 100644 system/types/resource_test.go diff --git a/system/types/resource.go b/system/types/resource.go new file mode 100644 index 000000000..2b477e67d --- /dev/null +++ b/system/types/resource.go @@ -0,0 +1,39 @@ +package types + +import ( + "fmt" + + "encoding/json" +) + +type Resource struct { + ID uint64 `json:"id,string"` + Name string `json:"name"` + Scope string `json:"scope"` +} + +type ResourceJSON struct { + ID uint64 `json:"id,string"` + Name string `json:"name"` + Scope string `json:"scope"` + ResourceID string `json:"resource"` +} + +func (r Resource) String() string { + return fmt.Sprintf("%s:%d", r.Scope, r.ID) +} + +func (r Resource) All() string { + return fmt.Sprintf("%s:*", r.Scope) +} + +func (r Resource) MarshalJSON() ([]byte, error) { + return json.Marshal(ResourceJSON{ + r.ID, + r.Name, + r.Scope, + r.String(), + }) +} + +var _ fmt.Stringer = Resource{} diff --git a/system/types/resource_test.go b/system/types/resource_test.go new file mode 100644 index 000000000..723511215 --- /dev/null +++ b/system/types/resource_test.go @@ -0,0 +1,33 @@ +package types + +import ( + "fmt" + "testing" + + "encoding/json" + + "github.com/crusttech/crust/internal/test" +) + +func TestResource(t *testing.T) { + var ( + assert = test.Assert + ) + r := Resource{123, "Test name", "team"} + assert(t, r.String() == "team:123", "Resource ID doesn't match, team:123 != '%s'", r.String()) + + b, _ := json.Marshal(r) + fmt.Println(string(b)) + + { + r := ResourceJSON{} + json.Unmarshal(b, &r) + assert(t, r.ResourceID == "team:123", "Decoded full-json resource ID doesn't match, team:123 != '%s'", r.ResourceID) + } + + { + r := Resource{} + json.Unmarshal(b, &r) + assert(t, r.String() == "team:123", "Decoded full-json resource ID doesn't match, team:123 != '%s'", r.String()) + } +}