Create a strain.

This commit is contained in:
Matthew Dillon 2014-10-29 13:09:54 -08:00
parent 6c118f47f7
commit 6bba9058aa
9 changed files with 146 additions and 2 deletions

View file

@ -2,6 +2,7 @@ package models
import (
"errors"
"net/http"
"strconv"
"time"
@ -30,6 +31,9 @@ func NewStrain() *Strain {
type StrainsService interface {
// Get a strain
Get(id int64) (*Strain, error)
// Create a strain record
Create(strain *Strain) (bool, error)
}
var (
@ -62,8 +66,28 @@ func (s *strainsService) Get(id int64) (*Strain, error) {
return strain, nil
}
func (s *strainsService) Create(strain *Strain) (bool, error) {
url, err := s.client.url(router.CreateStrain, nil, nil)
if err != nil {
return false, err
}
req, err := s.client.NewRequest("POST", url.String(), strain)
if err != nil {
return false, err
}
resp, err := s.client.Do(req, &strain)
if err != nil {
return false, err
}
return resp.StatusCode == http.StatusCreated, nil
}
type MockStrainsService struct {
Get_ func(id int64) (*Strain, error)
Get_ func(id int64) (*Strain, error)
Create_ func(strain *Strain) (bool, error)
}
var _ StrainsService = &MockStrainsService{}
@ -74,3 +98,10 @@ func (s *MockStrainsService) Get(id int64) (*Strain, error) {
}
return s.Get_(id)
}
func (s *MockStrainsService) Create(strain *Strain) (bool, error) {
if s.Create_ == nil {
return false, nil
}
return s.Create_(strain)
}

View file

@ -44,3 +44,39 @@ func TestStrainService_Get(t *testing.T) {
t.Errorf("Strain.Get return %+v, want %+v", strain, want)
}
}
func TestStrainService_Create(t *testing.T) {
setup()
defer teardown()
want := newStrain()
var called bool
mux.HandleFunc(urlPath(t, router.CreateStrain, nil), func(w http.ResponseWriter, r *http.Request) {
called = true
testMethod(t, r, "POST")
testBody(t, r, `{"id":1,"species_id":1,"strain_name":"Test Strain","strain_type":"Test Type","etymology":"Test Etymology","accession_banks":"Test Accession","genbank_eml_ddb":"Test Genbank","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)
})
strain := newStrain()
created, err := client.Strains.Create(strain)
if err != nil {
t.Errorf("Strains.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(strain, want) {
t.Errorf("Strains.Create returned %+v, want %+v", strain, want)
}
}