TimestampBehaviorTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\ORM\Behavior;
  16. use Cake\Database\TypeFactory;
  17. use Cake\Event\Event;
  18. use Cake\I18n\FrozenTime;
  19. use Cake\I18n\Time;
  20. use Cake\ORM\Behavior\TimestampBehavior;
  21. use Cake\ORM\Entity;
  22. use Cake\ORM\Table;
  23. use Cake\TestSuite\TestCase;
  24. use RuntimeException;
  25. /**
  26. * Behavior test case
  27. */
  28. class TimestampBehaviorTest extends TestCase
  29. {
  30. /**
  31. * autoFixtures
  32. *
  33. * Don't load fixtures for all tests
  34. *
  35. * @var bool
  36. */
  37. public $autoFixtures = false;
  38. /**
  39. * fixtures
  40. *
  41. * @var array
  42. */
  43. public $fixtures = [
  44. 'core.users'
  45. ];
  46. /**
  47. * Sanity check Implemented events
  48. *
  49. * @return void
  50. */
  51. public function testImplementedEventsDefault()
  52. {
  53. $table = $this->getTable();
  54. $this->Behavior = new TimestampBehavior($table);
  55. $expected = [
  56. 'Model.beforeSave' => 'handleEvent'
  57. ];
  58. $this->assertEquals($expected, $this->Behavior->implementedEvents());
  59. }
  60. /**
  61. * testImplementedEventsCustom
  62. *
  63. * The behavior allows for handling any event - test an example
  64. *
  65. * @return void
  66. */
  67. public function testImplementedEventsCustom()
  68. {
  69. $table = $this->getTable();
  70. $settings = ['events' => ['Something.special' => ['date_specialed' => 'always']]];
  71. $this->Behavior = new TimestampBehavior($table, $settings);
  72. $expected = [
  73. 'Something.special' => 'handleEvent'
  74. ];
  75. $this->assertEquals($expected, $this->Behavior->implementedEvents());
  76. }
  77. /**
  78. * testCreatedAbsent
  79. *
  80. * @return void
  81. * @triggers Model.beforeSave
  82. */
  83. public function testCreatedAbsent()
  84. {
  85. $table = $this->getTable();
  86. $this->Behavior = new TimestampBehavior($table);
  87. $ts = new \DateTime('2000-01-01');
  88. $this->Behavior->timestamp($ts);
  89. $event = new Event('Model.beforeSave');
  90. $entity = new Entity(['name' => 'Foo']);
  91. $return = $this->Behavior->handleEvent($event, $entity);
  92. $this->assertTrue($return, 'Handle Event is expected to always return true');
  93. $this->assertInstanceOf(FrozenTime::class, $entity->created);
  94. $this->assertSame($ts->format('c'), $entity->created->format('c'), 'Created timestamp is not the same');
  95. }
  96. /**
  97. * testCreatedPresent
  98. *
  99. * @return void
  100. * @triggers Model.beforeSave
  101. */
  102. public function testCreatedPresent()
  103. {
  104. $table = $this->getTable();
  105. $this->Behavior = new TimestampBehavior($table);
  106. $ts = new \DateTime('2000-01-01');
  107. $this->Behavior->timestamp($ts);
  108. $event = new Event('Model.beforeSave');
  109. $existingValue = new \DateTime('2011-11-11');
  110. $entity = new Entity(['name' => 'Foo', 'created' => $existingValue]);
  111. $return = $this->Behavior->handleEvent($event, $entity);
  112. $this->assertTrue($return, 'Handle Event is expected to always return true');
  113. $this->assertSame($existingValue, $entity->created, 'Created timestamp is expected to be unchanged');
  114. }
  115. /**
  116. * testCreatedNotNew
  117. *
  118. * @return void
  119. * @triggers Model.beforeSave
  120. */
  121. public function testCreatedNotNew()
  122. {
  123. $table = $this->getTable();
  124. $this->Behavior = new TimestampBehavior($table);
  125. $ts = new \DateTime('2000-01-01');
  126. $this->Behavior->timestamp($ts);
  127. $event = new Event('Model.beforeSave');
  128. $entity = new Entity(['name' => 'Foo']);
  129. $entity->isNew(false);
  130. $return = $this->Behavior->handleEvent($event, $entity);
  131. $this->assertTrue($return, 'Handle Event is expected to always return true');
  132. $this->assertNull($entity->created, 'Created timestamp is expected to be untouched if the entity is not new');
  133. }
  134. /**
  135. * testModifiedAbsent
  136. *
  137. * @return void
  138. * @triggers Model.beforeSave
  139. */
  140. public function testModifiedAbsent()
  141. {
  142. $table = $this->getTable();
  143. $this->Behavior = new TimestampBehavior($table);
  144. $ts = new \DateTime('2000-01-01');
  145. $this->Behavior->timestamp($ts);
  146. $event = new Event('Model.beforeSave');
  147. $entity = new Entity(['name' => 'Foo']);
  148. $entity->isNew(false);
  149. $return = $this->Behavior->handleEvent($event, $entity);
  150. $this->assertTrue($return, 'Handle Event is expected to always return true');
  151. $this->assertInstanceOf(FrozenTime::class, $entity->modified);
  152. $this->assertSame($ts->format('c'), $entity->modified->format('c'), 'Modified timestamp is not the same');
  153. }
  154. /**
  155. * testModifiedPresent
  156. *
  157. * @return void
  158. * @triggers Model.beforeSave
  159. */
  160. public function testModifiedPresent()
  161. {
  162. $table = $this->getTable();
  163. $this->Behavior = new TimestampBehavior($table);
  164. $ts = new \DateTime('2000-01-01');
  165. $this->Behavior->timestamp($ts);
  166. $event = new Event('Model.beforeSave');
  167. $existingValue = new \DateTime('2011-11-11');
  168. $entity = new Entity(['name' => 'Foo', 'modified' => $existingValue]);
  169. $entity->clean();
  170. $entity->isNew(false);
  171. $return = $this->Behavior->handleEvent($event, $entity);
  172. $this->assertTrue($return, 'Handle Event is expected to always return true');
  173. $this->assertInstanceOf(FrozenTime::class, $entity->modified);
  174. $this->assertSame($ts->format('c'), $entity->modified->format('c'), 'Modified timestamp is expected to be updated');
  175. }
  176. /**
  177. * test that timestamp creation doesn't fail on missing columns
  178. *
  179. * @return void
  180. */
  181. public function testModifiedMissingColumn()
  182. {
  183. $table = $this->getTable();
  184. $table->getSchema()->removeColumn('created')->removeColumn('modified');
  185. $this->Behavior = new TimestampBehavior($table);
  186. $ts = new \DateTime('2000-01-01');
  187. $this->Behavior->timestamp($ts);
  188. $event = new Event('Model.beforeSave');
  189. $entity = new Entity(['name' => 'Foo']);
  190. $return = $this->Behavior->handleEvent($event, $entity);
  191. $this->assertTrue($return, 'Handle Event is expected to always return true');
  192. $this->assertNull($entity->created);
  193. $this->assertNull($entity->modified);
  194. }
  195. /**
  196. * testUseImmutable
  197. *
  198. * @return void
  199. * @triggers Model.beforeSave
  200. */
  201. public function testUseImmutable()
  202. {
  203. $table = $this->getTable();
  204. $this->Behavior = new TimestampBehavior($table);
  205. $entity = new Entity();
  206. $event = new Event('Model.beforeSave');
  207. $entity->clean();
  208. $this->Behavior->handleEvent($event, $entity);
  209. $this->assertInstanceOf('Cake\I18n\FrozenTime', $entity->modified);
  210. TypeFactory::build('timestamp')->useMutable();
  211. $entity->clean();
  212. $this->Behavior->handleEvent($event, $entity);
  213. $this->assertInstanceOf('Cake\I18n\Time', $entity->modified);
  214. // Revert back to using immutable class to avoid causing problems in
  215. // other test cases when running full test suite.
  216. TypeFactory::build('timestamp')->useImmutable();
  217. }
  218. /**
  219. * tests using non-DateTimeType throws runtime exception
  220. *
  221. * @return void
  222. */
  223. public function testNonDateTimeTypeException()
  224. {
  225. $this->expectException(RuntimeException::class);
  226. $this->expectExceptionMessage('TimestampBehavior only supports columns of type DateTimeType.');
  227. $table = $this->getTable();
  228. $this->Behavior = new TimestampBehavior($table, [
  229. 'events' => [
  230. 'Model.beforeSave' => [
  231. 'timestamp_str' => 'always',
  232. ]
  233. ],
  234. ]);
  235. $entity = new Entity();
  236. $event = new Event('Model.beforeSave');
  237. $this->Behavior->handleEvent($event, $entity);
  238. $this->assertInternalType('string', $entity->timestamp_str);
  239. }
  240. /**
  241. * testInvalidEventConfig
  242. *
  243. * @return void
  244. * @triggers Model.beforeSave
  245. */
  246. public function testInvalidEventConfig()
  247. {
  248. $this->expectException(\UnexpectedValueException::class);
  249. $this->expectExceptionMessage('When should be one of "always", "new" or "existing". The passed value "fat fingers" is invalid');
  250. $table = $this->getTable();
  251. $settings = ['events' => ['Model.beforeSave' => ['created' => 'fat fingers']]];
  252. $this->Behavior = new TimestampBehavior($table, $settings);
  253. $event = new Event('Model.beforeSave');
  254. $entity = new Entity(['name' => 'Foo']);
  255. $this->Behavior->handleEvent($event, $entity);
  256. }
  257. /**
  258. * testGetTimestamp
  259. *
  260. * @return void
  261. */
  262. public function testGetTimestamp()
  263. {
  264. $table = $this->getTable();
  265. $behavior = new TimestampBehavior($table);
  266. $return = $behavior->timestamp();
  267. $this->assertInstanceOf(
  268. 'DateTime',
  269. $return,
  270. 'Should return a timestamp object'
  271. );
  272. $now = Time::now();
  273. $this->assertEquals($now, $return);
  274. }
  275. /**
  276. * testGetTimestampPersists
  277. *
  278. * @return void
  279. */
  280. public function testGetTimestampPersists()
  281. {
  282. $table = $this->getTable();
  283. $behavior = new TimestampBehavior($table);
  284. $initialValue = $behavior->timestamp();
  285. $postValue = $behavior->timestamp();
  286. $this->assertSame(
  287. $initialValue,
  288. $postValue,
  289. 'The timestamp should be exactly the same object'
  290. );
  291. }
  292. /**
  293. * testGetTimestampRefreshes
  294. *
  295. * @return void
  296. */
  297. public function testGetTimestampRefreshes()
  298. {
  299. $table = $this->getTable();
  300. $behavior = new TimestampBehavior($table);
  301. $initialValue = $behavior->timestamp();
  302. $postValue = $behavior->timestamp(null, true);
  303. $this->assertNotSame(
  304. $initialValue,
  305. $postValue,
  306. 'The timestamp should be a different object if refreshTimestamp is truthy'
  307. );
  308. }
  309. /**
  310. * testSetTimestampExplicit
  311. *
  312. * @return void
  313. */
  314. public function testSetTimestampExplicit()
  315. {
  316. $table = $this->getTable();
  317. $this->Behavior = new TimestampBehavior($table);
  318. $ts = new \DateTime();
  319. $this->Behavior->timestamp($ts);
  320. $return = $this->Behavior->timestamp();
  321. $this->assertEquals(
  322. $ts->format('c'),
  323. $return->format('c'),
  324. 'Should return the same value as initially set'
  325. );
  326. }
  327. /**
  328. * testTouch
  329. *
  330. * @return void
  331. */
  332. public function testTouch()
  333. {
  334. $table = $this->getTable();
  335. $this->Behavior = new TimestampBehavior($table);
  336. $ts = new \DateTime('2000-01-01');
  337. $this->Behavior->timestamp($ts);
  338. $entity = new Entity(['username' => 'timestamp test']);
  339. $return = $this->Behavior->touch($entity);
  340. $this->assertTrue($return, 'touch is expected to return true if it sets a field value');
  341. $this->assertSame(
  342. $ts->format('Y-m-d H:i:s'),
  343. $entity->modified->format('Y-m-d H:i:s'),
  344. 'Modified field is expected to be updated'
  345. );
  346. $this->assertNull($entity->created, 'Created field is NOT expected to change');
  347. }
  348. /**
  349. * testTouchNoop
  350. *
  351. * @return void
  352. */
  353. public function testTouchNoop()
  354. {
  355. $table = $this->getTable();
  356. $config = [
  357. 'events' => [
  358. 'Model.beforeSave' => [
  359. 'created' => 'new',
  360. ]
  361. ]
  362. ];
  363. $this->Behavior = new TimestampBehavior($table, $config);
  364. $ts = new \DateTime('2000-01-01');
  365. $this->Behavior->timestamp($ts);
  366. $entity = new Entity(['username' => 'timestamp test']);
  367. $return = $this->Behavior->touch($entity);
  368. $this->assertFalse($return, 'touch is expected to do nothing and return false');
  369. $this->assertNull($entity->modified, 'Modified field is NOT expected to change');
  370. $this->assertNull($entity->created, 'Created field is NOT expected to change');
  371. }
  372. /**
  373. * testTouchCustomEvent
  374. *
  375. * @return void
  376. */
  377. public function testTouchCustomEvent()
  378. {
  379. $table = $this->getTable();
  380. $settings = ['events' => ['Something.special' => ['date_specialed' => 'always']]];
  381. $this->Behavior = new TimestampBehavior($table, $settings);
  382. $ts = new \DateTime('2000-01-01');
  383. $this->Behavior->timestamp($ts);
  384. $entity = new Entity(['username' => 'timestamp test']);
  385. $return = $this->Behavior->touch($entity, 'Something.special');
  386. $this->assertTrue($return, 'touch is expected to return true if it sets a field value');
  387. $this->assertSame(
  388. $ts->format('Y-m-d H:i:s'),
  389. $entity->date_specialed->format('Y-m-d H:i:s'),
  390. 'Modified field is expected to be updated'
  391. );
  392. $this->assertNull($entity->created, 'Created field is NOT expected to change');
  393. }
  394. /**
  395. * Test that calling save, triggers an insert including the created and updated field values
  396. *
  397. * @return void
  398. */
  399. public function testSaveTriggersInsert()
  400. {
  401. $this->loadFixtures('Users');
  402. $table = $this->getTableLocator()->get('users');
  403. $table->addBehavior('Timestamp', [
  404. 'events' => [
  405. 'Model.beforeSave' => [
  406. 'created' => 'new',
  407. 'updated' => 'always'
  408. ]
  409. ]
  410. ]);
  411. $entity = new Entity(['username' => 'timestamp test']);
  412. $return = $table->save($entity);
  413. $this->assertSame($entity, $return, 'The returned object is expected to be the same entity object');
  414. $row = $table->find('all')->where(['id' => $entity->id])->first();
  415. $now = Time::now();
  416. $this->assertEquals($now->toDateTimeString(), $row->created->toDateTimeString());
  417. $this->assertEquals($now->toDateTimeString(), $row->updated->toDateTimeString());
  418. }
  419. /**
  420. * Helper method to get Table instance with created/modified column
  421. *
  422. * @return \Cake\ORM\Table
  423. */
  424. protected function getTable()
  425. {
  426. $schema = [
  427. 'created' => ['type' => 'datetime'],
  428. 'modified' => ['type' => 'timestamp'],
  429. 'date_specialed' => ['type' => 'datetime'],
  430. 'timestamp_str' => ['type' => 'string'],
  431. ];
  432. return new Table([
  433. 'alias' => 'Articles',
  434. 'schema' => $schema
  435. ]);
  436. }
  437. }