1
|
|
|
package devto |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"encoding/json" |
5
|
|
|
"errors" |
6
|
|
|
"io/ioutil" |
7
|
|
|
"reflect" |
8
|
|
|
"strings" |
9
|
|
|
"testing" |
10
|
|
|
) |
11
|
|
|
|
12
|
|
|
func TestWebURL_UnmarshalJSON(t *testing.T) { |
13
|
|
|
tests := []struct { |
14
|
|
|
name string |
15
|
|
|
content string |
16
|
|
|
wantErr bool |
17
|
|
|
err error |
18
|
|
|
}{ |
19
|
|
|
{ |
20
|
|
|
"Unmarshal works fine", |
21
|
|
|
`{"visit": "https://dev.to/victoravelar"}`, |
22
|
|
|
false, |
23
|
|
|
nil, |
24
|
|
|
}, |
25
|
|
|
{ |
26
|
|
|
"Unmarshal fails when parsing url", |
27
|
|
|
`{"visit": " http://localhost"}`, |
28
|
|
|
false, |
29
|
|
|
errors.New("parse http://localhost: first path segment in URL cannot contain colon"), |
30
|
|
|
}, |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
type tester struct { |
34
|
|
|
Visit WebURL `json:"visit"` |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
for _, tt := range tests { |
38
|
|
|
t.Run(tt.name, func(t *testing.T) { |
39
|
|
|
var wu tester |
40
|
|
|
c, err := ioutil.ReadAll(strings.NewReader(tt.content)) |
41
|
|
|
json.Unmarshal(c, &wu) |
42
|
|
|
if tt.wantErr && err != nil { |
43
|
|
|
if !reflect.DeepEqual(tt.err, err) { |
44
|
|
|
t.Errorf("want: %v, got: %v", tt.err, err) |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
}) |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
func TestWebURL_UnmarshalJSON1(t *testing.T) { |
52
|
|
|
type args struct { |
53
|
|
|
b []byte |
54
|
|
|
} |
55
|
|
|
tests := []struct { |
56
|
|
|
name string |
57
|
|
|
args args |
58
|
|
|
wantErr bool |
59
|
|
|
}{ |
60
|
|
|
{ |
61
|
|
|
"Unmarshal google.com", |
62
|
|
|
args{b: []byte("https://dev.to")}, |
63
|
|
|
false, |
64
|
|
|
}, |
65
|
|
|
{ |
66
|
|
|
"Unmarshal parse error", |
67
|
|
|
args{b: []byte(" https://dev.to")}, |
68
|
|
|
true, |
69
|
|
|
}, |
70
|
|
|
{ |
71
|
|
|
"unmarshal partial url", |
72
|
|
|
args{b: []byte("dev.to")}, |
73
|
|
|
false, |
74
|
|
|
}, |
75
|
|
|
{ |
76
|
|
|
"unmarshal url with query", |
77
|
|
|
args{b: []byte("https://dev.to/api/articles?username=victoravelar")}, |
78
|
|
|
false, |
79
|
|
|
}, |
80
|
|
|
} |
81
|
|
|
for _, tt := range tests { |
82
|
|
|
t.Run(tt.name, func(t *testing.T) { |
83
|
|
|
s := &WebURL{} |
84
|
|
|
if err := s.UnmarshalJSON(tt.args.b); (err != nil) != tt.wantErr { |
85
|
|
|
t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr) |
86
|
|
|
} |
87
|
|
|
}) |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|