TableModelTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. // Copyright 2019 Hackware SpA <human@hackware.cl>
  3. // "Hackware Web Services Core" is released under the MIT License terms.
  4. namespace Hawese\Tests;
  5. use Hawese\Core\TableModel;
  6. use Laravel\Lumen\Testing\DatabaseTransactions;
  7. use Illuminate\Support\Carbon;
  8. class TableModelTest extends TestCase
  9. {
  10. use DatabaseTransactions;
  11. protected function setUp(): void
  12. {
  13. parent::setUp();
  14. $this->dumbObj = new DumbTableModel();
  15. }
  16. public function testConstructorWithData()
  17. {
  18. $dumbObject = new DumbTableModel(['attr1' => 'something']);
  19. $this->assertSame('something', $dumbObject->attr1);
  20. }
  21. public function testEmptyConstructor()
  22. {
  23. $this->assertNull($this->dumbObj->attr1);
  24. }
  25. public function testAccesorWithCustomGetter()
  26. {
  27. $this->dumbObj->custom_getter = 'never_seen_value';
  28. $this->assertSame('custom_getter_value', $this->dumbObj->custom_getter);
  29. }
  30. public function testUndefinedAccesor()
  31. {
  32. $this->expectExceptionMessage('Undefined property via __get()');
  33. $this->dumbObj->nonexistent_attr;
  34. }
  35. public function testMutatorWithCustomSetter()
  36. {
  37. $this->dumbObj->custom_setter = 'never_set_value';
  38. $this->assertSame('custom_setter_value', $this->dumbObj->custom_setter);
  39. }
  40. public function testUndefinedMutator()
  41. {
  42. $this->expectExceptionMessage('Undefined property via __set()');
  43. $this->dumbObj->nonexistent_attr = 'any_value';
  44. $this->assertNull($this->dumbObj->nonexistent_attr);
  45. }
  46. // I probably could write a better test
  47. // $dumbObj->data is protected and I intend to keep it that way.
  48. public function testAccesorAndMutatorWithData()
  49. {
  50. $this->dumbObj->attr1 = 'something_else';
  51. $this->assertSame('something_else', $this->dumbObj->attr1);
  52. }
  53. public function testAutomagicallyUseCarbonOnCrudDates()
  54. {
  55. $this->dumbObj->created_at = '2019-01-01 00:00';
  56. $this->dumbObj->updated_at = '2019-01-01 01:00';
  57. $this->dumbObj->deleted_at = '2019-01-01';
  58. $this->dumbObj->else_at = '2019-01-01 00:00';
  59. foreach (['created_at', 'updated_at', 'deleted_at'] as $dateAttr) {
  60. $this->assertInstanceOf(
  61. Carbon::class,
  62. $this->dumbObj->{$dateAttr}
  63. );
  64. }
  65. $this->assertNotInstanceOf(
  66. Carbon::class,
  67. $this->dumbObj->else_at
  68. );
  69. }
  70. public function testIsset()
  71. {
  72. $this->assertFalse(isset($this->dumbObj->attr1));
  73. $this->dumbObj->attr1 = 'anything';
  74. $this->assertTrue(isset($this->dumbObj->attr1));
  75. }
  76. /* implements ArrayAccess */
  77. public function testOffsetExists()
  78. {
  79. $this->assertFalse(isset($this->dumbObj['attr1']));
  80. $this->dumbObj->attr1 = '';
  81. $this->assertTrue(isset($this->dumbObj['attr1']));
  82. $this->assertTrue(empty($this->dumbObj['attr1']));
  83. $this->dumbObj->attr1 = true;
  84. $this->assertFalse(empty($this->dumbObj['attr1']));
  85. }
  86. public function testOffsetGet()
  87. {
  88. $this->dumbObj->attr1 = 'value';
  89. $this->assertSame('value', $this->dumbObj['attr1']);
  90. }
  91. public function testOffsetSet()
  92. {
  93. $this->dumbObj['attr1'] = 'value';
  94. $this->assertSame('value', $this->dumbObj->attr1);
  95. }
  96. public function testOffsetUnset()
  97. {
  98. $this->dumbObj->attr1 = 'value';
  99. $this->assertNotNull($this->dumbObj->attr1);
  100. unset($this->dumbObj['attr1']);
  101. $this->assertNull($this->dumbObj->attr1);
  102. }
  103. /* /implements ArrayAccess */
  104. public function arrayableJsonSerializableDumbObj()
  105. {
  106. $otherDumbObj = new class extends TableModel {
  107. public static $table = 'other_dumbs';
  108. public static $attributes = [
  109. 'id' => [],
  110. 'foreign_id' => [],
  111. 'created_at' => []
  112. ];
  113. public static $foreign_keys = [
  114. 'foreign_id' => ForeignTableModel::class
  115. ];
  116. };
  117. $foreignObj = new ForeignTableModel();
  118. $otherDumbObj->foreign_id = $foreignObj->insert();
  119. $otherDumbObj->foreignObjectGetter('foreign'); // test nested
  120. $otherDumbObj->appendInstanceAttribute('other_attr');
  121. $otherDumbObj->other_attr = 'other_val';
  122. return $otherDumbObj;
  123. }
  124. // Implements Arrayable
  125. public function testToArray()
  126. {
  127. $otherDumbObj = $this->arrayableJsonSerializableDumbObj();
  128. $this->assertEqualsCanonicalizing(
  129. [
  130. 'id' => null,
  131. 'foreign_id' => $otherDumbObj->foreign->id,
  132. 'foreign' => ['id' => $otherDumbObj->foreign->id],
  133. 'created_at' => null,
  134. 'other_attr' => 'other_val'
  135. ],
  136. $otherDumbObj->toArray()
  137. );
  138. }
  139. // Implements JsonSerializable
  140. public function testJsonSerialize()
  141. {
  142. $otherDumbObj = $this->arrayableJsonSerializableDumbObj();
  143. // Timezone settings are likely to mess with this test, be my guest
  144. $reset_timezone = date_default_timezone_get();
  145. date_default_timezone_set('UTC');
  146. $otherDumbObj->created_at = new Carbon('2019-01-01 01:02:03');
  147. date_default_timezone_set($reset_timezone);
  148. $this->assertJsonStringEqualsJsonString(
  149. json_encode([
  150. 'id' => null,
  151. 'foreign_id' => $otherDumbObj->foreign->id,
  152. 'foreign' => ['id' => $otherDumbObj->foreign->id],
  153. 'created_at' => '2019-01-01T01:02:03+00:00',
  154. 'other_attr' => 'other_val'
  155. ]),
  156. json_encode($otherDumbObj)
  157. );
  158. }
  159. // Implements Jsonable
  160. public function testToJson()
  161. {
  162. $otherDumbObj = new class extends TableModel {
  163. public static $table = 'other_dumbs';
  164. public static $attributes = [
  165. 'id' => [],
  166. 'attr' => []
  167. ];
  168. };
  169. $otherDumbObj->attr = '<>';
  170. $this->assertJsonStringEqualsJsonString(
  171. json_encode(['id' => null, 'attr' => '<>']),
  172. $otherDumbObj->toJson()
  173. );
  174. $this->assertJsonStringEqualsJsonString(
  175. json_encode(['id' => null, 'attr' => '<>'], JSON_HEX_TAG),
  176. $otherDumbObj->toJson(JSON_HEX_TAG)
  177. );
  178. }
  179. public function testForeignObjectGetter()
  180. {
  181. $foreignObj = new ForeignTableModel();
  182. $foreignObj->insert();
  183. $dumbObj = new DumbTableModel(['foreign_id' => $foreignObj->id]);
  184. $dumbObj->insert();
  185. $this->expectExceptionMessage('Undefined property via __get()');
  186. try {
  187. $dumbObj->foreign;
  188. } finally {
  189. $this->assertNotNull($dumbObj->foreignObjectGetter('foreign'));
  190. $this->assertInstanceOf(ForeignTableModel::class, $dumbObj->foreign);
  191. $this->assertEquals(
  192. $dumbObj->foreign,
  193. $dumbObj->foreignObjectGetter('foreign')
  194. );
  195. }
  196. }
  197. public function testSelectWithoutAttributes()
  198. {
  199. $this->dumbObj->insert();
  200. $this->dumbObj->id = null; // This is actually a trick
  201. $this->dumbObj->insert();
  202. $dumbSelect = DumbTableModel::select();
  203. $this->assertSame(2, $dumbSelect->count());
  204. $modelAttrKeys = array_keys(DumbTableModel::$attributes);
  205. $selectAttrKeys = array_keys((array)$dumbSelect->first());
  206. $this->assertEqualsCanonicalizing($modelAttrKeys, $selectAttrKeys);
  207. }
  208. public function testSelectWithValidAttributes()
  209. {
  210. $this->dumbObj->insert();
  211. $dumbSelect = DumbTableModel::select(['id', 'attr1']);
  212. $this->assertSame(2, count(array_keys((array)$dumbSelect->first())));
  213. }
  214. public function testSelectWithDeleted()
  215. {
  216. $this->dumbObj->insert();
  217. $this->dumbObj->delete();
  218. $this->assertSame(0, DumbTableModel::select()->count());
  219. $this->assertSame(1, DumbTableModel::select(null, true)->count());
  220. }
  221. public function testSelectWithInvalidAttributes()
  222. {
  223. $this->dumbObj->insert();
  224. $dumbSelect = DumbTableModel::select(['nonexistent_attr']);
  225. $this->expectException(\Illuminate\Database\QueryException::class);
  226. $dumbSelect->first();
  227. }
  228. public function testFindByPrimaryKey()
  229. {
  230. $this->dumbObj->insert();
  231. $id = $this->dumbObj->id;
  232. $foundObj = DumbTableModel::find($id);
  233. $this->assertInstanceOf(DumbTableModel::class, $foundObj);
  234. $this->assertSame($id, $foundObj->id);
  235. }
  236. public function testFindByNonPrimaryKey()
  237. {
  238. $this->dumbObj->attr1 = 'rock';
  239. $this->dumbObj->insert();
  240. $foundObj = DumbTableModel::find('rock', 'attr1');
  241. $this->assertInstanceOf(DumbTableModel::class, $foundObj);
  242. $this->assertSame('rock', $foundObj->attr1);
  243. }
  244. public function testFindByMultipleFields()
  245. {
  246. $this->dumbObj->attr1 = 'rocktor';
  247. $this->dumbObj->insert();
  248. $foundObj = DumbTableModel::find('rocktor', ['id', 'attr1']);
  249. $this->assertInstanceOf(DumbTableModel::class, $foundObj);
  250. $this->assertSame('rocktor', $foundObj->attr1);
  251. }
  252. public function testFindByInvalidField()
  253. {
  254. $this->expectException(\Illuminate\Database\QueryException::class);
  255. $foundObj = DumbTableModel::find('lasglbasd', 'nonexistent_attr');
  256. }
  257. public function testFindByInvalidValue()
  258. {
  259. $this->expectException(
  260. \Hawese\Core\Exceptions\ModelObjectNotFoundException::class
  261. );
  262. $foundObj = DumbTableModel::find('nonexistent_val', 'attr1');
  263. }
  264. public function testInsertWithAutoincrement()
  265. {
  266. $this->assertIsInt($this->dumbObj->insert());
  267. $this->assertNotNull($this->dumbObj->id);
  268. $this->assertNotNull($this->dumbObj->created_at);
  269. }
  270. public function testInsertWithoutAutoincrement()
  271. {
  272. static::schema()->create(
  273. 'other_dumbs',
  274. function (\Illuminate\Database\Schema\Blueprint $table) {
  275. $table->string('non_auto_id')->primary();
  276. }
  277. );
  278. $otherDumbObj = new class extends TableModel {
  279. public static $table = 'other_dumbs';
  280. public static $attributes = ['non_auto_id' => []];
  281. public static $primary_key = 'non_auto_id';
  282. protected static $incrementing = false;
  283. };
  284. $otherDumbObj->non_auto_id = 'string';
  285. $this->assertSame('string', $otherDumbObj->insert());
  286. $this->assertSame(1, $otherDumbObj->select()->count());
  287. static::schema()->drop('other_dumbs');
  288. }
  289. public function testUpdateAllFields()
  290. {
  291. $this->dumbObj->insert();
  292. $this->assertNull($this->dumbObj->updated_at);
  293. $this->dumbObj->attr1 = 'value1';
  294. $this->dumbObj->attr2 = 'value2';
  295. $this->assertTrue($this->dumbObj->update());
  296. $dumbObjFromDb = DumbTableModel::find($this->dumbObj->id);
  297. $this->assertSame('value1', $dumbObjFromDb->attr1);
  298. $this->assertSame('value2', $dumbObjFromDb->attr2);
  299. $this->assertNotNull($dumbObjFromDb->updated_at);
  300. }
  301. public function testUpdateSpecificFields()
  302. {
  303. $this->dumbObj->insert();
  304. $this->assertNull($this->dumbObj->updated_at);
  305. $this->dumbObj->attr1 = 'value1';
  306. $this->dumbObj->attr2 = 'value2';
  307. $this->assertTrue($this->dumbObj->update(['attr2']));
  308. $dumbObjFromDb = DumbTableModel::find($this->dumbObj->id);
  309. $this->assertNull($dumbObjFromDb->attr1);
  310. $this->assertSame('value2', $dumbObjFromDb->attr2);
  311. $this->assertNotNull($dumbObjFromDb->updated_at);
  312. }
  313. public function testUpdateSpecificInvalidFields()
  314. {
  315. $this->dumbObj->insert();
  316. $this->expectExceptionMessage('Undefined index');
  317. $this->dumbObj->update(['nonexistent_attr']);
  318. }
  319. public function testDelete()
  320. {
  321. $this->dumbObj->insert();
  322. $id = $this->dumbObj->id;
  323. $this->assertNotNull(DumbTableModel::find($id)->id);
  324. $this->assertTrue($this->dumbObj->delete());
  325. $this->expectException(
  326. \Hawese\Core\Exceptions\ModelObjectNotFoundException::class
  327. );
  328. DumbTableModel::find($id);
  329. }
  330. public function testStaticDeleteWithDeletedAt()
  331. {
  332. $ids_to_delete = [];
  333. $id_to_keep = $this->dumbObj->insert(); // don't delete this id
  334. $this->dumbObj->id = null;
  335. $ids_to_delete[] = $this->dumbObj->insert();
  336. $this->dumbObj->id = null;
  337. $ids_to_delete[] = $this->dumbObj->insert();
  338. $this->assertTrue(DumbTableModel::staticDelete($ids_to_delete));
  339. $this->assertSame(1, DumbTableModel::select()->count());
  340. $this->assertSame($id_to_keep, DumbTableModel::select()->first()->id);
  341. }
  342. public function testStaticDeleteWithoutDeletedAt()
  343. {
  344. $modelWithoutDeletedAt = new ForeignTableModel();
  345. $modelWithoutDeletedAt->insert();
  346. $this->assertSame(1, ForeignTableModel::select()->count());
  347. $this->assertTrue(
  348. ForeignTableModel::staticDelete([$modelWithoutDeletedAt->id])
  349. );
  350. $this->assertSame(0, ForeignTableModel::select()->count());
  351. }
  352. public function testValidate()
  353. {
  354. $this->dumbObj->attr1 = 'string_value';
  355. $this->dumbObj->validate();
  356. $this->dumbObj->attr1 = 1;
  357. $this->expectException(
  358. \Hawese\Core\Exceptions\ModelValidationException::class
  359. );
  360. $this->dumbObj->validate();
  361. }
  362. // TODO: Get rid of the TableModelCollection class, I don't like it at all
  363. public function testProcessCollection()
  364. {
  365. for ($i = 0; $i < 10; $i++) {
  366. $this->dumbObj->id = null;
  367. $this->dumbObj->insert();
  368. }
  369. $dumbCollection = DumbTableModel::select()->get();
  370. $this->assertSame(10, $dumbCollection->count());
  371. $dumbObjCollection = DumbTableModel::processCollection($dumbCollection);
  372. $this->assertSame(10, $dumbObjCollection->get()->count());
  373. $this->assertInstanceOf(
  374. DumbTableModel::class,
  375. $dumbObjCollection->get()->first()
  376. );
  377. }
  378. public function testAttributes()
  379. {
  380. $this->assertEqualsCanonicalizing(
  381. array_keys(DumbTableModel::$attributes),
  382. DumbTableModel::attributes()
  383. );
  384. }
  385. public function testInstanceAttributes()
  386. {
  387. $this->dumbObj->appendInstanceAttribute('new_attr');
  388. $this->assertEqualsCanonicalizing(
  389. array_merge(DumbTableModel::attributes(), ['new_attr']),
  390. $this->dumbObj->instanceAttributes()
  391. );
  392. }
  393. public function testForeignKeys()
  394. {
  395. $this->assertEqualsCanonicalizing(
  396. array_keys(DumbTableModel::$foreign_keys),
  397. DumbTableModel::foreignKeys()
  398. );
  399. }
  400. public function testGuessFk()
  401. {
  402. $this->assertSame(
  403. 'foreign_id',
  404. DumbTableModel::guessFk('foreign')
  405. );
  406. $this->expectException(
  407. \Hawese\Core\Exceptions\UnknownForeignObjectException::class
  408. );
  409. DumbTableModel::guessFk('unknown');
  410. }
  411. public function testAppendInstanceAttribute()
  412. {
  413. $this->dumbObj->appendInstanceAttribute('new_attr');
  414. $this->assertContains('new_attr', $this->dumbObj->instanceAttributes());
  415. }
  416. public function testSnakeToPascalCase()
  417. {
  418. $this->assertSame(
  419. 'HelloWorldImAPhrase',
  420. DumbTableModel::snakeToPascalCase('hello_world_im_a_phrase')
  421. );
  422. }
  423. public function testCommaStrRepeat()
  424. {
  425. $this->assertSame('', DumbTableModel::commaStrRepeat('?', 0));
  426. $this->assertSame('?,?,?,?,?', DumbTableModel::commaStrRepeat('?', 5));
  427. }
  428. }