Skip to content
This repository has been archived by the owner on May 18, 2023. It is now read-only.

AfterFunc underlying function is executed in its own goroutine #45

Merged
merged 4 commits into from
Apr 23, 2023

Conversation

smirnov-vs
Copy link
Contributor

Original AfterFunc executes function in its own goroutine
Mock should do it in the same way, otherwise tests doesn't cover races with this kind of timer

@vincentbernat
Copy link
Contributor

This introduces race conditions in the tests. To fix them:

diff --git a/clock_test.go b/clock_test.go
index 73813fb679c5..053ca6ece4d3 100644
--- a/clock_test.go
+++ b/clock_test.go
@@ -604,24 +604,25 @@ func ExampleMock_After() {
 func ExampleMock_AfterFunc() {
        // Create a new mock clock.
        clock := NewMock()
-       count := 0
+       var count counter
+       count.incr()

        // Execute a function after 10 mock seconds.
        clock.AfterFunc(10*time.Second, func() {
-               count = 100
+               count.incr()
        })
        gosched()

        // Print the starting value.
-       fmt.Printf("%s: %d\n", clock.Now().UTC(), count)
+       fmt.Printf("%s: %d\n", clock.Now().UTC(), count.get())

        // Move the clock forward 10 seconds and print the new value.
        clock.Add(10 * time.Second)
-       fmt.Printf("%s: %d\n", clock.Now().UTC(), count)
+       fmt.Printf("%s: %d\n", clock.Now().UTC(), count.get())

        // Output:
-       // 1970-01-01 00:00:00 +0000 UTC: 0
-       // 1970-01-01 00:00:10 +0000 UTC: 100
+       // 1970-01-01 00:00:00 +0000 UTC: 1
+       // 1970-01-01 00:00:10 +0000 UTC: 2
 }

 func ExampleMock_Sleep() {
@@ -728,9 +729,9 @@ func TestMock_AddAfterFuncRace(t *testing.T) {

        mockedClock := NewMock()

-       called := false
+       var called counter
        defer func() {
-               if !called {
+               if called.get() == 0 {
                        t.Errorf("AfterFunc did not call the function")
                }
        }()
@@ -741,7 +742,7 @@ func TestMock_AddAfterFuncRace(t *testing.T) {
                <-start

                mockedClock.AfterFunc(time.Millisecond, func() {
-                       called = true
+                       called.incr()
                })
        }()

(this patch also includes code for #42)

@vincentbernat vincentbernat mentioned this pull request Sep 23, 2022
@djmitche
Copy link
Collaborator

(The second commit is from @vincentbernat's comment)

@djmitche djmitche merged commit c7aedc1 into benbjohnson:master Apr 23, 2023
3 checks passed
@djmitche
Copy link
Collaborator

Done, and released as 1.3.3

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants