jeudi 24 décembre 2020

How to check how many times a function has been called in a Golang test?

I'm working on a web server with an API which calls a function. This function does a heavy job and caches the result. I've designed it in a way that if there is no cache and multiple users call this API with the same parameters at the same time, the server call that function only once for the first request and all other requests wait for finishing the job and return response from the cache.

I've written a test for it in this way:


func TestConcurentRequests(t *testing.T) {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func() {
            // do the request
            wg.Done()
        }
    }
    wg.Wait()
}

I can check that my code works correctly by printing a value inside that heavy function and check the console to see if it appears only once, but I'm searching for a way to fail the test if this function has been called more times. Something like this:


if n := NumberOfCalls(MyHeavyFunction); n > 1 {
    t.Fatalf("Expected heavy function to run only once but called %d times", n)
}

Aucun commentaire:

Enregistrer un commentaire