storage test
[m6w6/pq-gateway] / tests / lib / pq / Mapper / StorageTest.php
1 <?php
2
3 namespace pq\Mapper;
4
5 use PHPUnit_Framework_TestCase;
6 use pq\Connection;
7 use pq\Gateway\Table;
8 use QueryLogger;
9 use RefTestModel;
10 use TestModel;
11
12 require_once __DIR__."/../../../setup.inc";
13
14 class StorageTest extends PHPUnit_Framework_TestCase
15 {
16 /**
17 * @var Connection
18 */
19 protected $conn;
20
21 /**
22 * @var Mapper
23 */
24 protected $mapper;
25
26 /**
27 * @var Storage
28 */
29 protected $storage;
30
31 protected function setUp() {
32 $this->conn = new Connection(PQ_TEST_DSN);
33 $this->conn->exec(PQ_TEST_SETUP_SQL);
34 Table::$defaultConnection = $this->conn;
35 $this->mapper = new Mapper;
36 $this->mapper->mapOf(TestModel::class)->getGateway()->getQueryExecutor()->attach(new QueryLogger());
37 $this->mapper->mapOf(RefTestModel::class)->getGateway()->getQueryExecutor()->attach(new QueryLogger());
38 $this->storage = $this->mapper->createStorage(TestModel::class);
39 }
40
41 protected function tearDown() {
42 $this->conn->exec(PQ_TEST_TEARDOWN_SQL);
43 }
44
45 function testFind() {
46 $objects = $this->storage->find();
47 for ($i = 0; $i < count($objects); ++$i) {
48 $this->assertSame($i+1, $objects[$i]->id);
49 }
50 }
51
52 function testSave() {
53 $test = new TestModel;
54 $test->ref1 = $test->ref2 = [
55 new RefTestModel
56 ];
57 $this->storage->save($test);
58
59 $this->mapper->mapOf(TestModel::class)->getObjects()->reset();
60 $this->mapper->mapOf(RefTestModel::class)->getObjects()->reset();
61
62 $this->assertEquals([$test], $this->storage->find(["id="=>$test->id]));
63 }
64
65 function testDelete() {
66 $obj = current($this->storage->find());
67 $this->storage->delete($obj);
68 $this->mapper->mapOf(TestModel::class)->getObjects()->resetRow($obj);
69 $this->assertCount(0, $this->storage->find(["id="=>$obj->id]));
70 }
71
72 function testBuffer() {
73 $this->storage->buffer();
74 $this->assertEquals("yesterday", $this->storage->get(1)->data);
75 $this->mapper->mapOf(TestModel::class)->getObjects()->reset();
76 $exec = $this->mapper->mapOf(TestModel::class)->getGateway()->getQueryExecutor();
77 $xact = executeInConcurrentTransaction($exec, "UPDATE test SET data=\$2 WHERE id=\$1", [1, "the day before"]);
78 $this->assertEquals("yesterday", $this->storage->get(1)->data);
79 $xact->commit();
80 $this->storage->discard();
81 $this->assertEquals("the day before", $this->storage->get(1)->data);
82 }
83 }