onsi / gomega

Ginkgo's Preferred Matcher Library
http://onsi.github.io/gomega/
MIT License
2.19k stars 284 forks source link

Stop Eventually/Consistently with success #786

Closed grosser closed 1 month ago

grosser commented 1 month ago

as per https://onsi.github.io/gomega/#bailing-out-early StopTrying is the only way to stop iteration without having to implement a custom matcher but I'd like to also stop with a success, for example

    errChan := make(chan error)
    go func() {
        time.Sleep(10 * time.Second)
        errChan <- fmt.Errorf("error")
    }()
    Consistently(func() (bool) {
        select {
        case err := <-errChan:
            StopTrying("background task finished").Now()
            return true
        default:
            return true // actual check goes here
        }
    }, timeout, interval).Should(BeTrue())

to not fail, for example with StopTrying("background task stopped").Success() or return return true, StopTrying("background task stopped").Success()

onsi commented 1 month ago

hey - this makes sense, though really only for Consistently. I'll implement StopTrying(...).Success() but will have it error if you use it with Eventually but do what you're describing fro Consistently.

grosser commented 1 month ago

thx! :D yeah it would be weird for eventually

onsi commented 1 month ago

do you mind if I use your example in the docs?

grosser commented 1 month ago

go ahead 👍

onsi commented 1 month ago

alrighty, this is pushed now. will cut a release oon

grosser commented 1 month ago

thank you 🎉

grosser commented 4 weeks ago

FYI using this wrapper

func ConsistentlyUntil[T any](fn func() T, timeout any, interval any, errChan chan error) AsyncAssertion {
    return Consistently(func() T {
        select {
        case err := <-errChan:
            if err == nil {
                StopTrying("success!").Successfully().Now()
            }
            StopTrying(fmt.Sprintf("background task faild: %v", err)).Now()
            return fn() // unreachable since StopTrying will panic
        default:
            return fn()
        }
    }, timeout, interval)
}
onsi commented 4 weeks ago

ooh that's nice. glad it's proven useful :)