inaka / erlang_guidelines

Inaka's Erlang Coding Guidelines
Apache License 2.0
623 stars 121 forks source link

Do not use timer:sleep/1 in tests #82

Closed elbrujohalcon closed 6 years ago

elbrujohalcon commented 6 years ago

Do not use timer:sleep/1 in tests

When testing some asynchronous behavior, you should never rely on letting your test sleep for a long enough time. You should use some polling mechanism, instead.

%% bad
bad(Config) ->
    something:that(kicks, off, a, {background, task}),
    timer:sleep(1000),
    done = that_task:status().

%% good
good(Config) ->
    something:that(kicks, off, a, {background, task}),
    ktn_task:wait_for(fun() -> that_task:status() end, done).

Reasoning: If you use timer:sleep/1 with a number that's too small, scheduler load or other factors may randomly make your test fail. On the other hand, using a number that's big enough to ensure test success may waste lots of time in each run thus slowing down your test suite and your development process as a whole. Using ktn_task:wait_for/2 or similar alternatives (i.e. periodically polling for results until the right one is found), you get the best of both worlds: you don't fail too early but you also don't wait too much.

harenson commented 6 years ago

:+1:

igaray commented 6 years ago

👍

HernanRivasAcosta commented 6 years ago

👌