Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: timecop_scale() should speed up sleep() and usleep() #34

Open
RopoMen opened this issue Nov 22, 2017 · 1 comment
Open

Feature: timecop_scale() should speed up sleep() and usleep() #34

RopoMen opened this issue Nov 22, 2017 · 1 comment

Comments

@RopoMen
Copy link

RopoMen commented Nov 22, 2017

I have a function which uses sleep(2)

I wrapped PHPUnit call in following way

if(extension_loaded('timecop')) {
    timecop_scale(1000);
}

$res = $instance->methodUsingSleep();

if(extension_loaded('timecop')) {
    timecop_scale(1);
}

I was wondering why this wasn't speeding up my unit tests, until I looked closer the list of overriden functions.

methodUsingSleep contains code that is using while loop to wait until specific time has passed or one other variable becomes true, I use sleep() to overcome max_execution_time, because in Linux environments (at least) sleep() is not counted as execution time. This allows that while loop to run longer than max_execution_time and wait that one variable to become 'true'.

I was trying to use timecop_scale() to speed up the test :)

@IonBazan
Copy link
Contributor

IonBazan commented Nov 26, 2017

sleep() and usleep() is not affected because this is not really a time function. I would suggest you not to test sleep-aware methods. Move the code responsible for checking the conditions to different class/method or replace the sleep() call with a class and inject an interface to your service. This way you will be able to mock the Waiter to do nothing and speed up your test.

interface Waiter
{
    public function wait(int $seconds);
}

class SleepWaiter implements Waiter
{
    public function wait(int $seconds)
    {
        sleep($seconds);
    }
}

class MyService
{
    /** @var Waiter */
    protected $waiter;
    
    protected $importantVariable = false;
    
    public function __construct(Waiter $waiter)
    {
        $this->waiter = $waiter;
    }
    
    public function doSomething()
    {
        while (!$this->importantVariable) {
            $this->waiter->wait(2);
        }
        
        echo 'The variable has been set!';
    }
}

PS. Use better names for these classes. This is just an example 😄

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

No branches or pull requests

2 participants