Create species, cleanup schema.

- create species
- species genus_id not null
This commit is contained in:
Matthew Dillon 2014-10-15 16:43:09 -08:00
parent ed2ba26654
commit 7fe5566edf
10 changed files with 155 additions and 3 deletions

View file

@ -2,6 +2,7 @@ package models
import (
"errors"
"net/http"
"strconv"
"time"
@ -22,6 +23,9 @@ type Species struct {
type SpeciesService interface {
// Get a species
Get(id int64) (*Species, error)
// Create a species record
Create(species *Species) (bool, error)
}
var (
@ -55,8 +59,28 @@ func (s *speciesService) Get(id int64) (*Species, error) {
return species, nil
}
func (s *speciesService) Create(species *Species) (bool, error) {
url, err := s.client.url(router.CreateSpecies, nil, nil)
if err != nil {
return false, err
}
req, err := s.client.NewRequest("POST", url.String(), species)
if err != nil {
return false, err
}
resp, err := s.client.Do(req, &species)
if err != nil {
return false, err
}
return resp.StatusCode == http.StatusCreated, nil
}
type MockSpeciesService struct {
Get_ func(id int64) (*Species, error)
Get_ func(id int64) (*Species, error)
Create_ func(species *Species) (bool, error)
}
var _ SpeciesService = &MockSpeciesService{}
@ -67,3 +91,10 @@ func (s *MockSpeciesService) Get(id int64) (*Species, error) {
}
return s.Get_(id)
}
func (s *MockSpeciesService) Create(species *Species) (bool, error) {
if s.Create_ == nil {
return false, nil
}
return s.Create_(species)
}

View file

@ -37,3 +37,39 @@ func TestSpeciesService_Get(t *testing.T) {
t.Errorf("Species.Get returned %+v, want %+v", species, want)
}
}
func TestSpeciesService_Create(t *testing.T) {
setup()
defer teardown()
want := &Species{Id: 1, GenusId: 1, SpeciesName: "Test Species"}
var called bool
mux.HandleFunc(urlPath(t, router.CreateSpecies, nil), func(w http.ResponseWriter, r *http.Request) {
called = true
testMethod(t, r, "POST")
testBody(t, r, `{"id":1,"genus_id":1,"species_name":"Test Species","created_at":"0001-01-01T00:00:00Z","updated_at":"0001-01-01T00:00:00Z","deleted_at":"0001-01-01T00:00:00Z"}`+"\n")
w.WriteHeader(http.StatusCreated)
writeJSON(w, want)
})
species := &Species{Id: 1, GenusId: 1, SpeciesName: "Test Species"}
created, err := client.Species.Create(species)
if err != nil {
t.Errorf("Species.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(species, want) {
t.Errorf("Species.Create returned %+v, want %+v", species, want)
}
}