You are here

class ExternalAuthTest in External Authentication 8

Same name in this branch
  1. 8 tests/src/Unit/ExternalAuthTest.php \Drupal\Tests\externalauth\Unit\ExternalAuthTest
  2. 8 tests/src/Kernel/ExternalAuthTest.php \Drupal\Tests\externalauth\Kernel\ExternalAuthTest
Same name and namespace in other branches
  1. 2.0.x tests/src/Unit/ExternalAuthTest.php \Drupal\Tests\externalauth\Unit\ExternalAuthTest

ExternalAuth unit tests.

@group externalauth

@coversDefaultClass \Drupal\externalauth\ExternalAuth

Hierarchy

Expanded class hierarchy of ExternalAuthTest

File

tests/src/Unit/ExternalAuthTest.php, line 19

Namespace

Drupal\Tests\externalauth\Unit
View source
class ExternalAuthTest extends UnitTestCase {

  /**
   * The mocked entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entityTypeManager;

  /**
   * The mocked authmap service.
   *
   * @var \Drupal\externalauth\AuthmapInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $authmap;

  /**
   * The mocked logger instance.
   *
   * @var \Psr\Log\LoggerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $logger;

  /**
   * The mocked event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispatcher;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();

    // Create a mock EntityTypeManager object.
    $this->entityTypeManager = $this
      ->createMock(EntityTypeManagerInterface::class);

    // Create a Mock Logger object.
    $this->logger = $this
      ->getMockBuilder('\\Psr\\Log\\LoggerInterface')
      ->disableOriginalConstructor()
      ->getMock();

    // Create a Mock EventDispatcher object.
    $this->eventDispatcher = $this
      ->getMockBuilder('\\Symfony\\Component\\EventDispatcher\\EventDispatcherInterface')
      ->disableOriginalConstructor()
      ->getMock();

    // Create a Mock Authmap object.
    $this->authmap = $this
      ->getMockBuilder('\\Drupal\\externalauth\\Authmap')
      ->disableOriginalConstructor()
      ->getMock();
  }

  /**
   * Test the load() method.
   *
   * @covers ::load
   * @covers ::__construct
   */
  public function testLoad() {

    // Set up a mock for Authmap class,
    // mocking getUid() method.
    $authmap = $this
      ->getMockBuilder('\\Drupal\\externalauth\\Authmap')
      ->disableOriginalConstructor()
      ->setMethods([
      'getUid',
    ])
      ->getMock();
    $authmap
      ->expects($this
      ->once())
      ->method('getUid')
      ->will($this
      ->returnValue(2));

    // Mock the User storage layer.
    $account = $this
      ->createMock('Drupal\\user\\UserInterface');
    $entity_storage = $this
      ->createMock('Drupal\\Core\\Entity\\EntityStorageInterface');

    // Expect the external loading method to return a user object.
    $entity_storage
      ->expects($this
      ->once())
      ->method('load')
      ->will($this
      ->returnValue($account));
    $this->entityTypeManager
      ->expects($this
      ->once())
      ->method('getStorage')
      ->will($this
      ->returnValue($entity_storage));
    $externalauth = new ExternalAuth($this->entityTypeManager, $authmap, $this->logger, $this->eventDispatcher);
    $result = $externalauth
      ->load("test_authname", "test_provider");
    $this
      ->assertInstanceOf(UserInterface::class, $result);
  }

  /**
   * Test the login() method.
   *
   * @covers ::login
   * @covers ::__construct
   */
  public function testLogin() {

    // Set up a mock for ExternalAuth class,
    // mocking load() & userLoginFinalize() methods.
    $externalauth = $this
      ->getMockBuilder('Drupal\\externalauth\\ExternalAuth')
      ->setMethods([
      'load',
      'userLoginFinalize',
    ])
      ->setConstructorArgs([
      $this->entityTypeManager,
      $this->authmap,
      $this->logger,
      $this->eventDispatcher,
    ])
      ->getMock();

    // Mock load method.
    $externalauth
      ->expects($this
      ->once())
      ->method('load')
      ->will($this
      ->returnValue(FALSE));

    // Expect userLoginFinalize() to not be called.
    $externalauth
      ->expects($this
      ->never())
      ->method('userLoginFinalize');
    $result = $externalauth
      ->login("test_authname", "test_provider");
    $this
      ->assertEquals(FALSE, $result);
  }

  /**
   * Test the register() method.
   *
   * @covers ::register
   * @covers ::__construct
   *
   * @dataProvider registerDataProvider
   */
  public function testRegister($registration_data, $expected_data) {

    // Mock the returned User object.
    $account = $this
      ->createMock('Drupal\\user\\UserInterface');
    $account
      ->expects($this
      ->once())
      ->method('enforceIsNew');
    $account
      ->expects($this
      ->once())
      ->method('save');
    $account
      ->expects($this
      ->any())
      ->method('getTimeZone')
      ->will($this
      ->returnValue($expected_data['timezone']));

    // Mock the User storage layer to create a new user.
    $entity_storage = $this
      ->createMock('Drupal\\Core\\Entity\\EntityStorageInterface');

    // Expect the external registration to return us a user object.
    $entity_storage
      ->expects($this
      ->any())
      ->method('create')
      ->will($this
      ->returnValue($account));
    $entity_storage
      ->expects($this
      ->any())
      ->method('loadByProperties')
      ->will($this
      ->returnValue([]));
    $this->entityTypeManager
      ->expects($this
      ->any())
      ->method('getStorage')
      ->will($this
      ->returnValue($entity_storage));

    // Set up a mock for Authmap class,
    // mocking getUid() method.
    $authmap = $this
      ->getMockBuilder('\\Drupal\\externalauth\\Authmap')
      ->disableOriginalConstructor()
      ->setMethods([
      'save',
    ])
      ->getMock();
    $authmap
      ->expects($this
      ->once())
      ->method('save');
    $dispatched_event = $this
      ->getMockBuilder('\\Drupal\\externalauth\\Event\\ExternalAuthAuthmapAlterEvent')
      ->disableOriginalConstructor()
      ->getMock();
    $dispatched_event
      ->expects($this
      ->any())
      ->method('getUsername')
      ->will($this
      ->returnValue($expected_data['username']));
    $dispatched_event
      ->expects($this
      ->any())
      ->method('getAuthname')
      ->will($this
      ->returnValue($expected_data['authname']));
    $dispatched_event
      ->expects($this
      ->any())
      ->method('getData')
      ->will($this
      ->returnValue($expected_data['data']));
    $this->eventDispatcher
      ->expects($this
      ->any())
      ->method('dispatch')
      ->will($this
      ->returnValue($dispatched_event));
    $externalauth = new ExternalAuth($this->entityTypeManager, $authmap, $this->logger, $this->eventDispatcher);
    $registered_account = $externalauth
      ->register($registration_data['authname'], $registration_data['provider'], $registration_data['account_data'], $registration_data['authmap_data']);
    $this
      ->assertInstanceOf(UserInterface::class, $registered_account);
    $this
      ->assertEquals($expected_data['timezone'], $registered_account
      ->getTimeZone());
    $this
      ->assertEquals($expected_data['data'], $dispatched_event
      ->getData());
  }

  /**
   * Provides test data for testRegister.
   *
   * @return array
   *   Parameters
   */
  public function registerDataProvider() {
    return [
      // Test basic registration.
      [
        [
          'authname' => 'test_authname',
          'provider' => 'test_provider',
          'account_data' => [],
          'authmap_data' => NULL,
        ],
        [
          'username' => 'test_provider-test_authname',
          'authname' => 'test_authname',
          'timezone' => 'Europe/Brussels',
          'data' => [],
        ],
      ],
      // Test with added account data.
      [
        [
          'authname' => 'test_authname',
          'provider' => 'test_provider',
          'account_data' => [
            'timezone' => 'Europe/Prague',
          ],
          'authmap_data' => NULL,
        ],
        [
          'username' => 'test_provider-test_authname',
          'authname' => 'test_authname',
          'timezone' => 'Europe/Prague',
          'data' => [],
        ],
      ],
      // Test with added authmap data.
      [
        [
          'authname' => 'test_authname',
          'provider' => 'test_provider',
          'account_data' => [],
          'authmap_data' => [
            'extra_property' => 'extra',
          ],
        ],
        [
          'username' => 'test_provider-test_authname',
          'authname' => 'test_authname',
          'timezone' => 'Europe/Brussels',
          'data' => [
            'extra_property' => 'extra',
          ],
        ],
      ],
    ];
  }

  /**
   * Test the loginRegister() method.
   *
   * @covers ::loginRegister
   * @covers ::__construct
   */
  public function testLoginRegister() {
    $account = $this
      ->createMock('Drupal\\user\\UserInterface');

    // Set up a mock for ExternalAuth class,
    // mocking login(), register() & userLoginFinalize() methods.
    $externalauth = $this
      ->getMockBuilder('Drupal\\externalauth\\ExternalAuth')
      ->setMethods([
      'login',
      'register',
      'userLoginFinalize',
    ])
      ->setConstructorArgs([
      $this->entityTypeManager,
      $this->authmap,
      $this->logger,
      $this->eventDispatcher,
    ])
      ->getMock();

    // Mock ExternalAuth methods.
    $externalauth
      ->expects($this
      ->once())
      ->method('login')
      ->will($this
      ->returnValue(FALSE));
    $externalauth
      ->expects($this
      ->once())
      ->method('register')
      ->will($this
      ->returnValue($account));
    $externalauth
      ->expects($this
      ->once())
      ->method('userLoginFinalize')
      ->will($this
      ->returnValue($account));
    $result = $externalauth
      ->loginRegister("test_authname", "test_provider");
    $this
      ->assertInstanceOf(UserInterface::class, $result);
  }

  /**
   * Test linking an existing account.
   */
  public function testLinkExistingAccount() {
    $account = $this
      ->createMock('Drupal\\user\\UserInterface');
    $account
      ->expects($this
      ->once())
      ->method('id')
      ->will($this
      ->returnValue(5));

    // Set up a mock for Authmap class,
    // mocking get() & save() methods.
    $authmap = $this
      ->getMockBuilder('\\Drupal\\externalauth\\Authmap')
      ->disableOriginalConstructor()
      ->setMethods([
      'save',
      'get',
    ])
      ->getMock();
    $authmap
      ->expects($this
      ->once())
      ->method('get')
      ->will($this
      ->returnValue(FALSE));
    $authmap
      ->expects($this
      ->once())
      ->method('save');
    $dispatched_event = $this
      ->getMockBuilder('\\Drupal\\externalauth\\Event\\ExternalAuthAuthmapAlterEvent')
      ->disableOriginalConstructor()
      ->getMock();
    $dispatched_event
      ->expects($this
      ->any())
      ->method('getUsername')
      ->will($this
      ->returnValue("Test username"));
    $dispatched_event
      ->expects($this
      ->any())
      ->method('getAuthname')
      ->will($this
      ->returnValue("Test authname"));
    $dispatched_event
      ->expects($this
      ->any())
      ->method('getData')
      ->will($this
      ->returnValue("Test data"));
    $this->eventDispatcher
      ->expects($this
      ->any())
      ->method('dispatch')
      ->will($this
      ->returnValue($dispatched_event));
    $externalauth = new ExternalAuth($this->entityTypeManager, $authmap, $this->logger, $this->eventDispatcher);
    $externalauth
      ->linkExistingAccount("test_authname", "test_provider", $account);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ExternalAuthTest::$authmap protected property The mocked authmap service.
ExternalAuthTest::$entityTypeManager protected property The mocked entity type manager service.
ExternalAuthTest::$eventDispatcher protected property The mocked event dispatcher.
ExternalAuthTest::$logger protected property The mocked logger instance.
ExternalAuthTest::registerDataProvider public function Provides test data for testRegister.
ExternalAuthTest::setUp protected function Overrides UnitTestCase::setUp
ExternalAuthTest::testLinkExistingAccount public function Test linking an existing account.
ExternalAuthTest::testLoad public function Test the load() method.
ExternalAuthTest::testLogin public function Test the login() method.
ExternalAuthTest::testLoginRegister public function Test the loginRegister() method.
ExternalAuthTest::testRegister public function Test the register() method.
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.