Merge branch 'master' into 4823-python-sdk-writable-collection-api
[arvados.git] / services / crunchstat / crunchstat_test.go
1 package main
2
3 import (
4         "bufio"
5         "io"
6         "os"
7         "regexp"
8         "testing"
9 )
10
11 func TestReadAllOrWarnFail(t *testing.T) {
12         logChan = make(chan string)
13         go func() {
14                 defer close(logChan)
15                 // The special file /proc/self/mem can be opened for
16                 // reading, but reading from byte 0 returns an error.
17                 f, err := os.Open("/proc/self/mem")
18                 if err != nil {
19                         t.Fatalf("Opening /proc/self/mem: %s", err)
20                 }
21                 if x, err := ReadAllOrWarn(f); err == nil {
22                         t.Fatalf("Expected error, got %v", x)
23                 }
24         }()
25         if _, ok := <-logChan; !ok {
26                 t.Fatalf("Expected error message about nonexistent file")
27         }
28         if msg, ok := <-logChan; ok {
29                 t.Fatalf("Expected channel to close, got %s", msg)
30         }
31 }
32
33 func TestReadAllOrWarnSuccess(t *testing.T) {
34         logChan = make(chan string)
35         go func() {
36                 defer close(logChan)
37                 f, err := os.Open("./crunchstat_test.go")
38                 if err != nil {
39                         t.Fatalf("Opening ./crunchstat_test.go: %s", err)
40                 }
41                 data, err := ReadAllOrWarn(f)
42                 if err != nil {
43                         t.Fatalf("got error %s", err)
44                 }
45                 if matched, err := regexp.MatchString("^package main\n", string(data)); err != nil || !matched {
46                         t.Fatalf("data failed regexp: %s", err)
47                 }
48         }()
49         if msg, ok := <-logChan; ok {
50                 t.Fatalf("Expected channel to close, got %s", msg)
51         }
52 }
53
54 // Test that if CopyPipeToChan reads a line longer than
55 // bufio.MaxScanTokenSize, it emits an error to the output channel.
56 func TestCopyPipeToChanLongLines(t *testing.T) {
57         logChan := make(chan string)
58         control := make(chan bool)
59
60         pipeIn, pipeOut := io.Pipe()
61         go CopyPipeToChan(pipeIn, logChan, control)
62
63         go func() {
64                 long_line := make([]byte, bufio.MaxScanTokenSize+1)
65                 for i := range long_line {
66                         long_line[i] = byte('x')
67                 }
68                 pipeOut.Write(long_line)
69         }()
70
71         // Expect error message from logChan.
72
73         errmsg := <-logChan
74         if matched, err := regexp.MatchString("^crunchstat: line buffering error:.*token too long", errmsg); err != nil || !matched {
75                 t.Fatalf("expected CopyPipeToChan error, got %s", errmsg)
76         }
77
78         <-control
79 }