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

tests/src/Unit/XeroClientFactoryTest.php
<?php

namespace Drupal\Tests\xero\Unit;

use Drupal\Tests\UnitTestCase;
use Drupal\Tests\xero\Traits\XeroGuidTrait;
use Drupal\Tests\xero\Traits\XeroTokenTrait;
use Drupal\xero\XeroClientFactory;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use League\OAuth2\Client\Token\AccessToken;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * Tests getting the XeroClient class.
 *
 * @coversDefaultClass \Drupal\xero\XeroClientFactory
 * @group xero
 */
class XeroClientFactoryTest extends UnitTestCase {

  use ProphecyTrait;
  use XeroTokenTrait;
  use XeroGuidTrait;

  /**
   * Xero client factory service.
   *
   * @var \Drupal\xero\XeroClientFactory
   */
  protected $factory;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->factory = new XeroClientFactory();
  }

  /**
   * Get xero configuration dummy data.
   *
   * @return array
   *   An associative array of configuration values to use.
   */
  protected function getConfiguration() {
    return [
      'consumer_key' => $this->getRandomGenerator()->string(32),
      'consumer_secret' => $this->getRandomGenerator()->string(32),
    ];
  }

  /**
   * Get the logger factory.
   *
   * @return \Drupal\Core\Logger\LoggerChannelFactoryInterface
   *   A prophesized logger channel factory.
   */
  protected function getLoggerFactory() {
    $logProphet = $this->prophesize('\Psr\Log\LoggerInterface');
    $logProphet->error(Argument::any(), Argument::any());
    $logger = $logProphet->reveal();
    $loggerFactoryProphet = $this->prophesize('\Drupal\Core\Logger\LoggerChannelFactoryInterface');
    $loggerFactoryProphet->addLogger($logger);
    $loggerFactoryProphet->get('xero')->willReturn($logger);
    return $loggerFactoryProphet->reveal();
  }

  /**
   * Get the time mock.
   *
   * @param int $time
   *   An optional unix time to set.
   *
   * @return \Drupal\Component\DateTime\TimeInterface|object
   *   A prophesized time service.
   */
  protected function getTime($time = NULL) {
    $timeProphet = $this->prophesize('\Drupal\Component\Datetime\TimeInterface');
    $timeProphet->getCurrentTime()->will(fn () => $time || time());
    return $timeProphet->reveal();
  }

  /**
   * Mocks the xero.token.manager service.
   *
   * @param array $getData
   *   An optional array of key/value pairs to get.
   * @param array $setData
   *   An optional array of key/value pairs to set.
   *
   * @return \Drupal\xero\XeroTokenManager|object
   *   A prophesized token manager.
   */
  protected function getTokenManager(array $getData = [], array $setData = []) {
    $prophet = $this->prophesize('\Drupal\xero\XeroTokenManagerInterface');
    $prophet->setToken($setData, Argument::any());
    $prophet
      ->getToken(Argument::any(), Argument::any())
      ->will(fn () => $getData ? new AccessToken($getData) : FALSE);
    $prophet->hasUserToken(Argument::any())->willReturn(TRUE);
    return $prophet->reveal();
  }

  /**
   * Mocks http client.
   *
   * @param \GuzzleHttp\Psr7\Response $response
   *   The http response to use for access or refresh token requests.
   *
   * @return \GuzzleHttp\Client
   *   A mock guzzle client.
   */
  protected function getHttpClient(Response $response) {
    $mock = new MockHandler([$response]);
    $handler = new HandlerStack($mock);

    return new Client(['handler' => $handler]);
  }

  /**
   * Asserts the get method on the factory returns correctly.
   *
   * @param array $data
   *   The key value store data.
   *
   * @dataProvider clientTestProvider
   *
   * @risky
   */
  public function testGetFailure(array $data) {
    $httpClient = $this->getHttpClient(new Response(403, [
      'Content-Type' => 'application/json',
    ], json_encode([
      'title' => 'Forbidden',
      'status' => 403,
      'detail' => 'AuthenticationUnsuccessful',
      'instance' => $this->createGuid(),
    ])));

    $accountProphet = $this->prophesize('\Drupal\Core\Session\AccountProxyInterface');
    $accountProphet->id()->willReturn(1);
    $accountProphet->hasPermission(Argument::any())->willReturn(TRUE);

    $loggerFactory = $this->getLoggerFactory();
    $tokenManager = $this->getTokenManager($data, $data);

    $configProphet = $this->prophesize('\Drupal\Core\Config\ImmutableConfig');
    $configProphet->get(Argument::type('string'))->willReturn(NULL);
    $configFactoryProphet = $this->prophesize('\Drupal\Core\Config\ConfigFactoryInterface');
    $configFactoryProphet->get('xero.settings')->willReturn($configProphet->reveal());

    $client = $this->factory->get(
      $configFactoryProphet->reveal(),
      $loggerFactory,
      $accountProphet->reveal(),
      $tokenManager,
      $this->getTime(),
      $httpClient);

    $this->assertInstanceOf('\Radcliffe\Xero\XeroClientInterface', $client);
  }

  /**
   * Provides test arguments and expected values.
   *
   * @return array
   *   An indexed array of test data.
   */
  public static function clientTestProvider() {
    return [
      // Expected client, key/value arguments.
      'no token' => [[]],
      'expired toked' => [
        [
          'access_token' => self::createToken(),
          'refresh_token' => self::createToken(),
          'expires' => time() - 3600,
        ],
      ],
      'valid token' => [
        ['access_token' => self::createToken(), 'expires' => time() + 3600],
      ],
    ];
  }

}

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

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