| Abhay Kumar | a61c522 | 2025-11-10 07:32:50 +0000 | [diff] [blame^] | 1 | // Copyright (c) 2016 Uber Technologies, Inc. |
| 2 | // |
| 3 | // Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 | // of this software and associated documentation files (the "Software"), to deal |
| 5 | // in the Software without restriction, including without limitation the rights |
| 6 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 | // copies of the Software, and to permit persons to whom the Software is |
| 8 | // furnished to do so, subject to the following conditions: |
| 9 | // |
| 10 | // The above copyright notice and this permission notice shall be included in |
| 11 | // all copies or substantial portions of the Software. |
| 12 | // |
| 13 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 19 | // THE SOFTWARE. |
| 20 | |
| 21 | package ztest |
| 22 | |
| 23 | import ( |
| 24 | "log" |
| 25 | "os" |
| 26 | "strconv" |
| 27 | "time" |
| 28 | ) |
| 29 | |
| 30 | var _timeoutScale = 1.0 |
| 31 | |
| 32 | // Timeout scales the provided duration by $TEST_TIMEOUT_SCALE. |
| 33 | func Timeout(base time.Duration) time.Duration { |
| 34 | return time.Duration(float64(base) * _timeoutScale) |
| 35 | } |
| 36 | |
| 37 | // Sleep scales the sleep duration by $TEST_TIMEOUT_SCALE. |
| 38 | func Sleep(base time.Duration) { |
| 39 | time.Sleep(Timeout(base)) |
| 40 | } |
| 41 | |
| 42 | // Initialize checks the environment and alters the timeout scale accordingly. |
| 43 | // It returns a function to undo the scaling. |
| 44 | func Initialize(factor string) func() { |
| 45 | fv, err := strconv.ParseFloat(factor, 64) |
| 46 | if err != nil { |
| 47 | panic(err) |
| 48 | } |
| 49 | original := _timeoutScale |
| 50 | _timeoutScale = fv |
| 51 | return func() { _timeoutScale = original } |
| 52 | } |
| 53 | |
| 54 | func init() { |
| 55 | if v := os.Getenv("TEST_TIMEOUT_SCALE"); v != "" { |
| 56 | Initialize(v) |
| 57 | log.Printf("Scaling timeouts by %vx.\n", _timeoutScale) |
| 58 | } |
| 59 | } |