1package govalidator
2
3import (
4	"fmt"
5	"testing"
6)
7
8func TestToInt(t *testing.T) {
9	tests := []interface{}{"1000", "-123", "abcdef", "100000000000000000000000000000000000000000000", false}
10	expected := []int64{1000, -123, 0, 0, 0}
11	for i := 0; i < len(tests); i++ {
12		result, _ := ToInt(tests[i])
13		if result != expected[i] {
14			t.Log("Case ", i, ": expected ", expected[i], " when result is ", result)
15			t.FailNow()
16		}
17	}
18}
19
20func TestToBoolean(t *testing.T) {
21	tests := []string{"true", "1", "True", "false", "0", "abcdef"}
22	expected := []bool{true, true, true, false, false, false}
23	for i := 0; i < len(tests); i++ {
24		res, _ := ToBoolean(tests[i])
25		if res != expected[i] {
26			t.Log("Case ", i, ": expected ", expected[i], " when result is ", res)
27			t.FailNow()
28		}
29	}
30}
31
32func toString(t *testing.T, test interface{}, expected string) {
33	res := ToString(test)
34	if res != expected {
35		t.Log("Case ToString: expected ", expected, " when result is ", res)
36		t.FailNow()
37	}
38}
39
40func TestToString(t *testing.T) {
41	toString(t, "str123", "str123")
42	toString(t, 123, "123")
43	toString(t, 12.3, "12.3")
44	toString(t, true, "true")
45	toString(t, 1.5+10i, "(1.5+10i)")
46	// Sprintf function not guarantee that maps with equal keys always will be equal in string  representation
47	//toString(t, struct{ Keys map[int]int }{Keys: map[int]int{1: 2, 3: 4}}, "{map[1:2 3:4]}")
48}
49
50func TestToFloat(t *testing.T) {
51	tests := []string{"", "123", "-.01", "10.", "string", "1.23e3", ".23e10"}
52	expected := []float64{0, 123, -0.01, 10.0, 0, 1230, 0.23e10}
53	for i := 0; i < len(tests); i++ {
54		res, _ := ToFloat(tests[i])
55		if res != expected[i] {
56			t.Log("Case ", i, ": expected ", expected[i], " when result is ", res)
57			t.FailNow()
58		}
59	}
60}
61
62func TestToJSON(t *testing.T) {
63	tests := []interface{}{"test", map[string]string{"a": "b", "b": "c"}, func() error { return fmt.Errorf("Error") }}
64	expected := [][]string{
65		{"\"test\"", "<nil>"},
66		{"{\"a\":\"b\",\"b\":\"c\"}", "<nil>"},
67		{"", "json: unsupported type: func() error"},
68	}
69	for i, test := range tests {
70		actual, err := ToJSON(test)
71		if actual != expected[i][0] {
72			t.Errorf("Expected toJSON(%v) to return '%v', got '%v'", test, expected[i][0], actual)
73		}
74		if fmt.Sprintf("%v", err) != expected[i][1] {
75			t.Errorf("Expected error returned from toJSON(%v) to return '%v', got '%v'", test, expected[i][1], fmt.Sprintf("%v", err))
76		}
77	}
78}
79