forked from wikiwi/robots-disallow
/
main_test.go
71 lines (61 loc) · 1.27 KB
/
main_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
/*
* Copyright (C) 2016 wikiwi.io
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package main
import (
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"testing"
"time"
)
func getFreePort() string {
l, _ := net.Listen("tcp", "localhost:0")
defer l.Close()
return strings.Split(l.Addr().String(), ":")[1]
}
func runServer() {
main()
panic("main routine exited")
}
func TestServe(t *testing.T) {
addr := "localhost:" + getFreePort()
os.Args = []string{"robots-disallow", "--listen", addr}
go runServer()
time.Sleep(time.Second)
resp, err := http.Get("http://" + addr)
if err != nil {
t.Fatal(err)
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
content := string(bytes)
if content != "User-agent: *\nDisallow: /\n" {
t.Fatalf("unexpected content %s", content)
}
}
func TestVersion(t *testing.T) {
stdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
output := make(chan string)
go func() {
bytes, _ := ioutil.ReadAll(r)
output <- strings.TrimSpace(string(bytes))
}()
os.Args = []string{"robots-disallow", "--version"}
main()
w.Close()
os.Stdout = stdout
content := <-output
if content != version {
t.Fatalf("%q != %q", content, version)
}
}