TableModelTest.php 16 KB

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