Skip to content
Snippets Groups Projects
Commit 2016a8df authored by Aleksey Zubenko's avatar Aleksey Zubenko
Browse files

Resolve #3484108 "Create tests"

parent c233c14e
No related branches found
No related tags found
1 merge request!6Resolve #3484108 "Create tests"
Pipeline #420040 passed with warnings
<?php
declare(strict_types=1);
namespace Drupal\Tests\b24\Functional;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
/**
* Test description.
*
* @group b24
*/
final class AuthTest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'claro';
/**
* {@inheritdoc}
*/
protected static $modules = ['b24'];
/**
* Test callback.
*/
public function testAuthPageAvailability(): void {
$admin_user = $this->drupalCreateUser(['administer b24 configuration']);
$this->drupalLogin($admin_user);
$this->drupalGet(Url::fromRoute('b24.auth'));
$this->assertSession()->statusCodeEquals(200);
$this->assertSession()->pageTextContains('No bitrix24 account configured');
}
}
<?php
declare(strict_types=1);
namespace Drupal\Tests\b24\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\User;
/**
* Test description.
*
* @group b24
*/
final class B24UITest extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'claro';
/**
* {@inheritdoc}
*/
protected static $modules = ['b24'];
/**
* The test user having access to the module configuration.
*
* @var \Drupal\user\Entity\User
*/
private User $adminUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(['administer b24 configuration']);
}
/**
* Tests top level configuration page availability.
*/
public function testRouteConfigPageAvailability() {
$this->drupalGet('/admin/config/b24');
$this->assertSession()->statusCodeEquals(403);
$this->drupalLogin($this->adminUser);
$this->drupalGet('/admin/config/b24');
$this->assertSession()->statusCodeEquals(200);
}
/**
* Tests credentials form availability.
*/
public function testCredentialsForm(): void {
$this->drupalGet('/admin/config/b24/credentials');
$this->assertSession()->statusCodeEquals(403);
$this->drupalLogin($this->adminUser);
$this->drupalGet('/admin/config/b24/credentials');
$this->assertSession()->statusCodeEquals(200);
$this->submitForm([
'site' => 'tst.bitrix24.ru',
], 'Save configuration');
$this->assertSession()->pageTextContains('The configuration options have been saved.');
$this->assertSession()->fieldValueEquals(
'site',
'tst.bitrix24.ru',
);
$config = $this->config('b24.settings');
$this->assertSession()->fieldValueEquals(
'site',
$config->get('site'),
);
}
/**
* Tests settings form availability.
*/
public function testSettingsForm(): void {
$this->drupalGet('/admin/config/b24/settings');
$this->assertSession()->statusCodeEquals(403);
$this->drupalLogin($this->adminUser);
$this->drupalGet('/admin/config/b24/settings');
$this->assertSession()->statusCodeEquals(200);
$this->submitForm([
'assignee' => 'custom',
'user_id' => 12,
], 'Save configuration');
$this->assertSession()->pageTextContains('The configuration options have been saved.');
$this->assertSession()->fieldValueEquals(
'assignee',
'custom',
);
$this->assertSession()->fieldValueEquals(
'user_id',
12,
);
$config = $this->config('b24.default_settings');
$this->assertSession()->fieldValueEquals(
'assignee',
$config->get('assignee'),
);
$this->assertSession()->fieldValueEquals(
'user_id',
$config->get('user_id'),
);
}
}
<?php
declare(strict_types=1);
namespace Drupal\Tests\b24\Unit;
use Drupal\Component\Datetime\Time;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Query\Delete;
use Drupal\Core\Database\Query\Select;
use Drupal\Core\Database\Query\Update;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandler;
use Drupal\Core\Logger\LoggerChannel;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Session\AccountProxy;
use Drupal\Core\State\StateInterface;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\b24\Service\RestManager;
use Drupal\sqlite\Driver\Database\sqlite\Statement;
use Drupal\user\Entity\User;
use Drupal\user\UserStorageInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Response;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* Test description.
*
* @coversDefaultClass \Drupal\b24\Service\RestManager
* @group b24
*/
final class RestManagerTest extends UnitTestCase {
/* cspell:enable */
/**
* Bitrix24 application client id credential stub.
*/
const B24_CLIENT_ID = 'local.abc123def456tst.stub123';
/**
* Bitrix24 application secret code stub.
*/
const B24_CLIENT_SECRET = '123stubsecretcode456';
/**
* Bitrix24 application domain name stub.
*/
const B24_DOMAIN = 'example.bitrix24.site';
/**
* Test config data.
*
* @var array
*/
protected array $testConfig;
/**
* The B24 rest manager instance.
*
* @var \Drupal\b24\Service\RestManager
*/
protected RestManager $restManager;
/**
* The mocked entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->testConfig = [
'b24.settings' => [
'site' => self::B24_DOMAIN,
'client_id' => self::B24_CLIENT_ID,
'client_secret' => self::B24_CLIENT_SECRET,
],
'b24.default_settings' => [
'assignee' => 'custom',
'user_id' => 1,
],
];
$storage = $this->createMock(UserStorageInterface::class);
$this->entityTypeManager = $this->createMock(EntityTypeManagerInterface::class);
$this->entityTypeManager
->expects($this->any())
->method('getStorage')
->willReturn($storage);
$mockConnection = $this->createMock(Connection::class);
$mockDelete = $this->getMockBuilder(Delete::class)
->disableOriginalConstructor()
->getMock();
$mockDelete
->method('execute')
->willReturn(1);
$mockDelete
->method('condition')
->willReturnSelf();
$mockSelectStatement = $this->getMockBuilder(Statement::class)
->disableOriginalConstructor()
->getMock();
$mockSelectStatement->expects($this->any())
->method('fetchAssoc')
->willReturn(['ext_id' => 1, 'hash' => 'sdf234jhgf']);
$mockSelect = $this->getMockBuilder(Select::class)
->disableOriginalConstructor()
->getMock();
$mockSelect
->method('condition')
->willReturnSelf();
$mockSelect
->method('fields')
->willReturnSelf();
$mockSelect
->method('execute')
->willReturn($mockSelectStatement);
$mockUpdate = $this->getMockBuilder(Update::class)
->disableOriginalConstructor()
->getMock();
$mockUpdate
->method('condition')
->willReturnSelf();
$mockUpdate
->method('fields')
->willReturnSelf();
$mockUpdate
->method('execute')
->willReturn(1);
$mockConnection->method('delete')
->willReturn($mockDelete);
$mockConnection->method('select')
->willReturn($mockSelect);
$mockConnection->method('update')
->willReturn($mockUpdate);
$mockRequest = $this->createMock(Request::class);
$mockRequestStack = $this->createMock(RequestStack::class);
$mockRequestStack->expects($this->any())
->method('getCurrentRequest')
->willReturn($mockRequest);
$headers = ['Content-Type' => ['application/json']];
$refreshResponseBody = json_encode([
'access_token' => 'sdfghjkl',
'refresh_token' => 'asdfghjkl',
'expires' => 1738142693,
]);
$valid_refresh_response = new Response(200, $headers, $refreshResponseBody);
$mockHttpClient = $this->createMock(Client::class);
// Mock condition for testRefreshAccessToken.
$mockHttpClient
->method('get')
->with('https://' . self::B24_DOMAIN . '/oauth/token/?grant_type=refresh_token&client_id=' . self::B24_CLIENT_ID . '&client_secret=' . self::B24_CLIENT_SECRET . '&scope=crm&refresh_token&redirect_uri=/b24/oauth', ['headers' => ['Accept' => 'text/plain']])
->willReturn($valid_refresh_response);
$valid_response = new Response(200, $headers, json_encode(['result' => 1]));
$valid_get_response = new Response(200, $headers, json_encode(['result' => ['ID' => 1]]));
$valid_add_response = new Response(200, $headers, json_encode(['result' => 1]));
$valid_update_response = new Response(200, $headers, json_encode(['result' => TRUE]));
$valid_list_response = new Response(200, $headers, json_encode(['result' => [['ID' => 1]]]));
$empty_list_response = new Response(200, $headers, json_encode(['result' => []]));
$mockHttpClient
->method('post')
->willReturnCallback(function ($url, $params) use ($valid_response, $valid_get_response, $valid_add_response, $valid_update_response, $valid_list_response, $empty_list_response) {
return match ([$url, $params]) {
[
'https://' . self::B24_DOMAIN . '/rest/crm.lead.add/',
['form_params' => ['auth' => NULL]],
] => $valid_response,
[
'https://' . self::B24_DOMAIN . '/rest/crm.lead.get/',
['form_params' => ['id' => 1, 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.deal.get/',
['form_params' => ['id' => 1, 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.contact.get/',
['form_params' => ['id' => 1, 'auth' => NULL]],
] => $valid_get_response,
[
'https://' . self::B24_DOMAIN . '/rest/crm.lead.add/',
[
'form_params' => [
'fields' => ['ASSIGNED_BY_ID' => 1],
'params' => [],
'auth' => NULL,
],
],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.deal.add/',
[
'form_params' => [
'fields' => ['ASSIGNED_BY_ID' => 1],
'params' => ['REGISTER_SONET_EVENT' => 'Y'],
'auth' => NULL,
],
],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.contact.add/',
[
'form_params' => [
'fields' => ['ASSIGNED_BY_ID' => 1],
'params' => ['REGISTER_SONET_EVENT' => 'Y'],
'auth' => NULL,
],
],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.lead.add/',
[
'form_params' => [
'fields' => [
'SOURCE_ID' => 'WEB',
'OPENED' => 'Y',
'ASSIGNED_BY_ID' => 1,
],
'params' => ['REGISTER_SONET_EVENT' => 'Y'],
'auth' => NULL,
],
],
] => $valid_add_response,
[
'https://' . self::B24_DOMAIN . '/rest/crm.lead.update/',
[
'form_params' => [
'id' => 1,
'fields' => [],
'params' => ['REGISTER_SONET_EVENT' => 'Y'],
'auth' => NULL,
],
],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.deal.update/',
[
'form_params' => [
'id' => 1,
'fields' => [],
'params' => ['REGISTER_SONET_EVENT' => 'Y'],
'auth' => NULL,
],
],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.contact.update/',
[
'form_params' => [
'id' => 1,
'fields' => [],
'params' => ['REGISTER_SONET_EVENT' => 'Y'],
'auth' => NULL,
],
],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.contact.delete/',
['form_params' => ['id' => 1, 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.product.delete/',
['form_params' => ['id' => 1, 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.lead.productrows.set/',
['form_params' => ['id' => 1, 'rows' => [], 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.deal.productrows.set/',
['form_params' => ['id' => 1, 'rows' => [], 'auth' => NULL]],
] => $valid_update_response,
[
'https://' . self::B24_DOMAIN . '/rest/crm.lead.list/',
['form_params' => ['filter' => ['XML_ID' => 1], 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.lead.productrows.get/',
['form_params' => ['id' => 1, 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.deal.productrows.get/',
['form_params' => ['id' => 1, 'auth' => NULL]],
] => $valid_list_response,
[
'https://' . self::B24_DOMAIN . '/rest/crm.lead.list/',
['form_params' => ['filter' => ['XML_ID' => 2], 'auth' => NULL]],
], [
'https://' . self::B24_DOMAIN . '/rest/crm.lead.fields/',
['form_params' => ['auth' => NULL]],
] => $empty_list_response,
};
});
$mockLogger = $this->createMock(LoggerChannel::class);
$mockLoggerFactory = $this->createMock(LoggerChannelFactoryInterface::class);
$mockLoggerFactory->expects($this->any())
->method('get')
->willReturn($mockLogger);
$this->restManager = new RestManager(
$this->getConfigFactoryStub($this->testConfig),
$mockRequestStack,
$this->createMock(StateInterface::class),
$mockLoggerFactory,
$mockHttpClient,
$this->createMock(ModuleHandler::class),
$this->createMock(EventDispatcherInterface::class),
$mockConnection,
$this->entityTypeManager,
$this->createMock(AccountProxy::class),
$this->createMock(LinkGeneratorInterface::class),
$this->createMock(Time::class)
);
}
/**
* @covers ::refreshAccessToken
*/
public function testRefreshAccessToken() {
$refreshResult = $this->restManager->refreshAccessToken();
$expectedAccessToken = 'sdfghjkl';
$this->assertTrue(isset($refreshResult['access_token']));
$this->assertSame($expectedAccessToken, $refreshResult['access_token']);
}
/**
* @covers ::get
*/
public function testGet() {
$response = $this->restManager->get('crm.lead.add');
$this->assertTrue(isset($response['result']));
$this->assertEquals(1, $response['result']);
}
/**
* @covers ::addEntity
*/
public function testAddEntity() {
$response = $this->restManager->addEntity('lead');
$this->assertEquals(1, $response);
}
/**
* @covers ::getLead
*/
public function testGetLead() {
$response = $this->restManager->getLead(1);
$this->assertTrue(isset($response['ID']));
$this->assertEquals(1, $response['ID']);
}
/**
* @covers ::addLead
*/
public function testAddLead() {
$response = $this->restManager->addLead();
$this->assertEquals(1, $response);
}
/**
* @covers ::updateLead
*/
public function testUpdateLead() {
$response = $this->restManager->updateLead(1);
$this->assertTrue(isset($response['result']));
$this->assertTrue($response['result']);
}
/**
* @covers ::getDeal
*/
public function testGetDeal() {
$response = $this->restManager->getDeal(1);
$this->assertTrue(isset($response['ID']));
$this->assertEquals(1, $response['ID']);
}
/**
* @covers ::addDeal
*/
public function testAddDeal() {
$response = $this->restManager->addDeal();
$this->assertEquals(1, $response);
}
/**
* @covers ::updateDeal
*/
public function testUpdateDeal() {
$response = $this->restManager->updateDeal(1);
$this->assertTrue(isset($response['result']));
$this->assertTrue($response['result']);
}
/**
* @covers ::addContact
*/
public function testAddContact() {
$response = $this->restManager->addContact();
$this->assertEquals(1, $response);
}
/**
* @covers ::updateContact
*/
public function testUpdateContact() {
$response = $this->restManager->updateContact(1);
$this->assertTrue(isset($response['result']));
$this->assertTrue($response['result']);
}
/**
* @covers ::deleteEntity
*/
public function testDeleteEntity() {
$response = $this->restManager->deleteEntity(1, 'contact');
$this->assertTrue($response);
}
/**
* @covers ::deleteContact
*/
public function testDeleteContact() {
$response = $this->restManager->deleteContact(1);
$this->assertTrue($response);
}
/**
* @covers ::deleteProduct
*/
public function testDeleteProduct() {
$response = $this->restManager->deleteProduct(1);
$this->assertTrue($response);
}
/**
* @covers ::getContact
*/
public function testGetContact() {
$response = $this->restManager->getContact(1);
$this->assertTrue(isset($response['ID']));
$this->assertEquals(1, $response['ID']);
}
/**
* @covers ::getFields
*/
public function testGetFields() {
$response = $this->restManager->getFields('lead');
$this->assertIsArray($response);
}
/**
* @covers ::getList
*/
public function testGetList() {
$response = $this->restManager->getList('lead', ['filter' => ['XML_ID' => 1]]);
$this->assertIsArray($response);
$this->assertTrue(isset($response[0]['ID']));
$this->assertIsInt($response[0]['ID']);
}
/**
* @covers ::setLeadProducts
*/
public function testSetLeadProducts() {
$response = $this->restManager->setProductRows(1, 'lead', []);
$this->assertTrue($response);
}
/**
* @covers ::setDealProducts
*/
public function testSetDealProducts() {
$response = $this->restManager->setProductRows(1, 'deal', []);
$this->assertTrue($response);
}
/**
* @covers ::setProductRows
*/
public function testSetProductRows() {
$response = $this->restManager->setProductRows(1, 'lead', []);
$this->assertTrue($response);
}
/**
* @covers ::getReference
*/
public function testGetReference() {
$user = $this->getMockBuilder(User::class)
->disableOriginalConstructor()
->getMock();
$result = $this->restManager->getReference($user, 'contact');
$this->assertIsArray($result);
$this->assertContains('sdf234jhgf', $result);
}
/**
* @covers ::deleteReference
*/
public function testDeleteReference() {
$result = $this->restManager->deleteReference('contact', 1);
$this->assertIsInt($result);
}
/**
* @covers ::updateHash
*/
public function testUpdateHash() {
$entity = $this->getMockBuilder(User::class)
->disableOriginalConstructor()
->getMock();
$result = $this->restManager->updateHash($entity, 'contact', 'qwerty');
$this->assertIsInt($result);
}
/**
* @covers ::getAuthorizeUri
*/
public function testGetAuthorizeUri() {
$uri = $this->restManager->getAuthorizeUri();
$expected = 'https://' . self::B24_DOMAIN . '/oauth/authorize?client_id=' . self::B24_CLIENT_ID . '&response_type=code&redirect_uri=/b24/oauth';
$this->assertEquals($expected, $uri);
}
/**
* @covers ::getHash
*/
public function testGetHash() {
$fields = [
'one_field_key' => 'one_field_value',
'another_field_key' => 'another_field_value',
];
$expected = 'u8wL2k9KsIRyxfPPO4wsXKKq3lI7MCMZprnLqZLtbPE';
$hash = $this->restManager->getHash($fields);
$this->assertEquals($expected, $hash);
}
/**
* Tests successful search result for getId method.
*
* @covers ::getId
*/
public function testGetId() {
$response = $this->restManager->getId(1, 'lead');
$this->assertIsInt($response);
}
/**
* Tests empty search result for getId method.
*
* @covers ::getId
*/
public function testEmptyGetId() {
$response = $this->restManager->getId(2, 'lead');
$this->assertFalse($response);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment