Create a unit type

This commit is contained in:
Matthew Dillon 2014-11-30 15:11:51 -09:00
parent c2bfc8b93b
commit b7caffa373
9 changed files with 155 additions and 4 deletions

View file

@ -2,6 +2,7 @@ package models
import (
"errors"
"net/http"
"strconv"
"time"
@ -11,7 +12,7 @@ import (
// A UnitType is a lookup type
type UnitType struct {
Id int64 `json:id,omitempty"`
Id int64 `json:"id,omitempty"`
Name string `db:"name" json:"name"`
Symbol string `db:"symbol" json:"symbol"`
CreatedAt time.Time `db:"created_at" json:"createdAt"`
@ -29,6 +30,9 @@ func NewUnitType() *UnitType {
type UnitTypesService interface {
// Get a unit type
Get(id int64) (*UnitType, error)
// Create a unit type
Create(unit_type *UnitType) (bool, error)
}
var (
@ -61,8 +65,28 @@ func (s *unitTypesService) Get(id int64) (*UnitType, error) {
return unit_type, nil
}
func (s *unitTypesService) Create(unit_type *UnitType) (bool, error) {
url, err := s.client.url(router.CreateUnitType, nil, nil)
if err != nil {
return false, err
}
req, err := s.client.NewRequest("POST", url.String(), unit_type)
if err != nil {
return false, err
}
resp, err := s.client.Do(req, &unit_type)
if err != nil {
return false, err
}
return resp.StatusCode == http.StatusCreated, nil
}
type MockUnitTypesService struct {
Get_ func(id int64) (*UnitType, error)
Get_ func(id int64) (*UnitType, error)
Create_ func(unit_type *UnitType) (bool, error)
}
var _ UnitTypesService = &MockUnitTypesService{}
@ -73,3 +97,10 @@ func (s *MockUnitTypesService) Get(id int64) (*UnitType, error) {
}
return s.Get_(id)
}
func (s *MockUnitTypesService) Create(unit_type *UnitType) (bool, error) {
if s.Create_ == nil {
return false, nil
}
return s.Create_(unit_type)
}

View file

@ -43,3 +43,39 @@ func TestUnitTypeService_Get(t *testing.T) {
t.Errorf("UnitTypes.Get return %+v, want %+v", unit_type, want)
}
}
func TestUnitTypeService_Create(t *testing.T) {
setup()
defer teardown()
want := newUnitType()
var called bool
mux.HandleFunc(urlPath(t, router.CreateUnitType, nil), func(w http.ResponseWriter, r *http.Request) {
called = true
testMethod(t, r, "POST")
testBody(t, r, `{"id":1,"name":"Test Unit Type","symbol":"x","createdAt":"0001-01-01T00:00:00Z","updatedAt":"0001-01-01T00:00:00Z","deletedAt":{"Time":"0001-01-01T00:00:00Z","Valid":false}}`+"\n")
w.WriteHeader(http.StatusCreated)
writeJSON(w, want)
})
unit_type := newUnitType()
created, err := client.UnitTypes.Create(unit_type)
if err != nil {
t.Errorf("UnitTypes.Create returned error: %v", err)
}
if !created {
t.Error("!created")
}
if !called {
t.Fatal("!called")
}
normalizeTime(&want.CreatedAt, &want.UpdatedAt, &want.DeletedAt)
if !reflect.DeepEqual(unit_type, want) {
t.Errorf("UnitTypes.Create returned %+v, want %+v", unit_type, want)
}
}