Unittesting begins

This commit is contained in:
Bel LaPointe
2019-11-12 13:45:32 -07:00
commit 8c4bc81694
35 changed files with 3231 additions and 0 deletions

60
server/ajax/form/form.go Normal file
View File

@@ -0,0 +1,60 @@
package form
import (
"bytes"
"encoding/json"
"html"
"io"
"io/ioutil"
"net/http"
"strconv"
"strings"
"time"
)
type readCloser struct {
io.Reader
}
func (rc readCloser) Close() error {
return nil
}
func Get(r *http.Request, k string) string {
s := r.FormValue(k)
if s == "" {
b, _ := ioutil.ReadAll(r.Body)
var m map[string]json.RawMessage
if err := json.Unmarshal(b, &m); err != nil {
return ""
}
v, _ := m[k]
s = strings.TrimPrefix(strings.TrimSuffix(string(v), `"`), `"`)
r.Body = readCloser{bytes.NewReader(b)}
}
s = html.UnescapeString(s)
s = strings.ReplaceAll(s, "\r", "")
return s
}
func ToInt(s string) int {
v, _ := strconv.Atoi(s)
return v
}
func ToStrArr(k string) []string {
arr := strings.Split(k, ",")
outArr := []string{}
for i := range arr {
s := strings.TrimSpace(arr[i])
if len(s) > 0 {
outArr = append(outArr, s)
}
}
return outArr
}
func ToTime(s string) time.Time {
v, _ := time.Parse("2006-01-02 15:04:05", s)
return v
}

View File

@@ -0,0 +1,132 @@
package form
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestGet(t *testing.T) {
r := testReq()
if v := Get(r, "a"); v != "b" {
t.Error(v)
}
if v := Get(r, "c"); v != "4" {
t.Error(v)
}
if v := Get(r, "d"); v != "e, f,g" {
t.Error(v)
}
}
func TestToStrArr(t *testing.T) {
cases := []struct {
in string
out int
}{
{
in: "4",
out: 1,
},
{
in: "a,b,c",
out: 3,
},
{
in: " a, b, c ",
out: 3,
},
{
in: "a,b, c",
out: 3,
},
{
in: "a,b",
out: 2,
},
{
in: "a,",
out: 1,
},
{
in: "a",
out: 1,
},
{
in: "",
out: 0,
},
}
for _, c := range cases {
if len(ToStrArr(c.in)) != c.out {
t.Error(c)
}
}
}
func TestToTime(t *testing.T) {
cases := []struct {
in string
out string
}{
{
in: "2001-02-03 04:05:06",
out: "2001-02-03 04:05:06",
},
{
in: "5",
out: "0001-01-01 00:00:00",
},
}
for _, c := range cases {
time := ToTime(c.in)
if v := time.Format("2006-01-02 15:04:05"); v != c.out {
t.Error(c, v)
}
}
}
func TestToInt(t *testing.T) {
cases := []struct {
in string
out int
}{
{
in: "4",
out: 4,
},
{
in: "a",
out: 0,
},
{
in: "",
out: 0,
},
{
in: "-1",
out: -1,
},
{
in: "5",
out: 5,
},
}
for _, c := range cases {
if ToInt(c.in) != c.out {
t.Error(c)
}
}
}
func testReq() *http.Request {
return httptest.NewRequest("POST", "/path/to", strings.NewReader(`{
"a": "b",
"c": 4,
"d": "e, f,g"
}`))
}