You are here

class CsvParserTest in Feeds 8.3

Same name in this branch
  1. 8.3 tests/src/Unit/Component/CsvParserTest.php \Drupal\Tests\feeds\Unit\Component\CsvParserTest
  2. 8.3 tests/src/FunctionalJavascript/Feeds/Parser/CsvParserTest.php \Drupal\Tests\feeds\FunctionalJavascript\Feeds\Parser\CsvParserTest
  3. 8.3 tests/src/Unit/Feeds/Parser/CsvParserTest.php \Drupal\Tests\feeds\Unit\Feeds\Parser\CsvParserTest
  4. 8.3 tests/src/Kernel/Feeds/Parser/CsvParserTest.php \Drupal\Tests\feeds\Kernel\Feeds\Parser\CsvParserTest

@coversDefaultClass \Drupal\feeds\Component\CsvParser @group feeds

Hierarchy

Expanded class hierarchy of CsvParserTest

File

tests/src/Unit/Component/CsvParserTest.php, line 13

Namespace

Drupal\Tests\feeds\Unit\Component
View source
class CsvParserTest extends FeedsUnitTestCase {

  /**
   * Tests parsing a CSV source with several line endings.
   *
   * @dataProvider provider
   */
  public function testAlternateLineEnding(array $expected, $ending) {
    $text = file_get_contents(dirname(dirname(dirname(dirname(__DIR__)))) . '/tests/resources/csv/example.csv');
    $text = str_replace("\r\n", $ending, $text);
    $parser = new \LimitIterator(CsvParser::createFromString($text), 0, 4);
    $first = array_slice($expected, 0, 4);
    $this
      ->assertSame(count(iterator_to_array($parser)), 4);
    $this
      ->assertSame(count(iterator_to_array($parser)), 4);
    foreach ($parser as $delta => $row) {
      $this
        ->assertSame($first[$delta], $row);
    }

    // Test second batch.
    $last_pos = $parser
      ->lastLinePos();
    $parser = (new \LimitIterator(CsvParser::createFromString($text), 0, 4))
      ->setStartByte($last_pos);
    $second = array_slice($expected, 4);

    // // Test that rewinding works as expected.
    $this
      ->assertSame(3, count(iterator_to_array($parser)));
    $this
      ->assertSame(3, count(iterator_to_array($parser)));
    foreach ($parser as $delta => $row) {
      $this
        ->assertSame($second[$delta], $row);
    }
  }

  /**
   * Data provider for testAlternateLineEnding().
   */
  public function provider() {
    $expected = [
      [
        'Header A',
        'Header B',
        'Header C',
      ],
      [
        '"1"',
        '"2"',
        '"3"',
      ],
      [
        'qu"ote',
        'qu"ote',
        'qu"ote',
      ],
      [
        "\r\n\r\nline1",
        "\r\n\r\nline2",
        "\r\n\r\nline3",
      ],
      [
        "new\r\nline 1",
        "new\r\nline 2",
        "new\r\nline 3",
      ],
      [
        "\r\n\r\nline1\r\n\r\n",
        "\r\n\r\nline2\r\n\r\n",
        "\r\n\r\nline3\r\n\r\n",
      ],
      [
        'Col A',
        'Col B',
        'Col, C',
      ],
    ];
    $unix = $expected;
    array_walk_recursive($unix, function (&$item, $key) {
      $item = str_replace("\r\n", "\n", $item);
    });
    $mac = $expected;
    array_walk_recursive($mac, function (&$item, $key) {
      $item = str_replace("\r\n", "\r", $item);
    });
    return [
      [
        $expected,
        "\r\n",
      ],
      [
        $unix,
        "\n",
      ],
      [
        $mac,
        "\r",
      ],
    ];
  }

  /**
   * @covers ::setHasHeader
   * @covers ::getHeader
   */
  public function testHasHeader() {
    $file = dirname(dirname(dirname(dirname(__DIR__)))) . '/tests/resources/csv/example.csv';
    $parser = CsvParser::createFromFilePath($file)
      ->setHasHeader();
    $this
      ->assertSame(count(iterator_to_array($parser)), 6);
    $this
      ->assertSame([
      'Header A',
      'Header B',
      'Header C',
    ], $parser
      ->getHeader());
  }

  /**
   * Tests using an asterisk as delimiter.
   */
  public function testAlternateSeparator() {

    // This implicitly tests lines without a newline.
    $parser = CsvParser::createFromString("a*b*c")
      ->setDelimiter('*');
    $this
      ->assertSame([
      'a',
      'b',
      'c',
    ], iterator_to_array($parser)[0]);
  }

  /**
   * Tries to create a CsvParser instance with an invalid file path.
   */
  public function testInvalidFilePath() {
    $this
      ->expectException(InvalidArgumentException::class);
    CsvParser::createFromFilePath('beep boop');
  }

  /**
   * Creates a new CsvParser instance with an invalid CSV source.
   */
  public function testInvalidResourcePath() {
    $this
      ->expectException(InvalidArgumentException::class);
    new CsvParser('beep boop');
  }

  /**
   * Basic test for parsing CSV.
   *
   * @dataProvider csvFileProvider
   */
  public function testCsvParsing($file, $expected) {
    $parser = CsvParser::createFromFilePath($file);
    $parser
      ->setHasHeader();
    $header = $parser
      ->getHeader();
    $output = [];
    $test = [];
    foreach (iterator_to_array($parser) as $row) {
      $new_row = [];
      foreach ($row as $key => $value) {
        if (isset($header[$key])) {
          $new_row[$header[$key]] = $value;
        }
      }
      $output[] = $new_row;
    }
    $this
      ->assertSame($expected, $output);
  }

  /**
   * Data provider for testCsvParsing().
   */
  public function csvFileProvider() {
    $path = dirname(dirname(dirname(dirname(__DIR__)))) . '/tests/resources/csv-parser-component-files';
    $return = [];
    foreach (glob($path . '/csv/*.csv') as $file) {
      $json_file = $path . '/json/' . str_replace('.csv', '.json', basename($file));
      $return[] = [
        $file,
        json_decode(file_get_contents($json_file), TRUE),
      ];
    }
    return $return;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CsvParserTest::csvFileProvider public function Data provider for testCsvParsing().
CsvParserTest::provider public function Data provider for testAlternateLineEnding().
CsvParserTest::testAlternateLineEnding public function Tests parsing a CSV source with several line endings.
CsvParserTest::testAlternateSeparator public function Tests using an asterisk as delimiter.
CsvParserTest::testCsvParsing public function Basic test for parsing CSV.
CsvParserTest::testHasHeader public function @covers ::setHasHeader @covers ::getHeader
CsvParserTest::testInvalidFilePath public function Tries to create a CsvParser instance with an invalid file path.
CsvParserTest::testInvalidResourcePath public function Creates a new CsvParser instance with an invalid CSV source.
FeedsMockingTrait::getMockAccount protected function Mocks an account object.
FeedsMockingTrait::getMockedAccountSwitcher protected function Returns a mocked AccountSwitcher object.
FeedsMockingTrait::getMockFeed protected function Returns a mocked feed entity.
FeedsMockingTrait::getMockFeedType protected function Returns a mocked feed type entity.
FeedsMockingTrait::getMockFieldDefinition protected function Mocks a field definition. 1
FeedsMockingTrait::getMockFileSystem protected function Mocks the file system.
FeedsReflectionTrait::callProtectedMethod protected function Calls a protected method on the given object.
FeedsReflectionTrait::getMethod protected function Gets a ReflectionMethod for a class method.
FeedsReflectionTrait::getProtectedClosure protected function Returns a dynamically created closure for the object's method.
FeedsReflectionTrait::setProtectedProperty protected function Sets a protected property.
FeedsUnitTestCase::absolutePath protected function Returns the absolute directory path of the Feeds module.
FeedsUnitTestCase::defineConstants protected function Defines stub constants.
FeedsUnitTestCase::getMockStreamWrapperManager protected function Returns a mock stream wrapper manager.
FeedsUnitTestCase::resourcesPath protected function Returns the absolute directory path of the resources folder.
FeedsUnitTestCase::setUp public function Overrides UnitTestCase::setUp 27
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.