snapshot of https://github.com/espocrm/espocrm.git (master, 2026-09-18; blobs > 131072B omitted)
Some checks failed
Test / Test on PHP 8.3 (push) Failing after 5s
Test / Test on PHP 8.4 (push) Failing after 4s
Test / Test on PHP 8.5 (push) Failing after 3s
TypeScript static analysis / TypeScript check (push) Failing after 14s
Test Integration on MySQL / Test on PHP 8.3 (push) Failing after 2s
Test Integration on MySQL / Test on PHP 8.5 (push) Failing after 0s
Test Integration on PostgreSQL / Test on PHP 8.4 fix (push) Failing after 1s
Test Integration on PostgreSQL / Test on PHP 8.4 master (push) Failing after 1s
Some checks failed
Test / Test on PHP 8.3 (push) Failing after 5s
Test / Test on PHP 8.4 (push) Failing after 4s
Test / Test on PHP 8.5 (push) Failing after 3s
TypeScript static analysis / TypeScript check (push) Failing after 14s
Test Integration on MySQL / Test on PHP 8.3 (push) Failing after 2s
Test Integration on MySQL / Test on PHP 8.5 (push) Failing after 0s
Test Integration on PostgreSQL / Test on PHP 8.4 fix (push) Failing after 1s
Test Integration on PostgreSQL / Test on PHP 8.4 master (push) Failing after 1s
This commit is contained in:
228
tests/integration/Core/ApiClient.php
Normal file
228
tests/integration/Core/ApiClient.php
Normal file
@@ -0,0 +1,228 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace tests\integration\Core;
|
||||
|
||||
class ApiClient
|
||||
{
|
||||
private $url;
|
||||
private $userName;
|
||||
private $password;
|
||||
private $portalId;
|
||||
protected $apiPath = '/api/v1/';
|
||||
protected $portalApiPath = '/api/v1/portal-access/{PORTAL_ID}/';
|
||||
protected $userAgent =
|
||||
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36';
|
||||
private $lastCh;
|
||||
|
||||
public function __construct($url = null, $userName = null, $password = null, $portalId = null)
|
||||
{
|
||||
if (isset($url)) {
|
||||
$this->url = $url;
|
||||
}
|
||||
|
||||
if (isset($userName)) {
|
||||
$this->userName = $userName;
|
||||
}
|
||||
|
||||
if (isset($password)) {
|
||||
$this->password = $password;
|
||||
}
|
||||
|
||||
if (isset($portalId)) {
|
||||
$this->portalId = $portalId;
|
||||
}
|
||||
}
|
||||
|
||||
public function setUrl($url)
|
||||
{
|
||||
$this->url = $url;
|
||||
}
|
||||
|
||||
public function setUserName($userName)
|
||||
{
|
||||
$this->userName = $userName;
|
||||
}
|
||||
|
||||
public function setPassword($password)
|
||||
{
|
||||
$this->password = $password;
|
||||
}
|
||||
|
||||
public function setPortalId($portalId)
|
||||
{
|
||||
$this->portalId = $portalId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send request to EspoCRM.
|
||||
*
|
||||
* @param string $method
|
||||
* @param string $action
|
||||
* @param array|string|null $jsonData
|
||||
*
|
||||
* @return array|\Exception
|
||||
*/
|
||||
public function request($method, $action, $jsonData = null)
|
||||
{
|
||||
$this->checkParams();
|
||||
|
||||
$this->lastCh = null;
|
||||
|
||||
if (is_array($jsonData)) {
|
||||
$jsonData = json_encode($jsonData);
|
||||
}
|
||||
|
||||
$url = $this->normalizeUrl($action);
|
||||
|
||||
$ch = curl_init($url);
|
||||
|
||||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($ch, CURLOPT_USERPWD, $this->userName.':'.$this->password);
|
||||
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
|
||||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||||
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
|
||||
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
|
||||
curl_setopt($ch, CURLOPT_HEADER, true);
|
||||
|
||||
if (isset($jsonData)) {
|
||||
if ($method == 'GET') {
|
||||
$data = json_decode($jsonData, true);
|
||||
curl_setopt($ch, CURLOPT_URL, $url. '?' . http_build_query($data));
|
||||
} else {
|
||||
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
|
||||
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
|
||||
curl_setopt($ch, CURLOPT_HTTPHEADER, [
|
||||
'Content-Type: application/json',
|
||||
'Content-Length: ' . strlen($jsonData),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$lastResponse = curl_exec($ch);
|
||||
$this->lastCh = $ch;
|
||||
|
||||
$parsedResponse = $this->parseResponse($lastResponse);
|
||||
|
||||
if ($this->getResponseHttpCode() == 200 && !empty($parsedResponse['body'])) {
|
||||
return json_decode($parsedResponse['body'], true);
|
||||
}
|
||||
|
||||
$header = $this->normalizeHeader($parsedResponse['header']);
|
||||
$errorCode = $this->getResponseHttpCode();
|
||||
$errorMessage = !empty($header['X-Status-Reason']) ? $header['X-Status-Reason'] : $errorCode;
|
||||
|
||||
throw new \Exception($errorMessage, $errorCode);
|
||||
}
|
||||
|
||||
public function getResponseContentType()
|
||||
{
|
||||
return $this->getInfo(CURLINFO_CONTENT_TYPE);
|
||||
}
|
||||
|
||||
public function getResponseTotalTime()
|
||||
{
|
||||
return $this->getInfo(CURLINFO_TOTAL_TIME);
|
||||
}
|
||||
|
||||
public function getResponseHttpCode()
|
||||
{
|
||||
return $this->getInfo(CURLINFO_HTTP_CODE);
|
||||
}
|
||||
|
||||
protected function normalizeUrl($action)
|
||||
{
|
||||
$apiPath = $this->portalId ? str_replace('{PORTAL_ID}', $this->portalId, $this->portalApiPath) : $this->apiPath;
|
||||
|
||||
return $this->url . $apiPath . $action;
|
||||
}
|
||||
|
||||
protected function checkParams()
|
||||
{
|
||||
$paramList = [
|
||||
'url',
|
||||
'userName',
|
||||
'password',
|
||||
];
|
||||
|
||||
foreach ($paramList as $name) {
|
||||
if (empty($this->$name)) {
|
||||
throw new \Exception('EspoClient: Parameter "'.$name.'" is not defined.');
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function getInfo($option)
|
||||
{
|
||||
if (isset($this->lastCh)) {
|
||||
return curl_getinfo($this->lastCh, $option);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse response to get header and body.
|
||||
*
|
||||
* @param string $response
|
||||
* @return array
|
||||
*/
|
||||
protected function parseResponse($response)
|
||||
{
|
||||
$headerSize = $this->getInfo(CURLINFO_HEADER_SIZE);
|
||||
|
||||
return [
|
||||
'header' => trim( substr($response, 0, $headerSize) ),
|
||||
'body' => substr($response, $headerSize),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert header string to array.
|
||||
*
|
||||
* @param string $header
|
||||
* @return array
|
||||
*/
|
||||
protected function normalizeHeader($header)
|
||||
{
|
||||
preg_match_all('/(.*): (.*)\r\n/', $header, $matches);
|
||||
|
||||
$headerArray = [];
|
||||
|
||||
foreach ($matches[1] as $index => $name) {
|
||||
if (isset($matches[2][$index])) {
|
||||
$headerArray[$name] = trim($matches[2][$index]);
|
||||
}
|
||||
}
|
||||
|
||||
return $headerArray;
|
||||
}
|
||||
}
|
||||
453
tests/integration/Core/BaseTestCase.php
Normal file
453
tests/integration/Core/BaseTestCase.php
Normal file
@@ -0,0 +1,453 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace tests\integration\Core;
|
||||
|
||||
use Closure;
|
||||
use Espo\Core\Api\RequestWrapper;
|
||||
use Espo\Core\Api\ResponseWrapper;
|
||||
use Espo\Core\Application;
|
||||
use Espo\Core\Binding\Binder;
|
||||
use Espo\Core\Binding\BindingProcessor;
|
||||
use Espo\Core\Container;
|
||||
use Espo\Core\DataManager;
|
||||
use Espo\Core\Exceptions\Error;
|
||||
use Espo\Core\InjectableFactory;
|
||||
use Espo\Core\Utils\Cache\DataCacheServiceName as CacheServiceName;
|
||||
use Espo\Core\Utils\Config;
|
||||
use Espo\Core\Utils\Config\ConfigWriter;
|
||||
use Espo\Core\Utils\File\Manager as FileManager;
|
||||
use Espo\Core\Utils\Metadata;
|
||||
use Espo\Entities\User;
|
||||
use Espo\ORM\EntityManager;
|
||||
|
||||
use Espo\ORM\TransactionManager;
|
||||
use Exception;
|
||||
use integration\Core\NoTransaction;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use ReflectionClass;
|
||||
use ReflectionException;
|
||||
use ReflectionMethod;
|
||||
use RuntimeException;
|
||||
use Slim\Psr7\Factory\RequestFactory;
|
||||
use Slim\Psr7\Factory\ResponseFactory;
|
||||
use Slim\Psr7\Factory\StreamFactory;
|
||||
|
||||
/**
|
||||
* Note. Rebuild code were removed after PHPUnit upgrading.
|
||||
*/
|
||||
abstract class BaseTestCase extends TestCase
|
||||
{
|
||||
private ?Tester $espoTester = null;
|
||||
private ?Application $espoApplication = null;
|
||||
private ?string $authenticationMethod = null;
|
||||
|
||||
/** Path to file with data. */
|
||||
protected ?string $dataFile = null;
|
||||
/** Path to files which needs to be copied. */
|
||||
protected ?string $pathToFiles = null;
|
||||
/** Username used for authentication. */
|
||||
protected ?string $userName = null;
|
||||
/** Password used for authentication. */
|
||||
protected ?string $password = null;
|
||||
|
||||
private ?TransactionManager $transactionManager = null;
|
||||
|
||||
/**
|
||||
* @var ?array{
|
||||
* entities?: array<string, array<string, mixed>>,
|
||||
* files?: string,
|
||||
* config?: array<string, mixed>,
|
||||
* preferences?: array<string, mixed>,
|
||||
* }
|
||||
*/
|
||||
protected $initData = null;
|
||||
|
||||
protected function createApplication(
|
||||
bool $clearCache = true,
|
||||
?string $portalId = null,
|
||||
?BindingProcessor $binding = null,
|
||||
bool $reuse = false,
|
||||
bool $noUser = false,
|
||||
): Application {
|
||||
|
||||
if (!$this->isNotCleanTest() && !$reuse) {
|
||||
if ($this->transactionManager?->isStarted()) {
|
||||
try {
|
||||
$this->transactionManager->commit();
|
||||
} catch (Exception) {}
|
||||
}
|
||||
|
||||
Registry::$isCleanAndReady = false;
|
||||
}
|
||||
|
||||
return $this->espoTester->getApplication(
|
||||
reload: true,
|
||||
clearCache: $clearCache,
|
||||
portalId: $portalId,
|
||||
binding: $binding,
|
||||
reuse: $reuse,
|
||||
noUser: $noUser,
|
||||
);
|
||||
}
|
||||
|
||||
protected function setApplication(Application $application): void
|
||||
{
|
||||
$this->espoApplication = $application;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set authentication credentials. It does not authenticate.
|
||||
*/
|
||||
protected function auth(
|
||||
?string $userName = null,
|
||||
?string $password = null,
|
||||
?string $portalId = null,
|
||||
?string $authenticationMethod = null,
|
||||
?RequestWrapper $request = null,
|
||||
): void {
|
||||
|
||||
$this->userName = $userName;
|
||||
$this->password = $password;
|
||||
$this->authenticationMethod = $authenticationMethod;
|
||||
|
||||
$this->espoTester?->auth(
|
||||
userName: $userName,
|
||||
password: $password,
|
||||
portalId: $portalId,
|
||||
authenticationMethod: $authenticationMethod,
|
||||
request: $request,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the application.
|
||||
*/
|
||||
protected function getApplication(): Application
|
||||
{
|
||||
return $this->espoApplication;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get container.
|
||||
*/
|
||||
protected function getContainer(): Container
|
||||
{
|
||||
return $this->getApplication()->getContainer();
|
||||
}
|
||||
|
||||
protected function getFileManager(): FileManager
|
||||
{
|
||||
return $this->getApplication()->getContainer()->getByClass(FileManager::class);
|
||||
}
|
||||
|
||||
protected function getDataManager(): DataManager
|
||||
{
|
||||
return $this->getApplication()->getContainer()->getByClass(DataManager::class);
|
||||
}
|
||||
|
||||
protected function getInjectableFactory(): InjectableFactory
|
||||
{
|
||||
return $this->getApplication()->getContainer()->getByClass(InjectableFactory::class);
|
||||
}
|
||||
|
||||
protected function getMetadata(): Metadata
|
||||
{
|
||||
return $this->getApplication()->getContainer()->getByClass(Metadata::class);
|
||||
}
|
||||
|
||||
protected function getEntityManager(): EntityManager
|
||||
{
|
||||
return $this->getApplication()->getContainer()->getByClass(EntityManager::class);
|
||||
}
|
||||
|
||||
protected function getConfig(): Config
|
||||
{
|
||||
return $this->getApplication()->getContainer()->getByClass(Config::class);
|
||||
}
|
||||
|
||||
protected function normalizePath(string $path): string
|
||||
{
|
||||
return $this->espoTester->normalizePath($path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Important. CWD is not set to `build/test before `setUp` is called. Do not clean up anything before.
|
||||
*/
|
||||
protected function setUp(): void
|
||||
{
|
||||
$params = [
|
||||
'className' => get_class($this),
|
||||
'dataFile' => $this->dataFile,
|
||||
'pathToFiles' => $this->pathToFiles,
|
||||
'initData' => $this->initData,
|
||||
];
|
||||
|
||||
$this->espoTester = new Tester($params);
|
||||
|
||||
$this->beforeSetUp();
|
||||
|
||||
try {
|
||||
$this->espoTester->install();
|
||||
$this->espoTester->loadData();
|
||||
} catch (Error $e) {
|
||||
throw new RuntimeException("Initialization error.", previous: $e);
|
||||
}
|
||||
|
||||
$this->auth($this->userName, $this->password, null, $this->authenticationMethod);
|
||||
|
||||
$this->beforeStartApplication();
|
||||
|
||||
$this->espoApplication = $this->espoTester->getApplication(reload: true);
|
||||
|
||||
$this->afterStartApplication();
|
||||
|
||||
$this->setUpTransaction();
|
||||
|
||||
$this->espoApplication = $this->espoTester->getApplication();
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates. The user is supposed to be created by the test before.
|
||||
*
|
||||
* @param ?string $username A username. Null for the system user.
|
||||
*/
|
||||
protected function authenticate(
|
||||
?string $username = null,
|
||||
?string $method = null,
|
||||
?RequestWrapper $request = null,
|
||||
): void {
|
||||
|
||||
$this->auth($username, authenticationMethod: $method, request: $request);
|
||||
|
||||
$this->getEntityManager()->getMetadata()->updateData();
|
||||
|
||||
$this->getContainer()->reset([
|
||||
'entityManager',
|
||||
'ormMetadataData',
|
||||
'ormDefs',
|
||||
'metadata',
|
||||
'config',
|
||||
'module',
|
||||
'fileManager',
|
||||
'applicationParams',
|
||||
CacheServiceName::SYSTEM,
|
||||
]);
|
||||
|
||||
if ($username === null && $method === null) {
|
||||
$this->espoApplication->setupSystemUser();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->espoTester->login();
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-create an application.
|
||||
*
|
||||
* @param bool $reuse Re-use the previous application for performance.
|
||||
* @param bool $noUser Do not set current user. May be needed when testing authentication.
|
||||
*/
|
||||
protected function reCreateApplication(
|
||||
bool $reuse = false,
|
||||
bool $noUser = false,
|
||||
?BindingProcessor $binding = null,
|
||||
): void {
|
||||
|
||||
$this->espoApplication = $this->createApplication(
|
||||
binding: $binding,
|
||||
reuse: $reuse,
|
||||
noUser: $noUser,
|
||||
);
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
$isNotClean = $this->isNotCleanTest();
|
||||
|
||||
if (
|
||||
!$isNotClean &&
|
||||
$this->transactionManager?->isStarted()
|
||||
) {
|
||||
try {
|
||||
$this->transactionManager->rollback();
|
||||
} catch (Exception) {}
|
||||
}
|
||||
|
||||
$this->transactionManager = null;
|
||||
|
||||
$this->espoTester->terminate();
|
||||
$this->espoTester = null;
|
||||
$this->espoApplication = null;
|
||||
|
||||
if ($isNotClean) {
|
||||
Registry::$isCleanAndReady = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed>|string $userData Data or a user name.
|
||||
* @param ?array<string, mixed> $role
|
||||
*/
|
||||
protected function createUser($userData, ?array $role = null, bool $isPortal = false): User
|
||||
{
|
||||
return $this->espoTester->createUser($userData, $role, $isPortal);
|
||||
}
|
||||
|
||||
protected function beforeSetUp(): void
|
||||
{}
|
||||
|
||||
protected function beforeStartApplication(): void
|
||||
{}
|
||||
|
||||
protected function afterStartApplication(): void
|
||||
{}
|
||||
|
||||
/**
|
||||
* @param array<string, string> $headers
|
||||
* @param array<string, string> $queryParams
|
||||
* @param array<string, string> $cookieParams
|
||||
*/
|
||||
protected function createRequest(
|
||||
string $method,
|
||||
array $queryParams = [],
|
||||
array $headers = [],
|
||||
?string $body = null,
|
||||
array $routeParams = [],
|
||||
array $cookieParams = [],
|
||||
string $resourcePath = '',
|
||||
): RequestWrapper {
|
||||
|
||||
if (!str_starts_with($resourcePath, '/')) {
|
||||
$resourcePath = '/' . $resourcePath;
|
||||
}
|
||||
|
||||
$request = (new RequestFactory())
|
||||
->createRequest($method, "http://localhost$resourcePath?" . http_build_query($queryParams));
|
||||
|
||||
if (!$request instanceof ServerRequestInterface) {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
|
||||
$request = $request->withCookieParams($cookieParams);
|
||||
|
||||
foreach ($headers as $name => $value) {
|
||||
$request = $request->withHeader($name, $value);
|
||||
}
|
||||
|
||||
if ($body) {
|
||||
$request = $request->withBody(
|
||||
(new StreamFactory)->createStream($body)
|
||||
);
|
||||
|
||||
$contentType = $request->getHeaderLine('Content-Type');
|
||||
|
||||
if ($contentType === 'application/x-www-form-urlencoded') {
|
||||
parse_str($body, $parsedBody);
|
||||
|
||||
$request = $request->withParsedBody($parsedBody);
|
||||
}
|
||||
}
|
||||
|
||||
return new RequestWrapper($request, '', $routeParams);
|
||||
}
|
||||
|
||||
protected function createResponse(): ResponseWrapper
|
||||
{
|
||||
return new ResponseWrapper(
|
||||
(new ResponseFactory())->createResponse()
|
||||
);
|
||||
}
|
||||
|
||||
protected function fullReset(): void
|
||||
{
|
||||
$this->espoTester->setParam('fullReset', true);
|
||||
}
|
||||
|
||||
private function isNotCleanTest(): bool
|
||||
{
|
||||
if ($this->dataFile || $this->pathToFiles || $this->initData) {
|
||||
return true;
|
||||
}
|
||||
|
||||
try {
|
||||
$reflectionMethod = new ReflectionMethod($this, $this->name());
|
||||
$reflectionClass = new ReflectionClass($this);
|
||||
} catch (ReflectionException $e) {
|
||||
throw new RuntimeException(previous: $e);
|
||||
}
|
||||
|
||||
return $reflectionMethod->getAttributes(NoTransaction::class) ||
|
||||
$reflectionClass->getAttributes(NoTransaction::class);
|
||||
}
|
||||
|
||||
private function setUpTransaction(): void
|
||||
{
|
||||
$this->transactionManager = null;
|
||||
|
||||
if (!$this->isNotCleanTest()) {
|
||||
$this->transactionManager = $this->getEntityManager()->getTransactionManager();
|
||||
|
||||
$this->transactionManager->start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set and save config parameters.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
protected function setConfigParams(array $params): void
|
||||
{
|
||||
$configWriter = $this->getInjectableFactory()->create(ConfigWriter::class);
|
||||
$configWriter->setMultiple($params);
|
||||
$configWriter->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Closure(Binder): void $callback
|
||||
*/
|
||||
protected function prepareBinding(Closure $callback): BindingProcessor
|
||||
{
|
||||
return new class ($callback) implements BindingProcessor {
|
||||
/**
|
||||
* @param Closure(Binder): void $callback
|
||||
*/
|
||||
public function __construct(private Closure $callback) {}
|
||||
|
||||
public function process(Binder $binder): void
|
||||
{
|
||||
($this->callback)($binder);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
194
tests/integration/Core/DataLoader.php
Normal file
194
tests/integration/Core/DataLoader.php
Normal file
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace tests\integration\Core;
|
||||
|
||||
use Espo\Core\Application;
|
||||
use Espo\Core\Container;
|
||||
use Espo\Core\Utils\Config;
|
||||
use Espo\Core\Utils\File\Manager as FileManager;
|
||||
use Espo\Core\Utils\PasswordHash;
|
||||
use Espo\Entities\Preferences;
|
||||
use Espo\Entities\User;
|
||||
use Espo\ORM\EntityManager;
|
||||
use Exception;
|
||||
use RuntimeException;
|
||||
|
||||
class DataLoader
|
||||
{
|
||||
private Application $application;
|
||||
private PasswordHash $passwordHash;
|
||||
|
||||
public function __construct(Application $application)
|
||||
{
|
||||
$this->application = $application;
|
||||
|
||||
$config = $this->getContainer()->getByClass(Config::class);
|
||||
|
||||
$this->passwordHash = new PasswordHash($config);
|
||||
}
|
||||
|
||||
private function getContainer(): Container
|
||||
{
|
||||
return $this->application->getContainer();
|
||||
}
|
||||
|
||||
private function getPasswordHash(): PasswordHash
|
||||
{
|
||||
return $this->passwordHash;
|
||||
}
|
||||
|
||||
public function loadData(string $dataFile): void
|
||||
{
|
||||
if (!file_exists($dataFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$data = include($dataFile);
|
||||
|
||||
$this->handleData($data);
|
||||
}
|
||||
|
||||
public function setData(array $data): void
|
||||
{
|
||||
$this->handleData($data);
|
||||
}
|
||||
|
||||
protected function handleData(array $fullData): void
|
||||
{
|
||||
foreach ($fullData as $type => $data) {
|
||||
if ($type === 'files') {
|
||||
$this->loadFiles($data);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($type === 'entities') {
|
||||
$this->loadEntities($data);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($type === 'data') {
|
||||
$this->loadData($data);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($type === 'config') {
|
||||
$this->loadConfig($data);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($type === 'preferences') {
|
||||
$this->loadPreferences($data);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
throw new RuntimeException('DataLoader: Data type is not supported in dataFile.');
|
||||
}
|
||||
}
|
||||
|
||||
public function loadFiles(string $path): void
|
||||
{
|
||||
try {
|
||||
$fileManager = $this->getContainer()->getByClass(FileManager::class);
|
||||
|
||||
$fileManager->copy($path, '.', true);
|
||||
} catch (Exception $e) {
|
||||
throw new RuntimeException('Error loadFiles: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
protected function loadEntities(array $data)
|
||||
{
|
||||
$entityManager = $this->getContainer()->getByClass(EntityManager::class);
|
||||
|
||||
foreach ($data as $entityType => $entities) {
|
||||
foreach($entities as $entityData) {
|
||||
$entity = $entityManager->getEntityById($entityType, $entityData['id']);
|
||||
|
||||
if (empty($entity)) {
|
||||
$entity = $entityManager->getNewEntity($entityType);
|
||||
}
|
||||
|
||||
foreach($entityData as $field => $value) {
|
||||
if ($field == 'password' && $entityType == User::ENTITY_TYPE) {
|
||||
$value = $this->getPasswordHash()->hash($value);
|
||||
}
|
||||
|
||||
$entity->set($field, $value);
|
||||
}
|
||||
|
||||
try {
|
||||
$entityManager->saveEntity($entity);
|
||||
} catch (Exception $e) {
|
||||
throw new RuntimeException('Save entity error.', previous: $e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function loadConfig(array $data): void
|
||||
{
|
||||
if (empty($data)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$config = $this->getContainer()->getByClass(Config::class);
|
||||
$config->set($data);
|
||||
|
||||
try {
|
||||
$config->save();
|
||||
} catch (Exception $e) {
|
||||
throw new RuntimeException('Error loadConfig: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private function loadPreferences(array $data): void
|
||||
{
|
||||
$entityManager = $this->getContainer()->getByClass(EntityManager::class);
|
||||
|
||||
foreach ($data as $userId => $params) {
|
||||
$entityManager->getRepository(Preferences::ENTITY_TYPE)->resetToDefaults($userId);
|
||||
|
||||
$preferences = $entityManager->getEntityById(Preferences::ENTITY_TYPE, $userId);
|
||||
$preferences->set($params);
|
||||
|
||||
try {
|
||||
$entityManager->saveEntity($preferences);
|
||||
} catch (Exception $e) {
|
||||
throw new RuntimeException('Error loadPreferences: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
36
tests/integration/Core/NoTransaction.php
Normal file
36
tests/integration/Core/NoTransaction.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace integration\Core;
|
||||
|
||||
use Attribute;
|
||||
|
||||
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
|
||||
class NoTransaction
|
||||
{}
|
||||
40
tests/integration/Core/Registry.php
Normal file
40
tests/integration/Core/Registry.php
Normal file
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace tests\integration\Core;
|
||||
|
||||
class Registry
|
||||
{
|
||||
public static $isCleanAndReady = false;
|
||||
|
||||
/**
|
||||
* Set before the first test run, and never set back.
|
||||
*/
|
||||
public static $isNamespaceConfigured = false;
|
||||
}
|
||||
660
tests/integration/Core/Tester.php
Normal file
660
tests/integration/Core/Tester.php
Normal file
@@ -0,0 +1,660 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace tests\integration\Core;
|
||||
|
||||
use Composer\Autoload\ClassLoader;
|
||||
use Doctrine\DBAL\Exception;
|
||||
use Doctrine\DBAL\Schema\SchemaException;
|
||||
use Doctrine\DBAL\Schema\Table;
|
||||
use Espo\Core\Authentication\Authentication;
|
||||
use Espo\Core\Authentication\AuthenticationData;
|
||||
use Espo\Core\Application;
|
||||
use Espo\Core\Binding\BindingProcessor;
|
||||
use Espo\Core\Exceptions\Error;
|
||||
use Espo\Core\Exceptions\Forbidden;
|
||||
use Espo\Core\Exceptions\NotFound;
|
||||
use Espo\Core\Exceptions\ServiceUnavailable;
|
||||
use Espo\Core\InjectableFactory;
|
||||
use Espo\Core\ORM\DatabaseParamsFactory;
|
||||
use Espo\Core\Portal\Application as PortalApplication;
|
||||
use Espo\Core\Api\RequestWrapper;
|
||||
use Espo\Core\Api\ResponseWrapper;
|
||||
use Espo\Core\ApplicationRunners\Rebuild;
|
||||
use Espo\Core\Utils\Config;
|
||||
use Espo\Core\Utils\Database\Dbal\ConnectionFactoryFactory;
|
||||
use Espo\Core\Utils\Database\Helper as DatabaseHelper;
|
||||
use Espo\Core\Utils\File\Manager as FileManager;
|
||||
use Espo\Core\Utils\PasswordHash;
|
||||
use Espo\Entities\PortalRole;
|
||||
use Espo\Entities\Role;
|
||||
use Espo\Entities\User;
|
||||
use Espo\ORM\Entity;
|
||||
use Espo\ORM\EntityManager;
|
||||
use Installer;
|
||||
use Psr\Http\Message\ServerRequestInterface as Psr7Request;
|
||||
use RuntimeException;
|
||||
use Slim\Psr7\Factory\RequestFactory;
|
||||
use Slim\Psr7\Response;
|
||||
|
||||
class Tester
|
||||
{
|
||||
private string $configPath = 'tests/integration/config.php';
|
||||
private string $envConfigPath = 'tests/integration/config-env.php';
|
||||
|
||||
private string $buildPath = 'build';
|
||||
private string $installPath = 'build/test';
|
||||
private string $testDataPath = 'tests/integration/testData';
|
||||
private string $packageJsonPath = 'package.json';
|
||||
|
||||
private ?Application $application = null;
|
||||
private ?DataLoader $dataLoader = null;
|
||||
private array $params;
|
||||
|
||||
private ?string $userName = null;
|
||||
private ?string $password = null;
|
||||
|
||||
private ?string $portalId = null;
|
||||
private ?string $authenticationMethod = null;
|
||||
private string $defaultUserPassword = '1';
|
||||
|
||||
private ?RequestWrapper $request = null;
|
||||
|
||||
public function __construct(array $params)
|
||||
{
|
||||
$this->params = $this->normalizeParams($params);
|
||||
}
|
||||
|
||||
private function normalizeParams(array $params): array
|
||||
{
|
||||
$namespaceToRemove = 'tests\\integration\\Espo';
|
||||
|
||||
$classPath = preg_replace(
|
||||
'/^' . preg_quote($namespaceToRemove) . '\\\\(.+)Test$/',
|
||||
'${1}',
|
||||
$params['className']
|
||||
);
|
||||
|
||||
$params['testDataPath'] = realpath($this->testDataPath);
|
||||
|
||||
if (isset($params['dataFile'])) {
|
||||
$params['dataFile'] = realpath($this->testDataPath) . '/' . $params['dataFile'];
|
||||
|
||||
$dataFile = $params['dataFile'];
|
||||
|
||||
if (!file_exists($dataFile)) {
|
||||
throw new RuntimeException("File '$dataFile' not found.");
|
||||
}
|
||||
} else {
|
||||
$params['dataFile'] = realpath($this->testDataPath) . '/' . str_replace('\\', '/', $classPath) . '.php';
|
||||
}
|
||||
|
||||
if (isset($params['pathToFiles'])) {
|
||||
$params['pathToFiles'] = realpath($this->testDataPath) . '/' . $params['pathToFiles'];
|
||||
|
||||
$pathToFiles = $params['pathToFiles'];
|
||||
|
||||
if (!file_exists($pathToFiles)) {
|
||||
throw new RuntimeException("File '$pathToFiles' not found.");
|
||||
}
|
||||
} else {
|
||||
$params['pathToFiles'] = realpath($this->testDataPath) . '/' . str_replace('\\', '/', $classPath);
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
private function getParam(string $name): mixed
|
||||
{
|
||||
if (isset($this->params[$name])) {
|
||||
return $this->params[$name];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function setParam(string $name, mixed $value): void
|
||||
{
|
||||
$this->params[$name] = $value;
|
||||
}
|
||||
|
||||
protected function getTestConfigData(): array
|
||||
{
|
||||
$this->changeDirToBase();
|
||||
|
||||
if (file_exists($this->configPath)) {
|
||||
$data = include($this->configPath);
|
||||
} else if (getenv('TEST_DATABASE_NAME')) {
|
||||
$data = include($this->envConfigPath);
|
||||
} else {
|
||||
throw new RuntimeException("Config `$this->configPath` not found. Create the config file.");
|
||||
}
|
||||
|
||||
$packageData = json_decode(file_get_contents($this->packageJsonPath));
|
||||
|
||||
$version = $packageData->version;
|
||||
|
||||
$data['version'] = $version;
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function setLastModifiedTime($time): void
|
||||
{
|
||||
$configData = $this->getTestConfigData();
|
||||
|
||||
if (array_key_exists('lastModifiedTime', $configData) && $configData['lastModifiedTime'] === $time) {
|
||||
return;
|
||||
}
|
||||
|
||||
$configData['lastModifiedTime'] = $time;
|
||||
|
||||
(new FileManager())->putPhpContents($this->configPath, $configData);
|
||||
}
|
||||
|
||||
public function auth(
|
||||
?string $userName,
|
||||
?string $password = null,
|
||||
?string $portalId = null,
|
||||
?string $authenticationMethod = null,
|
||||
?RequestWrapper $request = null,
|
||||
): void {
|
||||
|
||||
$this->userName = $userName;
|
||||
$this->password = $password;
|
||||
$this->portalId = $portalId;
|
||||
$this->authenticationMethod = $authenticationMethod;
|
||||
$this->request = $request;
|
||||
}
|
||||
|
||||
public function getApplication(
|
||||
bool $reload = false,
|
||||
bool $clearCache = true,
|
||||
?string $portalId = null,
|
||||
?BindingProcessor $binding = null,
|
||||
bool $reuse = false,
|
||||
bool $noUser = false,
|
||||
): Application {
|
||||
|
||||
if ($this->application && !$reload) {
|
||||
return $this->application;
|
||||
}
|
||||
|
||||
$portalId ??= $this->portalId ?? null;
|
||||
|
||||
$applicationParams = new Application\ApplicationParams(
|
||||
noErrorHandler: true,
|
||||
binding: $binding,
|
||||
services: $this->prepareServices($reuse),
|
||||
);
|
||||
|
||||
if ($clearCache) {
|
||||
$this->clearCache();
|
||||
}
|
||||
|
||||
if ($portalId) {
|
||||
try {
|
||||
$this->application = new PortalApplication($portalId, $applicationParams);
|
||||
} catch (Forbidden|NotFound $e) {
|
||||
throw new RuntimeException(previous: $e);
|
||||
}
|
||||
} else {
|
||||
$this->application = new Application($applicationParams);
|
||||
}
|
||||
|
||||
if (!$noUser) {
|
||||
if (isset($this->userName) || $this->authenticationMethod) {
|
||||
$this->login();
|
||||
} else {
|
||||
$this->application->setupSystemUser();
|
||||
}
|
||||
}
|
||||
|
||||
return $this->application;
|
||||
}
|
||||
|
||||
private function getDataLoader(): DataLoader
|
||||
{
|
||||
if (!isset($this->dataLoader)) {
|
||||
$this->dataLoader = new DataLoader($this->getApplication());
|
||||
}
|
||||
|
||||
return $this->dataLoader;
|
||||
}
|
||||
|
||||
private function changeDirToBase(): void
|
||||
{
|
||||
$installPath = str_replace('/', DIRECTORY_SEPARATOR, $this->installPath);
|
||||
|
||||
$baseDir = str_replace(DIRECTORY_SEPARATOR . $installPath, '', getcwd());
|
||||
|
||||
chdir($baseDir);
|
||||
set_include_path($baseDir);
|
||||
}
|
||||
|
||||
public function terminate(): void
|
||||
{
|
||||
$this->changeDirToBase();
|
||||
|
||||
if ($this->getParam('fullReset')) {
|
||||
$this->setLastModifiedTime(null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws Error
|
||||
*/
|
||||
public function install(): void
|
||||
{
|
||||
$fileManager = new FileManager();
|
||||
|
||||
$configData = $this->getTestConfigData();
|
||||
|
||||
$latestEspoDir = Utils::getLatestBuiltPath($this->buildPath);
|
||||
|
||||
if (empty($latestEspoDir)) {
|
||||
throw new RuntimeException("Espo build is not found. Run `grunt test`.");
|
||||
}
|
||||
|
||||
if (!isset($configData['siteUrl']) && file_exists('data/config.php')) {
|
||||
$mainConfigData = include('data/config.php');
|
||||
|
||||
if (isset($mainConfigData['siteUrl'])) {
|
||||
$configData['siteUrl'] = $mainConfigData['siteUrl'] . '/' . $this->installPath;
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($configData['siteUrl'])) {
|
||||
$this->params['siteUrl'] = $configData['siteUrl'];
|
||||
}
|
||||
|
||||
if (!file_exists($this->installPath)) {
|
||||
$fileManager->mkdir($this->installPath);
|
||||
}
|
||||
|
||||
if (!is_writable($this->installPath)) {
|
||||
throw new RuntimeException("Dir '$this->installPath' is not writable. Check permissions.");
|
||||
}
|
||||
|
||||
$this->reset($fileManager, $latestEspoDir);
|
||||
|
||||
Utils::fixUndefinedVariables();
|
||||
|
||||
chdir($this->installPath);
|
||||
set_include_path($this->installPath);
|
||||
|
||||
if (!file_exists('bootstrap.php')) {
|
||||
throw new RuntimeException("Could not read bootstrap.php.");
|
||||
}
|
||||
|
||||
require_once('install/core/Installer.php');
|
||||
|
||||
$applicationParams = new Application\ApplicationParams(noErrorHandler: true);
|
||||
|
||||
$installer = new Installer($applicationParams);
|
||||
|
||||
$installer->saveData(array_merge($configData, [
|
||||
'language' => 'en_US'
|
||||
]));
|
||||
|
||||
$installer->saveConfig($configData);
|
||||
|
||||
$app = new Application($applicationParams);
|
||||
|
||||
try {
|
||||
$this->createDatabaseIfDoesNotExist($app);
|
||||
$this->prepareDatabase($app);
|
||||
} catch (Exception $e) {
|
||||
throw new RuntimeException("DBAL error.", previous: $e);
|
||||
}
|
||||
|
||||
$installer = new Installer($applicationParams); // reload installer to have all config data
|
||||
$installer->rebuild();
|
||||
$installer->setSuccess();
|
||||
|
||||
Registry::$isCleanAndReady = true;
|
||||
|
||||
if (!Registry::$isNamespaceConfigured) {
|
||||
$this->configureNamespace();
|
||||
}
|
||||
}
|
||||
|
||||
// PDO can't be instantiated as dbname is set but database does not exist.
|
||||
|
||||
/**
|
||||
* @throws Exception
|
||||
*/
|
||||
private function createDatabaseIfDoesNotExist(Application $app): void
|
||||
{
|
||||
$injectableFactory = $app->getContainer()->getByClass(InjectableFactory::class);
|
||||
|
||||
$databaseHelper = $injectableFactory->create(DatabaseHelper::class);
|
||||
$databaseParamsFactory = $injectableFactory->create(DatabaseParamsFactory::class);
|
||||
$connectionFactoryFactory = $injectableFactory->create(ConnectionFactoryFactory::class);
|
||||
|
||||
$params = $databaseParamsFactory->create();
|
||||
|
||||
$dbname = $params->getName();
|
||||
|
||||
if (!$dbname) {
|
||||
throw new RuntimeException('No "dbname" in database config.');
|
||||
}
|
||||
|
||||
$params = $params->withName(null);
|
||||
|
||||
$pdo = $databaseHelper->createPDO($params);
|
||||
|
||||
$connection = $connectionFactoryFactory
|
||||
->create($params->getPlatform(), $pdo)
|
||||
->create($params);
|
||||
|
||||
$schemaManager = $connection->createSchemaManager();
|
||||
$platform = $connection->getDatabasePlatform();
|
||||
|
||||
if (in_array($dbname, $schemaManager->listDatabases())) {
|
||||
return;
|
||||
}
|
||||
|
||||
$schemaManager->createDatabase($platform->quoteIdentifier($dbname));
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws SchemaException
|
||||
* @throws Exception
|
||||
*/
|
||||
private function prepareDatabase(Application $app): void
|
||||
{
|
||||
if (Registry::$isCleanAndReady) {
|
||||
return;
|
||||
}
|
||||
|
||||
$databaseHelper = $app->getContainer()
|
||||
->getByClass(InjectableFactory::class)
|
||||
->create(DatabaseHelper::class);
|
||||
|
||||
$schemaManager = $databaseHelper->getDbalConnection()->createSchemaManager();
|
||||
$platform = $databaseHelper->getDbalConnection()->getDatabasePlatform();
|
||||
|
||||
$pdo = $databaseHelper->getPDO();
|
||||
|
||||
$tables = $schemaManager->listTableNames();
|
||||
|
||||
foreach ($tables as $table) {
|
||||
$sql = $platform->getDropTableSQL(new Table($table));
|
||||
|
||||
$pdo->query($sql);
|
||||
}
|
||||
}
|
||||
|
||||
private function reset(FileManager $fileManager, string $latestEspoDir): void
|
||||
{
|
||||
$configData = $this->getTestConfigData();
|
||||
|
||||
$fullReset = true;
|
||||
|
||||
if (file_exists($latestEspoDir . '/application')) {
|
||||
$modifiedTime = filemtime($latestEspoDir . '/application');
|
||||
|
||||
if (
|
||||
!$this->getParam('fullReset') &&
|
||||
isset($configData['lastModifiedTime']) &&
|
||||
$configData['lastModifiedTime'] == $modifiedTime
|
||||
) {
|
||||
$fullReset = false;
|
||||
}
|
||||
|
||||
$this->setLastModifiedTime($modifiedTime);
|
||||
}
|
||||
|
||||
if ($fullReset) {
|
||||
if ($this->isShellEnabled()) {
|
||||
shell_exec('rm -rf "' . $this->installPath . '"');
|
||||
shell_exec('cp -r "' . $latestEspoDir . '" "' . $this->installPath . '"');
|
||||
} else {
|
||||
$fileManager->removeInDir($this->installPath);
|
||||
$fileManager->copy($latestEspoDir, $this->installPath, true);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$fileManager->removeInDir($this->installPath . '/data');
|
||||
$fileManager->removeInDir($this->installPath . '/custom/Espo/Custom');
|
||||
$fileManager->removeInDir($this->installPath . '/client/custom');
|
||||
$fileManager->unlink($this->installPath . '/install/config.php');
|
||||
}
|
||||
|
||||
public function loadData(): void
|
||||
{
|
||||
$applyChanges = false;
|
||||
|
||||
if (!empty($this->params['pathToFiles']) && file_exists($this->params['pathToFiles'])) {
|
||||
$this->getDataLoader()->loadFiles($this->params['pathToFiles']);
|
||||
|
||||
$this->getApplication(true)->run(Rebuild::class);
|
||||
}
|
||||
|
||||
if (!empty($this->params['dataFile']) && file_exists($this->params['dataFile'])) {
|
||||
$this->getDataLoader()->loadData($this->params['dataFile']);
|
||||
|
||||
$applyChanges = true;
|
||||
}
|
||||
|
||||
if (!empty($this->params['initData'])) {
|
||||
$this->getDataLoader()->setData($this->params['initData']);
|
||||
|
||||
$applyChanges = true;
|
||||
}
|
||||
|
||||
if ($applyChanges) {
|
||||
$this->getApplication(true)->run(Rebuild::class);
|
||||
}
|
||||
}
|
||||
|
||||
public function clearCache(): void
|
||||
{
|
||||
$this->clearVars();
|
||||
|
||||
(new FileManager())->removeInDir('data/cache');
|
||||
}
|
||||
|
||||
private function clearVars(): void
|
||||
{
|
||||
$this->dataLoader = null;
|
||||
$this->application = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a user with roles.
|
||||
*
|
||||
* @param string|array<string, mixed> $userData If string, then it's a userName with the default password.
|
||||
*/
|
||||
public function createUser($userData, ?array $roleData = null, bool $isPortal = false): User
|
||||
{
|
||||
if (!is_array($userData)) {
|
||||
$userData = [
|
||||
'userName' => $userData,
|
||||
'lastName' => $userData,
|
||||
];
|
||||
}
|
||||
|
||||
if (!empty($roleData)) {
|
||||
if (!isset($roleData['name'])) {
|
||||
$roleData['name'] = $userData['userName'] . 'Role';
|
||||
}
|
||||
|
||||
$role = $this->createRole($roleData, $isPortal);
|
||||
|
||||
$fieldName = $isPortal ? 'portalRolesIds' : 'rolesIds';
|
||||
|
||||
if (!isset($userData[$fieldName])) {
|
||||
$userData[$fieldName] = [];
|
||||
}
|
||||
|
||||
$userData[$fieldName][] = $role->getId();
|
||||
}
|
||||
|
||||
$application = $this->getApplication();
|
||||
|
||||
$entityManager = $application->getContainer()->getByClass(EntityManager::class);
|
||||
$config = $application->getContainer()->getByClass(Config::class);
|
||||
|
||||
if (!isset($userData['password'])) {
|
||||
$userData['password'] = $this->defaultUserPassword;
|
||||
}
|
||||
|
||||
$passwordHash = new PasswordHash($config);
|
||||
|
||||
$userData['password'] = $passwordHash->hash($userData['password']);
|
||||
|
||||
if ($isPortal) {
|
||||
$userData['type'] = 'portal';
|
||||
}
|
||||
|
||||
$user = $entityManager->getNewEntity(User::ENTITY_TYPE);
|
||||
$user->setMultiple($userData);
|
||||
|
||||
$entityManager->saveEntity($user);
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function createRole(array $roleData, bool $isPortal = false): Entity
|
||||
{
|
||||
$entityType = $isPortal ? PortalRole::ENTITY_TYPE : Role::ENTITY_TYPE;
|
||||
|
||||
if (isset($roleData['data']) && is_array($roleData['data'])) {
|
||||
$roleData['data'] = json_encode($roleData['data']);
|
||||
}
|
||||
|
||||
if (isset($roleData['fieldData']) && is_array($roleData['fieldData'])) {
|
||||
$roleData['fieldData'] = json_encode($roleData['fieldData']);
|
||||
}
|
||||
|
||||
$application = $this->getApplication();
|
||||
$entityManager = $application->getContainer()->getByClass(EntityManager::class);
|
||||
|
||||
$role = $entityManager->getNewEntity($entityType);
|
||||
$role->set($roleData);
|
||||
$entityManager->saveEntity($role);
|
||||
|
||||
return $role;
|
||||
}
|
||||
|
||||
public function normalizePath($path): string
|
||||
{
|
||||
return $this->getParam('testDataPath') . '/' . $path;
|
||||
}
|
||||
|
||||
private function isShellEnabled(): bool
|
||||
{
|
||||
if (!function_exists('exec') || !is_callable('shell_exec')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$result = shell_exec("echo test");
|
||||
|
||||
if (empty($result)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function login(): void
|
||||
{
|
||||
$this->password ??= $this->defaultUserPassword;
|
||||
|
||||
$authenticationData = AuthenticationData::create()
|
||||
->withUsername($this->userName)
|
||||
->withPassword($this->password)
|
||||
->withMethod($this->authenticationMethod);
|
||||
|
||||
$auth = $this->application
|
||||
->getInjectableFactory()
|
||||
->createWith(Authentication::class, ['allowAnyAccess' => false]);
|
||||
|
||||
/** @var Psr7Request $requestWrapped */
|
||||
$requestWrapped = (new RequestFactory())->createRequest('POST', '');
|
||||
|
||||
$request = $this->request ?? new RequestWrapper($requestWrapped);
|
||||
|
||||
$response = new ResponseWrapper(new Response());
|
||||
|
||||
try {
|
||||
$auth->login($authenticationData, $request, $response);
|
||||
} catch (ServiceUnavailable|Forbidden $e) {
|
||||
throw new RuntimeException(previous: $e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, object>
|
||||
*/
|
||||
private function prepareServices(bool $reuse): array
|
||||
{
|
||||
$services = [];
|
||||
|
||||
if ($reuse && $this->application) {
|
||||
$this->application
|
||||
->getContainer()
|
||||
->getByClass(EntityManager::class)
|
||||
->getMetadata()
|
||||
->updateData();
|
||||
|
||||
$serviceList = [
|
||||
'entityManager',
|
||||
'ormMetadataData',
|
||||
'ormDefs',
|
||||
'metadata',
|
||||
];
|
||||
|
||||
foreach ($serviceList as $service) {
|
||||
$instance = $this->application->getContainer()->get($service);
|
||||
|
||||
$services[$service] = $instance;
|
||||
}
|
||||
}
|
||||
|
||||
return $services;
|
||||
}
|
||||
|
||||
/**
|
||||
* Called after cwd if set to the install-path.
|
||||
*/
|
||||
private function configureNamespace(): void
|
||||
{
|
||||
$classLoader = new ClassLoader();
|
||||
|
||||
$classLoader->setPsr4("Espo\\Custom\\", "custom/Espo/Custom");
|
||||
$classLoader->register();
|
||||
|
||||
Registry::$isNamespaceConfigured = true;
|
||||
}
|
||||
}
|
||||
145
tests/integration/Core/Utils.php
Normal file
145
tests/integration/Core/Utils.php
Normal file
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
/************************************************************************
|
||||
* This file is part of EspoCRM.
|
||||
*
|
||||
* EspoCRM – Open Source CRM application.
|
||||
* Copyright (C) 2014-2026 EspoCRM, Inc.
|
||||
* Website: https://www.espocrm.com
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*
|
||||
* The interactive user interfaces in modified source and object code versions
|
||||
* of this program must display Appropriate Legal Notices, as required under
|
||||
* Section 5 of the GNU Affero General Public License version 3.
|
||||
*
|
||||
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
|
||||
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
|
||||
************************************************************************/
|
||||
|
||||
namespace tests\integration\Core;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class Utils
|
||||
{
|
||||
/**
|
||||
* Get the latest EspoCRM built path.
|
||||
*
|
||||
* @param string $path
|
||||
* @return ?string
|
||||
*/
|
||||
public static function getLatestBuiltPath($path): ?string
|
||||
{
|
||||
$archives = [];
|
||||
|
||||
$buildDir = dir($path);
|
||||
|
||||
if (!$buildDir) {
|
||||
throw new RuntimeException("No test build. Run `grunt test`.");
|
||||
}
|
||||
|
||||
while ($folderName = $buildDir->read()) {
|
||||
if ($folderName === '.'|| $folderName === '..' || empty($folderName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$pattern = '/^EspoCRM-([0-9]+)\.([0-9]+)(?:\.([0-9]+))?(?:-((a|alpha|b|beta|pre|rc)([0-9]+)?)?)?$/';
|
||||
|
||||
if (preg_match($pattern, $folderName)) {
|
||||
$archives[] = $folderName;
|
||||
}
|
||||
}
|
||||
|
||||
if (count($archives) > 0) {
|
||||
static::sortVersions($archives);
|
||||
|
||||
return $path . '/' . $archives[count($archives) - 1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function sortVersions(&$existVersions)
|
||||
{
|
||||
usort($existVersions, ["\\tests\\integration\\Core\\Utils", "versionCmp"]);
|
||||
}
|
||||
|
||||
public static function versionCmp($a, $b): int
|
||||
{
|
||||
$order = ['a' => 0, 'alpha' => 1, 'b' => 2, 'beta' => 3, 'pre' => 4, 'rc' => 5];
|
||||
|
||||
$ma = $mb = [];
|
||||
|
||||
$pattern = '/^EspoCRM-([0-9]+)\.([0-9]+)(?:\.([0-9]+))?(?:-((a|alpha|b|beta|pre|rc)[0-9]+)?)?$/';
|
||||
|
||||
preg_match($pattern, $a, $ma);
|
||||
preg_match($pattern, $b, $mb);
|
||||
|
||||
if ($ma[1] != $mb[1]) {
|
||||
return (int) $ma[1] < (int) $mb[1] ? -1 : 1;
|
||||
}
|
||||
|
||||
if ($ma[2] != $mb[2]) {
|
||||
return (int) $ma[2] < (int) $mb[2] ? -1 : 1;
|
||||
}
|
||||
|
||||
if (!isset($ma[3])) {
|
||||
$ma[3] = 0;
|
||||
}
|
||||
|
||||
if (!isset($mb[3])) {
|
||||
$mb[3] = 0;
|
||||
}
|
||||
|
||||
if ($ma[3] != $mb[3]) {
|
||||
return (int) $ma[3] < (int) $mb[3] ? -1 : 1;
|
||||
}
|
||||
|
||||
if (isset($ma[4]) && !isset($mb[4])) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!isset($ma[4]) && isset($mb[4])) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (@$ma[5] != @$mb[5]) {
|
||||
return ($order[$ma[5]] < $order[$mb[5]]) ? -1 : 1;
|
||||
}
|
||||
|
||||
if (@$ma[4] != @$mb[4]) {
|
||||
return ($ma[4] < $mb[4]) ? -1 : 1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public static function fixUndefinedVariables(): void
|
||||
{
|
||||
$list = [
|
||||
'REQUEST_METHOD',
|
||||
'REMOTE_ADDR',
|
||||
'SERVER_NAME',
|
||||
'SERVER_PORT',
|
||||
'REQUEST_URI',
|
||||
'HTTPS',
|
||||
];
|
||||
|
||||
foreach ($list as $name) {
|
||||
if (!array_key_exists($name, $_SERVER)) {
|
||||
$_SERVER[$name] = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user