PdoReaderTest.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace Ddeboer\DataImport\Tests\Reader;
  3. use Ddeboer\DataImport\Reader\PdoReader;
  4. // use Doctrine\DBAL\Configuration;
  5. // use Doctrine\DBAL\DriverManager;
  6. // use Doctrine\DBAL\Platforms\SqlitePlatform;
  7. class PdoReaderTest extends \PHPUnit_Framework_TestCase
  8. {
  9. public function testGetFields()
  10. {
  11. $fields = $this->getReader()->getFields();
  12. $this->assertInternalType('array', $fields);
  13. $this->assertEquals(array('id', 'username', 'name'), $fields);
  14. }
  15. public function testCount()
  16. {
  17. $this->assertEquals(100, $this->getReader()->count());
  18. }
  19. public function testIterate()
  20. {
  21. $i=1;
  22. foreach ($this->getReader() as $row) {
  23. $this->assertInternalType('array', $row);
  24. $this->assertEquals('user-'.$i, $row['username']);
  25. $i++;
  26. }
  27. }
  28. public function testReaderRewindWorksCorrectly()
  29. {
  30. $reader = $this->getReader();
  31. foreach ($reader as $row) {
  32. }
  33. foreach ($reader as $row) {
  34. }
  35. }
  36. public function getConnection()
  37. {
  38. $connection = new \PDO('sqlite::memory:');
  39. // Set error mode = exception for easy debugging
  40. $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  41. // Build schema
  42. $connection->query('CREATE TABLE pdo_group (
  43. id INTEGER PRIMARY KEY AUTOINCREMENT,
  44. name VARCHAR(45)
  45. )');
  46. $connection->query('CREATE TABLE pdo_user (
  47. id INTEGER PRIMARY KEY AUTOINCREMENT,
  48. username VARCHAR(32),
  49. group_id INTEGER,
  50. FOREIGN KEY(group_id) REFERENCES pdo_group(id)
  51. )');
  52. $connection->query('CREATE UNIQUE INDEX user_username ON pdo_user(username)');
  53. return $connection;
  54. }
  55. protected function getReader()
  56. {
  57. $connection = $this->getConnection();
  58. $group_insert = $connection->prepare('INSERT INTO pdo_group (name) VALUES (:name)');
  59. $user_insert = $connection->prepare('INSERT INTO pdo_user (username, group_id) VALUES (:username, :group)');
  60. $counter = 1;
  61. for ($i = 1; $i <= 10; $i++) {
  62. $group_insert->execute(array(':name' => "name {$i}"));
  63. $id = $connection->lastInsertId();
  64. for ($j = 1; $j <= 10; $j++) {
  65. $user_insert->execute(array(
  66. ':username' => "user-{$counter}",
  67. ':group' => $id
  68. ));
  69. $counter++;
  70. }
  71. }
  72. return new PdoReader($connection, 'SELECT u.id, u.username, g.name FROM `pdo_user` u INNER JOIN `pdo_group` g ON u.group_id = g.id');
  73. }
  74. }