Skip to content

Commit

Permalink
完成 add
Browse files Browse the repository at this point in the history
這次也抓到測試碼的錯誤:go 似乎是依字母順序來執行測試的,所以新增資料的
測試碼會造成資料污染。這裡先把正常 add 的資料獨立出來.確認 add 的程式正
常之後,再另外處理資料獨立的問題
  • Loading branch information
Ronmi committed Jul 11, 2016
1 parent fcf5fa3 commit 220e9ae
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
40 changes: 40 additions & 0 deletions cmd/xchg/add.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package main

import (
"encoding/json"
"fmt"
"net/http"
"strings"

"git.ronmi.tw/ronmi/sdm"
"github.com/Patrolavia/jsonapi"
)

type add struct {
M *sdm.Manager
}

func (h *add) Handle(enc *json.Encoder, dec *json.Decoder, httpData *jsonapi.HTTP) {
var param Order
if err := dec.Decode(&param); err != nil {
httpData.WriteHeader(http.StatusBadRequest)
enc.Encode("Parameter is not Order object")
return
}

// validating data
param.Code = strings.ToUpper(strings.TrimSpace(param.Code))
if len(param.Code) != 3 || param.Local == 0 || param.Foreign == 0 || param.Time <= 0 {
httpData.WriteHeader(http.StatusBadRequest)
enc.Encode("Parameter is not Order object")
return
}

if _, err := h.M.Insert("orders", param); err != nil {
httpData.WriteHeader(http.StatusInternalServerError)
enc.Encode(fmt.Sprintf("Error saving order: %s", err))
return
}

enc.Encode(nil)
}
14 changes: 12 additions & 2 deletions cmd/xchg/add_test.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
package main

import (
"database/sql"
"net/http"
"strings"
"testing"

"git.ronmi.tw/ronmi/sdm"

"github.com/Patrolavia/jsonapi"
)

func TestAddOK(t *testing.T) {
h := &add{mgr}
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatalf("Cannot connect to another db: %s", err)
}
initTable(db)
defer db.Close()

h := &add{sdm.New(db)}

resp, err := jsonapi.HandlerTest(h.Handle).Post("/api/add", "", `{"when":1468248043,"foreign":100,"local":-100,"code":"USD"}`)
resp, err := jsonapi.HandlerTest(h.Handle).Post("/api/add", "", `{"when":1468248043,"foreign":100,"local":-100,"code":"AUD"}`)

if err != nil {
t.Fatalf("unexpected error occured when testing add: %s", err)
Expand Down

0 comments on commit 220e9ae

Please sign in to comment.