ActiveRecordTest.php 18.2 KB
Newer Older
1 2
<?php

3
namespace yiiunit\extensions\elasticsearch;
4

5
use yii\elasticsearch\Connection;
6
use yii\helpers\Json;
7
use yiiunit\framework\ar\ActiveRecordTestTrait;
8 9 10 11 12 13
use yiiunit\data\ar\elasticsearch\ActiveRecord;
use yiiunit\data\ar\elasticsearch\Customer;
use yiiunit\data\ar\elasticsearch\OrderItem;
use yiiunit\data\ar\elasticsearch\Order;
use yiiunit\data\ar\elasticsearch\Item;

14 15 16
/**
 * @group elasticsearch
 */
17 18
class ActiveRecordTest extends ElasticSearchTestCase
{
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
	use ActiveRecordTestTrait;

	public function callCustomerFind($q = null)	 { return Customer::find($q); }
	public function callOrderFind($q = null)     { return Order::find($q); }
	public function callOrderItemFind($q = null) { return OrderItem::find($q); }
	public function callItemFind($q = null)      { return Item::find($q); }

	public function getCustomerClass() { return Customer::className(); }
	public function getItemClass() { return Item::className(); }
	public function getOrderClass() { return Order::className(); }
	public function getOrderItemClass() { return OrderItem::className(); }

	/**
	 * can be overridden to do things after save()
	 */
	public function afterSave()
	{
Carsten Brandt committed
36
		$this->getConnection()->createCommand()->flushIndex('yiitest');
37 38
	}

39 40 41
	public function setUp()
	{
		parent::setUp();
42 43 44 45

		/** @var Connection $db */
		$db = ActiveRecord::$db = $this->getConnection();

46 47 48 49
		// delete index
		if ($db->createCommand()->indexExists('yiitest')) {
			$db->createCommand()->deleteIndex('yiitest');
		}
50

51
		$db->post(['yiitest'], [], Json::encode([
52 53 54 55 56 57 58 59 60
			'mappings' => [
				"item" => [
		            "_source" => [ "enabled" => true ],
		            "properties" => [
						// allow proper sorting by name
		                "name" => ["type" => "string", "index" => "not_analyzed"],
		            ]
		        ]
			],
61
		]));
62

63
		$customer = new Customer();
64
		$customer->id = 1;
65
		$customer->setAttributes(['email' => 'user1@example.com', 'name' => 'user1', 'address' => 'address1', 'status' => 1], false);
66 67
		$customer->save(false);
		$customer = new Customer();
68
		$customer->id = 2;
69
		$customer->setAttributes(['email' => 'user2@example.com', 'name' => 'user2', 'address' => 'address2', 'status' => 1], false);
70 71
		$customer->save(false);
		$customer = new Customer();
72
		$customer->id = 3;
73
		$customer->setAttributes(['email' => 'user3@example.com', 'name' => 'user3', 'address' => 'address3', 'status' => 2], false);
74 75 76 77 78 79
		$customer->save(false);

//		INSERT INTO tbl_category (name) VALUES ('Books');
//		INSERT INTO tbl_category (name) VALUES ('Movies');

		$item = new Item();
80
		$item->id = 1;
81
		$item->setAttributes(['name' => 'Agile Web Application Development with Yii1.1 and PHP5', 'category_id' => 1], false);
82 83
		$item->save(false);
		$item = new Item();
84
		$item->id = 2;
85
		$item->setAttributes(['name' => 'Yii 1.1 Application Development Cookbook', 'category_id' => 1], false);
86 87
		$item->save(false);
		$item = new Item();
88
		$item->id = 3;
89
		$item->setAttributes(['name' => 'Ice Age', 'category_id' => 2], false);
90 91
		$item->save(false);
		$item = new Item();
92
		$item->id = 4;
93
		$item->setAttributes(['name' => 'Toy Story', 'category_id' => 2], false);
94 95
		$item->save(false);
		$item = new Item();
96
		$item->id = 5;
97
		$item->setAttributes(['name' => 'Cars', 'category_id' => 2], false);
98 99 100
		$item->save(false);

		$order = new Order();
101
		$order->id = 1;
102
		$order->setAttributes(['customer_id' => 1, 'create_time' => 1325282384, 'total' => 110.0], false);
103 104
		$order->save(false);
		$order = new Order();
105
		$order->id = 2;
106
		$order->setAttributes(['customer_id' => 2, 'create_time' => 1325334482, 'total' => 33.0], false);
107 108
		$order->save(false);
		$order = new Order();
109
		$order->id = 3;
110
		$order->setAttributes(['customer_id' => 2, 'create_time' => 1325502201, 'total' => 40.0], false);
111 112
		$order->save(false);

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 1, 'item_id' => 1, 'quantity' => 1, 'subtotal' => 30.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 1, 'item_id' => 2, 'quantity' => 2, 'subtotal' => 40.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 2, 'item_id' => 4, 'quantity' => 1, 'subtotal' => 10.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 2, 'item_id' => 5, 'quantity' => 1, 'subtotal' => 15.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 2, 'item_id' => 3, 'quantity' => 1, 'subtotal' => 8.0], false);
		$orderItem->save(false);
		$orderItem = new OrderItem();
		$orderItem->setAttributes(['order_id' => 3, 'item_id' => 2, 'quantity' => 1, 'subtotal' => 40.0], false);
		$orderItem->save(false);
131

Carsten Brandt committed
132
		$db->createCommand()->flushIndex('yiitest');
133 134
	}

135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	public function testSearch()
	{
		$customers = $this->callCustomerFind()->search()['hits'];
		$this->assertEquals(3, $customers['total']);
		$this->assertEquals(3, count($customers['hits']));
		$this->assertTrue($customers['hits'][0] instanceof Customer);
		$this->assertTrue($customers['hits'][1] instanceof Customer);
		$this->assertTrue($customers['hits'][2] instanceof Customer);

		// limit vs. totalcount
		$customers = $this->callCustomerFind()->limit(2)->search()['hits'];
		$this->assertEquals(3, $customers['total']);
		$this->assertEquals(2, count($customers['hits']));

		// asArray
		$result = $this->callCustomerFind()->asArray()->search()['hits'];
		$this->assertEquals(3, $result['total']);
		$customers = $result['hits'];
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers[0]);
		$this->assertArrayHasKey('name', $customers[0]);
		$this->assertArrayHasKey('email', $customers[0]);
		$this->assertArrayHasKey('address', $customers[0]);
		$this->assertArrayHasKey('status', $customers[0]);
		$this->assertArrayHasKey('id', $customers[1]);
		$this->assertArrayHasKey('name', $customers[1]);
		$this->assertArrayHasKey('email', $customers[1]);
		$this->assertArrayHasKey('address', $customers[1]);
		$this->assertArrayHasKey('status', $customers[1]);
		$this->assertArrayHasKey('id', $customers[2]);
		$this->assertArrayHasKey('name', $customers[2]);
		$this->assertArrayHasKey('email', $customers[2]);
		$this->assertArrayHasKey('address', $customers[2]);
		$this->assertArrayHasKey('status', $customers[2]);

		// TODO test asArray() + fields() + indexBy()

		// find by attributes
		$result = $this->callCustomerFind()->where(['name' => 'user2'])->search()['hits'];
		$customer = reset($result['hits']);
		$this->assertTrue($customer instanceof Customer);
		$this->assertEquals(2, $customer->id);

		// TODO test query() and filter()
	}

	public function testSearchFacets()
	{
		$result = $this->callCustomerFind()->addStatisticalFacet('status_stats', ['field' => 'status'])->search();
		$this->assertArrayHasKey('facets', $result);
		$this->assertEquals(3, $result['facets']['status_stats']['count']);
		$this->assertEquals(4, $result['facets']['status_stats']['total']); // sum of values
		$this->assertEquals(1, $result['facets']['status_stats']['min']);
		$this->assertEquals(2, $result['facets']['status_stats']['max']);
	}

191 192 193 194 195 196
	public function testGetDb()
	{
		$this->mockApplication(['components' => ['elasticsearch' => Connection::className()]]);
		$this->assertInstanceOf(Connection::className(), ActiveRecord::getDb());
	}

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	public function testGet()
	{
		$this->assertInstanceOf(Customer::className(), Customer::get(1));
		$this->assertNull(Customer::get(5));
	}

	public function testMget()
	{
		$this->assertEquals([], Customer::mget([]));

		$records = Customer::mget([1]);
		$this->assertEquals(1, count($records));
		$this->assertInstanceOf(Customer::className(), reset($records));

		$records = Customer::mget([5]);
		$this->assertEquals(0, count($records));

		$records = Customer::mget([1,3,5]);
		$this->assertEquals(2, count($records));
		$this->assertInstanceOf(Customer::className(), $records[0]);
		$this->assertInstanceOf(Customer::className(), $records[1]);
	}

220 221 222 223 224 225 226 227 228
	public function testFindLazy()
	{
		/** @var $customer Customer */
		$customer = Customer::find(2);
		$orders = $customer->orders;
		$this->assertEquals(2, count($orders));

		$orders = $customer->getOrders()->where(['between', 'create_time', 1325334000, 1325400000])->all();
		$this->assertEquals(1, count($orders));
229
		$this->assertEquals(2, $orders[0]->id);
230 231 232 233
	}

	public function testFindEagerViaRelation()
	{
234
		$orders = Order::find()->with('items')->orderBy('create_time')->all();
235 236
		$this->assertEquals(3, count($orders));
		$order = $orders[0];
237
		$this->assertEquals(1, $order->id);
238
		$this->assertTrue($order->isRelationPopulated('items'));
239
		$this->assertEquals(2, count($order->items));
240 241
		$this->assertEquals(1, $order->items[0]->id);
		$this->assertEquals(2, $order->items[1]->id);
242 243 244 245
	}

	public function testInsertNoPk()
	{
246 247
		$this->assertEquals([ActiveRecord::PRIMARY_KEY_NAME], Customer::primaryKey());
		$pkName = ActiveRecord::PRIMARY_KEY_NAME;
248

249 250 251 252 253
		$customer = new Customer;
		$customer->email = 'user4@example.com';
		$customer->name = 'user4';
		$customer->address = 'address4';

254
		$this->assertNull($customer->primaryKey);
255
		$this->assertNull($customer->oldPrimaryKey);
256
		$this->assertNull($customer->$pkName);
257 258 259 260
		$this->assertTrue($customer->isNewRecord);

		$customer->save();

261
		$this->assertNotNull($customer->primaryKey);
262
		$this->assertNotNull($customer->oldPrimaryKey);
263
		$this->assertNotNull($customer->$pkName);
264
		$this->assertEquals($customer->primaryKey, $customer->oldPrimaryKey);
265
		$this->assertEquals($customer->primaryKey, $customer->$pkName);
266 267 268 269 270
		$this->assertFalse($customer->isNewRecord);
	}

	public function testInsertPk()
	{
271 272
		$pkName = ActiveRecord::PRIMARY_KEY_NAME;

273
		$customer = new Customer;
274
		$customer->$pkName = 5;
275 276 277 278 279 280 281 282
		$customer->email = 'user5@example.com';
		$customer->name = 'user5';
		$customer->address = 'address5';

		$this->assertTrue($customer->isNewRecord);

		$customer->save();

283
		$this->assertEquals(5, $customer->primaryKey);
284 285
		$this->assertEquals(5, $customer->oldPrimaryKey);
		$this->assertEquals(5, $customer->$pkName);
286 287 288 289 290
		$this->assertFalse($customer->isNewRecord);
	}

	public function testUpdatePk()
	{
291 292 293
		$pkName = ActiveRecord::PRIMARY_KEY_NAME;

		$pk = [$pkName => 2];
294
		$orderItem = Order::find($pk);
295
		$this->assertEquals(2, $orderItem->primaryKey);
296 297
		$this->assertEquals(2, $orderItem->oldPrimaryKey);
		$this->assertEquals(2, $orderItem->$pkName);
298

299
		$this->setExpectedException('yii\base\InvalidCallException');
300
		$orderItem->$pkName = 13;
301 302
		$orderItem->save();
	}
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329

	public function testFindLazyVia2()
	{
		/** @var TestCase|ActiveRecordTestTrait $this */
		/** @var Order $order */
		$orderClass = $this->getOrderClass();
		$pkName = ActiveRecord::PRIMARY_KEY_NAME;

		$order = new $orderClass();
		$order->$pkName = 100;
		$this->assertEquals([], $order->items);
	}

	public function testUpdateCounters()
	{
		// Update Counters is not supported by elasticsearch
//		$this->setExpectedException('yii\base\NotSupportedException');
//		ActiveRecordTestTrait::testUpdateCounters();
	}

	/**
	 * Some PDO implementations(e.g. cubrid) do not support boolean values.
	 * Make sure this does not affect AR layer.
	 */
	public function testBooleanAttribute()
	{
		$db = $this->getConnection();
330 331
		$db->createCommand()->deleteIndex('yiitest');
		$db->post(['yiitest'], [], Json::encode([
332
			'mappings' => [
333
				"customer" => [
334 335 336 337 338 339 340
		            "_source" => [ "enabled" => true ],
		            "properties" => [
						// this is for the boolean test
		                "status" => ["type" => "boolean"],
		            ]
		        ]
			],
341
		]));
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

		$customerClass = $this->getCustomerClass();
		$customer = new $customerClass();
		$customer->name = 'boolean customer';
		$customer->email = 'mail@example.com';
		$customer->status = true;
		$customer->save(false);

		$customer->refresh();
		$this->assertEquals(true, $customer->status);

		$customer->status = false;
		$customer->save(false);

		$customer->refresh();
		$this->assertEquals(false, $customer->status);

		$customer = new Customer();
		$customer->setAttributes(['email' => 'user2b@example.com', 'name' => 'user2b', 'status' => true], false);
		$customer->save(false);
		$customer = new Customer();
		$customer->setAttributes(['email' => 'user3b@example.com', 'name' => 'user3b', 'status' => false], false);
		$customer->save(false);
		$this->afterSave();

		$customers = $this->callCustomerFind()->where(['status' => true])->all();
		$this->assertEquals(1, count($customers));

		$customers = $this->callCustomerFind()->where(['status' => false])->all();
		$this->assertEquals(2, count($customers));
	}
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494

	public function testfindAsArrayFields()
	{
		$customerClass = $this->getCustomerClass();
		/** @var TestCase|ActiveRecordTestTrait $this */
		// indexBy + asArray
		$customers = $this->callCustomerFind()->asArray()->fields(['id', 'name'])->all();
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers[0]);
		$this->assertArrayHasKey('name', $customers[0]);
		$this->assertArrayNotHasKey('email', $customers[0]);
		$this->assertArrayNotHasKey('address', $customers[0]);
		$this->assertArrayNotHasKey('status', $customers[0]);
		$this->assertArrayHasKey('id', $customers[1]);
		$this->assertArrayHasKey('name', $customers[1]);
		$this->assertArrayNotHasKey('email', $customers[1]);
		$this->assertArrayNotHasKey('address', $customers[1]);
		$this->assertArrayNotHasKey('status', $customers[1]);
		$this->assertArrayHasKey('id', $customers[2]);
		$this->assertArrayHasKey('name', $customers[2]);
		$this->assertArrayNotHasKey('email', $customers[2]);
		$this->assertArrayNotHasKey('address', $customers[2]);
		$this->assertArrayNotHasKey('status', $customers[2]);
	}

	public function testfindIndexByFields()
	{
		$customerClass = $this->getCustomerClass();
		/** @var TestCase|ActiveRecordTestTrait $this */
		// indexBy + asArray
		$customers = $this->callCustomerFind()->indexBy('name')->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertTrue($customers['user1'] instanceof $customerClass);
		$this->assertTrue($customers['user2'] instanceof $customerClass);
		$this->assertTrue($customers['user3'] instanceof $customerClass);
		$this->assertNotNull($customers['user1']->id);
		$this->assertNotNull($customers['user1']->name);
		$this->assertNull($customers['user1']->email);
		$this->assertNull($customers['user1']->address);
		$this->assertNull($customers['user1']->status);
		$this->assertNotNull($customers['user2']->id);
		$this->assertNotNull($customers['user2']->name);
		$this->assertNull($customers['user2']->email);
		$this->assertNull($customers['user2']->address);
		$this->assertNull($customers['user2']->status);
		$this->assertNotNull($customers['user3']->id);
		$this->assertNotNull($customers['user3']->name);
		$this->assertNull($customers['user3']->email);
		$this->assertNull($customers['user3']->address);
		$this->assertNull($customers['user3']->status);

		// indexBy callable + asArray
		$customers = $this->callCustomerFind()->indexBy(function ($customer) {
			return $customer->id . '-' . $customer->name;
		})->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertTrue($customers['1-user1'] instanceof $customerClass);
		$this->assertTrue($customers['2-user2'] instanceof $customerClass);
		$this->assertTrue($customers['3-user3'] instanceof $customerClass);
		$this->assertNotNull($customers['1-user1']->id);
		$this->assertNotNull($customers['1-user1']->name);
		$this->assertNull($customers['1-user1']->email);
		$this->assertNull($customers['1-user1']->address);
		$this->assertNull($customers['1-user1']->status);
		$this->assertNotNull($customers['2-user2']->id);
		$this->assertNotNull($customers['2-user2']->name);
		$this->assertNull($customers['2-user2']->email);
		$this->assertNull($customers['2-user2']->address);
		$this->assertNull($customers['2-user2']->status);
		$this->assertNotNull($customers['3-user3']->id);
		$this->assertNotNull($customers['3-user3']->name);
		$this->assertNull($customers['3-user3']->email);
		$this->assertNull($customers['3-user3']->address);
		$this->assertNull($customers['3-user3']->status);
	}

	public function testfindIndexByAsArrayFields()
	{
		$customerClass = $this->getCustomerClass();
		/** @var TestCase|ActiveRecordTestTrait $this */
		// indexBy + asArray
		$customers = $this->callCustomerFind()->indexBy('name')->asArray()->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers['user1']);
		$this->assertArrayHasKey('name', $customers['user1']);
		$this->assertArrayNotHasKey('email', $customers['user1']);
		$this->assertArrayNotHasKey('address', $customers['user1']);
		$this->assertArrayNotHasKey('status', $customers['user1']);
		$this->assertArrayHasKey('id', $customers['user2']);
		$this->assertArrayHasKey('name', $customers['user2']);
		$this->assertArrayNotHasKey('email', $customers['user2']);
		$this->assertArrayNotHasKey('address', $customers['user2']);
		$this->assertArrayNotHasKey('status', $customers['user2']);
		$this->assertArrayHasKey('id', $customers['user3']);
		$this->assertArrayHasKey('name', $customers['user3']);
		$this->assertArrayNotHasKey('email', $customers['user3']);
		$this->assertArrayNotHasKey('address', $customers['user3']);
		$this->assertArrayNotHasKey('status', $customers['user3']);

		// indexBy callable + asArray
		$customers = $this->callCustomerFind()->indexBy(function ($customer) {
			return $customer['id'] . '-' . $customer['name'];
		})->asArray()->fields('id', 'name')->all();
		$this->assertEquals(3, count($customers));
		$this->assertArrayHasKey('id', $customers['1-user1']);
		$this->assertArrayHasKey('name', $customers['1-user1']);
		$this->assertArrayNotHasKey('email', $customers['1-user1']);
		$this->assertArrayNotHasKey('address', $customers['1-user1']);
		$this->assertArrayNotHasKey('status', $customers['1-user1']);
		$this->assertArrayHasKey('id', $customers['2-user2']);
		$this->assertArrayHasKey('name', $customers['2-user2']);
		$this->assertArrayNotHasKey('email', $customers['2-user2']);
		$this->assertArrayNotHasKey('address', $customers['2-user2']);
		$this->assertArrayNotHasKey('status', $customers['2-user2']);
		$this->assertArrayHasKey('id', $customers['3-user3']);
		$this->assertArrayHasKey('name', $customers['3-user3']);
		$this->assertArrayNotHasKey('email', $customers['3-user3']);
		$this->assertArrayNotHasKey('address', $customers['3-user3']);
		$this->assertArrayNotHasKey('status', $customers['3-user3']);
	}


495
}