xero-8.x-2.x-dev/tests/src/Unit/Controller/XeroAuthorizeControllerTest.php

tests/src/Unit/Controller/XeroAuthorizeControllerTest.php
<?php

namespace Drupal\Tests\xero\Unit\Form;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\Core\Form\FormTestBase;
use Drupal\Tests\xero\Traits\XeroTokenTrait;
use Drupal\xero\Controller\XeroAuthorizeController;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Test the Xero authorize controller.
 *
 * @coversDefaultClass \Drupal\xero\Controller\XeroAuthorizeController
 * @group xero
 */
class XeroAuthorizeControllerTest extends FormTestBase {

  use ProphecyTrait;
  use XeroTokenTrait;

  /**
   * The authorize controller instance to test.
   *
   * @var \Drupal\xero\Controller\XeroAuthorizeController
   */
  protected $authorizeController;

  /**
   * Consumer id mock.
   *
   * @var string
   */
  protected $consumerId;

  /**
   * Consumer secret mock.
   *
   * @var string
   */
  protected $consumerSecret;

  /**
   * CSRF token mock.
   *
   * @var string
   */
  protected $csrfTestToken;

  /**
   * Drupal messenger service mock.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface|\Prophecy\Prophecy\ObjectProphecy
   */
  protected $messengerProphet;

  /**
   * Drupal logger channel mock.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface|\Prophecy\Prophecy\ObjectProphecy
   */
  protected $loggerProphet;

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

    $this->consumerId = $this->createToken();
    $this->consumerSecret = $this->createToken();
    $this->csrfTestToken = $this->createToken();

    // Mock config objects with mock objects because prophecy is opinionated.
    $immutableConfig = $this->createMock('\Drupal\Core\Config\ImmutableConfig');
    $immutableConfig->expects($this->any())
      ->method('get')
      ->willReturnMap([
        [
          'oauth.consumer_key' => $this->consumerId,
          'oauth.consumer_secret' => $this->consumerSecret,
        ],
      ]);

    $mutableConfig = $this->createMock('\Drupal\Core\Config\Config');
    $mutableConfig->expects($this->any())
      ->method('set')
      ->willReturnSelf();
    $mutableConfig->expects($this->any())
      ->method('get')
      ->willReturnCallback(fn ($key) => $immutableConfig->get($key));

    // Mock ConfigFactory service.
    $configFactoryProphet = $this->prophesize('\Drupal\Core\Config\ConfigFactoryInterface');
    $configFactoryProphet
      ->getEditable('xero.settings')
      ->willReturn($mutableConfig);
    $configFactoryProphet
      ->get('xero.settings')
      ->willReturn($immutableConfig);

    $messengerProphet = $this->prophesize('\Drupal\Core\Messenger\MessengerInterface');
    $messengerProphet->addStatus(Argument::any());
    $this->messengerProphet = $messengerProphet;

    $token = $this->createToken();

    $tempStoreProphet = $this->prophesize('\Drupal\Core\TempStore\PrivateTempStore');
    $tempStoreProphet->set('state', Argument::any());
    $tempStoreProphet->get('state')->willReturn($token);
    $tempStoreProphet->delete('state')->willReturn(TRUE);
    $tempStoreProphet->set('global', Argument::any());
    $tempStoreProphet->get('global')->willReturn(TRUE);
    $tempStoreProphet->delete('global')->willReturn(TRUE);
    $tempStoreFactoryProphet = $this->prophesize('\Drupal\Core\TempStore\PrivateTempStoreFactory');
    $tempStoreFactoryProphet->get('xero.auth')->willReturn($tempStoreProphet->reveal());

    $currentUserProphet = $this->prophesize('\Drupal\Core\Session\AccountProxyInterface');

    $tokenManagerProphet = $this->prophesize('\Drupal\xero\XeroTokenManagerInterface');

    $urlGeneratorProphet = $this->prophesize('\Drupal\Core\Routing\UrlGeneratorInterface');
    $urlGeneratorProphet
      ->generateFromRoute('xero.configure', [], [], FALSE)
      ->willReturn('/admin/config/services/xero');

    // Mocks the OAuth2 Client request factory and requests.
    $tokenResponse = json_encode([
      'access_token' => $this->createToken(),
      'refresh_token' => $this->createToken(),
      'expires' => time() + 1800,
      'token_type' => 'Bearer',
    ]);
    $providerMock = new MockHandler([
      new Response(200, ['Content-Type' => 'application/json'], $tokenResponse),
    ]);
    $providerOptions = ['handler' => new HandlerStack($providerMock)];
    $httpClient = new Client($providerOptions);

    $this->loggerProphet = $this->prophesize('\Drupal\Core\Logger\LoggerChannelInterface');
    $loggerFactoryProphet = $this->prophesize('\Drupal\Core\Logger\LoggerChannelFactoryInterface');
    $loggerFactoryProphet->get('xero')->willReturn($this->loggerProphet->reveal());

    // Mock the container.
    $container = new ContainerBuilder();
    $container->set('config.factory', $configFactoryProphet->reveal());
    $container->set('messenger', $messengerProphet->reveal());
    $container->set('tempstore.private', $tempStoreFactoryProphet->reveal());
    $container->set('current_user', $currentUserProphet->reveal());
    $container->set('xero.token_manager', $tokenManagerProphet->reveal());
    $container->set('url_generator', $urlGeneratorProphet->reveal());
    // $container->set('http_client_factory', $httpFactoryProphet->reveal());
    $container->set('http_client', $httpClient);
    $container->set('logger.factory', $loggerFactoryProphet->reveal());
    $container->set('string_translation', $this->getStringTranslationStub());
    \Drupal::setContainer($container);

    $this->authorizeController = XeroAuthorizeController::create($container);

    $params = [
      'code' => $this->createToken(),
      'state' => $token,
      'global' => TRUE,
      'destination' => 'xero.configure',
    ];
    $this->request = Request::create('/xero/authorize', 'json', $params);
  }

  /**
   * Test the authorise controller.
   *
   * Currently this only tests the functioning of the controller, not of the
   * actual authorisation and token-persistence processes.
   *
   * @todo test the token is properly set.
   */
  public function testController() {
    // @todo $this->messengerProphet->addError(Argument::any())->shouldNotBeCalled();
    $response = $this->authorizeController->authorize($this->request);
    $this->assertInstanceOf(RedirectResponse::class, $response);
    $this->assertEquals("/admin/config/services/xero", $response->getTargetUrl());
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc