You are here

class HttpTest in Migrate Plus 8.5

Same name in this branch
  1. 8.5 tests/src/Unit/data_fetcher/HttpTest.php \Drupal\Tests\migrate_plus\Unit\data_fetcher\HttpTest
  2. 8.5 tests/src/Kernel/Plugin/migrate_plus/data_fetcher/HttpTest.php \Drupal\Tests\migrate_plus\Kernel\Plugin\migrate_plus\data_fetcher\HttpTest
Same name and namespace in other branches
  1. 8.4 tests/src/Unit/data_fetcher/HttpTest.php \Drupal\Tests\migrate_plus\Unit\data_fetcher\HttpTest

@coversDefaultClass \Drupal\migrate_plus\Plugin\migrate_plus\data_fetcher\Http

@group migrate_plus

Hierarchy

Expanded class hierarchy of HttpTest

File

tests/src/Unit/data_fetcher/HttpTest.php, line 25
PHPUnit tests for the Migrate Plus Http 'data fetcher' plugin.

Namespace

Drupal\Tests\migrate_plus\Unit\data_fetcher
View source
class HttpTest extends MigrateTestCase {

  /**
   * Minimal migration configuration data.
   *
   * @var array
   */
  private $specificMigrationConfig = [
    'source' => 'url',
    'urls' => [
      'http://example.org/http_fetcher_test',
    ],
    'data_fetcher_plugin' => 'http',
    'data_parser_plugin' => 'json',
    'item_selector' => 0,
    'authentication' => [
      'plugin' => 'basic',
      'username' => 'testing',
      'password' => 'password',
    ],
    'fields' => [],
    'ids' => [
      'id' => [
        'type' => 'integer',
      ],
    ],
  ];

  /**
   * The data fetcher plugin ID being tested.
   *
   * @var string
   */
  private $dataFetcherPluginId = 'http';

  /**
   * The data fetcher plugin definition.
   *
   * @var array
   */
  private $pluginDefinition = [
    'id' => 'http',
    'title' => 'HTTP',
  ];

  /**
   * Test data to validate an HTTP response against.
   *
   * @var string
   */
  private $testData = '
    {
      "id": 1,
      "name": "Joe Bloggs"
    }
  ';

  /**
   * Mocked up Basic authentication plugin.
   *
   * @var \PHPUnit_Framework_MockObject_MockObject
   */
  private $basicAuthenticator = NULL;

  /**
   * Set up test environment.
   */
  public function setUp() : void {

    // Mock up a Basic authentication plugin that will be used in requests.
    $basic_authenticator = $this
      ->getMockBuilder(Basic::class)
      ->disableOriginalConstructor()
      ->getMock();
    $basic_authenticator
      ->method('getAuthenticationOptions')
      ->will($this
      ->returnValue([
      'auth' => [
        'username',
        'password',
      ],
    ]));
    $this->basicAuthenticator = $basic_authenticator;
  }

  /**
   * Test 'http' data fetcher (with auth) returns an expected response.
   */
  public function testFetchHttpWithAuth() : void {
    $migration_config = $this->migrationConfiguration + $this->specificMigrationConfig;
    $plugin = new TestHttp($migration_config, $this->dataFetcherPluginId, $this->pluginDefinition);
    $plugin
      ->mockHttpClient([
      [
        200,
        'application/json',
        $this->testData,
      ],
    ], $this->basicAuthenticator);

    // The Guzzle mock returns an instance of StreamInterface.
    // http://docs.guzzlephp.org/en/latest/psr7.html
    $stream = $plugin
      ->getResponseContent($migration_config['urls'][0]);
    $body = json_decode((string) $stream, TRUE);

    // Compare what we got back from the parser to what we expected to get.
    $expected = json_decode($this->testData, TRUE);
    $this
      ->assertSame($expected, $body);
  }

  /**
   * Test 'http' data fetcher (without auth) returns an expected response.
   */
  public function testFetchHttpNoAuth() : void {
    $migration_config = $this->migrationConfiguration + $this->specificMigrationConfig;
    unset($migration_config['authentication']);
    $plugin = new TestHttp($migration_config, $this->dataFetcherPluginId, $this->pluginDefinition);
    $plugin
      ->mockHttpClient([
      [
        200,
        'application/json',
        $this->testData,
      ],
    ], NULL);
    $stream = $plugin
      ->getResponseContent($migration_config['urls'][0]);
    $body = json_decode((string) $stream, TRUE);
    $expected = json_decode($this->testData, TRUE);
    $this
      ->assertSame($expected, $body);
  }

  /**
   * Test 'http' data fetcher (with auth) dies as expected when auth fails.
   */
  public function testFetchHttpAuthFailure() : void {
    $migration_config = $this->migrationConfiguration + $this->specificMigrationConfig;
    $plugin = new TestHttp($migration_config, $this->dataFetcherPluginId, $this->pluginDefinition);
    $plugin
      ->mockHttpClient([
      [
        403,
        'text/html',
        'Forbidden',
      ],
    ], $this->basicAuthenticator);
    $this
      ->expectException(MigrateException::class);
    $this
      ->expectExceptionMessage('Error message: Client error: `GET http://example.org/http_fetcher_test` resulted in a `403 Forbidden');
    $plugin
      ->getResponseContent($migration_config['urls'][0]);
  }

  /**
   * Test 'http' data fetcher (with auth) dies as expected when server down.
   */
  public function testFetchHttp500Error() : void {
    $migration_config = $this->migrationConfiguration + $this->specificMigrationConfig;
    $plugin = new TestHttp($migration_config, $this->dataFetcherPluginId, $this->pluginDefinition);
    $plugin
      ->mockHttpClient([
      [
        500,
        'text/html',
        'Internal Server Error',
      ],
    ], $this->basicAuthenticator);
    $this
      ->expectException(MigrateException::class);
    $this
      ->expectExceptionMessage('GET http://example.org/http_fetcher_test` resulted in a `500 Internal Server Error');
    $plugin
      ->getResponseContent($migration_config['urls'][0]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
HttpTest::$basicAuthenticator private property Mocked up Basic authentication plugin.
HttpTest::$dataFetcherPluginId private property The data fetcher plugin ID being tested.
HttpTest::$pluginDefinition private property The data fetcher plugin definition.
HttpTest::$specificMigrationConfig private property Minimal migration configuration data.
HttpTest::$testData private property Test data to validate an HTTP response against.
HttpTest::setUp public function Set up test environment. Overrides UnitTestCase::setUp
HttpTest::testFetchHttp500Error public function Test 'http' data fetcher (with auth) dies as expected when server down.
HttpTest::testFetchHttpAuthFailure public function Test 'http' data fetcher (with auth) dies as expected when auth fails.
HttpTest::testFetchHttpNoAuth public function Test 'http' data fetcher (without auth) returns an expected response.
HttpTest::testFetchHttpWithAuth public function Test 'http' data fetcher (with auth) returns an expected response.
MigrateTestCase::$idMap protected property The migration ID map.
MigrateTestCase::$migrationConfiguration protected property An array of migration configuration values. 16
MigrateTestCase::$migrationStatus protected property Local store for mocking setStatus()/getStatus().
MigrateTestCase::createSchemaFromRow protected function Generates a table schema from a row.
MigrateTestCase::getDatabase protected function Gets an SQLite database connection object for use in tests.
MigrateTestCase::getMigration protected function Retrieves a mocked migration. 1
MigrateTestCase::getValue protected function Gets the value on a row for a given key. 1
MigrateTestCase::queryResultTest public function Tests a query.
MigrateTestCase::retrievalAssertHelper protected function Asserts tested values during test retrieval.
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.