diff --git a/internal/handlers/errors.go b/internal/handlers/errors.go index e475014..fd05742 100644 --- a/internal/handlers/errors.go +++ b/internal/handlers/errors.go @@ -4,6 +4,7 @@ import ( "encoding/json" "log" "net/http" + "strings" ) type Error struct { @@ -11,6 +12,16 @@ type Error struct { ErrorString string } +func (e *Error) Read(json_str string) error { + dec := json.NewDecoder(strings.NewReader(json_str)) + return dec.Decode(e) +} + +func (e *Error) Write(w http.ResponseWriter) error { + enc := json.NewEncoder(w) + return enc.Encode(e) +} + var error_codes = map[int]string{ 1: "Not Signed In", 2: "Unauthorized Access", @@ -29,8 +40,7 @@ func WriteError(w http.ResponseWriter, error_code int) { } e := Error{error_code, msg} - enc := json.NewEncoder(w) - err := enc.Encode(e) + err := e.Write(w) if err != nil { log.Fatal(err) } diff --git a/internal/handlers/security_template_test.go b/internal/handlers/security_template_test.go index 14ef459..5bad9b4 100644 --- a/internal/handlers/security_template_test.go +++ b/internal/handlers/security_template_test.go @@ -108,3 +108,49 @@ func TestSecurityTemplateLimit(t *testing.T) { t.Fatalf("Requested only 5 securities, received %d\n", len(*sl.Securities)) } } + +func TestSecurityTemplateInvalidType(t *testing.T) { + var e handlers.Error + response, err := http.Get(server.URL + "/securitytemplate/?search=e&type=blah") + if err != nil { + t.Fatal(err) + } + + body, err := ioutil.ReadAll(response.Body) + response.Body.Close() + if err != nil { + t.Fatal(err) + } + + err = (&e).Read(string(body)) + if err != nil { + t.Fatal(err) + } + + if e.ErrorId != 3 { + t.Fatal("Expected ErrorId 3, Invalid Request") + } +} + +func TestSecurityTemplateInvalidLimit(t *testing.T) { + var e handlers.Error + response, err := http.Get(server.URL + "/securitytemplate/?search=e&type=Currency&limit=foo") + if err != nil { + t.Fatal(err) + } + + body, err := ioutil.ReadAll(response.Body) + response.Body.Close() + if err != nil { + t.Fatal(err) + } + + err = (&e).Read(string(body)) + if err != nil { + t.Fatal(err) + } + + if e.ErrorId != 3 { + t.Fatal("Expected ErrorId 3, Invalid Request") + } +}