ActiveDataProviderTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace yiiunit\extensions\mongodb;
  3. use MongoDB\BSON\ObjectID;
  4. use yii\data\ActiveDataProvider;
  5. use yii\mongodb\Query;
  6. use yiiunit\extensions\mongodb\data\ar\ActiveRecord;
  7. use yiiunit\extensions\mongodb\data\ar\Customer;
  8. class ActiveDataProviderTest extends TestCase
  9. {
  10. protected function setUp()
  11. {
  12. parent::setUp();
  13. $this->mockApplication();
  14. ActiveRecord::$db = $this->getConnection();
  15. $this->setUpTestRows();
  16. }
  17. protected function tearDown()
  18. {
  19. $this->dropCollection(Customer::collectionName());
  20. parent::tearDown();
  21. }
  22. /**
  23. * Sets up test rows.
  24. */
  25. protected function setUpTestRows()
  26. {
  27. $collection = $this->getConnection()->getCollection('customer');
  28. $rows = [];
  29. for ($i = 1; $i <= 10; $i++) {
  30. $rows[] = [
  31. 'name' => 'name' . $i,
  32. 'email' => 'email' . $i,
  33. 'address' => 'address' . $i,
  34. 'status' => $i,
  35. ];
  36. }
  37. $collection->batchInsert($rows);
  38. }
  39. // Tests :
  40. public function testQuery()
  41. {
  42. $query = new Query();
  43. $query->from('customer');
  44. $provider = new ActiveDataProvider([
  45. 'query' => $query,
  46. 'db' => $this->getConnection(),
  47. ]);
  48. $models = $provider->getModels();
  49. $this->assertEquals(10, count($models));
  50. $provider = new ActiveDataProvider([
  51. 'query' => $query,
  52. 'db' => $this->getConnection(),
  53. 'pagination' => [
  54. 'pageSize' => 5,
  55. ]
  56. ]);
  57. $models = $provider->getModels();
  58. $this->assertEquals(5, count($models));
  59. }
  60. public function testActiveQuery()
  61. {
  62. $provider = new ActiveDataProvider([
  63. 'query' => Customer::find()->orderBy('id ASC'),
  64. ]);
  65. $models = $provider->getModels();
  66. $this->assertEquals(10, count($models));
  67. $this->assertTrue($models[0] instanceof Customer);
  68. $keys = $provider->getKeys();
  69. $this->assertTrue($keys[0] instanceof ObjectID);
  70. $provider = new ActiveDataProvider([
  71. 'query' => Customer::find(),
  72. 'pagination' => [
  73. 'pageSize' => 5,
  74. ]
  75. ]);
  76. $models = $provider->getModels();
  77. $this->assertEquals(5, count($models));
  78. }
  79. }