github.com/olivere/camlistore@v0.0.0-20140121221811-1b7ac2da0199/pkg/test/test.go (about) 1 /* 2 Copyright 2013 The Camlistore Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package test 18 19 import ( 20 "bytes" 21 "io" 22 "io/ioutil" 23 "log" 24 "os" 25 "strconv" 26 "testing" 27 ) 28 29 // BrokenTest marks the test as broken and calls t.Skip, unless the environment 30 // variable RUN_BROKEN_TESTS is set to 1 (or some other boolean true value). 31 func BrokenTest(t *testing.T) { 32 if v, _ := strconv.ParseBool(os.Getenv("RUN_BROKEN_TESTS")); !v { 33 t.Skipf("Skipping broken tests without RUN_BROKEN_TESTS=1") 34 } 35 } 36 37 // TB is a copy of Go 1.2's testing.TB. 38 type TB interface { 39 Error(args ...interface{}) 40 Errorf(format string, args ...interface{}) 41 Fail() 42 FailNow() 43 Failed() bool 44 Fatal(args ...interface{}) 45 Fatalf(format string, args ...interface{}) 46 Log(args ...interface{}) 47 Logf(format string, args ...interface{}) 48 Skip(args ...interface{}) 49 SkipNow() 50 Skipf(format string, args ...interface{}) 51 Skipped() bool 52 } 53 54 // TLog changes the log package's output to log to t and returns a function 55 // to reset it back to stderr. 56 func TLog(t TB) func() { 57 // TODO(bradfitz): once we rely on Go 1.2, change this to take a testing.TB. 58 log.SetOutput(&twriter{t: t}) 59 return func() { 60 log.SetOutput(os.Stderr) 61 } 62 } 63 64 // TODO: This is unnecessarily complicated. I previously missed that 65 // the log package actually guarantees a 1:1 relationship between log 66 // method calls and Write calls: 67 // "Each logging operation makes a single call to the Writer's Write method" 68 type twriter struct { 69 t TB 70 buf bytes.Buffer 71 } 72 73 func (w *twriter) Write(p []byte) (n int, err error) { 74 n, err = w.buf.Write(p) 75 for { 76 i := bytes.IndexByte(w.buf.Bytes(), '\n') 77 if i < 0 { 78 return 79 } 80 if i > 0 { 81 w.t.Log(string(w.buf.Bytes()[:i])) 82 } 83 io.CopyN(ioutil.Discard, &w.buf, int64(i)+1) 84 } 85 }