Added pm.Meta

This commit is contained in:
Stephen McQuay 2018-03-02 23:22:57 -08:00
parent 4b79c0c765
commit 63c38d5e92
Signed by: sm
GPG Key ID: 4E4B72F479BA3CE5
2 changed files with 119 additions and 0 deletions

23
meta.go Normal file
View File

@ -0,0 +1,23 @@
package pm
import "errors"
type Meta struct {
Name string `json:"name"`
Version string `json:"version"`
Description string `json:"description"`
Namespace string `json:"namespace"`
}
func (m *Meta) Valid() (bool, error) {
if m.Name == "" {
return false, errors.New("name cannot be empty")
}
if m.Version == "" {
return false, errors.New("version cannot be empty")
}
if m.Description == "" {
return false, errors.New("description cannot be empty")
}
return true, nil
}

96
meta_test.go Normal file
View File

@ -0,0 +1,96 @@
package pm
import (
"bytes"
"encoding/json"
"errors"
"testing"
)
func TestValid(t *testing.T) {
tests := []struct {
label string
m Meta
ok bool
err error
}{
{
label: "valid",
m: Meta{
Name: "heat",
Version: "1.1.0",
Description: "some description",
},
ok: true,
},
{
label: "valid with namespace",
m: Meta{
Name: "heat",
Version: "1.1.0",
Description: "some description",
Namespace: "some/namespace",
},
ok: true,
},
{
label: "missing name",
m: Meta{
Version: "1.1.0",
Description: "some description",
},
err: errors.New("name"),
},
{
label: "missing version",
m: Meta{
Name: "heat",
Description: "some description",
},
err: errors.New("version"),
},
{
label: "missing description",
m: Meta{
Name: "heat",
Version: "1.1.0",
},
err: errors.New("description"),
},
}
for _, test := range tests {
t.Run(test.label, func(t *testing.T) {
ok, err := test.m.Valid()
if got, want := ok, test.ok; got != want {
t.Fatalf("validity: got %v, want %v", got, want)
}
if got, want := err, test.err; (err == nil) != (test.err == nil) {
t.Fatalf("error: got %v, want %v", got, want)
}
})
}
}
func TestJsonRoundTrip(t *testing.T) {
b := Meta{
Name: "heat",
Version: "1.1.0",
Description: "make heat using cpus",
Namespace: "/darwin/amd64",
}
buf := &bytes.Buffer{}
if err := json.NewEncoder(buf).Encode(&b); err != nil {
t.Fatalf("encode: %v", err)
}
a := Meta{}
if err := json.NewDecoder(buf).Decode(&a); err != nil {
t.Fatalf("decode: %v", err)
}
if b != a {
t.Fatalf("a != b: %v != %v", a, b)
}
}