-
Notifications
You must be signed in to change notification settings - Fork 0
/
fortune_test.go
87 lines (79 loc) · 1.6 KB
/
fortune_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package fortune_telling
import (
"encoding/json"
"fmt"
"github.com/PuerkitoBio/goquery"
"log"
"os"
"strings"
"testing"
)
const (
DownUrl = "https://www.buyiju.com/guandi/%d.html"
)
func init() {
fmt.Printf("test_init")
}
func downloadFortuneData(saveTo string) error {
var mSigns = make([]Telling, 0)
for i := 1; i <= 100; i++ {
doc, err := goquery.NewDocument(fmt.Sprintf(DownUrl, i))
if err != nil {
return err
}
var telling Telling
doc.Find("div.content").Find("p").Each(func(i int, selection *goquery.Selection) {
tmpText := selection.Text()
switch i {
case 0:
leftIndex := strings.Index(tmpText, "(")
rightIndex := strings.Index(tmpText, ")")
telling.Level = tmpText[leftIndex+1 : rightIndex]
case 3:
telling.Content = tmpText
case 7:
telling.Detail1 = tmpText
case 9:
left := strings.Index(tmpText, ":")
telling.Detail2 = tmpText[left+3:]
}
})
mSigns = append(mSigns, telling)
log.Printf("%d get: %v", i, telling)
}
ret, _ := json.Marshal(mSigns)
f, err := os.Create(saveTo)
if err != nil {
return err
}
_, _ = f.Write(ret)
return f.Close()
}
func exist(filepath string) bool {
_, err := os.Stat(filepath)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func TestDownload(t *testing.T) {
if !exist(fileJson) {
err := downloadFortuneData(fileJson)
if err != nil {
t.Error(err)
}
}
}
func TestAsk(t *testing.T) {
for i := 0; i < 10; i++ {
tell, err := Ask(fmt.Sprintf("%v", i))
if err != nil {
t.Errorf("ask: %v", err)
} else {
t.Logf("%v: %v", i, tell)
}
}
}