├── .editorconfig ├── .github ├── .editorconfig ├── dependabot.yaml ├── release.yml └── workflows │ ├── ci.yaml │ └── codeql.yaml ├── .gitignore ├── LICENSE ├── README.md ├── SECURITY.md ├── clockwork.go ├── clockwork_test.go ├── context.go ├── context_test.go ├── example_test.go ├── go.mod ├── ticker.go ├── ticker_test.go ├── timer.go └── timer_test.go /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_size = 4 7 | indent_style = space 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.go] 12 | indent_style = tab 13 | -------------------------------------------------------------------------------- /.github/.editorconfig: -------------------------------------------------------------------------------- 1 | [{*.yml,*.yaml}] 2 | indent_size = 2 3 | -------------------------------------------------------------------------------- /.github/dependabot.yaml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | updates: 4 | - package-ecosystem: github-actions 5 | directory: / 6 | labels: 7 | - dependencies 8 | schedule: 9 | interval: daily 10 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | changelog: 2 | exclude: 3 | labels: 4 | - release-note/ignore 5 | categories: 6 | - title: Exciting New Features 🎉 7 | labels: 8 | - release-note/new-feature 9 | - title: Enhancements 🚀 10 | labels: 11 | - enhancement 12 | - release-note/enhancement 13 | - title: Bug Fixes 🐛 14 | labels: 15 | - bug 16 | - release-note/bug-fix 17 | - title: Breaking Changes 🛠 18 | labels: 19 | - release-note/breaking-change 20 | - title: Deprecations ❌ 21 | labels: 22 | - release-note/deprecation 23 | - title: Dependency Updates ⬆️ 24 | labels: 25 | - dependencies 26 | - release-note/dependency-update 27 | - title: Other Changes 28 | labels: 29 | - "*" 30 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | 8 | permissions: 9 | contents: read 10 | 11 | jobs: 12 | test: 13 | name: Test 14 | runs-on: ubuntu-latest 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | go: ['1.21', '1.22', '1.23'] 19 | 20 | steps: 21 | - name: Set up Go 22 | uses: actions/setup-go@v5 23 | with: 24 | go-version: ${{ matrix.go }} 25 | 26 | - name: Checkout code 27 | uses: actions/checkout@v4 28 | 29 | - name: Run tests 30 | run: go test -v -race 31 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yaml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ "master" ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ "master" ] 20 | schedule: 21 | - cron: '27 12 * * 0' 22 | 23 | permissions: 24 | contents: read 25 | 26 | jobs: 27 | analyze: 28 | name: Analyze 29 | runs-on: ubuntu-latest 30 | permissions: 31 | actions: read 32 | security-events: write 33 | 34 | strategy: 35 | fail-fast: false 36 | matrix: 37 | language: [ 'go' ] 38 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 39 | # Use only 'java' to analyze code written in Java, Kotlin or both 40 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both 41 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 42 | 43 | steps: 44 | - name: Checkout repository 45 | uses: actions/checkout@v4 46 | 47 | # Initializes the CodeQL tools for scanning. 48 | - name: Initialize CodeQL 49 | uses: github/codeql-action/init@v3 50 | with: 51 | languages: ${{ matrix.language }} 52 | # If you wish to specify custom queries, you can do so here or in a config file. 53 | # By default, queries listed here will override any specified in a config file. 54 | # Prefix the list here with "+" to use these queries and those in the config file. 55 | 56 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 57 | # queries: security-extended,security-and-quality 58 | 59 | 60 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). 61 | # If this step fails, then you should remove it and run the build manually (see below) 62 | - name: Autobuild 63 | uses: github/codeql-action/autobuild@v3 64 | 65 | # ℹ️ Command-line programs to run using the OS shell. 66 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 67 | 68 | # If the Autobuild fails above, remove it and uncomment the following three lines. 69 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 70 | 71 | # - run: | 72 | # echo "Run, Build Application using script" 73 | # ./location_of_script_within_repo/buildscript.sh 74 | 75 | - name: Perform CodeQL Analysis 76 | uses: github/codeql-action/analyze@v3 77 | with: 78 | category: "/language:${{matrix.language}}" 79 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ 2 | 3 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 4 | *.o 5 | *.a 6 | *.so 7 | 8 | # Folders 9 | _obj 10 | _test 11 | 12 | # Architecture specific extensions/prefixes 13 | *.[568vq] 14 | [568vq].out 15 | 16 | *.cgo1.go 17 | *.cgo2.c 18 | _cgo_defun.c 19 | _cgo_gotypes.go 20 | _cgo_export.* 21 | 22 | _testmain.go 23 | 24 | *.exe 25 | *.test 26 | 27 | *.swp 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # clockwork 2 | 3 | [![Mentioned in Awesome Go](https://awesome.re/mentioned-badge-flat.svg)](https://github.com/avelino/awesome-go#utilities) 4 | 5 | [![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/jonboulle/clockwork/ci.yaml?style=flat-square)](https://github.com/jonboulle/clockwork/actions?query=workflow%3ACI) 6 | [![Go Report Card](https://goreportcard.com/badge/github.com/jonboulle/clockwork?style=flat-square)](https://goreportcard.com/report/github.com/jonboulle/clockwork) 7 | ![Go Version](https://img.shields.io/badge/go%20version-%3E=1.15-61CFDD.svg?style=flat-square) 8 | [![go.dev reference](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white&style=flat-square)](https://pkg.go.dev/mod/github.com/jonboulle/clockwork) 9 | 10 | **A simple fake clock for Go.** 11 | 12 | 13 | ## Usage 14 | 15 | Replace uses of the `time` package with the `clockwork.Clock` interface instead. 16 | 17 | For example, instead of using `time.Sleep` directly: 18 | 19 | ```go 20 | func myFunc() { 21 | time.Sleep(3 * time.Second) 22 | doSomething() 23 | } 24 | ``` 25 | 26 | Inject a clock and use its `Sleep` method instead: 27 | 28 | ```go 29 | func myFunc(clock clockwork.Clock) { 30 | clock.Sleep(3 * time.Second) 31 | doSomething() 32 | } 33 | ``` 34 | 35 | Now you can easily test `myFunc` with a `FakeClock`: 36 | 37 | ```go 38 | func TestMyFunc(t *testing.T) { 39 | ctx := context.Background() 40 | c := clockwork.NewFakeClock() 41 | 42 | // Start our sleepy function 43 | var wg sync.WaitGroup 44 | wg.Add(1) 45 | go func() { 46 | myFunc(c) 47 | wg.Done() 48 | }() 49 | 50 | // Ensure we wait until myFunc is waiting on the clock. 51 | // Use a context to avoid blocking forever if something 52 | // goes wrong. 53 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) 54 | defer cancel() 55 | c.BlockUntilContext(ctx, 1) 56 | 57 | assertState() 58 | 59 | // Advance the FakeClock forward in time 60 | c.Advance(3 * time.Second) 61 | 62 | // Wait until the function completes 63 | wg.Wait() 64 | 65 | assertState() 66 | } 67 | ``` 68 | 69 | and in production builds, simply inject the real clock instead: 70 | 71 | ```go 72 | myFunc(clockwork.NewRealClock()) 73 | ``` 74 | 75 | See [example_test.go](example_test.go) for a full example. 76 | 77 | 78 | # Credits 79 | 80 | clockwork is inspired by @wickman's [threaded fake clock](https://gist.github.com/wickman/3840816), and the [Golang playground](https://blog.golang.org/playground#TOC_3.1.) 81 | 82 | 83 | ## License 84 | 85 | Apache License, Version 2.0. Please see [License File](LICENSE) for more information. 86 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | If you have discovered a security vulnerability in this project, please report it 4 | privately. **Do not disclose it as a public issue.** This gives me time to work with you 5 | to fix the issue before public exposure, reducing the chance that the exploit will be 6 | used before a patch is released. 7 | 8 | You may submit the report in the following ways: 9 | 10 | - send an email to ???@???; and/or 11 | - send a [private vulnerability report](https://github.com/jonboulle/clockwork/security/advisories/new) 12 | 13 | Please provide the following information in your report: 14 | 15 | - A description of the vulnerability and its impact 16 | - How to reproduce the issue 17 | 18 | This project is maintained by a single maintainer on a reasonable-effort basis. As such, 19 | please give me 90 days to work on a fix before public exposure. 20 | -------------------------------------------------------------------------------- /clockwork.go: -------------------------------------------------------------------------------- 1 | // Package clockwork contains a simple fake clock for Go. 2 | package clockwork 3 | 4 | import ( 5 | "context" 6 | "errors" 7 | "slices" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | // Clock provides an interface that packages can use instead of directly using 13 | // the [time] module, so that chronology-related behavior can be tested. 14 | type Clock interface { 15 | After(d time.Duration) <-chan time.Time 16 | Sleep(d time.Duration) 17 | Now() time.Time 18 | Since(t time.Time) time.Duration 19 | Until(t time.Time) time.Duration 20 | NewTicker(d time.Duration) Ticker 21 | NewTimer(d time.Duration) Timer 22 | AfterFunc(d time.Duration, f func()) Timer 23 | } 24 | 25 | // NewRealClock returns a Clock which simply delegates calls to the actual time 26 | // package; it should be used by packages in production. 27 | func NewRealClock() Clock { 28 | return &realClock{} 29 | } 30 | 31 | type realClock struct{} 32 | 33 | func (rc *realClock) After(d time.Duration) <-chan time.Time { 34 | return time.After(d) 35 | } 36 | 37 | func (rc *realClock) Sleep(d time.Duration) { 38 | time.Sleep(d) 39 | } 40 | 41 | func (rc *realClock) Now() time.Time { 42 | return time.Now() 43 | } 44 | 45 | func (rc *realClock) Since(t time.Time) time.Duration { 46 | return rc.Now().Sub(t) 47 | } 48 | 49 | func (rc *realClock) Until(t time.Time) time.Duration { 50 | return t.Sub(rc.Now()) 51 | } 52 | 53 | func (rc *realClock) NewTicker(d time.Duration) Ticker { 54 | return realTicker{time.NewTicker(d)} 55 | } 56 | 57 | func (rc *realClock) NewTimer(d time.Duration) Timer { 58 | return realTimer{time.NewTimer(d)} 59 | } 60 | 61 | func (rc *realClock) AfterFunc(d time.Duration, f func()) Timer { 62 | return realTimer{time.AfterFunc(d, f)} 63 | } 64 | 65 | // FakeClock provides an interface for a clock which can be manually advanced 66 | // through time. 67 | // 68 | // FakeClock maintains a list of "waiters," which consists of all callers 69 | // waiting on the underlying clock (i.e. Tickers and Timers including callers of 70 | // Sleep or After). Users can call BlockUntil to block until the clock has an 71 | // expected number of waiters. 72 | type FakeClock struct { 73 | // l protects all attributes of the clock, including all attributes of all 74 | // waiters and blockers. 75 | l sync.RWMutex 76 | waiters []expirer 77 | blockers []*blocker 78 | time time.Time 79 | } 80 | 81 | // NewFakeClock returns a FakeClock implementation which can be 82 | // manually advanced through time for testing. The initial time of the 83 | // FakeClock will be the current system time. 84 | // 85 | // Tests that require a deterministic time must use NewFakeClockAt. 86 | func NewFakeClock() *FakeClock { 87 | return NewFakeClockAt(time.Now()) 88 | } 89 | 90 | // NewFakeClockAt returns a FakeClock initialised at the given time.Time. 91 | func NewFakeClockAt(t time.Time) *FakeClock { 92 | return &FakeClock{ 93 | time: t, 94 | } 95 | } 96 | 97 | // blocker is a caller of BlockUntil. 98 | type blocker struct { 99 | count int 100 | 101 | // ch is closed when the underlying clock has the specified number of blockers. 102 | ch chan struct{} 103 | } 104 | 105 | // expirer is a timer or ticker that expires at some point in the future. 106 | type expirer interface { 107 | // expire the expirer at the given time, returning the desired duration until 108 | // the next expiration, if any. 109 | expire(now time.Time) (next *time.Duration) 110 | 111 | // Get and set the expiration time. 112 | expiration() time.Time 113 | setExpiration(time.Time) 114 | } 115 | 116 | // After mimics [time.After]; it waits for the given duration to elapse on the 117 | // fakeClock, then sends the current time on the returned channel. 118 | func (fc *FakeClock) After(d time.Duration) <-chan time.Time { 119 | return fc.NewTimer(d).Chan() 120 | } 121 | 122 | // Sleep blocks until the given duration has passed on the fakeClock. 123 | func (fc *FakeClock) Sleep(d time.Duration) { 124 | <-fc.After(d) 125 | } 126 | 127 | // Now returns the current time of the fakeClock 128 | func (fc *FakeClock) Now() time.Time { 129 | fc.l.RLock() 130 | defer fc.l.RUnlock() 131 | return fc.time 132 | } 133 | 134 | // Since returns the duration that has passed since the given time on the 135 | // fakeClock. 136 | func (fc *FakeClock) Since(t time.Time) time.Duration { 137 | return fc.Now().Sub(t) 138 | } 139 | 140 | // Until returns the duration that has to pass from the given time on the fakeClock 141 | // to reach the given time. 142 | func (fc *FakeClock) Until(t time.Time) time.Duration { 143 | return t.Sub(fc.Now()) 144 | } 145 | 146 | // NewTicker returns a Ticker that will expire only after calls to 147 | // FakeClock.Advance() have moved the clock past the given duration. 148 | // 149 | // The duration d must be greater than zero; if not, NewTicker will panic. 150 | func (fc *FakeClock) NewTicker(d time.Duration) Ticker { 151 | // Maintain parity with 152 | // https://cs.opensource.google/go/go/+/refs/tags/go1.20.3:src/time/tick.go;l=23-25 153 | if d <= 0 { 154 | panic(errors.New("non-positive interval for NewTicker")) 155 | } 156 | ft := newFakeTicker(fc, d) 157 | fc.l.Lock() 158 | defer fc.l.Unlock() 159 | fc.setExpirer(ft, d) 160 | return ft 161 | } 162 | 163 | // NewTimer returns a Timer that will fire only after calls to 164 | // fakeClock.Advance() have moved the clock past the given duration. 165 | func (fc *FakeClock) NewTimer(d time.Duration) Timer { 166 | t, _ := fc.newTimer(d, nil) 167 | return t 168 | } 169 | 170 | // AfterFunc mimics [time.AfterFunc]; it returns a Timer that will invoke the 171 | // given function only after calls to fakeClock.Advance() have moved the clock 172 | // past the given duration. 173 | func (fc *FakeClock) AfterFunc(d time.Duration, f func()) Timer { 174 | t, _ := fc.newTimer(d, f) 175 | return t 176 | } 177 | 178 | // newTimer returns a new timer using an optional afterFunc and the time that 179 | // timer expires. 180 | func (fc *FakeClock) newTimer(d time.Duration, afterfunc func()) (*fakeTimer, time.Time) { 181 | ft := newFakeTimer(fc, afterfunc) 182 | fc.l.Lock() 183 | defer fc.l.Unlock() 184 | fc.setExpirer(ft, d) 185 | return ft, ft.expiration() 186 | } 187 | 188 | // newTimerAtTime is like newTimer, but uses a time instead of a duration. 189 | // 190 | // It is used to ensure FakeClock's lock is held constant through calling 191 | // fc.After(t.Sub(fc.Now())). It should not be exposed externally. 192 | func (fc *FakeClock) newTimerAtTime(t time.Time, afterfunc func()) *fakeTimer { 193 | ft := newFakeTimer(fc, afterfunc) 194 | fc.l.Lock() 195 | defer fc.l.Unlock() 196 | fc.setExpirer(ft, t.Sub(fc.time)) 197 | return ft 198 | } 199 | 200 | // Advance advances fakeClock to a new point in time, ensuring waiters and 201 | // blockers are notified appropriately before returning. 202 | func (fc *FakeClock) Advance(d time.Duration) { 203 | fc.l.Lock() 204 | defer fc.l.Unlock() 205 | end := fc.time.Add(d) 206 | // Expire the earliest waiter until the earliest waiter's expiration is after 207 | // end. 208 | // 209 | // We don't iterate because the callback of the waiter might register a new 210 | // waiter, so the list of waiters might change as we execute this. 211 | for len(fc.waiters) > 0 && !end.Before(fc.waiters[0].expiration()) { 212 | w := fc.waiters[0] 213 | fc.waiters = fc.waiters[1:] 214 | 215 | // Use the waiter's expiration as the current time for this expiration. 216 | now := w.expiration() 217 | fc.time = now 218 | if d := w.expire(now); d != nil { 219 | // Set the new expiration if needed. 220 | fc.setExpirer(w, *d) 221 | } 222 | } 223 | fc.time = end 224 | } 225 | 226 | // BlockUntil blocks until the FakeClock has the given number of waiters. 227 | // 228 | // Prefer BlockUntilContext in new code, which offers context cancellation to 229 | // prevent deadlock. 230 | // 231 | // Deprecated: New code should prefer BlockUntilContext. 232 | func (fc *FakeClock) BlockUntil(n int) { 233 | fc.BlockUntilContext(context.TODO(), n) 234 | } 235 | 236 | // BlockUntilContext blocks until the fakeClock has the given number of waiters 237 | // or the context is cancelled. 238 | func (fc *FakeClock) BlockUntilContext(ctx context.Context, n int) error { 239 | b := fc.newBlocker(n) 240 | if b == nil { 241 | return nil 242 | } 243 | 244 | select { 245 | case <-b.ch: 246 | return nil 247 | case <-ctx.Done(): 248 | return ctx.Err() 249 | } 250 | } 251 | 252 | func (fc *FakeClock) newBlocker(n int) *blocker { 253 | fc.l.Lock() 254 | defer fc.l.Unlock() 255 | // Fast path: we already have >= n waiters. 256 | if len(fc.waiters) >= n { 257 | return nil 258 | } 259 | // Set up a new blocker to wait for more waiters. 260 | b := &blocker{ 261 | count: n, 262 | ch: make(chan struct{}), 263 | } 264 | fc.blockers = append(fc.blockers, b) 265 | return b 266 | } 267 | 268 | // stop stops an expirer, returning true if the expirer was stopped. 269 | func (fc *FakeClock) stop(e expirer) bool { 270 | fc.l.Lock() 271 | defer fc.l.Unlock() 272 | return fc.stopExpirer(e) 273 | } 274 | 275 | // stopExpirer stops an expirer, returning true if the expirer was stopped. 276 | // 277 | // The caller must hold fc.l. 278 | func (fc *FakeClock) stopExpirer(e expirer) bool { 279 | idx := slices.Index(fc.waiters, e) 280 | if idx == -1 { 281 | return false 282 | } 283 | // Remove element, maintaining order, setting inaccessible elements to nil so 284 | // they can be garbage collected. 285 | copy(fc.waiters[idx:], fc.waiters[idx+1:]) 286 | fc.waiters[len(fc.waiters)-1] = nil 287 | fc.waiters = fc.waiters[:len(fc.waiters)-1] 288 | return true 289 | } 290 | 291 | // setExpirer sets an expirer to expire at a future point in time. 292 | // 293 | // The caller must hold fc.l. 294 | func (fc *FakeClock) setExpirer(e expirer, d time.Duration) { 295 | if d.Nanoseconds() <= 0 { 296 | // Special case for timers with duration <= 0: trigger immediately, never 297 | // reset. 298 | // 299 | // Tickers never get here, they panic if d is < 0. 300 | e.expire(fc.time) 301 | return 302 | } 303 | // Add the expirer to the set of waiters and notify any blockers. 304 | e.setExpiration(fc.time.Add(d)) 305 | fc.waiters = append(fc.waiters, e) 306 | slices.SortFunc(fc.waiters, func(a, b expirer) int { 307 | return a.expiration().Compare(b.expiration()) 308 | }) 309 | 310 | // Notify blockers of our new waiter. 311 | count := len(fc.waiters) 312 | fc.blockers = slices.DeleteFunc(fc.blockers, func(b *blocker) bool { 313 | if b.count <= count { 314 | close(b.ch) 315 | return true 316 | } 317 | return false 318 | }) 319 | } 320 | -------------------------------------------------------------------------------- /clockwork_test.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | // Use a consistent timeout across tests that block on channels. Keeps test 11 | // timeouts limited while being able to easily extend it to allow the test 12 | // process to get killed, providing a stack trace. 13 | const timeout = time.Minute 14 | 15 | func TestAfter(t *testing.T) { 16 | t.Parallel() 17 | fc := &FakeClock{} 18 | 19 | var timers []<-chan time.Time 20 | for i := 0; i < 3; i++ { 21 | timers = append(timers, fc.After(time.Duration(i*2+1))) // 1, 3, 5 22 | } 23 | 24 | // Nothing fired immediately. 25 | for i, ch := range timers { 26 | select { 27 | case <-ch: 28 | t.Errorf("Timer at time=%v fired at time=0", i*2+1) 29 | default: 30 | } 31 | } 32 | 33 | // First timer fires at time=1. 34 | fc.Advance(1) 35 | select { 36 | case <-timers[0]: 37 | default: 38 | t.Errorf("Timer at time=1 did not fire at time=1") 39 | } 40 | for i, ch := range timers[1:] { 41 | select { 42 | case <-ch: 43 | t.Errorf("Timer at time=%v fired at time=1", i*2+3) 44 | default: 45 | } 46 | } 47 | 48 | // Should not change anything. 49 | fc.Advance(1) 50 | for i, ch := range timers[1:] { 51 | select { 52 | case <-ch: 53 | t.Errorf("Timer at time=%v fired at time=2", i*2+3) 54 | default: 55 | } 56 | } 57 | 58 | // Add 1 more timer at time 5. Should fire at the same time as our timer in chs[2] 59 | timers = append(timers, fc.After(time.Duration(3))) // Current time + 3 = 2 + 3 = 5 60 | 61 | // Skip over timer at time 3, advancing directly to 4. Check it works as expected. 62 | fc.Advance(2) 63 | select { 64 | case <-timers[1]: 65 | default: 66 | t.Errorf("Timer at time=3 did not fire at time=4") 67 | } 68 | for _, i := range []int{2, 3} { 69 | select { 70 | case <-timers[i]: 71 | t.Errorf("Timer at time=5 fired at time=4") 72 | default: 73 | } 74 | } 75 | 76 | fc.Advance(1) 77 | for idx, tIdex := range []int{2, 3} { 78 | select { 79 | case <-timers[tIdex]: 80 | default: 81 | t.Errorf("Timer at time=5 #%v did not fire at time=5", idx) 82 | } 83 | } 84 | } 85 | 86 | func TestAfterZero(t *testing.T) { 87 | t.Parallel() 88 | cases := []struct { 89 | name string 90 | 91 | d time.Duration 92 | }{ 93 | {name: "zero"}, 94 | { 95 | name: "negative", 96 | d: -time.Second, 97 | }, 98 | } 99 | 100 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 101 | defer cancel() 102 | 103 | for _, tc := range cases { 104 | t.Run(tc.name, func(t *testing.T) { 105 | fc := &FakeClock{} 106 | select { 107 | case <-fc.After(tc.d): 108 | case <-ctx.Done(): 109 | t.Errorf("FakeClock.After() did not return.") 110 | } 111 | }) 112 | } 113 | } 114 | 115 | func TestNewFakeClockIsNotZero(t *testing.T) { 116 | t.Parallel() 117 | fc := NewFakeClock() 118 | if fc.Now().IsZero() { 119 | t.Errorf("NewFakeClock.Now().IsZero() returned true, want false") 120 | } 121 | } 122 | 123 | func TestNewFakeClockAt(t *testing.T) { 124 | t.Parallel() 125 | want := time.Date(1999, time.February, 3, 4, 5, 6, 7, time.UTC) 126 | if got := NewFakeClockAt(want).Now(); !got.Equal(want) { 127 | t.Errorf("fakeClock.Now() returned %v, want: %v", got, want) 128 | } 129 | } 130 | 131 | func TestSince(t *testing.T) { 132 | t.Parallel() 133 | start := time.Date(1999, time.February, 3, 4, 5, 6, 7, time.UTC) 134 | want := time.Second 135 | fc := NewFakeClockAt(start.Add(want)) 136 | if got := fc.Since(start); got != want { 137 | t.Errorf("fakeClock.Since() returned %v, want: %v", got, want) 138 | } 139 | } 140 | 141 | func TestUntil(t *testing.T) { 142 | t.Parallel() 143 | start := time.Date(1999, time.February, 3, 4, 5, 6, 7, time.UTC) 144 | fc := NewFakeClockAt(start) 145 | want := time.Second 146 | end := start.Add(want) 147 | if got := fc.Until(end); got != want { 148 | t.Errorf("fakeClock.Until() returned %v, want: %v", got, want) 149 | } 150 | } 151 | 152 | func TestBlockUntilContext(t *testing.T) { 153 | t.Parallel() 154 | fc := &FakeClock{} 155 | 156 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 157 | defer cancel() 158 | 159 | blockCtx, cancelBlock := context.WithCancel(ctx) 160 | errCh := make(chan error) 161 | 162 | go func() { 163 | select { 164 | case errCh <- fc.BlockUntilContext(blockCtx, 2): 165 | case <-ctx.Done(): // Error case, captured below. 166 | } 167 | }() 168 | cancelBlock() 169 | 170 | select { 171 | case err := <-errCh: 172 | if !errors.Is(err, context.Canceled) { 173 | t.Errorf("BlockUntilContext returned %v, want context.Canceled.", err) 174 | } 175 | case <-ctx.Done(): 176 | t.Errorf("Never received error on context cancellation.") 177 | } 178 | } 179 | 180 | func TestAfterDeliveryInOrder(t *testing.T) { 181 | t.Parallel() 182 | fc := &FakeClock{} 183 | for i := 0; i < 1000; i++ { 184 | three := fc.After(3 * time.Second) 185 | for j := 0; j < 100; j++ { 186 | fc.After(1 * time.Second) 187 | } 188 | two := fc.After(2 * time.Second) 189 | go func() { 190 | fc.Advance(5 * time.Second) 191 | }() 192 | <-three 193 | select { 194 | case <-two: 195 | default: 196 | t.Fatalf("Signals from After delivered out of order") 197 | } 198 | } 199 | } 200 | 201 | // TestFakeClockRace detects data races in fakeClock when invoked with run using `go -race ...`. 202 | // There are no failure conditions when invoked without the -race flag. 203 | func TestFakeClockRace(t *testing.T) { 204 | t.Parallel() 205 | fc := &FakeClock{} 206 | d := time.Second 207 | go func() { fc.Advance(d) }() 208 | go func() { fc.NewTicker(d) }() 209 | go func() { fc.NewTimer(d) }() 210 | go func() { fc.Sleep(d) }() 211 | } 212 | -------------------------------------------------------------------------------- /context.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | // contextKey is private to this package so we can ensure uniqueness here. This 11 | // type identifies context values provided by this package. 12 | type contextKey string 13 | 14 | // keyClock provides a clock for injecting during tests. If absent, a real clock 15 | // should be used. 16 | var keyClock = contextKey("clock") // clockwork.Clock 17 | 18 | // AddToContext creates a derived context that references the specified clock. 19 | // 20 | // Be aware this doesn't change the behavior of standard library functions, such 21 | // as [context.WithTimeout] or [context.WithDeadline]. For this reason, users 22 | // should prefer passing explicit [clockwork.Clock] variables rather can passing 23 | // the clock via the context. 24 | func AddToContext(ctx context.Context, clock Clock) context.Context { 25 | return context.WithValue(ctx, keyClock, clock) 26 | } 27 | 28 | // FromContext extracts a clock from the context. If not present, a real clock 29 | // is returned. 30 | func FromContext(ctx context.Context) Clock { 31 | if clock, ok := ctx.Value(keyClock).(Clock); ok { 32 | return clock 33 | } 34 | return NewRealClock() 35 | } 36 | 37 | // ErrFakeClockDeadlineExceeded is the error returned by [context.Context] when 38 | // the deadline passes on a context which uses a [FakeClock]. 39 | // 40 | // It wraps a [context.DeadlineExceeded] error, i.e.: 41 | // 42 | // // The following is true for any Context whose deadline has been exceeded, 43 | // // including contexts made with clockwork.WithDeadline or clockwork.WithTimeout. 44 | // 45 | // errors.Is(ctx.Err(), context.DeadlineExceeded) 46 | // 47 | // // The following can only be true for contexts made 48 | // // with clockwork.WithDeadline or clockwork.WithTimeout. 49 | // 50 | // errors.Is(ctx.Err(), clockwork.ErrFakeClockDeadlineExceeded) 51 | var ErrFakeClockDeadlineExceeded error = fmt.Errorf("clockwork.FakeClock: %w", context.DeadlineExceeded) 52 | 53 | // WithDeadline returns a context with a deadline based on a [FakeClock]. 54 | // 55 | // The returned context ignores parent cancelation if the parent was cancelled 56 | // with a [context.DeadlineExceeded] error. Any other error returned by the 57 | // parent is treated normally, cancelling the returned context. 58 | // 59 | // If the parent is cancelled with a [context.DeadlineExceeded] error, the only 60 | // way to then cancel the returned context is by calling the returned 61 | // context.CancelFunc. 62 | func WithDeadline(parent context.Context, clock Clock, t time.Time) (context.Context, context.CancelFunc) { 63 | if fc, ok := clock.(*FakeClock); ok { 64 | return newFakeClockContext(parent, t, fc.newTimerAtTime(t, nil).Chan()) 65 | } 66 | return context.WithDeadline(parent, t) 67 | } 68 | 69 | // WithTimeout returns a context with a timeout based on a [FakeClock]. 70 | // 71 | // The returned context follows the same behaviors as [WithDeadline]. 72 | func WithTimeout(parent context.Context, clock Clock, d time.Duration) (context.Context, context.CancelFunc) { 73 | if fc, ok := clock.(*FakeClock); ok { 74 | t, deadline := fc.newTimer(d, nil) 75 | return newFakeClockContext(parent, deadline, t.Chan()) 76 | } 77 | return context.WithTimeout(parent, d) 78 | } 79 | 80 | // fakeClockContext implements context.Context, using a fake clock for its 81 | // deadline. 82 | // 83 | // It ignores parent cancellation if the parent is cancelled with 84 | // context.DeadlineExceeded. 85 | type fakeClockContext struct { 86 | parent context.Context 87 | deadline time.Time // The user-facing deadline based on the fake clock's time. 88 | 89 | // Tracks timeout/deadline cancellation. 90 | timerDone <-chan time.Time 91 | 92 | // Tracks manual calls to the cancel function. 93 | cancel func() // Closes cancelCalled wrapped in a sync.Once. 94 | cancelCalled chan struct{} 95 | 96 | // The user-facing data from the context.Context interface. 97 | ctxDone chan struct{} // Returned by Done(). 98 | err error // nil until ctxDone is ready to be closed. 99 | } 100 | 101 | func newFakeClockContext(parent context.Context, deadline time.Time, timer <-chan time.Time) (context.Context, context.CancelFunc) { 102 | cancelCalled := make(chan struct{}) 103 | ctx := &fakeClockContext{ 104 | parent: parent, 105 | deadline: deadline, 106 | timerDone: timer, 107 | cancelCalled: cancelCalled, 108 | ctxDone: make(chan struct{}), 109 | cancel: sync.OnceFunc(func() { 110 | close(cancelCalled) 111 | }), 112 | } 113 | ready := make(chan struct{}, 1) 114 | go ctx.runCancel(ready) 115 | <-ready // Wait until the cancellation goroutine is running. 116 | return ctx, ctx.cancel 117 | } 118 | 119 | func (c *fakeClockContext) Deadline() (time.Time, bool) { 120 | return c.deadline, true 121 | } 122 | 123 | func (c *fakeClockContext) Done() <-chan struct{} { 124 | return c.ctxDone 125 | } 126 | 127 | func (c *fakeClockContext) Err() error { 128 | <-c.Done() // Don't return the error before it is ready. 129 | return c.err 130 | } 131 | 132 | func (c *fakeClockContext) Value(key any) any { 133 | return c.parent.Value(key) 134 | } 135 | 136 | // runCancel runs the fakeClockContext's cancel goroutine and returns the 137 | // fakeClockContext's cancel function. 138 | // 139 | // fakeClockContext is then cancelled when any of the following occur: 140 | // 141 | // - The fakeClockContext.done channel is closed by its timer. 142 | // - The returned CancelFunc is executed. 143 | // - The fakeClockContext's parent context is cancelled with an error other 144 | // than context.DeadlineExceeded. 145 | func (c *fakeClockContext) runCancel(ready chan struct{}) { 146 | parentDone := c.parent.Done() 147 | 148 | // Close ready when done, just in case the ready signal races with other 149 | // branches of our select statement below. 150 | defer close(ready) 151 | 152 | for c.err == nil { 153 | select { 154 | case <-c.timerDone: 155 | c.err = ErrFakeClockDeadlineExceeded 156 | case <-c.cancelCalled: 157 | c.err = context.Canceled 158 | case <-parentDone: 159 | c.err = c.parent.Err() 160 | 161 | case ready <- struct{}{}: 162 | // Signals the cancellation goroutine has begun, in an attempt to minimize 163 | // race conditions related to goroutine startup time. 164 | ready = nil // This case statement can only fire once. 165 | } 166 | } 167 | close(c.ctxDone) 168 | return 169 | } 170 | -------------------------------------------------------------------------------- /context_test.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import ( 4 | "context" 5 | "errors" 6 | "reflect" 7 | "testing" 8 | "time" 9 | ) 10 | 11 | func TestContextOps(t *testing.T) { 12 | t.Parallel() 13 | ctx := context.Background() 14 | assertIsType(t, NewRealClock(), FromContext(ctx)) 15 | 16 | ctx = AddToContext(ctx, NewFakeClock()) 17 | assertIsType(t, NewFakeClock(), FromContext(ctx)) 18 | } 19 | 20 | func assertIsType(t *testing.T, expectedType, object any) { 21 | t.Helper() 22 | if reflect.TypeOf(object) != reflect.TypeOf(expectedType) { 23 | t.Fatalf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)) 24 | } 25 | } 26 | 27 | func TestWithDeadlineDone(t *testing.T) { 28 | t.Parallel() 29 | cases := []struct { 30 | name string 31 | 32 | start, deadline time.Time 33 | 34 | action func(cancelParent, cancelChild context.CancelFunc, clock *FakeClock) 35 | 36 | want error 37 | }{ 38 | { 39 | name: "canceling parent cancels child", 40 | start: time.Unix(10, 0), 41 | deadline: time.Unix(20, 0), 42 | action: func(cancelParent, _ context.CancelFunc, _ *FakeClock) { 43 | cancelParent() 44 | }, 45 | want: context.Canceled, 46 | }, 47 | { 48 | name: "canceling child cancels child", 49 | start: time.Unix(10, 0), 50 | deadline: time.Unix(20, 0), 51 | action: func(_, cancelChild context.CancelFunc, _ *FakeClock) { 52 | cancelChild() 53 | }, 54 | want: context.Canceled, 55 | }, 56 | { 57 | name: "advancing past deadline cancels child", 58 | start: time.Unix(10, 0), 59 | deadline: time.Unix(20, 0), 60 | action: func(_, _ context.CancelFunc, clock *FakeClock) { 61 | clock.Advance(10 * time.Second) 62 | }, 63 | want: context.DeadlineExceeded, 64 | }, 65 | } 66 | 67 | // Background context for catching timeouts. 68 | base, cancelBase := context.WithTimeout(context.Background(), timeout) 69 | defer cancelBase() 70 | 71 | for _, tc := range cases { 72 | t.Run(tc.name, func(t *testing.T) { 73 | 74 | parent, cancelParent := context.WithCancel(base) 75 | clock := NewFakeClockAt(tc.start) 76 | child, cancelChild := WithDeadline(parent, clock, tc.deadline) 77 | 78 | select { 79 | case <-child.Done(): 80 | t.Fatal("WithDeadline context finished early.") 81 | default: 82 | } 83 | 84 | tc.action(cancelParent, cancelChild, clock) 85 | 86 | select { 87 | case <-child.Done(): 88 | if got := child.Err(); !errors.Is(got, tc.want) { 89 | t.Errorf("WithDeadline context returned %v, want %v", got, tc.want) 90 | } 91 | case <-base.Done(): 92 | t.Error("WithDeadline context was never canceled.") 93 | } 94 | }) 95 | } 96 | } 97 | func TestWithTimeoutDone(t *testing.T) { 98 | t.Parallel() 99 | cases := []struct { 100 | name string 101 | 102 | start time.Time 103 | timeout time.Duration 104 | 105 | action func(cancelParent, cancelChild context.CancelFunc, clock *FakeClock) 106 | 107 | want error 108 | }{ 109 | { 110 | name: "canceling parent cancels child", 111 | start: time.Unix(10, 0), 112 | timeout: 10 * time.Second, 113 | action: func(cancelParent, _ context.CancelFunc, _ *FakeClock) { 114 | cancelParent() 115 | }, 116 | want: context.Canceled, 117 | }, 118 | { 119 | name: "canceling child cancels child", 120 | start: time.Unix(10, 0), 121 | timeout: 10 * time.Second, 122 | action: func(_, cancelChild context.CancelFunc, _ *FakeClock) { 123 | cancelChild() 124 | }, 125 | want: context.Canceled, 126 | }, 127 | { 128 | name: "advancing past deadline cancels child", 129 | start: time.Unix(10, 0), 130 | timeout: 10 * time.Second, 131 | action: func(_, _ context.CancelFunc, clock *FakeClock) { 132 | clock.Advance(10 * time.Second) 133 | }, 134 | want: context.DeadlineExceeded, 135 | }, 136 | } 137 | 138 | // Background context for catching timeouts. 139 | background, cancelBase := context.WithTimeout(context.Background(), timeout) 140 | defer cancelBase() 141 | 142 | for _, tc := range cases { 143 | t.Run(tc.name, func(t *testing.T) { 144 | 145 | parent, cancelParent := context.WithCancel(background) 146 | clock := NewFakeClockAt(tc.start) 147 | child, cancelChild := WithTimeout(parent, clock, tc.timeout) 148 | 149 | select { 150 | case <-child.Done(): 151 | t.Fatal("WithTimeout context finished early.") 152 | default: 153 | } 154 | 155 | tc.action(cancelParent, cancelChild, clock) 156 | 157 | select { 158 | case <-child.Done(): 159 | if got := child.Err(); !errors.Is(got, tc.want) { 160 | t.Errorf("WithTimeout context returned %v, want %v", got, tc.want) 161 | } 162 | case <-background.Done(): 163 | t.Error("WithTimeout context was never canceled.") 164 | } 165 | }) 166 | } 167 | } 168 | 169 | func TestParentCancellationIsRespected(t *testing.T) { 170 | t.Parallel() 171 | cases := []struct { 172 | name string 173 | 174 | contextFunc func(context.Context, *FakeClock) (context.Context, context.CancelFunc) 175 | 176 | requireContextDeadlineExceeded bool 177 | }{ 178 | { 179 | name: "WithDeadline in the future", 180 | contextFunc: func(ctx context.Context, fc *FakeClock) (context.Context, context.CancelFunc) { 181 | return WithDeadline(ctx, fc, time.Now().Add(time.Hour)) 182 | }, 183 | // The FakeClock does not hit its deadline, so the error must be context.DeadlineExceeded. 184 | requireContextDeadlineExceeded: true, 185 | }, 186 | { 187 | name: "WithDeadline in the past", 188 | contextFunc: func(ctx context.Context, fc *FakeClock) (context.Context, context.CancelFunc) { 189 | return WithDeadline(ctx, fc, time.Now().Add(-time.Hour)) 190 | }, 191 | }, 192 | { 193 | name: "WithTimeout in the future", 194 | contextFunc: func(ctx context.Context, fc *FakeClock) (context.Context, context.CancelFunc) { 195 | return WithTimeout(ctx, fc, time.Hour) 196 | }, 197 | // The FakeClock does not hit its deadline, so the error must be context.DeadlineExceeded. 198 | requireContextDeadlineExceeded: true, 199 | }, 200 | { 201 | name: "WithTimeout immediately", 202 | contextFunc: func(ctx context.Context, fc *FakeClock) (context.Context, context.CancelFunc) { 203 | return WithTimeout(ctx, fc, 0) 204 | }, 205 | }, 206 | { 207 | name: "WithTimeout in the past", 208 | contextFunc: func(ctx context.Context, fc *FakeClock) (context.Context, context.CancelFunc) { 209 | return WithTimeout(ctx, fc, -time.Hour) 210 | }, 211 | }, 212 | } 213 | 214 | for _, tc := range cases { 215 | t.Run(tc.name, func(t *testing.T) { 216 | base, cancelBase := context.WithTimeout(context.Background(), timeout) 217 | defer cancelBase() 218 | 219 | // Parent context hits deadline effectively immediately. 220 | parent, cancelParent := context.WithTimeout(base, time.Nanosecond) 221 | defer cancelParent() 222 | 223 | clock := NewFakeClockAt(time.Unix(10, 0)) 224 | child, cancelChild := tc.contextFunc(parent, clock) 225 | defer cancelChild() 226 | 227 | select { 228 | case <-child.Done(): 229 | case <-base.Done(): 230 | t.Fatal("context did not respect parnet deadline") 231 | } 232 | 233 | if err := child.Err(); !errors.Is(err, context.DeadlineExceeded) { 234 | t.Errorf("errors.Is(Context.Err(), context.DeadlineExceeded) == falst, want true, error: %v", err) 235 | } 236 | if tc.requireContextDeadlineExceeded { 237 | if err := child.Err(); errors.Is(err, ErrFakeClockDeadlineExceeded) { 238 | t.Errorf("errors.Is(Context.Err(), ErrFakeClockDeadlineExceeded) == true, want false, error: %v", err) 239 | } 240 | } 241 | }) 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import ( 4 | "context" 5 | "sync" 6 | "testing" 7 | "time" 8 | ) 9 | 10 | // myFunc is an example of a time-dependent function, using an injected clock. 11 | func myFunc(clock Clock, i *int) { 12 | clock.Sleep(3 * time.Second) 13 | *i += 1 14 | } 15 | 16 | // assertState is an example of a state assertion in a test. 17 | func assertState(t *testing.T, i, j int) { 18 | if i != j { 19 | t.Fatalf("i %d, j %d", i, j) 20 | } 21 | } 22 | 23 | // TestMyFunc tests myFunc's behaviour with a FakeClock. 24 | func TestMyFunc(t *testing.T) { 25 | ctx := context.Background() 26 | var i int 27 | c := NewFakeClock() 28 | 29 | var wg sync.WaitGroup 30 | wg.Add(1) 31 | go func() { 32 | myFunc(c, &i) 33 | wg.Done() 34 | }() 35 | 36 | // Ensure we wait until myFunc is waiting on the clock. 37 | // Use a context to avoid blocking forever if something 38 | // goes wrong. 39 | ctx, cancel := context.WithTimeout(ctx, 10*time.Second) 40 | defer cancel() 41 | c.BlockUntilContext(ctx, 1) 42 | 43 | // Assert the initial state. 44 | assertState(t, i, 0) 45 | 46 | // Now advance the clock forward in time. 47 | c.Advance(1 * time.Hour) 48 | 49 | // Wait until the function completes. 50 | wg.Wait() 51 | 52 | // Assert the final state. 53 | assertState(t, i, 1) 54 | } 55 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/jonboulle/clockwork 2 | 3 | go 1.21 4 | -------------------------------------------------------------------------------- /ticker.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import "time" 4 | 5 | // Ticker provides an interface which can be used instead of directly using 6 | // [time.Ticker]. The real-time ticker t provides ticks through t.C which 7 | // becomes t.Chan() to make this channel requirement definable in this 8 | // interface. 9 | type Ticker interface { 10 | Chan() <-chan time.Time 11 | Reset(d time.Duration) 12 | Stop() 13 | } 14 | 15 | type realTicker struct{ *time.Ticker } 16 | 17 | func (r realTicker) Chan() <-chan time.Time { 18 | return r.C 19 | } 20 | 21 | type fakeTicker struct { 22 | // The channel associated with the firer, used to send expiration times. 23 | c chan time.Time 24 | 25 | // The time when the ticker expires. Only meaningful if the ticker is currently 26 | // one of a FakeClock's waiters. 27 | exp time.Time 28 | 29 | // reset and stop provide the implementation of the respective exported 30 | // functions. 31 | reset func(d time.Duration) 32 | stop func() 33 | 34 | // The duration of the ticker. 35 | d time.Duration 36 | } 37 | 38 | func newFakeTicker(fc *FakeClock, d time.Duration) *fakeTicker { 39 | var ft *fakeTicker 40 | ft = &fakeTicker{ 41 | c: make(chan time.Time, 1), 42 | d: d, 43 | reset: func(d time.Duration) { 44 | fc.l.Lock() 45 | defer fc.l.Unlock() 46 | ft.d = d 47 | fc.setExpirer(ft, d) 48 | }, 49 | stop: func() { fc.stop(ft) }, 50 | } 51 | return ft 52 | } 53 | 54 | func (f *fakeTicker) Chan() <-chan time.Time { return f.c } 55 | 56 | func (f *fakeTicker) Reset(d time.Duration) { f.reset(d) } 57 | 58 | func (f *fakeTicker) Stop() { f.stop() } 59 | 60 | func (f *fakeTicker) expire(now time.Time) *time.Duration { 61 | // Never block on expiration. 62 | select { 63 | case f.c <- now: 64 | default: 65 | } 66 | return &f.d 67 | } 68 | 69 | func (f *fakeTicker) expiration() time.Time { return f.exp } 70 | 71 | func (f *fakeTicker) setExpiration(t time.Time) { f.exp = t } 72 | -------------------------------------------------------------------------------- /ticker_test.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestFakeTickerStop(t *testing.T) { 10 | t.Parallel() 11 | fc := &FakeClock{} 12 | 13 | ft := fc.NewTicker(1) 14 | ft.Stop() 15 | select { 16 | case <-ft.Chan(): 17 | t.Errorf("received unexpected tick!") 18 | default: 19 | } 20 | } 21 | 22 | func TestFakeTickerTick(t *testing.T) { 23 | t.Parallel() 24 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 25 | defer cancel() 26 | 27 | fc := &FakeClock{} 28 | now := fc.Now() 29 | 30 | // The tick at now.Add(2) should not get through since we advance time by 31 | // two units below and the channel can hold at most one tick until it's 32 | // consumed. 33 | first := now.Add(1) 34 | second := now.Add(3) 35 | 36 | // We wrap the Advance() calls with blockers to make sure that the ticker 37 | // can go to sleep and produce ticks without time passing in parallel. 38 | ft := fc.NewTicker(1) 39 | fc.BlockUntil(1) 40 | fc.Advance(2) 41 | fc.BlockUntil(1) 42 | 43 | select { 44 | case tick := <-ft.Chan(): 45 | if tick != first { 46 | t.Errorf("wrong tick time, got: %v, want: %v", tick, first) 47 | } 48 | case <-ctx.Done(): 49 | t.Errorf("expected tick!") 50 | } 51 | 52 | // Advance by one more unit, we should get another tick now. 53 | fc.Advance(1) 54 | fc.BlockUntil(1) 55 | 56 | select { 57 | case tick := <-ft.Chan(): 58 | if tick != second { 59 | t.Errorf("wrong tick time, got: %v, want: %v", tick, second) 60 | } 61 | case <-ctx.Done(): 62 | t.Errorf("expected tick!") 63 | } 64 | ft.Stop() 65 | } 66 | 67 | func TestFakeTicker_Race(t *testing.T) { 68 | t.Parallel() 69 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 70 | defer cancel() 71 | 72 | fc := NewFakeClock() 73 | 74 | tickTime := 1 * time.Millisecond 75 | ticker := fc.NewTicker(tickTime) 76 | defer ticker.Stop() 77 | 78 | fc.Advance(tickTime) 79 | 80 | select { 81 | case <-ticker.Chan(): 82 | case <-ctx.Done(): 83 | t.Fatalf("Ticker didn't detect the clock advance!") 84 | } 85 | } 86 | 87 | func TestFakeTicker_Race2(t *testing.T) { 88 | t.Parallel() 89 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 90 | defer cancel() 91 | fc := NewFakeClock() 92 | ft := fc.NewTicker(5 * time.Second) 93 | for i := 0; i < 100; i++ { 94 | fc.Advance(5 * time.Second) 95 | select { 96 | case <-ft.Chan(): 97 | case <-ctx.Done(): 98 | t.Fatalf("Ticker didn't detect the clock advance!") 99 | } 100 | 101 | } 102 | ft.Stop() 103 | } 104 | 105 | func TestFakeTicker_DeliveryOrder(t *testing.T) { 106 | t.Parallel() 107 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 108 | defer cancel() 109 | fc := NewFakeClock() 110 | ticker := fc.NewTicker(2 * time.Second).Chan() 111 | timer := fc.NewTimer(5 * time.Second).Chan() 112 | go func() { 113 | for j := 0; j < 10; j++ { 114 | fc.BlockUntil(1) 115 | fc.Advance(1 * time.Second) 116 | } 117 | }() 118 | <-ticker 119 | a := <-timer 120 | // Only perform ordering check if ticker channel is drained at first. 121 | select { 122 | case <-ticker: 123 | default: 124 | select { 125 | case b := <-ticker: 126 | if a.After(b) { 127 | t.Fatalf("Expected timer before ticker, got timer %v after %v", a, b) 128 | } 129 | case <-ctx.Done(): 130 | t.Fatalf("Expected ticker event didn't arrive!") 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /timer.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import "time" 4 | 5 | // Timer provides an interface which can be used instead of directly using 6 | // [time.Timer]. The real-time timer t provides events through t.C which becomes 7 | // t.Chan() to make this channel requirement definable in this interface. 8 | type Timer interface { 9 | Chan() <-chan time.Time 10 | Reset(d time.Duration) bool 11 | Stop() bool 12 | } 13 | 14 | type realTimer struct{ *time.Timer } 15 | 16 | func (r realTimer) Chan() <-chan time.Time { 17 | return r.C 18 | } 19 | 20 | type fakeTimer struct { 21 | // The channel associated with the firer, used to send expiration times. 22 | c chan time.Time 23 | 24 | // The time when the firer expires. Only meaningful if the firer is currently 25 | // one of a FakeClock's waiters. 26 | exp time.Time 27 | 28 | // reset and stop provide the implementation of the respective exported 29 | // functions. 30 | reset func(d time.Duration) bool 31 | stop func() bool 32 | 33 | // If present when the timer fires, the timer calls afterFunc in its own 34 | // goroutine rather than sending the time on Chan(). 35 | afterFunc func() 36 | } 37 | 38 | func newFakeTimer(fc *FakeClock, afterfunc func()) *fakeTimer { 39 | var ft *fakeTimer 40 | ft = &fakeTimer{ 41 | c: make(chan time.Time, 1), 42 | reset: func(d time.Duration) bool { 43 | fc.l.Lock() 44 | defer fc.l.Unlock() 45 | // fc.l must be held across the calls to stopExpirer & setExpirer. 46 | stopped := fc.stopExpirer(ft) 47 | fc.setExpirer(ft, d) 48 | return stopped 49 | }, 50 | stop: func() bool { return fc.stop(ft) }, 51 | 52 | afterFunc: afterfunc, 53 | } 54 | return ft 55 | } 56 | 57 | func (f *fakeTimer) Chan() <-chan time.Time { return f.c } 58 | 59 | func (f *fakeTimer) Reset(d time.Duration) bool { return f.reset(d) } 60 | 61 | func (f *fakeTimer) Stop() bool { return f.stop() } 62 | 63 | func (f *fakeTimer) expire(now time.Time) *time.Duration { 64 | if f.afterFunc != nil { 65 | go f.afterFunc() 66 | return nil 67 | } 68 | 69 | // Never block on expiration. 70 | select { 71 | case f.c <- now: 72 | default: 73 | } 74 | return nil 75 | } 76 | 77 | func (f *fakeTimer) expiration() time.Time { return f.exp } 78 | 79 | func (f *fakeTimer) setExpiration(t time.Time) { f.exp = t } 80 | -------------------------------------------------------------------------------- /timer_test.go: -------------------------------------------------------------------------------- 1 | package clockwork 2 | 3 | import ( 4 | "context" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestFakeClockTimerStop(t *testing.T) { 10 | t.Parallel() 11 | fc := &FakeClock{} 12 | 13 | ft := fc.NewTimer(1) 14 | ft.Stop() 15 | select { 16 | case <-ft.Chan(): 17 | t.Errorf("received unexpected tick!") 18 | default: 19 | } 20 | } 21 | 22 | func TestFakeClockTimers(t *testing.T) { 23 | t.Parallel() 24 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 25 | defer cancel() 26 | 27 | fc := &FakeClock{} 28 | 29 | zero := fc.NewTimer(0) 30 | 31 | if zero.Stop() { 32 | t.Errorf("zero timer could be stopped") 33 | } 34 | 35 | select { 36 | case <-zero.Chan(): 37 | case <-ctx.Done(): 38 | t.Errorf("zero timer didn't emit time") 39 | } 40 | 41 | one := fc.NewTimer(1) 42 | 43 | select { 44 | case <-one.Chan(): 45 | t.Errorf("non-zero timer did emit time") 46 | default: 47 | } 48 | if !one.Stop() { 49 | t.Errorf("non-zero timer couldn't be stopped") 50 | } 51 | 52 | fc.Advance(5) 53 | 54 | select { 55 | case <-one.Chan(): 56 | t.Errorf("stopped timer did emit time") 57 | default: 58 | } 59 | 60 | if one.Reset(1) { 61 | t.Errorf("resetting stopped timer didn't return false") 62 | } 63 | if !one.Reset(1) { 64 | t.Errorf("resetting active timer didn't return true") 65 | } 66 | 67 | fc.Advance(1) 68 | 69 | select { 70 | case <-time.After(500 * time.Millisecond): 71 | } 72 | 73 | if one.Stop() { 74 | t.Errorf("triggered timer could be stopped") 75 | } 76 | 77 | select { 78 | case <-one.Chan(): 79 | case <-ctx.Done(): 80 | t.Errorf("triggered timer didn't emit time") 81 | } 82 | 83 | fc.Advance(1) 84 | 85 | select { 86 | case <-one.Chan(): 87 | t.Errorf("triggered timer emitted time more than once") 88 | default: 89 | } 90 | 91 | one.Reset(0) 92 | 93 | if one.Stop() { 94 | t.Errorf("reset to zero timer could be stopped") 95 | } 96 | 97 | select { 98 | case <-one.Chan(): 99 | case <-ctx.Done(): 100 | t.Errorf("reset to zero timer didn't emit time") 101 | } 102 | } 103 | 104 | func TestFakeClockTimer_Race(t *testing.T) { 105 | t.Parallel() 106 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 107 | defer cancel() 108 | 109 | fc := NewFakeClock() 110 | timer := fc.NewTimer(1 * time.Millisecond) 111 | defer timer.Stop() 112 | fc.Advance(1 * time.Millisecond) 113 | 114 | select { 115 | case <-timer.Chan(): 116 | case <-ctx.Done(): 117 | t.Fatalf("Timer didn't detect the clock advance!") 118 | } 119 | } 120 | 121 | func TestFakeClockTimer_Race2(t *testing.T) { 122 | t.Parallel() 123 | fc := NewFakeClock() 124 | timer := fc.NewTimer(5 * time.Second) 125 | for i := 0; i < 100; i++ { 126 | fc.Advance(5 * time.Second) 127 | <-timer.Chan() 128 | timer.Reset(5 * time.Second) 129 | } 130 | timer.Stop() 131 | } 132 | 133 | func TestFakeClockTimer_ResetRace(t *testing.T) { 134 | t.Parallel() 135 | fc := NewFakeClock() 136 | d := 5 * time.Second 137 | var times []time.Time 138 | timer := fc.NewTimer(d) 139 | timerStopped := make(chan struct{}) 140 | doneAddingTimes := make(chan struct{}) 141 | go func() { 142 | defer close(doneAddingTimes) 143 | for { 144 | select { 145 | case <-timerStopped: 146 | return 147 | case now := <-timer.Chan(): 148 | times = append(times, now) 149 | } 150 | } 151 | }() 152 | for i := 0; i < 100; i++ { 153 | for j := 0; j < 10; j++ { 154 | timer.Reset(d) 155 | } 156 | fc.Advance(d) 157 | } 158 | timer.Stop() 159 | close(timerStopped) 160 | <-doneAddingTimes // Prevent race condition on times. 161 | for i := 1; i < len(times); i++ { 162 | if times[i-1].Equal(times[i]) { 163 | t.Fatalf("Timer repeatedly reported the same time.") 164 | } 165 | } 166 | } 167 | 168 | func TestFakeClockTimer_ZeroResetDoesNotBlock(t *testing.T) { 169 | t.Parallel() 170 | fc := NewFakeClock() 171 | timer := fc.NewTimer(0) 172 | for i := 0; i < 10; i++ { 173 | timer.Reset(0) 174 | } 175 | <-timer.Chan() 176 | } 177 | 178 | func TestAfterFunc_Concurrent(t *testing.T) { 179 | t.Parallel() 180 | ctx, cancel := context.WithTimeout(context.Background(), timeout) 181 | defer cancel() 182 | fc := NewFakeClock() 183 | blocker := make(chan struct{}) 184 | ch := make(chan int) 185 | // AfterFunc should start goroutines, so each should be able to make progress 186 | // independent of the others. 187 | fc.AfterFunc(2*time.Second, func() { 188 | <-blocker 189 | ch <- 222 190 | }) 191 | fc.AfterFunc(2*time.Second, func() { 192 | ch <- 111 193 | }) 194 | fc.AfterFunc(2*time.Second, func() { 195 | <-blocker 196 | ch <- 222 197 | }) 198 | fc.Advance(2 * time.Second) 199 | select { 200 | case a := <-ch: 201 | if a != 111 { 202 | t.Fatalf("Expected 111, got %d", a) 203 | } 204 | case <-ctx.Done(): 205 | t.Fatalf("Expected signal hasn't arrived") 206 | } 207 | close(blocker) 208 | select { 209 | case a := <-ch: 210 | if a != 222 { 211 | t.Fatalf("Expected 222, got %d", a) 212 | } 213 | case <-ctx.Done(): 214 | t.Fatalf("Expected signal hasn't arrived") 215 | } 216 | select { 217 | case a := <-ch: 218 | if a != 222 { 219 | t.Fatalf("Expected 222, got %d", a) 220 | } 221 | case <-ctx.Done(): 222 | t.Fatalf("Expected signal hasn't arrived") 223 | } 224 | } 225 | --------------------------------------------------------------------------------