Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
php_cron_test
<?php
/**
* Test_Crontab
*
*/
require 'vendor/autoload.php';
class Test_Batch_Crontab extends PHPUnit_Framework_TestCase
{
public $TARGET_DATE = '2015-01-01 00:00:00';
public $TIME_FORMAT = 'Y-m-d H:i:s';
public $CRON_PATTERN = "!^([0-9]|\*|/|,)+(\s\S+){4}?.+\n!m";
public $TEST_PATTERN = "!(^(?:[0-9]|\*|/|,)+(?:\s\S+){4})?.+\n^###prev\s(.+)\n^###next\s(.+)\n!m";
public $CRON_FILE_PATH = "./cron_file";
public function test_batch_crontab()
{
$file_list = $this->search_file_list();
foreach( $file_list as $file) {
$data = file_get_contents($file, true);
preg_match_all( $this->CRON_PATTERN , $data , $cron_decrare);
preg_match_all( $this->TEST_PATTERN , $data , $cron_decrare_with_test);
$this->assertEquals(
count( $cron_decrare[0] ),
count( $cron_decrare_with_test[0] ),
'every crontab must be written with test'
);
$this->run_cron_test( $cron_decrare_with_test[0] );
}
}
private function run_cron_test( $cron_decrare_with_test )
{
foreach( $cron_decrare_with_test as $cron_and_explain){
$row_match = array();
preg_match($this->TEST_PATTERN ,$cron_and_explain, $row_match);
$cron_setting = $row_match[1];
$prev_time = $row_match[2];
$next_time = $row_match[3];
$parse_cron = Cron\CronExpression::factory($cron_setting);
$this->assertEquals(
$prev_time,
$this->generate_prev_date($parse_cron),
'prev time match'
);
$this->assertEquals(
$next_time,
$this->generate_next_date($parse_cron),
'next time match'
);
}
}
private function search_file_list()
{
$iterator = new RecursiveDirectoryIterator( $this->CRON_FILE_PATH );
$iterator = new RecursiveIteratorIterator($iterator);
$file_list = array();
foreach ($iterator as $fileinfo) { // $fileinfoはSplFiIeInfoオブジェクト
if ($fileinfo->isFile()) {
$file_list[] = $fileinfo->getPathname();
}
}
return $file_list;
}
private function generate_next_date($cron)
{
return $cron->getNextRunDate($this->TARGET_DATE)->format($this->TIME_FORMAT);
}
private function generate_prev_date($cron)
{
return $cron->getPreviousRunDate($this->TARGET_DATE)->format($this->TIME_FORMAT);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment