Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test shutdown routines (register_shutdown_function) in php with PHPUnit

Tags:

php

phpunit

I have a File class, with a ->deleteOnExit function. If this function is called, the file will delete itself on shutdown. The File class uses the register_shutdown_function function to achieve this, deleting the file when the shutdown handler is ran. Question is, how can i test this in PHPUnit. I tried this

$file = new File(__DIR__ . "/delete_on_exit.txt");
$file->createFile();
$file->deleteOnExit();
register_shutdown_function(function() use ($file) {
    $this->assertFalse($file->exists());
});

But that did not work. I guess that is because PHPUnit is already done with its testing by the time the function registered with register_shutdown_function is called.

Is there a way to do this?

like image 696
SomeNorwegianGuy Avatar asked Apr 08 '26 07:04

SomeNorwegianGuy


1 Answers

You should probably use tmpfile() (documentation) internally instead of deleting the file with a shutdown function.

Also, the way PHPUnit works, you cannot test proper shutdown deletion. PHPUnit tests run in a single huge "application" - any shutdown function will only ever be called when the last test finishes and any other tasks like generating code coverage have been done. At this time, it is way too late for your test to report that the file indeed has been deleted.

Additionally, because of this I'd have my doubts whether or not your code will reliably delete the file, because any other registered shutdown function that simply calls exit() would prevent your shutdown function to delete the file. All these problems seem to not exist when using tmpfile(), because that is a OS supported call that will delete the file if the process opening it dies for whatever reason.

like image 174
Sven Avatar answered Apr 10 '26 20:04

Sven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!