CronTest.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713
  1. <?php
  2. /**
  3. * CronTest
  4. *
  5. * @package Cron
  6. * @author Marc Liebig
  7. * @since 1.0.0
  8. */
  9. class CronTest extends TestCase {
  10. /**
  11. * @var string Holds the path to the test logfile
  12. */
  13. private $pathToLogfile;
  14. /**
  15. * @var int Laravel version
  16. */
  17. private $laravelVersion;
  18. /**
  19. * SetUp Method which is called before the class is started
  20. *
  21. */
  22. public static function setUpBeforeClass() {
  23. parent::setUpBeforeClass();
  24. }
  25. /**
  26. * SetUp Method which is called before a test method is called
  27. *
  28. */
  29. public function setUp() {
  30. if (function_exists('app')) {
  31. $laravel = app();
  32. $version = substr($laravel::VERSION, 0, 1);
  33. if(is_int(intval($version))) {
  34. $this->laravelVersion = intval($version);
  35. } else {
  36. $this->laravelVersion = 4;
  37. }
  38. } else {
  39. $this->laravelVersion = 4;
  40. }
  41. parent::setUp();
  42. // Refresh the application and reset Cron
  43. $this->refreshApplication();
  44. Cron::reset();
  45. // Set the default configuration values to the Laravel \Config object
  46. $this->setDefaultConfigValues();
  47. // Migrate all database tables
  48. if($this->laravelVersion >= 5) {
  49. \Artisan::call('migrate', array('--path' => 'vendor/liebig/cron/src/migrations'));
  50. } else {
  51. \Artisan::call('migrate', array('--package' => 'liebig/cron'));
  52. }
  53. // Set the path to logfile to the laravel storage / logs / directory as test.txt file
  54. // NOTE: THIS FILE HAS TO BE DELETED EACH TIME AFTER THE UNIT TEST WAS STARTED
  55. $this->pathToLogfile = storage_path() . '/logs/test.txt';
  56. }
  57. /**
  58. * Returns a Monolog Logger instance for testing purpose
  59. *
  60. * @return \Monolog\Logger Return a new Monolog Logger instance
  61. */
  62. private function returnLogger() {
  63. $logger = new \Monolog\Logger('test');
  64. $logger->pushHandler(new \Monolog\Handler\StreamHandler($this->pathToLogfile, \Monolog\Logger::DEBUG));
  65. return $logger;
  66. }
  67. /**
  68. * Set default (factory) config values for test cases
  69. *
  70. */
  71. private function setDefaultConfigValues() {
  72. \Config::set('database.connections.sqlite.database', ':memory:');
  73. \Config::set('database.default', 'sqlite');
  74. if($this->laravelVersion >= 5) {
  75. \Config::set('liebigCron.runInterval', 1);
  76. \Config::set('liebigCron.databaseLogging', true);
  77. \Config::set('liebigCron.laravelLogging', true);
  78. \Config::set('liebigCron.logOnlyErrorJobsToDatabase', true);
  79. \Config::set('liebigCron.deleteDatabaseEntriesAfter', 240);
  80. \Config::set('liebigCron.preventOverlapping', false);
  81. \Config::set('liebigCron.cronKey', '');
  82. } else {
  83. \Config::set('cron::runInterval', 1);
  84. \Config::set('cron::databaseLogging', true);
  85. \Config::set('cron::laravelLogging', true);
  86. \Config::set('cron::logOnlyErrorJobsToDatabase', true);
  87. \Config::set('cron::deleteDatabaseEntriesAfter', 240);
  88. \Config::set('cron::preventOverlapping', false);
  89. \Config::set('cron::cronKey', '');
  90. }
  91. }
  92. /**
  93. * Test method for setting the Logger
  94. *
  95. * @covers \Liebig\Cron\Cron::setLogger
  96. * @covers \Liebig\Cron\Cron::getLogger
  97. */
  98. public function testSetRemoveLogger() {
  99. $this->assertNull(Cron::getLogger());
  100. Cron::setLogger($this->returnLogger());
  101. $this->assertNotNull(Cron::getLogger());
  102. Cron::setLogger();
  103. $this->assertNull(Cron::getLogger());
  104. }
  105. /**
  106. * Test method for logging
  107. *
  108. * @covers \Liebig\Cron\Cron::setLogger
  109. * @covers \Liebig\Cron\Cron::getLogger
  110. */
  111. public function testLogging() {
  112. $this->assertNull(Cron::getLogger());
  113. Cron::setLogger($this->returnLogger());
  114. $this->assertNotNull(Cron::getLogger());
  115. $this->assertFileNotExists($this->pathToLogfile);
  116. Cron::run();
  117. $this->assertFileExists($this->pathToLogfile);
  118. $filesizeBefore = filesize($this->pathToLogfile);
  119. Cron::run();
  120. $this->refreshApplication();
  121. $this->assertGreaterThan($filesizeBefore, filesize($this->pathToLogfile));
  122. }
  123. /**
  124. * Test method for activating and deactivating database logging
  125. *
  126. * @covers \Liebig\Cron\Cron::setDatabaseLogging
  127. */
  128. public function testDeactivateDatabaseLogging() {
  129. $i = 0;
  130. Cron::add('test1', '* * * * *', function() use (&$i) {
  131. $i++;
  132. return false;
  133. });
  134. Cron::add('test2', '* * * * *', function() use (&$i) {
  135. $i++;
  136. return false;
  137. });
  138. Cron::run();
  139. $this->assertEquals($i, 2);
  140. $this->assertEquals(\Liebig\Cron\Models\Manager::count(), 1);
  141. $this->assertEquals(\Liebig\Cron\Models\Job::count(), 2);
  142. Cron::setDatabaseLogging(false);
  143. Cron::run();
  144. $this->assertEquals($i, 4);
  145. $this->assertEquals(\Liebig\Cron\Models\Manager::count(), 1);
  146. $this->assertEquals(\Liebig\Cron\Models\Job::count(), 2);
  147. Cron::setDatabaseLogging(true);
  148. Cron::run();
  149. $this->assertEquals($i, 6);
  150. $this->assertEquals(\Liebig\Cron\Models\Manager::count(), 2);
  151. $this->assertEquals(\Liebig\Cron\Models\Job::count(), 4);
  152. }
  153. /**
  154. * Test method for activating and deactivating the logging of all jobs to Database
  155. *
  156. * @covers \Liebig\Cron\Cron::setLogOnlyErrorJobsToDatabase
  157. */
  158. public function testLogAllJobsToDatabase() {
  159. $i = 0;
  160. Cron::add('test1', '* * * * *', function() use (&$i) {
  161. $i++;
  162. return null;
  163. });
  164. Cron::add('test2', '* * * * *', function() use (&$i) {
  165. $i++;
  166. return true;
  167. });
  168. Cron::add('test3', '* * * * *', function() use (&$i) {
  169. $i++;
  170. return false;
  171. });
  172. Cron::add('test4', '* * * * *', function() use (&$i) {
  173. $i++;
  174. return null;
  175. });
  176. Cron::setLogOnlyErrorJobsToDatabase(false);
  177. Cron::run();
  178. $this->assertEquals(4, $i);
  179. $jobs = \Liebig\Cron\Models\Job::all();
  180. $this->assertEquals(4, count($jobs));
  181. $this->assertEquals('test1', $jobs[0]->name);
  182. $this->assertEquals('', $jobs[0]->return);
  183. $this->assertEquals('test2', $jobs[1]->name);
  184. $this->assertEquals('true', $jobs[1]->return);
  185. $this->assertEquals('test3', $jobs[2]->name);
  186. $this->assertEquals('false', $jobs[2]->return);
  187. $this->assertEquals('test4', $jobs[3]->name);
  188. $this->assertEquals('', $jobs[3]->return);
  189. Cron::setLogOnlyErrorJobsToDatabase(true);
  190. Cron::run();
  191. $this->assertEquals(8, $i);
  192. $jobs2 = \Liebig\Cron\Models\Job::all();
  193. $this->assertEquals(6, count($jobs2));
  194. $this->assertEquals('test2', $jobs2[4]->name);
  195. $this->assertEquals('true', $jobs2[4]->return);
  196. $this->assertEquals('test3', $jobs2[5]->name);
  197. $this->assertEquals('false', $jobs2[5]->return);
  198. }
  199. /**
  200. * Test method for return values in database
  201. *
  202. * @covers \Liebig\Cron\Cron::run
  203. */
  204. public function testJobReturnValue() {
  205. $i = 0;
  206. Cron::setLogOnlyErrorJobsToDatabase(false);
  207. Cron::add('test1', '* * * * *', function() use (&$i) {
  208. $i++;
  209. return null;
  210. });
  211. Cron::add('test2', '* * * * *', function() use (&$i) {
  212. $i++;
  213. return true;
  214. });
  215. Cron::add('test3', '* * * * *', function() use (&$i) {
  216. $i++;
  217. return false;
  218. });
  219. Cron::add('test4', '* * * * *', function() use (&$i) {
  220. $i++;
  221. return 12345;
  222. });
  223. Cron::add('test5', '* * * * *', function() use (&$i) {
  224. $i++;
  225. return 12.3456789;
  226. });
  227. Cron::add('test6', '* * * * *', function() use (&$i) {
  228. $i++;
  229. return 'Return text';
  230. });
  231. Cron::add('test7', '* * * * *', function() use (&$i) {
  232. $i++;
  233. return new ArrayObject();
  234. });
  235. Cron::run();
  236. $this->assertEquals(7, $i);
  237. $jobs = \Liebig\Cron\Models\Job::all();
  238. $this->assertEquals(7, count($jobs));
  239. $this->assertEquals('test1', $jobs[0]->name);
  240. $this->assertEquals('', $jobs[0]->return);
  241. $this->assertEquals('test2', $jobs[1]->name);
  242. $this->assertEquals('true', $jobs[1]->return);
  243. $this->assertEquals('test3', $jobs[2]->name);
  244. $this->assertEquals('false', $jobs[2]->return);
  245. $this->assertEquals('test4', $jobs[3]->name);
  246. $this->assertEquals(12345, $jobs[3]->return);
  247. $this->assertEquals('test5', $jobs[4]->name);
  248. $this->assertEquals(12.3456789, $jobs[4]->return);
  249. $this->assertEquals('test6', $jobs[5]->name);
  250. $this->assertEquals('Return text', $jobs[5]->return);
  251. $this->assertEquals('test7', $jobs[6]->name);
  252. $this->assertEquals('Return object type is object', $jobs[6]->return);
  253. }
  254. /**
  255. * Test method for running cron jobs in the right time
  256. *
  257. * @covers \Liebig\Cron\Cron::run
  258. */
  259. public function testRunWithTime() {
  260. $i = 0;
  261. Cron::add('test1', '* * * * *', function() use (&$i) {
  262. $i++;
  263. return null;
  264. });
  265. $runResult1 = Cron::run();
  266. $this->assertEquals(1, $i);
  267. $this->assertEquals(0, $runResult1['errors']);
  268. $this->assertEquals(1, count($runResult1['crons']));
  269. $this->assertEquals('test1', $runResult1['crons'][0]['name']);
  270. $this->assertEquals(null, $runResult1['crons'][0]['return']);
  271. $this->assertEquals(-1, $runResult1['inTime']);
  272. Cron::add('test2', '* * * * *', function() {
  273. return 'return of test2';
  274. });
  275. $runResult2 = Cron::run();
  276. $this->assertEquals(2, $i);
  277. $this->assertEquals(1, $runResult2['errors']);
  278. $this->assertEquals(2, count($runResult2['crons']));
  279. $this->assertEquals('test1', $runResult2['crons'][0]['name']);
  280. $this->assertEquals(null, $runResult2['crons'][0]['return']);
  281. $this->assertEquals('test2', $runResult2['crons'][1]['name']);
  282. $this->assertEquals('return of test2', $runResult2['crons'][1]['return']);
  283. sleep(60);
  284. $runResult3 = Cron::run();
  285. $this->assertEquals(3, $i);
  286. $this->assertEquals(true, $runResult3['inTime']);
  287. sleep(25);
  288. $runResult4 = Cron::run();
  289. $this->assertEquals(4, $i);
  290. $this->assertEquals(false, $runResult4['inTime']);
  291. sleep(95);
  292. $runResult5 = Cron::run();
  293. $this->assertEquals($i, 5);
  294. $this->assertEquals(false, $runResult5['inTime']);
  295. Cron::setRunInterval(2);
  296. sleep(120);
  297. $runResult6 = Cron::run();
  298. $this->assertEquals($i, 6);
  299. $this->assertEquals(true, $runResult6['inTime']);
  300. }
  301. /**
  302. * Test method for enabling and disabling cron jobs
  303. *
  304. * @covers \Liebig\Cron\Cron::add
  305. */
  306. public function testRunEnabled() {
  307. $i = 0;
  308. Cron::add('test1', '* * * * *', function() use (&$i) {
  309. $i++;
  310. return null;
  311. }, false);
  312. Cron::run();
  313. $this->assertEquals(0, $i);
  314. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  315. $this->assertEquals(0, \Liebig\Cron\Models\Job::count());
  316. Cron::run();
  317. $this->assertEquals(0, $i);
  318. $this->assertEquals(2, \Liebig\Cron\Models\Manager::count());
  319. $this->assertEquals(0, \Liebig\Cron\Models\Job::count());
  320. Cron::add('test2', '* * * * *', function() use (&$i) {
  321. $i++;
  322. return false;
  323. }, true);
  324. Cron::run();
  325. $this->assertEquals(1, $i);
  326. $this->assertEquals(3, \Liebig\Cron\Models\Manager::count());
  327. $this->assertEquals(1, \Liebig\Cron\Models\Job::count());
  328. Cron::add('test3', '* * * * *', function() use (&$i) {
  329. $i++;
  330. return false;
  331. });
  332. Cron::run();
  333. $this->assertEquals(3, $i);
  334. $this->assertEquals(4, \Liebig\Cron\Models\Manager::count());
  335. $this->assertEquals(3, \Liebig\Cron\Models\Job::count());
  336. }
  337. /**
  338. * Test method for adding cron jobs
  339. *
  340. * @expectedException InvalidArgumentException
  341. * @expectedExceptionMessage Cron job $name "test2" is not unique and already used.
  342. * @covers \Liebig\Cron\Cron::add
  343. */
  344. public function testAddCronJobWithSameName() {
  345. $i = 0;
  346. $this->assertEquals(null, Cron::add('test1', '* * * * *', function() use (&$i) {
  347. $i++;
  348. return false;
  349. }));
  350. $this->assertEquals(null, Cron::add('test2', '* * * * * *', function() use (&$i) {
  351. $i++;
  352. return false;
  353. }));
  354. Cron::run();
  355. $this->assertEquals(2, $i);
  356. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  357. $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
  358. // Should not work - same job name
  359. Cron::add('test2', '* * * * *', function() {
  360. return false;
  361. });
  362. }
  363. /**
  364. * Test method for adding cron jobs
  365. *
  366. * @expectedException InvalidArgumentException
  367. * @expectedExceptionMessage Method argument $expression is not set or invalid.
  368. * @covers \Liebig\Cron\Cron::add
  369. */
  370. public function testAddCronJobWithWrongExpressionOne() {
  371. // Should not work - expression wrong
  372. Cron::add('test3', 'NOT', function() {
  373. return false;
  374. });
  375. }
  376. /**
  377. * Test method for adding cron jobs
  378. *
  379. * @expectedException InvalidArgumentException
  380. * @expectedExceptionMessage Method argument $expression is not set or invalid.
  381. * @covers \Liebig\Cron\Cron::add
  382. */
  383. public function testAddCronJobWithWrongExpressionTwo() {
  384. // Should not work - expression wrong (too long)
  385. Cron::add('test4', '* * * * * * *', function() {
  386. return false;
  387. });
  388. }
  389. /**
  390. * Test method for adding cron jobs
  391. *
  392. * @expectedException InvalidArgumentException
  393. * @expectedExceptionMessage Method argument $function is not set or not callable.
  394. * @covers \Liebig\Cron\Cron::add
  395. */
  396. public function testAddCronJobWithWrongFunction() {
  397. // Should not work - function is not a function
  398. Cron::add('test5', '* * * * *', 'This is not a function');
  399. }
  400. /**
  401. * Test method for testing the method for removing a single cron job by name
  402. *
  403. * @covers \Liebig\Cron\Cron::remove
  404. */
  405. public function testRemoveCronJob() {
  406. $i = 0;
  407. Cron::add('test1', '* * * * *', function() use (&$i) {
  408. $i++;
  409. return false;
  410. });
  411. Cron::run();
  412. $this->assertEquals(1, $i);
  413. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  414. $this->assertEquals(1, \Liebig\Cron\Models\Job::count());
  415. $this->assertEquals(true, Cron::remove('test1'));
  416. Cron::run();
  417. $this->assertEquals(1, $i);
  418. $this->assertEquals(2, \Liebig\Cron\Models\Manager::count());
  419. $this->assertEquals(1, \Liebig\Cron\Models\Job::count());
  420. Cron::add('test1', '* * * * *', function() use (&$i) {
  421. $i++;
  422. return false;
  423. });
  424. Cron::run();
  425. $this->assertEquals(2, $i);
  426. $this->assertEquals(3, \Liebig\Cron\Models\Manager::count());
  427. $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
  428. Cron::run();
  429. $this->assertEquals(3, $i);
  430. $this->assertEquals(4, \Liebig\Cron\Models\Manager::count());
  431. $this->assertEquals(3, \Liebig\Cron\Models\Job::count());
  432. $this->assertEquals(true, Cron::remove('test1'));
  433. Cron::run();
  434. $this->assertEquals(3, $i);
  435. $this->assertEquals(5, \Liebig\Cron\Models\Manager::count());
  436. $this->assertEquals(3, \Liebig\Cron\Models\Job::count());
  437. $this->assertEquals(false, Cron::remove('unknown'));
  438. Cron::run();
  439. $this->assertEquals(3, $i);
  440. $this->assertEquals(6, \Liebig\Cron\Models\Manager::count());
  441. $this->assertEquals(3, \Liebig\Cron\Models\Job::count());
  442. }
  443. /**
  444. * Test method for heavily run 1000 cron jobs five times
  445. *
  446. * @covers \Liebig\Cron\Cron::run
  447. */
  448. public function testHeavyRunWithLongExpression() {
  449. $count = 0;
  450. for ($i = 1; $i <= 1000; $i++) {
  451. Cron::add('test' . $i, '* * * * * *', function() use (&$count) {
  452. $count++;
  453. return null;
  454. });
  455. }
  456. Cron::run();
  457. $this->assertEquals(1000, $count);
  458. Cron::run();
  459. $this->assertEquals(2000, $count);
  460. Cron::run();
  461. $this->assertEquals(3000, $count);
  462. Cron::run();
  463. $this->assertEquals(4000, $count);
  464. Cron::run();
  465. $this->assertEquals(5000, $count);
  466. }
  467. /**
  468. * Test method for testing the save and load functions of the database models
  469. *
  470. * @covers \Liebig\Cron\Models\Manager
  471. * @covers \Liebig\Cron\Models\Job
  472. */
  473. public function testDatabaseModelsSaveLoad() {
  474. $newManager = new \Liebig\Cron\Models\Manager();
  475. $date = new \DateTime();
  476. $newManager->rundate = $date;
  477. $newManager->runtime = 0.007;
  478. $this->assertNotNull($newManager->save());
  479. $newError1 = new \Liebig\Cron\Models\Job();
  480. $newError1->name = "test11";
  481. $newError1->return = "test11 fails";
  482. $newError1->runtime = 0.0001;
  483. $newError1->cron_manager_id = $newManager->id;
  484. $this->assertNotNull($newError1->save());
  485. $newError2 = new \Liebig\Cron\Models\Job();
  486. $newError2->name = "test12";
  487. $newError2->return = "test12 fails";
  488. $newError2->runtime = 0.0002;
  489. $newError2->cron_manager_id = $newManager->id;
  490. $this->assertNotNull($newError2->save());
  491. $newError3 = new \Liebig\Cron\Models\Job();
  492. $newError3->name = "test13";
  493. $newError3->return = "test13 fails";
  494. $newError3->runtime = 0.0003;
  495. $newError3->cron_manager_id = $newManager->id;
  496. $this->assertNotNull($newError3->save());
  497. $newSuccess1 = new \Liebig\Cron\Models\Job();
  498. $newSuccess1->name = "test14";
  499. $newSuccess1->return = '';
  500. $newSuccess1->runtime = 0.0004;
  501. $newSuccess1->cron_manager_id = $newManager->id;
  502. $this->assertNotNull($newSuccess1->save());
  503. $newManagerFind = \Liebig\Cron\Models\Manager::find(1);
  504. $this->assertNotNull($newManagerFind);
  505. $this->assertEquals($date->format('Y-m-d H:i:s'), $newManagerFind->rundate);
  506. $this->assertEquals(0.007, $newManagerFind->runtime);
  507. $finder = $newManagerFind->cronJobs()->get();
  508. $this->assertEquals(4, count($finder));
  509. $this->assertEquals('test11', $finder[0]->name);
  510. $this->assertEquals('test11 fails', $finder[0]->return);
  511. $this->assertEquals('0.0001', $finder[0]->runtime);
  512. $this->assertEquals($newManager->id, $finder[0]->cron_manager_id);
  513. $this->assertEquals('test12', $finder[1]->name);
  514. $this->assertEquals('test12 fails', $finder[1]->return);
  515. $this->assertEquals('0.0002', $finder[1]->runtime);
  516. $this->assertEquals($newManager->id, $finder[1]->cron_manager_id);
  517. $this->assertEquals('test13', $finder[2]->name);
  518. $this->assertEquals('test13 fails', $finder[2]->return);
  519. $this->assertEquals('0.0003', $finder[2]->runtime);
  520. $this->assertEquals($newManager->id, $finder[2]->cron_manager_id);
  521. $this->assertEquals('test14', $finder[3]->name);
  522. $this->assertEquals('', $finder[3]->return);
  523. $this->assertEquals('0.0004', $finder[3]->runtime);
  524. $this->assertEquals($newManager->id, $finder[3]->cron_manager_id);
  525. }
  526. /**
  527. * Test method for testing the database models created after the run method
  528. *
  529. * @covers \Liebig\Cron\Models\Manager
  530. * @covers \Liebig\Cron\Models\Job
  531. */
  532. public function testDatabaseModelsAfterRun() {
  533. Cron::add('test1', '* * * * *', function() {
  534. return 'test1 fails';
  535. });
  536. Cron::add('test2', '* * * * *', function() {
  537. return null;
  538. });
  539. Cron::add('test3', '* * * * *', function() {
  540. return 'test3 fails';
  541. });
  542. Cron::run();
  543. $manager = \Liebig\Cron\Models\Manager::first();
  544. $this->assertNotNull($manager);
  545. $errors = $manager->cronJobs()->get();
  546. $this->assertEquals(2, count($errors));
  547. $this->assertEquals('test1', $errors[0]->name);
  548. $this->assertEquals('test1 fails', $errors[0]->return);
  549. $this->assertEquals($manager->id, $errors[0]->cron_manager_id);
  550. $this->assertEquals('test3', $errors[1]->name);
  551. $this->assertEquals('test3 fails', $errors[1]->return);
  552. $this->assertEquals($manager->id, $errors[1]->cron_manager_id);
  553. }
  554. /**
  555. * Test method for testing the reset method
  556. *
  557. * @covers \Liebig\Cron\Cron::reset
  558. */
  559. public function testReset() {
  560. $i = 0;
  561. Cron::add('test1', '* * * * *', function() use (&$i) {
  562. $i++;
  563. return false;
  564. });
  565. Cron::add('test2', '* * * * *', function() use (&$i) {
  566. $i++;
  567. return false;
  568. });
  569. Cron::run();
  570. $this->assertEquals(2, $i);
  571. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  572. $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
  573. Cron::setLogger($this->returnLogger());
  574. Cron::reset();
  575. Cron::run();
  576. $this->assertEquals(2, $i);
  577. $this->assertEquals(2, \Liebig\Cron\Models\Manager::count());
  578. $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
  579. $this->assertEquals(null, Cron::getLogger());
  580. }
  581. /**
  582. * Test method for testing the delete old database entries function
  583. *
  584. * @covers \Liebig\Cron\Cron::setDeleteDatabaseEntriesAfter
  585. * @covers \Liebig\Cron\Cron::run
  586. */
  587. public function testDeleteOldDatabaseEntries() {
  588. $manager1 = new \Liebig\Cron\Models\Manager();
  589. $date1 = new \DateTime();
  590. date_sub($date1, date_interval_create_from_date_string('240 hours'));
  591. $manager1->rundate = $date1;
  592. $manager1->runtime = 0.01;
  593. $this->assertNotNull($manager1->save());
  594. $newError1 = new \Liebig\Cron\Models\Job();
  595. $newError1->name = "test1";
  596. $newError1->return = "test1 fails";
  597. $newError1->runtime = 0.001;
  598. $newError1->cron_manager_id = $manager1->id;
  599. $this->assertNotNull($newError1->save());
  600. $newError2 = new \Liebig\Cron\Models\Job();
  601. $newError2->name = "test2";
  602. $newError2->return = "test2 fails";
  603. $newError2->runtime = 0.002;
  604. $newError2->cron_manager_id = $manager1->id;
  605. $this->assertNotNull($newError2->save());
  606. $manager2 = new \Liebig\Cron\Models\Manager();
  607. $date2 = new \DateTime();
  608. date_sub($date2, date_interval_create_from_date_string('240 hours'));
  609. $manager2->rundate = $date2;
  610. $manager2->runtime = 0.02;
  611. $this->assertNotNull($manager2->save());
  612. $newError3 = new \Liebig\Cron\Models\Job();
  613. $newError3->name = "test3";
  614. $newError3->return = "tes31 fails";
  615. $newError3->runtime = 0.003;
  616. $newError3->cron_manager_id = $manager2->id;
  617. $this->assertNotNull($newError3->save());
  618. $manager3 = new \Liebig\Cron\Models\Manager();
  619. $date3 = new \DateTime();
  620. date_sub($date3, date_interval_create_from_date_string('10 hours'));
  621. $manager3->rundate = $date3;
  622. $manager3->runtime = 0.03;
  623. $this->assertNotNull($manager3->save());
  624. $newError4 = new \Liebig\Cron\Models\Job();
  625. $newError4->name = "test4";
  626. $newError4->return = "test4 fails";
  627. $newError4->runtime = 0.004;
  628. $newError4->cron_manager_id = $manager3->id;
  629. $this->assertNotNull($newError4->save());
  630. $newError5 = new \Liebig\Cron\Models\Job();
  631. $newError5->name = "test5";
  632. $newError5->return = "test5 fails";
  633. $newError5->runtime = 0.005;
  634. $newError5->cron_manager_id = $manager3->id;
  635. $this->assertNotNull($newError5->save());
  636. $this->assertEquals(3, \Liebig\Cron\Models\Manager::count());
  637. $this->assertEquals(5, \Liebig\Cron\Models\Job::count());
  638. Cron::setDeleteDatabaseEntriesAfter(240);
  639. Cron::run();
  640. $this->assertEquals(2, \Liebig\Cron\Models\Manager::count());
  641. $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
  642. Cron::setDeleteDatabaseEntriesAfter(0);
  643. $manager4 = new \Liebig\Cron\Models\Manager();
  644. $date4 = new \DateTime();
  645. date_sub($date4, date_interval_create_from_date_string('2400 hours'));
  646. $manager4->rundate = $date4;
  647. $manager4->runtime = 0.04;
  648. $this->assertNotNull($manager4->save());
  649. $newError6 = new \Liebig\Cron\Models\Job();
  650. $newError6->name = "test6";
  651. $newError6->return = "test6 fails";
  652. $newError6->runtime = 0.006;
  653. $newError6->cron_manager_id = $manager4->id;
  654. $this->assertNotNull($newError6->save());
  655. $newError7 = new \Liebig\Cron\Models\Job();
  656. $newError7->name = "test7";
  657. $newError7->return = "test7 fails";
  658. $newError7->runtime = 0.007;
  659. $newError7->cron_manager_id = $manager3->id;
  660. $this->assertNotNull($newError7->save());
  661. Cron::run();
  662. $this->assertEquals(4, \Liebig\Cron\Models\Manager::count());
  663. $this->assertEquals(4, \Liebig\Cron\Models\Job::count());
  664. }
  665. /**
  666. * Test method for enable and disable jobs by using the setter methods
  667. *
  668. * @covers \Liebig\Cron\Cron::setEnableJob
  669. * @covers \Liebig\Cron\Cron::setDisableJob
  670. * @covers \Liebig\Cron\Cron::isJobEnabled
  671. */
  672. public function testEnableDisableJobsBySetter() {
  673. $iTest1 = 0;
  674. $iTest2 = 0;
  675. $iTest3 = 0;
  676. Cron::add('test1', '* * * * *', function() use (&$iTest1) {
  677. $iTest1++;
  678. return false;
  679. }, true);
  680. Cron::add('test2', '* * * * *', function() use (&$iTest2) {
  681. $iTest2++;
  682. return false;
  683. }, true);
  684. Cron::add('test3', '* * * * *', function() use (&$iTest3) {
  685. $iTest3++;
  686. return false;
  687. }, false);
  688. $this->assertEquals(true, Cron::isJobEnabled('test1'));
  689. $this->assertEquals(true, Cron::isJobEnabled('test2'));
  690. $this->assertEquals(false, Cron::isJobEnabled('test3'));
  691. $this->assertEquals(null, Cron::isJobEnabled('test4'));
  692. Cron::run();
  693. $this->assertEquals(1, $iTest1);
  694. $this->assertEquals(1, $iTest2);
  695. $this->assertEquals(0, $iTest3);
  696. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  697. $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
  698. $this->assertEquals(true, Cron::setEnableJob('test3'));
  699. $this->assertEquals(true, Cron::isJobEnabled('test1'));
  700. $this->assertEquals(true, Cron::isJobEnabled('test2'));
  701. $this->assertEquals(true, Cron::isJobEnabled('test3'));
  702. $this->assertEquals(null, Cron::isJobEnabled('test4'));
  703. Cron::run();
  704. $this->assertEquals(2, $iTest1);
  705. $this->assertEquals(2, $iTest2);
  706. $this->assertEquals(1, $iTest3);
  707. $this->assertEquals(2, \Liebig\Cron\Models\Manager::count());
  708. $this->assertEquals(5, \Liebig\Cron\Models\Job::count());
  709. $this->assertEquals(true, Cron::setDisableJob('test1'));
  710. $this->assertEquals(true, Cron::setDisableJob('test3'));
  711. $this->assertEquals(false, Cron::setDisableJob('noSuchJob'));
  712. $this->assertEquals(false, Cron::isJobEnabled('test1'));
  713. $this->assertEquals(true, Cron::isJobEnabled('test2'));
  714. $this->assertEquals(false, Cron::isJobEnabled('test3'));
  715. $this->assertEquals(null, Cron::isJobEnabled('test4'));
  716. Cron::run();
  717. $this->assertEquals(2, $iTest1);
  718. $this->assertEquals(3, $iTest2);
  719. $this->assertEquals(1, $iTest3);
  720. $this->assertEquals(3, \Liebig\Cron\Models\Manager::count());
  721. $this->assertEquals(6, \Liebig\Cron\Models\Job::count());
  722. $this->assertEquals(true, Cron::setEnableJob('test2', false));
  723. $this->assertEquals(false, Cron::isJobEnabled('test1'));
  724. $this->assertEquals(false, Cron::isJobEnabled('test2'));
  725. $this->assertEquals(false, Cron::isJobEnabled('test3'));
  726. $this->assertEquals(null, Cron::isJobEnabled('test4'));
  727. Cron::run();
  728. $this->assertEquals(2, $iTest1);
  729. $this->assertEquals(3, $iTest2);
  730. $this->assertEquals(1, $iTest3);
  731. $this->assertEquals(4, \Liebig\Cron\Models\Manager::count());
  732. $this->assertEquals(6, \Liebig\Cron\Models\Job::count());
  733. $this->assertEquals(true, Cron::setEnableJob('test1', true));
  734. $this->assertEquals(true, Cron::isJobEnabled('test1'));
  735. $this->assertEquals(false, Cron::isJobEnabled('test2'));
  736. $this->assertEquals(false, Cron::isJobEnabled('test3'));
  737. $this->assertEquals(null, Cron::isJobEnabled('test4'));
  738. Cron::run();
  739. $this->assertEquals(3, $iTest1);
  740. $this->assertEquals(3, $iTest2);
  741. $this->assertEquals(1, $iTest3);
  742. $this->assertEquals(5, \Liebig\Cron\Models\Manager::count());
  743. $this->assertEquals(7, \Liebig\Cron\Models\Job::count());
  744. }
  745. /**
  746. * Test method for activating and deactivating the logging of all jobs to
  747. * Database and testing with full namespace declaration
  748. *
  749. * @covers \Liebig\Cron\Cron::setLogOnlyErrorJobsToDatabase
  750. */
  751. public function testLogAllJobsToDatabaseWithFullNamespaceDeclaration() {
  752. $i = 0;
  753. \Liebig\Cron\Cron::add('test1', '* * * * *', function() use (&$i) {
  754. $i++;
  755. return null;
  756. });
  757. \Liebig\Cron\Cron::add('test2', '* * * * *', function() use (&$i) {
  758. $i++;
  759. return true;
  760. });
  761. \Liebig\Cron\Cron::add('test3', '* * * * *', function() use (&$i) {
  762. $i++;
  763. return false;
  764. });
  765. \Liebig\Cron\Cron::add('test4', '* * * * *', function() use (&$i) {
  766. $i++;
  767. return null;
  768. });
  769. \Liebig\Cron\Cron::setLogOnlyErrorJobsToDatabase(false);
  770. \Liebig\Cron\Cron::run();
  771. $this->assertEquals(4, $i);
  772. $jobs = \Liebig\Cron\Models\Job::all();
  773. $this->assertEquals(4, count($jobs));
  774. $this->assertEquals('test1', $jobs[0]->name);
  775. $this->assertEquals('', $jobs[0]->return);
  776. $this->assertEquals('test2', $jobs[1]->name);
  777. $this->assertEquals('true', $jobs[1]->return);
  778. $this->assertEquals('test3', $jobs[2]->name);
  779. $this->assertEquals('false', $jobs[2]->return);
  780. $this->assertEquals('test4', $jobs[3]->name);
  781. $this->assertEquals('', $jobs[3]->return);
  782. \Liebig\Cron\Cron::setLogOnlyErrorJobsToDatabase(true);
  783. \Liebig\Cron\Cron::run();
  784. $this->assertEquals(8, $i);
  785. $jobs2 = \Liebig\Cron\Models\Job::all();
  786. $this->assertEquals(6, count($jobs2));
  787. $this->assertEquals('test2', $jobs2[4]->name);
  788. $this->assertEquals('true', $jobs2[4]->return);
  789. $this->assertEquals('test3', $jobs2[5]->name);
  790. $this->assertEquals('false', $jobs2[5]->return);
  791. }
  792. /**
  793. * Test method for changing config to an invalid value
  794. *
  795. * @expectedException UnexpectedValueException
  796. * @expectedExceptionMessage Config option "databaseLogging" is not a boolean or not equals NULL.
  797. * @covers \Liebig\Cron\Cron::isDatabaseLogging
  798. */
  799. public function testWrongConfigValueOne() {
  800. $this->assertEquals(true, Cron::isDatabaseLogging());
  801. if($this->laravelVersion >=5) {
  802. Config::set('liebigCron.databaseLogging', '');
  803. $this->assertEquals(null, Cron::isDatabaseLogging());
  804. Config::set('liebigCron.databaseLogging', 'true');
  805. $this->assertEquals(true, Cron::isDatabaseLogging());
  806. Config::set('liebigCron.databaseLogging', 'false');
  807. $this->assertEquals(false, Cron::isDatabaseLogging());
  808. Config::set('liebigCron.databaseLogging', 'Not-a-boolean-and-not-null');
  809. Cron::isDatabaseLogging();
  810. } else {
  811. Config::set('cron::databaseLogging', '');
  812. $this->assertEquals(null, Cron::isDatabaseLogging());
  813. Config::set('cron::databaseLogging', 'true');
  814. $this->assertEquals(true, Cron::isDatabaseLogging());
  815. Config::set('cron::databaseLogging', 'false');
  816. $this->assertEquals(false, Cron::isDatabaseLogging());
  817. Config::set('cron::databaseLogging', 'Not-a-boolean-and-not-null');
  818. Cron::isDatabaseLogging();
  819. }
  820. }
  821. /**
  822. * Test method for changing config to an invalid value
  823. *
  824. * @expectedException UnexpectedValueException
  825. * @expectedExceptionMessage Config option "laravelLogging" is not a boolean or not equals NULL.
  826. * @covers \Liebig\Cron\Cron::isLaravelLogging
  827. */
  828. public function testWrongConfigValueTwo() {
  829. $this->assertEquals(true, Cron::isLaravelLogging());
  830. if($this->laravelVersion >=5) {
  831. Config::set('liebigCron.laravelLogging', '');
  832. $this->assertEquals(null, Cron::isLaravelLogging());
  833. Config::set('liebigCron.laravelLogging', 'true');
  834. $this->assertEquals(true, Cron::isLaravelLogging());
  835. Config::set('liebigCron.laravelLogging', 'false');
  836. $this->assertEquals(false, Cron::isLaravelLogging());
  837. Config::set('liebigCron.laravelLogging', 12345);
  838. Cron::isDatabaseLogging();
  839. } else {
  840. Config::set('cron::laravelLogging', '');
  841. $this->assertEquals(null, Cron::isLaravelLogging());
  842. Config::set('cron::laravelLogging', 'true');
  843. $this->assertEquals(true, Cron::isLaravelLogging());
  844. Config::set('cron::laravelLogging', 'false');
  845. $this->assertEquals(false, Cron::isLaravelLogging());
  846. Config::set('cron::laravelLogging', 12345);
  847. Cron::isDatabaseLogging();
  848. }
  849. }
  850. /**
  851. * Test method for setting Laravals build in logging value
  852. *
  853. * @expectedException InvalidArgumentException
  854. * @expectedExceptionMessage Function paramter $bool with value "not a boolean!" is not a boolean.
  855. * @covers \Liebig\Cron\Cron::setLaravelLogging
  856. * @covers \Liebig\Cron\Cron::isLaravelLogging
  857. */
  858. public function testSetLaravelLogging() {
  859. $this->assertEquals(true, Cron::isLaravelLogging());
  860. Cron::setLaravelLogging(false);
  861. $this->assertEquals(false, Cron::isLaravelLogging());
  862. if($this->laravelVersion >=5) {
  863. Config::set('liebigCron.laravelLogging', null);
  864. } else {
  865. Config::set('cron::laravelLogging', null);
  866. }
  867. $this->assertEquals(null, Cron::isLaravelLogging());
  868. Cron::setLaravelLogging('not a boolean!');
  869. }
  870. /**
  871. * Test method for Laravals build in logging value
  872. *
  873. * @covers \Liebig\Cron\Cron::setLaravelLogging
  874. * @covers \Liebig\Cron\Cron::isLaravelLogging
  875. */
  876. public function testLaravelLogging() {
  877. $this->assertEquals(true, Cron::isLaravelLogging());
  878. $this->assertEquals(null, Cron::getLogger());
  879. $i = 0;
  880. $tester = $this;
  881. Log::listen(function($level, $message) use (&$i, $tester) {
  882. switch ($i) {
  883. case 0:
  884. $tester->assertEquals('notice', $level);
  885. $tester->assertEquals('Cron run with manager id 1 has no previous managers.', $message);
  886. break;
  887. case 1:
  888. $tester->assertEquals('info', $level);
  889. $tester->assertEquals('The cron run with the manager id 1 was finished without errors.', $message);
  890. break;
  891. case 2:
  892. $tester->assertEquals('error', $level);
  893. $tester->assertEquals('Job with the name test1 was run with errors.', $message);
  894. break;
  895. case 3:
  896. $tester->assertEquals('error', $level);
  897. break;
  898. case 4:
  899. $tester->assertEquals('error', $level);
  900. $tester->assertEquals('The cron run with the manager id 2 was finished with 1 errors.', $message);
  901. break;
  902. default:
  903. throw new \UnexpectedValueException('Log listener is called to often - test case failed');
  904. }
  905. $i++;
  906. });
  907. Cron::run();
  908. Cron::add('test1', '* * * * *', function() {
  909. return 'test error';
  910. });
  911. Cron::run();
  912. Cron::setLaravelLogging(false);
  913. Cron::run();
  914. // Check if the Log is called 5 times
  915. $this->assertEquals(5, $i);
  916. }
  917. /**
  918. * Test the run method with $checkRunTime = true
  919. *
  920. * @covers \Liebig\Cron\Cron::run
  921. */
  922. public function testRunMethodWithCheckRuntimeDefaultValue() {
  923. $i = 0;
  924. $minute = date("i");
  925. Cron::add('test1', "$minute * * * *", function() use (&$i) {
  926. $i++;
  927. sleep(60);
  928. return null;
  929. });
  930. Cron::add('test2', "$minute * * * *", function() use (&$i) {
  931. $i++;
  932. return null;
  933. });
  934. Cron::add('test3', "$minute * * * *", function() use (&$i) {
  935. $i++;
  936. return false;
  937. });
  938. Cron::run(true);
  939. $this->assertEquals(3, $i);
  940. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  941. $this->assertEquals(1, \Liebig\Cron\Models\Job::count());
  942. }
  943. /**
  944. * Test the run method with $checkRunTime = false
  945. *
  946. * @covers \Liebig\Cron\Cron::run
  947. */
  948. public function testRunMethodWithCheckRuntimeSetToFalse() {
  949. $i = 0;
  950. $minute = date("i");
  951. Cron::add('test1', "$minute * * * *", function() use (&$i) {
  952. $i++;
  953. sleep(60);
  954. return null;
  955. });
  956. Cron::add('test2', "$minute * * * *", function() use (&$i) {
  957. $i++;
  958. return null;
  959. });
  960. Cron::add('test3', "$minute * * * *", function() use (&$i) {
  961. $i++;
  962. return false;
  963. });
  964. Cron::run(false);
  965. $this->assertEquals(1, $i);
  966. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  967. $this->assertEquals(0, \Liebig\Cron\Models\Job::count());
  968. }
  969. /**
  970. * Test the prevent job overlapping functionality
  971. *
  972. * @covers \Liebig\Cron\Cron::run
  973. * @covers \Liebig\Cron\Cron::setEnablePreventOverlapping
  974. * @covers \Liebig\Cron\Cron::setDisablePreventOverlapping
  975. * @covers \Liebig\Cron\Cron::isPreventOverlapping
  976. */
  977. public function testPreventOverlapping() {
  978. // Disable database logging because we need this later
  979. Cron::setDatabaseLogging(false);
  980. // Getting storage path with Laravel3 fallback
  981. $storagePath = "";
  982. if (function_exists('storage_path')) {
  983. $storagePath = storage_path();
  984. } else if (function_exists('path')) {
  985. $storagePath = path('storage');
  986. } else {
  987. throw new RuntimeException('Could not find the path to Laravels storage directory.');
  988. }
  989. // We disabled this at startup -> have a look at the setDefaultConfigValues method
  990. $this->assertEquals(false, Cron::isPreventOverlapping());
  991. // Enabling prevention
  992. Cron::setEnablePreventOverlapping();
  993. $this->assertEquals(true, Cron::isPreventOverlapping());
  994. // Disabling prevention
  995. Cron::setDisablePreventOverlapping();
  996. $this->assertEquals(false, Cron::isPreventOverlapping());
  997. // Sorry, for windows 7 servers unlink and touch does not work
  998. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  999. return;
  1000. }
  1001. // Create a example job which writes to the $lockfileExists variable if a lock file exists
  1002. $lockfileExists;
  1003. Cron::add('testlockfile', "* * * * *", function() use (&$lockfileExists, $storagePath) {
  1004. if (file_exists($storagePath . DIRECTORY_SEPARATOR . 'cron.lock')) {
  1005. $lockfileExists = true;
  1006. } else {
  1007. $lockfileExists = false;
  1008. }
  1009. });
  1010. Cron::run();
  1011. $this->assertEquals(false, $lockfileExists);
  1012. $this->assertEquals(false, file_exists($storagePath . DIRECTORY_SEPARATOR . 'cron.lock'));
  1013. $lockfileExists = "";
  1014. Cron::setEnablePreventOverlapping();
  1015. $this->assertEquals(true, Cron::isPreventOverlapping());
  1016. Cron::run();
  1017. $this->assertEquals(true, $lockfileExists);
  1018. $this->assertEquals(false, file_exists($storagePath . DIRECTORY_SEPARATOR . 'cron.lock'));
  1019. // Simulate two run calls at the same time
  1020. touch($storagePath . DIRECTORY_SEPARATOR . 'cron.lock');
  1021. $this->assertEquals(true, file_exists($storagePath . DIRECTORY_SEPARATOR . 'cron.lock'));
  1022. Cron::setDatabaseLogging(true);
  1023. $lockfileExists = "Not called";
  1024. $report = Cron::run();
  1025. $this->assertEquals("Not called", $lockfileExists);
  1026. $this->assertEquals(-1, $report['runtime']);
  1027. $newManagerFind = \Liebig\Cron\Models\Manager::find(1);
  1028. $this->assertNotNull($newManagerFind);
  1029. $this->assertEquals(-1, $newManagerFind->runtime);
  1030. unlink($storagePath . DIRECTORY_SEPARATOR . 'cron.lock');
  1031. $this->assertEquals(false, file_exists($storagePath . DIRECTORY_SEPARATOR . 'cron.lock'));
  1032. }
  1033. /**
  1034. * Test the try-catch-block of the job execution call
  1035. *
  1036. * @covers \Liebig\Cron\Cron::run
  1037. */
  1038. public function testCatchJobException() {
  1039. Cron::add('exception1', "* * * * *", function() {
  1040. throw new \Exception('Test Exception.');
  1041. return false;
  1042. });
  1043. Cron::run();
  1044. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  1045. $jobs = \Liebig\Cron\Models\Job::all();
  1046. $this->assertEquals(1, count($jobs));
  1047. $this->assertEquals('exception1', $jobs[0]->name);
  1048. $this->assertEquals('Exception in job exception1: Test Exception.', $jobs[0]->return);
  1049. }
  1050. /**
  1051. * Tests the Cron run events
  1052. *
  1053. * @covers \Liebig\Cron\Cron::run
  1054. */
  1055. public function testRunEvents() {
  1056. $result = array();
  1057. \Event::listen('cron.afterRun', function($rundate, $inTime, $runtime, $errors, $crons) use (&$result) {
  1058. array_push($result, array($rundate, $inTime, $runtime, $errors, $crons));
  1059. });
  1060. \Event::listen('cron.collectJobs', function() use (&$result) {
  1061. array_push($result, "Collect");
  1062. Cron::add('test1', "* * * * *", function() use (&$result) {
  1063. array_push($result, 'Job');
  1064. return 'No';
  1065. });
  1066. Cron::add('test2', "* * * * *", function() use (&$result) {
  1067. array_push($result, 'Job');
  1068. });
  1069. });
  1070. \Event::listen('cron.beforeRun', function($runDate) use (&$result) {
  1071. $now = new \DateTime();
  1072. if(empty($runDate) || !is_int($runDate) || $runDate > $now->getTimestamp()) {
  1073. throw new \Exception('$runDate with value ' . $runDate . ' should not be empty, has to be an integer value and has to be lower then the current timestamp');
  1074. }
  1075. array_push($result, 'Before');
  1076. });
  1077. $successArray = array();
  1078. \Event::Listen('cron.jobSuccess', function($name, $runtime, $rundate) use (&$successArray) {
  1079. array_push($successArray, $name);
  1080. });
  1081. $errorArray = array();
  1082. \Event::Listen('cron.jobError', function($name, $runtime, $rundate) use (&$errorArray) {
  1083. array_push($errorArray, $name);
  1084. });
  1085. \Artisan::call('cron:run', array());
  1086. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  1087. $this->assertEquals(1, \Liebig\Cron\Models\Job::count());
  1088. $this->assertEquals('Collect', $result[0]);
  1089. $this->assertEquals('Before', $result[1]);
  1090. $this->assertEquals('Job', $result[2]);
  1091. $this->assertEquals('Job', $result[3]);
  1092. // [0]$rundate, [1]$inTime, [2]$runtime, [3]$errors, [4]$crons
  1093. $this->assertEquals(true, is_array($result[4]));
  1094. // Errors
  1095. $this->assertEquals(1, $result[4][3]);
  1096. // Crons
  1097. $this->assertEquals(2, count($result[4][4]));
  1098. // Crons -> first -> name
  1099. $this->assertEquals('test1', $result[4][4][0]['name']);
  1100. // Crons -> first -> return
  1101. $this->assertEquals('No', $result[4][4][0]['return']);
  1102. $this->assertEquals(1, count($successArray));
  1103. $this->assertEquals('test2', $successArray[0]);
  1104. $this->assertEquals(1, count($errorArray));
  1105. $this->assertEquals('test1', $errorArray[0]);
  1106. }
  1107. /**
  1108. * Tests the Cron run events
  1109. *
  1110. * @covers \Liebig\Cron\Cron::run
  1111. */
  1112. public function testAfterRunEvent() {
  1113. $result = array();
  1114. \Event::listen('cron.afterRun', function($rundate, $inTime, $runtime, $errors, $crons, $lastRun) use (&$result) {
  1115. array_push($result, array($rundate, $inTime, $runtime, $errors, $crons, $lastRun));
  1116. });
  1117. Cron::add('test1', "* * * * *", function() {
  1118. return 'Test 1 done';
  1119. });
  1120. Cron::add('test2', "* * * * *", function() {
  1121. });
  1122. $firstRun = Cron::run();
  1123. $this->assertEquals(-1, $firstRun['inTime']);
  1124. $this->assertEquals(1, $firstRun['errors']);
  1125. sleep(5);
  1126. $secondRun = Cron::run();
  1127. $this->assertEquals(false, $secondRun['inTime']);
  1128. $this->assertEquals(1, $secondRun['errors']);
  1129. // inTime
  1130. $this->assertEquals(-1, $result[0][1]);
  1131. $this->assertEquals(false, $result[1][1]);
  1132. // errors
  1133. $this->assertEquals(1, $result[0][3]);
  1134. $this->assertEquals(1, $result[1][3]);
  1135. // lastRun
  1136. $this->assertEquals($result[0][5], array());
  1137. $secondRundate = new \DateTime($result[1][5]['rundate']);
  1138. $this->assertEquals($firstRun['rundate'], $secondRundate->getTimestamp());
  1139. }
  1140. /**
  1141. * Tests the Cron run command
  1142. *
  1143. * @covers \Liebig\Cron\RunCommand
  1144. */
  1145. public function testRunCommand() {
  1146. $result = array();
  1147. \Event::listen('cron.collectJobs', function() use (&$result) {
  1148. Cron::add('test1', "* * * * *", function() use (&$result) {
  1149. array_push($result, 'test1');
  1150. });
  1151. Cron::add('test2', "* * * * *", function() use (&$result) {
  1152. array_push($result, 'test2');
  1153. return 'No';
  1154. });
  1155. });
  1156. \Artisan::call('cron:run', array());
  1157. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  1158. $this->assertEquals(1, \Liebig\Cron\Models\Job::count());
  1159. $this->assertEquals(2, count($result));
  1160. $this->assertEquals('test1', $result[0]);
  1161. $this->assertEquals('test2', $result[1]);
  1162. }
  1163. /**
  1164. * Tests the Cron list command
  1165. *
  1166. * @covers \Liebig\Cron\ListCommand
  1167. */
  1168. public function testListCommand() {
  1169. $commandOutput = '';
  1170. if($this->laravelVersion >= 5) {
  1171. \Artisan::call('cron:list', array());
  1172. $commandOutput = \Artisan::output();
  1173. } else {
  1174. $outputStream = new \Symfony\Component\Console\Output\StreamOutput(
  1175. fopen('php://output', 'w')
  1176. );
  1177. ob_start();
  1178. \Artisan::call('cron:list', array(), $outputStream);
  1179. $commandOutput = ob_get_clean();
  1180. }
  1181. $this->assertTrue(is_int(strpos($commandOutput, 'Jobname')));
  1182. $this->assertTrue(is_int(strpos($commandOutput, 'Expression')));
  1183. $this->assertTrue(is_int(strpos($commandOutput, 'Activated')));
  1184. \Event::listen('cron.collectJobs', function() {
  1185. Cron::add('test1', "* * * * *", function() {
  1186. });
  1187. Cron::add('test2', "* * * * *", function() {
  1188. return 'No';
  1189. }, false);
  1190. });
  1191. if($this->laravelVersion >= 5) {
  1192. \Artisan::call('cron:list', array());
  1193. $commandOutput = \Artisan::output();
  1194. } else {
  1195. $outputStream = new \Symfony\Component\Console\Output\StreamOutput(
  1196. fopen('php://output', 'w')
  1197. );
  1198. ob_start();
  1199. \Artisan::call('cron:list', array(), $outputStream);
  1200. $commandOutput = ob_get_clean();
  1201. }
  1202. $this->assertTrue(is_int(strpos($commandOutput, 'Jobname')));
  1203. $this->assertTrue(is_int(strpos($commandOutput, 'Expression')));
  1204. $this->assertTrue(is_int(strpos($commandOutput, 'Activated')));
  1205. $this->assertTrue(is_int(strpos($commandOutput, 'test1')));
  1206. $this->assertTrue(is_int(strpos($commandOutput, 'test2')));
  1207. $this->assertTrue(is_int(strpos($commandOutput, '* * * * *')));
  1208. $this->assertTrue(is_int(strpos($commandOutput, 'Enabled')));
  1209. $this->assertTrue(is_int(strpos($commandOutput, 'Disabled')));
  1210. }
  1211. /**
  1212. * Tests the Cron keygen command
  1213. *
  1214. * @covers \Liebig\Cron\KeygenCommand
  1215. */
  1216. public function testKeygenCommand() {
  1217. $commandOutput = '';
  1218. if($this->laravelVersion >= 5) {
  1219. \Artisan::call('cron:keygen', array());
  1220. $commandOutput = \Artisan::output();
  1221. } else {
  1222. $outputStream = new \Symfony\Component\Console\Output\StreamOutput(
  1223. fopen('php://output', 'w')
  1224. );
  1225. ob_start();
  1226. \Artisan::call('cron:keygen', array(), $outputStream);
  1227. $commandOutput = ob_get_clean();
  1228. }
  1229. $commandOutput = str_replace("\r",'', $commandOutput);
  1230. $commandOutput = str_replace("\n",'', $commandOutput);
  1231. $this->assertEquals(32, strlen($commandOutput));
  1232. $this->assertTrue(ctype_alnum($commandOutput));
  1233. if($this->laravelVersion >= 5) {
  1234. \Artisan::call('cron:keygen', array('length' => 5));
  1235. $commandOutput = \Artisan::output();
  1236. } else {
  1237. $outputStream = new \Symfony\Component\Console\Output\StreamOutput(
  1238. fopen('php://output', 'w')
  1239. );
  1240. ob_start();
  1241. \Artisan::call('cron:keygen', array('length' => 5), $outputStream);
  1242. $commandOutput = ob_get_clean();
  1243. }
  1244. $commandOutput = str_replace("\r",'', $commandOutput);
  1245. $commandOutput = str_replace("\n",'', $commandOutput);
  1246. $this->assertEquals(5, strlen($commandOutput));
  1247. $this->assertTrue(ctype_alnum($commandOutput));
  1248. }
  1249. /**
  1250. * Tests the Cron run route without setting up the security key
  1251. *
  1252. * @covers \Liebig\Cron\CronServiceProvider
  1253. */
  1254. public function testRunRouteWithoutKey() {
  1255. \Event::listen('cron.collectJobs', function() {
  1256. Cron::add('test1', "* * * * *", function() {
  1257. });
  1258. Cron::add('test2', "* * * * *", function() {
  1259. return 'No';
  1260. });
  1261. });
  1262. if($this->laravelVersion >= 5) {
  1263. $response = $this->call('GET', 'cron.php');
  1264. $this->assertEquals(404, $response->getStatusCode());
  1265. } else {
  1266. try {
  1267. $this->call('GET', 'cron.php');
  1268. $this->fail('The Symfony\Component\HttpKernel\Exception\NotFoundHttpException has not been raised.');
  1269. } catch (\Exception $e) {
  1270. $this->assertEquals('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', get_class($e));
  1271. }
  1272. }
  1273. }
  1274. /**
  1275. * Tests the Cron run route with setting up the security key but without sending a key
  1276. *
  1277. * @covers \Liebig\Cron\CronServiceProvider
  1278. */
  1279. public function testRunRouteWithKeyWithNoSendKey() {
  1280. \Event::listen('cron.collectJobs', function() {
  1281. Cron::add('test1', "* * * * *", function() {
  1282. });
  1283. Cron::add('test2', "* * * * *", function() {
  1284. return 'No';
  1285. });
  1286. });
  1287. if($this->laravelVersion >= 5) {
  1288. \Config::set('liebigCron.cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1289. $response = $this->call('GET', 'cron.php');
  1290. $this->assertEquals(404, $response->getStatusCode());
  1291. } else {
  1292. \Config::set('cron::cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1293. try {
  1294. $this->call('GET', 'cron.php');
  1295. $this->fail('The Symfony\Component\HttpKernel\Exception\NotFoundHttpException has not been raised.');
  1296. } catch (\Exception $e) {
  1297. $this->assertEquals('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', get_class($e));
  1298. }
  1299. }
  1300. }
  1301. /**
  1302. * Tests the Cron run route with setting up the security key but with sending a wrong key
  1303. *
  1304. * @covers \Liebig\Cron\CronServiceProvider
  1305. */
  1306. public function testRunRouteWithKeyWithWrongSendKey() {
  1307. \Event::listen('cron.collectJobs', function() {
  1308. Cron::add('test1', "* * * * *", function() {
  1309. });
  1310. Cron::add('test2', "* * * * *", function() {
  1311. return 'No';
  1312. });
  1313. });
  1314. if($this->laravelVersion >= 5) {
  1315. \Config::set('liebigCron.cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1316. $response = $this->call('GET', 'cron.php', array('key'=>'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ9'));
  1317. $this->assertEquals(404, $response->getStatusCode());
  1318. } else {
  1319. \Config::set('cron::cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1320. try {
  1321. $this->call('GET', 'cron.php', array('key'=>'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ9'));
  1322. $this->fail('The Symfony\Component\HttpKernel\Exception\NotFoundHttpException has not been raised.');
  1323. } catch (\Exception $e) {
  1324. $this->assertEquals('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', get_class($e));
  1325. }
  1326. }
  1327. }
  1328. /**
  1329. * Tests the Cron run route with setting up the security key but with sending a key with not alphanumeric characters
  1330. *
  1331. * @covers \Liebig\Cron\CronServiceProvider
  1332. */
  1333. public function testRunRouteWithKeyWithNotAlphanumericSendKey() {
  1334. \Event::listen('cron.collectJobs', function() {
  1335. Cron::add('test1', "* * * * *", function() {
  1336. });
  1337. Cron::add('test2', "* * * * *", function() {
  1338. return 'No';
  1339. });
  1340. });
  1341. if($this->laravelVersion >= 5) {
  1342. \Config::set('liebigCron.cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1343. $response = $this->call('GET', 'cron.php', array('key'=>'&!€%<>'));
  1344. $this->assertEquals(404, $response->getStatusCode());
  1345. } else {
  1346. \Config::set('cron::cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1347. try {
  1348. $this->call('GET', 'cron.php', array('key'=>'&!€%<>'));
  1349. $this->fail('The Symfony\Component\HttpKernel\Exception\NotFoundHttpException has not been raised.');
  1350. } catch (\Exception $e) {
  1351. $this->assertEquals('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', get_class($e));
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * Tests the Cron run route with setting up the security key and with sending the right key
  1357. *
  1358. * @covers \Liebig\Cron\CronServiceProvider
  1359. */
  1360. public function testRunRouteWithKeyWithCorrectSendKey() {
  1361. \Event::listen('cron.collectJobs', function() {
  1362. Cron::add('test1', "* * * * *", function() {
  1363. });
  1364. Cron::add('test2', "* * * * *", function() {
  1365. return 'No';
  1366. });
  1367. });
  1368. if($this->laravelVersion >= 5) {
  1369. \Config::set('liebigCron.cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1370. \Config::set('liebigCron.logOnlyErrorJobsToDatabase', false);
  1371. } else {
  1372. \Config::set('cron::cronKey', 'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8');
  1373. \Config::set('cron::logOnlyErrorJobsToDatabase', false);
  1374. }
  1375. $response = $this->call('GET', 'cron.php', array('key'=>'yT7yt3sa4tg5vtlLWbofF95v65FSWWZ8'));
  1376. $this->assertEquals(200, $response->getStatusCode());
  1377. $this->assertEquals(1, \Liebig\Cron\Models\Manager::count());
  1378. $this->assertEquals(2, \Liebig\Cron\Models\Job::count());
  1379. $jobs = \Liebig\Cron\Models\Job::all();
  1380. $this->assertEquals(2, count($jobs));
  1381. $this->assertEquals('test1', $jobs[0]->name);
  1382. $this->assertEquals('', $jobs[0]->return);
  1383. $this->assertEquals('test2', $jobs[1]->name);
  1384. $this->assertEquals('No', $jobs[1]->return);
  1385. }
  1386. }