1

I'm currently writing a function that would retry with exponential backoff up to 5 times. How do I write the unit test for testing the wait time is correct or not? Here's my function:

func (OdinClient) GetPrivateKeySigner(materialSet string) (ssh.Signer, error) {
    # If it fails on first try, then retry 5 times, or return the value
    signer, err := ssh.NewSignerFromKey(privateKeyMaterial.PrivateKey)
    if err != nil {
        for i := 0; i < 5; i++ {
            time.Sleep(time.Duration(math.Pow(2, float64(i)) * 100) * time.Millisecond)
            signer, err := ssh.NewSignerFromKey(privateKeyMaterial.PrivateKey)
            if err == nil {
                return signer, nil
            }
        }
        # If still fails after 5 retries, return error message. 
        return nil, novaerr.New("utils/getPrivateKey", fmt.Sprintf("failed"), err)
    } else {
        return signer, nil
    }
}
Charmander
  • 109
  • 14
  • 1
    Split it to a function that sleeps for specified duration, and another function that calculates duration. – zerkms Feb 28 '23 at 00:29
  • Where does `privateKeyMaterial` come from? `materialSet` is never used. – Schwern Feb 28 '23 at 00:38
  • 1
    Does [`NewSignerFromKey`](https://github.com/golang/crypto/blob/9be5aaad42d5e8b858864f1bec7f0fb3844130a9/ssh/keys.go#L916) require a backoff? I don't believe it does any network calls. – Schwern Feb 28 '23 at 00:45

0 Answers0