1 /* 2 Copyright 2013 The Perkeep 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 "log" 21 "os" 22 "strconv" 23 "strings" 24 "testing" 25 "time" 26 ) 27 28 // ClockOrigin is an arbitrary contemporary date that can be used as a starting 29 // time in tests. It is 2011-11-28 01:32:36.000123456 +0000 UTC. 30 var ClockOrigin = time.Unix(1322443956, 123456) 31 32 // BrokenTest marks the test as broken and calls t.Skip, unless the environment 33 // variable RUN_BROKEN_TESTS is set to 1 (or some other boolean true value). 34 func BrokenTest(t *testing.T) { 35 if v, _ := strconv.ParseBool(os.Getenv("RUN_BROKEN_TESTS")); !v { 36 t.Skipf("Skipping broken tests without RUN_BROKEN_TESTS=1") 37 } 38 } 39 40 // TLog changes the log package's output to log to t and returns a function 41 // to reset it back to stderr. 42 func TLog(t testing.TB) func() { 43 log.SetOutput(twriter{t: t}) 44 return func() { 45 log.SetOutput(os.Stderr) 46 } 47 } 48 49 type twriter struct { 50 t testing.TB 51 quietPhrases []string 52 } 53 54 func (w twriter) Write(p []byte) (n int, err error) { 55 if len(w.quietPhrases) > 0 { 56 s := string(p) 57 for _, phrase := range w.quietPhrases { 58 if strings.Contains(s, phrase) { 59 return len(p), nil 60 } 61 } 62 } 63 if w.t != nil { 64 w.t.Log(strings.TrimSuffix(string(p), "\n")) 65 } 66 return len(p), nil 67 } 68 69 // NewLogger returns a logger that logs to t with the given prefix. 70 // 71 // The optional quietPhrases are substrings to match in writes to 72 // determine whether those log messages are muted. 73 func NewLogger(t *testing.T, prefix string, quietPhrases ...string) *log.Logger { 74 return log.New(twriter{t: t, quietPhrases: quietPhrases}, prefix, log.LstdFlags) 75 }