textmagic - textmagic_test.go
1 package textmagic
2
3 import (
4 "net/http"
5 "net/http/httptest"
6 "net/url"
7 "os"
8 "reflect"
9 "testing"
10 )
11
12 var apiConfig TextMagic
13
14 const (
15 testUsername = "testUser"
16 testPassword = "testPassword"
17 )
18
19 func apiServer(w http.ResponseWriter, r *http.Request) {
20 if r.Method != "GET" {
21 http.Error(w, "invalid method", http.StatusMethodNotAllowed)
22 return
23 }
24 r.ParseForm()
25 if r.Form.Get("username") != testUsername || r.Form.Get("password") != testPassword {
26 w.Write([]byte(`{"error_code":5,"error_message":"Invalid username & password combination"}`))
27 return
28 }
29 switch r.Form.Get("cmd") {
30 case "send":
31 case "account":
32 w.Write([]byte(`{"balance":417.7}`))
33 case "message_status":
34 case "receive":
35 case "delete_reply":
36 case "check_number":
37 default:
38 w.Write([]byte(`{"error_code":3,"error_message":"Command is undefined"}`))
39 }
40
41 }
42
43 func TestAccount(t *testing.T) {
44 balance, err := apiConfig.Account()
45 if err != nil {
46 t.Errorf("test 1: unexpected error, %s", err)
47 } else if balance != 417.7 {
48 t.Errorf("test 1: expecting balance 417.7, got %f", balance)
49 }
50 _, err = New("", "").Account()
51 if e, ok := err.(APIError); !ok {
52 t.Errorf("test 2: expecting error of type APIError, got %s", err)
53 } else if e.Code != 5 {
54 t.Errorf("test 2: expecting error value of 5, got %d", e.Code)
55 }
56
57 }
58
59 func TestWrongCommand(t *testing.T) {
60 err := apiConfig.sendAPI("unknown_command", url.Values{}, struct{}{})
61 if err == nil {
62 t.Errorf("expecting error, received nil")
63 } else if e, ok := err.(APIError); !ok {
64 t.Errorf("expecting error of type APIError, got %s: %s", reflect.TypeOf(err).Name(), err)
65 } else if e.Code != 3 {
66 t.Errorf("expecting error code 3 (\"Command is undefined\"), got %d (%q)", e.Code, e.Message)
67 }
68 }
69
70 func TestMain(m *testing.M) {
71 username := os.Getenv("TMusername")
72 password := os.Getenv("TMpassword")
73 if username == "" || password == "" {
74 username = testUsername
75 password = testPassword
76 s := httptest.NewServer(http.HandlerFunc(apiServer))
77 apiURLPrefix = s.URL + "?"
78 }
79 apiConfig = New(username, password)
80 os.Exit(m.Run())
81 }
82