/sources`, use something like:
+```
+tests/php-static-analysis/vendor/bin/phpstan analyse \
+ --configuration ./tests/php-static-analysis/config/for-package.dist.neon \
+ --error-format raw \
+ setup sources
+```
+
+### Adjust configuration for a particular CI repository / job
+TODO
\ No newline at end of file
diff --git a/tests/php-static-analysis/composer.json b/tests/php-static-analysis/composer.json
new file mode 100644
index 000000000..1cf76a892
--- /dev/null
+++ b/tests/php-static-analysis/composer.json
@@ -0,0 +1,5 @@
+{
+ "require": {
+ "phpstan/phpstan": "^2.1"
+ }
+}
diff --git a/tests/php-static-analysis/composer.lock b/tests/php-static-analysis/composer.lock
new file mode 100644
index 000000000..36d8e1005
--- /dev/null
+++ b/tests/php-static-analysis/composer.lock
@@ -0,0 +1,72 @@
+{
+ "_readme": [
+ "This file locks the dependencies of your project to a known state",
+ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
+ "This file is @generated automatically"
+ ],
+ "content-hash": "cc6d7580a5e98236d68d8b91de9ddebb",
+ "packages": [
+ {
+ "name": "phpstan/phpstan",
+ "version": "2.1.33",
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/phpstan/phpstan/zipball/9e800e6bee7d5bd02784d4c6069b48032d16224f",
+ "reference": "9e800e6bee7d5bd02784d4c6069b48032d16224f",
+ "shasum": ""
+ },
+ "require": {
+ "php": "^7.4|^8.0"
+ },
+ "conflict": {
+ "phpstan/phpstan-shim": "*"
+ },
+ "bin": [
+ "phpstan",
+ "phpstan.phar"
+ ],
+ "type": "library",
+ "autoload": {
+ "files": [
+ "bootstrap.php"
+ ]
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "MIT"
+ ],
+ "description": "PHPStan - PHP Static Analysis Tool",
+ "keywords": [
+ "dev",
+ "static analysis"
+ ],
+ "support": {
+ "docs": "https://phpstan.org/user-guide/getting-started",
+ "forum": "https://github.com/phpstan/phpstan/discussions",
+ "issues": "https://github.com/phpstan/phpstan/issues",
+ "security": "https://github.com/phpstan/phpstan/security/policy",
+ "source": "https://github.com/phpstan/phpstan-src"
+ },
+ "funding": [
+ {
+ "url": "https://github.com/ondrejmirtes",
+ "type": "github"
+ },
+ {
+ "url": "https://github.com/phpstan",
+ "type": "github"
+ }
+ ],
+ "time": "2025-12-05T10:24:31+00:00"
+ }
+ ],
+ "packages-dev": [],
+ "aliases": [],
+ "minimum-stability": "stable",
+ "stability-flags": [],
+ "prefer-stable": false,
+ "prefer-lowest": false,
+ "platform": [],
+ "platform-dev": [],
+ "plugin-api-version": "2.6.0"
+}
diff --git a/tests/php-static-analysis/config/README.md b/tests/php-static-analysis/config/README.md
new file mode 100644
index 000000000..2ef085889
--- /dev/null
+++ b/tests/php-static-analysis/config/README.md
@@ -0,0 +1,29 @@
+## Disclaimer
+DON'T modify the following files without knowledge and discussing with the team:
+- base.dist.neon
+- for-package.dist.neon
+- for-module.dist.neon
+
+## Purpose of these files
+### base.dist.neon
+This configuration file contains the common parameters for all analysis, whereas it is a package, a module or something specific. Among others:
+- Rules level for analysis
+- PHP version to compare
+- Necessary files for autoloaders discovery and such
+- ...
+
+This file should not be modified for your specific needs, you should always include it and override the desired parameters. \
+See how it is done in `for-package.dist.neon` and `for-module.dist.neon` or on the documentation [here](https://phpstan.org/config-reference#multiple-files).
+
+### for-package.dist.neon
+This configuration file contains the parameters to analyse a package (iTop core, modules, third-party libs).
+
+### for-module.dist.neon
+This configuration file contains the parameters to analyse one or more modules only.
+
+## How / when can I modify these files?
+**You CAN'T!** \
+Well, unless there is a good reason and you talked about it with the team. But you should never modify them for a specific need on your local environment.
+
+- If you have a particular need for your local environment (eg. increase memory limit, change rules levels, analyse only a specific folder), check the [Configuration section](../#configuration) of the main README.md.
+- If you feel like there is need for an adjustment in the default configurations, discuss it with th team and make a PR.
\ No newline at end of file
diff --git a/tests/php-static-analysis/config/base.dist.neon b/tests/php-static-analysis/config/base.dist.neon
new file mode 100644
index 000000000..eaf30b872
--- /dev/null
+++ b/tests/php-static-analysis/config/base.dist.neon
@@ -0,0 +1,40 @@
+includes:
+ - php-includes/set-php-version-from-process.php # Workaround to set PHP version to the on running the CLI
+ # for an explanation of the baseline concept, see: https://phpstan.org/user-guide/baseline
+ #baseline HERE DO NOT REMOVE FOR CI
+
+parameters:
+ level: 0
+ #phpVersion: null # Explicitly commented as we rather use the detected version from the above include (`php-includes/target-php-version.php`)
+ editorUrl: 'phpstorm://open?file=%%file%%&line=%%line%%' # Open in PHPStorm as it's Combodo's default IDE
+ bootstrapFiles:
+ - ../../../approot.inc.php
+ - ../../../bootstrap.inc.php
+
+ scanFiles:
+ # Files necessary as they contain some declarations (constants, classes, functions, ...)
+ - ../../../approot.inc.php
+ - ../../../bootstrap.inc.php
+ excludePaths:
+ analyse:
+ # For third-party libs we should analyse them in a dedicated configuration as we can't improve / clean them which would
+ # prevent us from raising the rules level as we improve / clean our codebase
+ - ../../../lib # Irrelevant as we only want to analyze our codebase
+ - ../../../node_modules # Irrelevant as we only want to analyze our codebase
+ analyseAndScan:
+ # This file generates "unignorable errors" for the baseline due to its format, so we don't have any other choice than to exclude it.
+ # But mind that it will prevent PHPStan from warning us about PHP syntax errors in this file.
+ - ../../../core/oql/build/PHP/Lempar.php
+
+ #- ../../../data # Left and commented on purpose to show that we want to analyse the generated cache files
+
+ # Note 1: We can't analyse these folders as if a PHP file requires another PHP element declared in an XML file, it won't find it. So we rely only on `env-production`
+ # Note 2: Only the options selected during the setup will be analysed correctly in `env-production`. For unselected options, we still want to ignore them during the analysis as they would only give a false sentiment of security as their XML PHP classes / snippets / etc would not be tested.
+ - ../../../data/production-modules (?) # Irrelevent as it will already be in `env-production` (for local run only, not useful in the CI)
+ - ../../../datamodels # Irrelevent as it will already be in `env-production`
+ - ../../../extensions # Irrelevent as it will already be in `env-production` (for local run only, not useful in the CI)
+ - ../../../env-php-unit-tests (?) # Irrelevant as it will either already be in `env-production` or might be desynchronized from `env-production`
+ - ../../../env-toolkit (?) # Irrelevent as it will either already be in `env-production` or might be desynchronized from `env-production` (for local run only, not useful in the CI)
+
+ - ../../../tests (?) # Exclude tests for now
+ - ../../../toolkit (?) # Exlclude toolkit for now
diff --git a/tests/php-static-analysis/config/for-module.dist.neon b/tests/php-static-analysis/config/for-module.dist.neon
new file mode 100644
index 000000000..586be1801
--- /dev/null
+++ b/tests/php-static-analysis/config/for-module.dist.neon
@@ -0,0 +1,15 @@
+includes:
+ - base.dist.neon
+
+parameters:
+ paths:
+ # We just want to analyse the module folder(s), either:
+ # - Create your own `for-module.neon` file, include this one and override this parameter (see https://phpstan.org/config-reference#multiple-files)
+ # - Pass the module folder(s) in the commande line (see https://phpstan.org/config-reference#analysed-files)
+ scanDirectories:
+ # Unlike for `for-package.dist.neon`, here we need to scan all the folders to discover symbols, but we only want to analyse the module folder.
+ # We initially thought of doing it through the `excludePaths` param. by excluding everything but the module folder, but it doesn't seem to be possible, because it uses the `fnmatch()` function.
+ # As a workaround, we list here all the folders to scan.
+ #
+ # Scan the whole project and rely on the `excludePaths` param. to filter the unnecessary
+ - ../../..
diff --git a/tests/php-static-analysis/config/for-package.dist.neon b/tests/php-static-analysis/config/for-package.dist.neon
new file mode 100644
index 000000000..ff0d190eb
--- /dev/null
+++ b/tests/php-static-analysis/config/for-package.dist.neon
@@ -0,0 +1,7 @@
+includes:
+ - base.dist.neon
+
+parameters:
+ paths:
+ # We want to analyse almost the whole project, so we do a negative selection between the `paths` and `excludePaths` (see base.dist.neon) parameters
+ - ../../../
diff --git a/tests/php-static-analysis/config/php-includes/set-php-version-from-process.php b/tests/php-static-analysis/config/php-includes/set-php-version-from-process.php
new file mode 100644
index 000000000..921b907ce
--- /dev/null
+++ b/tests/php-static-analysis/config/php-includes/set-php-version-from-process.php
@@ -0,0 +1,25 @@
+DBDelete();
```
-Warning : when the condition is met the test is finished and following code will be ignored !
+> [!WARNING]
+> When the condition is met the test is finished and following code will be ignored !
Another way to do is using try/catch blocks, for example :
```php
diff --git a/tests/php-unit-tests/integration-tests/itop-hub-connector/AjaxPageTest.php b/tests/php-unit-tests/integration-tests/itop-hub-connector/AjaxPageTest.php
index ef433203c..dbd1595fe 100644
--- a/tests/php-unit-tests/integration-tests/itop-hub-connector/AjaxPageTest.php
+++ b/tests/php-unit-tests/integration-tests/itop-hub-connector/AjaxPageTest.php
@@ -28,14 +28,14 @@ class AjaxPageTest extends ItopDataTestCase
$iLastCompilation = filemtime(APPROOT.'env-production');
// When
- $sOutput = $this->CallItopUrl(
- "/pages/exec.php?exec_module=itop-hub-connector&exec_page=ajax.php",
+ $sOutput = $this->CallItopUri(
+ "pages/exec.php?exec_module=itop-hub-connector&exec_page=ajax.php",
[
'auth_user' => $sLogin,
'auth_pwd' => self::AUTHENTICATION_PASSWORD,
'operation' => "compile",
'authent' => self::AUTHENTICATION_TOKEN,
- ]
+ ],
);
// Then
@@ -53,26 +53,4 @@ class AjaxPageTest extends ItopDataTestCase
clearstatcache();
$this->assertGreaterThan($iLastCompilation, filemtime(APPROOT.'env-production'), 'The env-production directory should have been rebuilt');
}
-
- protected function CallItopUrl($sUri, ?array $aPostFields = null, bool $bXDebugEnabled = false)
- {
- $ch = curl_init();
- if ($bXDebugEnabled) {
- curl_setopt($ch, CURLOPT_COOKIE, 'XDEBUG_SESSION=phpstorm');
- }
-
- $sUrl = \MetaModel::GetConfig()->Get('app_root_url')."/$sUri";
- var_dump($sUrl);
- curl_setopt($ch, CURLOPT_URL, $sUrl);
- curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
- curl_setopt($ch, CURLOPT_POSTFIELDS, $aPostFields);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
- $sOutput = curl_exec($ch);
- //echo "$sUrl error code:".curl_error($ch);
- curl_close($ch);
-
- return $sOutput;
- }
}
diff --git a/tests/php-unit-tests/legacy-tests/display_cache_content.php b/tests/php-unit-tests/legacy-tests/display_cache_content.php
index bbb370f08..76b2f1861 100644
--- a/tests/php-unit-tests/legacy-tests/display_cache_content.php
+++ b/tests/php-unit-tests/legacy-tests/display_cache_content.php
@@ -1,4 +1,5 @@
$aEntry)
- {
+ foreach ($aCacheUserData['cache_list'] as $i => $aEntry) {
$sEntryKey = array_key_exists('info', $aEntry) ? $aEntry['info'] : $aEntry['key'];
- if (strpos($sEntryKey, $sPrefix) === 0)
- {
+ if (strpos($sEntryKey, $sPrefix) === 0) {
$aEntries[] = $sEntryKey;
}
}
@@ -44,52 +41,39 @@ if (is_array($aCacheUserData) && isset($aCacheUserData['cache_list']))
echo "";
-if (empty($aEntries))
-{
+if (empty($aEntries)) {
echo "No Data";
return;
}
$sKey = $aEntries[0];
$result = apc_fetch($sKey);
-if (!is_object($result))
-{
+if (!is_object($result)) {
return;
}
$oSQLQuery = $result;
echo "NB Tables before;NB Tables after;";
-foreach($oSQLQuery->m_aContextData as $sField => $oValue)
-{
+foreach ($oSQLQuery->m_aContextData as $sField => $oValue) {
echo $sField.';';
}
echo "\n";
sort($aEntries);
-foreach($aEntries as $sKey)
-{
+foreach ($aEntries as $sKey) {
$result = apc_fetch($sKey);
- if (is_object($result))
- {
+ if (is_object($result)) {
$oSQLQuery = $result;
- if (isset($oSQLQuery->m_aContextData))
- {
+ if (isset($oSQLQuery->m_aContextData)) {
echo $oSQLQuery->m_iOriginalTableCount.";".$oSQLQuery->CountTables().';';
- foreach($oSQLQuery->m_aContextData as $oValue)
- {
- if (is_array($oValue))
- {
+ foreach ($oSQLQuery->m_aContextData as $oValue) {
+ if (is_array($oValue)) {
$sVal = json_encode($oValue);
- }
- else
- {
- if (empty($oValue))
- {
+ } else {
+ if (empty($oValue)) {
$sVal = '';
- }
- else
- {
+ } else {
$sVal = $oValue;
}
}
@@ -101,4 +85,3 @@ foreach($aEntries as $sKey)
}
echo "";
-
diff --git a/tests/php-unit-tests/src/BaseTestCase/ItopDataTestCase.php b/tests/php-unit-tests/src/BaseTestCase/ItopDataTestCase.php
index af0e8fb89..f2086f8bb 100644
--- a/tests/php-unit-tests/src/BaseTestCase/ItopDataTestCase.php
+++ b/tests/php-unit-tests/src/BaseTestCase/ItopDataTestCase.php
@@ -18,6 +18,7 @@ use ArchivedObjectException;
use CMDBObject;
use CMDBSource;
use Combodo\iTop\Service\Events\EventService;
+use Config;
use Contact;
use CoreException;
use CoreUnexpectedValue;
@@ -70,6 +71,9 @@ abstract class ItopDataTestCase extends ItopTestCase
private $aCreatedObjects = [];
private $aEventListeners = [];
+ protected ?string $sConfigTmpBackupFile = null;
+ protected ?Config $oiTopConfig = null;
+
/**
* @var bool When testing with silo, there are some cache we need to update on tearDown. Doing it all the time will cost too much, so it's opt-in !
* @see tearDown
@@ -124,6 +128,8 @@ abstract class ItopDataTestCase extends ItopTestCase
{
parent::setUp();
+ \IssueLog::Error($this->getName());
+
$this->PrepareEnvironment();
if (static::USE_TRANSACTION) {
@@ -190,6 +196,8 @@ abstract class ItopDataTestCase extends ItopTestCase
CMDBObject::SetCurrentChange(null);
+ $this->RestoreConfiguration();
+
parent::tearDown();
}
@@ -1517,4 +1525,35 @@ abstract class ItopDataTestCase extends ItopTestCase
$oObject->Set($sStopwatchAttCode, $oStopwatch);
}
+ protected function BackupConfiguration(): void
+ {
+ $sConfigPath = MetaModel::GetConfig()->GetLoadedFile();
+ clearstatcache();
+ echo sprintf("rights via ls on %s:\n %s \n", $sConfigPath, exec("ls -al $sConfigPath"));
+ $sFilePermOutput = substr(sprintf('%o', fileperms('/etc/passwd')), -4);
+ echo sprintf("rights via fileperms on %s:\n %s \n", $sConfigPath, $sFilePermOutput);
+
+ $this->sConfigTmpBackupFile = tempnam(sys_get_temp_dir(), "config_");
+ MetaModel::GetConfig()->WriteToFile($this->sConfigTmpBackupFile);
+ $this->oiTopConfig = new Config($sConfigPath);
+ }
+
+ protected function RestoreConfiguration(): void
+ {
+ if (is_null($this->sConfigTmpBackupFile) || ! is_file($this->sConfigTmpBackupFile)) {
+ return;
+ }
+
+ if (is_null($this->oiTopConfig)) {
+ return;
+ }
+
+ //put config back
+ $sConfigPath = $this->oiTopConfig->GetLoadedFile();
+ @chmod($sConfigPath, 0770);
+ $oConfig = new Config($this->sConfigTmpBackupFile);
+ $oConfig->WriteToFile($sConfigPath);
+ @chmod($sConfigPath, 0440);
+ @unlink($this->sConfigTmpBackupFile);
+ }
}
diff --git a/tests/php-unit-tests/src/BaseTestCase/ItopTestCase.php b/tests/php-unit-tests/src/BaseTestCase/ItopTestCase.php
index 7dd545787..6e30f5ed4 100644
--- a/tests/php-unit-tests/src/BaseTestCase/ItopTestCase.php
+++ b/tests/php-unit-tests/src/BaseTestCase/ItopTestCase.php
@@ -11,9 +11,9 @@ use CMDBSource;
use DateTime;
use DeprecatedCallsLog;
use MySQLTransactionNotClosedException;
-use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use ReflectionMethod;
use SetupUtils;
+use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\HttpKernel\KernelInterface;
use const DEBUG_BACKTRACE_IGNORE_ARGS;
@@ -29,6 +29,7 @@ use const DEBUG_BACKTRACE_IGNORE_ARGS;
abstract class ItopTestCase extends KernelTestCase
{
public const TEST_LOG_DIR = 'test';
+ protected array $aFileToClean = [];
/**
* @var bool
@@ -37,7 +38,7 @@ abstract class ItopTestCase extends KernelTestCase
public const DISABLE_DEPRECATEDCALLSLOG_ERRORHANDLER = true;
public static $DEBUG_UNIT_TEST = false;
protected static $aBackupStaticProperties = [];
-
+ public ?array $aLastCurlGetInfo = null;
/**
* @link https://docs.phpunit.de/en/9.6/annotations.html#preserveglobalstate PHPUnit `preserveGlobalState` annotation documentation
*
@@ -175,6 +176,15 @@ abstract class ItopTestCase extends KernelTestCase
}
throw new MySQLTransactionNotClosedException('Some DB transactions were opened but not closed ! Fix the code by adding ROLLBACK or COMMIT statements !', []);
}
+
+ foreach ($this->aFileToClean as $sPath) {
+ if (is_file($sPath)) {
+ @unlink($sPath);
+ continue;
+ }
+
+ SetupUtils::tidydir($sPath);
+ }
}
/**
@@ -631,4 +641,52 @@ abstract class ItopTestCase extends KernelTestCase
fclose($handle);
return array_reverse($aLines);
}
+
+ /**
+ * @param $sUrl
+ * @param array|null $aPostFields
+ * @param array|null $aCurlOptions
+ * @param $bXDebugEnabled
+ * @return string
+ */
+ protected function CallItopUrl($sUrl, ?array $aPostFields = [], ?array $aCurlOptions = [], $bXDebugEnabled = false): string
+ {
+ $ch = curl_init();
+ if ($bXDebugEnabled) {
+ curl_setopt($ch, CURLOPT_COOKIE, "XDEBUG_SESSION=phpstorm");
+ }
+
+ curl_setopt($ch, CURLOPT_URL, $sUrl);
+ curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
+ if (!is_array($aPostFields)) {
+ var_dump($aPostFields);
+ }
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $aPostFields);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ // Force disable of certificate check as most of dev / test env have a self-signed certificate
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+
+ var_dump($aCurlOptions);
+ curl_setopt_array($ch, $aCurlOptions);
+
+ $sOutput = curl_exec($ch);
+ //\IssueLog::Info("$sUrl error code:", null, ['error' => curl_error($ch)]);
+
+ $info = curl_getinfo($ch);
+ $this->aLastCurlGetInfo = $info;
+ $sErrorMsg = curl_error($ch);
+ $iErrorCode = curl_errno($ch);
+ curl_close($ch);
+
+ \IssueLog::Info(__METHOD__, null, ['url' => $sUrl, 'error' => $sErrorMsg, 'error_code' => $iErrorCode, 'post_fields' => $aPostFields, 'info' => $info]);
+
+ return $sOutput;
+ }
+
+ protected function CallItopUri(string $sUri, ?array $aPostFields = [], ?array $aCurlOptions = [], $bXDebugEnabled = false): string
+ {
+ $sUrl = \MetaModel::GetConfig()->Get('app_root_url')."/$sUri";
+ return $this->CallItopUrl($sUrl, $aPostFields, $aCurlOptions, $bXDebugEnabled);
+ }
}
diff --git a/tests/php-unit-tests/unitary-tests/application/LoginTest.php b/tests/php-unit-tests/unitary-tests/application/LoginTest.php
index 1f28ded99..cea8785c7 100644
--- a/tests/php-unit-tests/unitary-tests/application/LoginTest.php
+++ b/tests/php-unit-tests/unitary-tests/application/LoginTest.php
@@ -7,7 +7,6 @@ use MetaModel;
class LoginTest extends ItopDataTestCase
{
- protected $sConfigTmpBackupFile;
protected $sConfigPath;
protected $sLoginMode;
diff --git a/tests/php-unit-tests/unitary-tests/application/query/QueryTest.php b/tests/php-unit-tests/unitary-tests/application/query/QueryTest.php
index 563ac64e5..63521d74d 100644
--- a/tests/php-unit-tests/unitary-tests/application/query/QueryTest.php
+++ b/tests/php-unit-tests/unitary-tests/application/query/QueryTest.php
@@ -143,34 +143,11 @@ class QueryTest extends ItopDataTestCase
{
// compute request url
$url = $oQuery->GetExportUrl();
-
- // open curl
- $curl = curl_init();
-
- // curl options
- curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
- curl_setopt($curl, CURLOPT_USERPWD, self::USER.':'.self::PASSWORD);
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- // Force disable of certificate check as most of dev / test env have a self-signed certificate
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
-
- // execute curl
- $result = curl_exec($curl);
- if (curl_errno($curl)) {
- $info = curl_getinfo($curl);
- var_export($info);
- var_dump([
- 'url' => $url,
- 'app_root_url:' => MetaModel::GetConfig()->Get('app_root_url'),
- 'GetAbsoluteUrlAppRoot:' => \utils::GetAbsoluteUrlAppRoot(),
- ]);
- }
- // close curl
- curl_close($curl);
-
- return $result;
+ $aCurlOptions = [
+ CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
+ CURLOPT_USERPWD => self::USER.':'.self::PASSWORD,
+ ];
+ return $this->CallItopUrl($url, [], $aCurlOptions);
}
/** @inheritDoc */
diff --git a/tests/php-unit-tests/unitary-tests/webservices/CliResetSessionTest.php b/tests/php-unit-tests/unitary-tests/webservices/CliResetSessionTest.php
index ecdbc1158..0cc764c84 100644
--- a/tests/php-unit-tests/unitary-tests/webservices/CliResetSessionTest.php
+++ b/tests/php-unit-tests/unitary-tests/webservices/CliResetSessionTest.php
@@ -12,10 +12,8 @@ class CliResetSessionTest extends ItopDataTestCase
public const USE_TRANSACTION = false;
private $sCookieFile = "";
- private $sUrl;
private $sLogin;
private $sPassword = "Iuytrez9876543ç_è-(";
- protected $sConfigTmpBackupFile;
/**
* @throws Exception
@@ -24,16 +22,13 @@ class CliResetSessionTest extends ItopDataTestCase
{
parent::setUp();
- $this->sConfigTmpBackupFile = tempnam(sys_get_temp_dir(), "config_");
- MetaModel::GetConfig()->WriteToFile($this->sConfigTmpBackupFile);
+ $this->BackupConfiguration();
$this->sLogin = "rest-user-".date('dmYHis');
$this->CreateTestOrganization();
$this->sCookieFile = tempnam(sys_get_temp_dir(), 'jsondata_');
- $this->sUrl = \MetaModel::GetConfig()->Get('app_root_url');
-
$oRestProfile = \MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", ['name' => 'REST Services User'], true);
$oAdminProfile = \MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", ['name' => 'Administrator'], true);
@@ -47,16 +42,6 @@ class CliResetSessionTest extends ItopDataTestCase
{
parent::tearDown();
- if (! is_null($this->sConfigTmpBackupFile) && is_file($this->sConfigTmpBackupFile)) {
- //put config back
- $sConfigPath = MetaModel::GetConfig()->GetLoadedFile();
- @chmod($sConfigPath, 0770);
- $oConfig = new Config($this->sConfigTmpBackupFile);
- $oConfig->WriteToFile($sConfigPath);
- @chmod($sConfigPath, 0444);
- unlink($this->sConfigTmpBackupFile);
- }
-
if (!empty($this->sCookieFile)) {
unlink($this->sCookieFile);
}
@@ -150,26 +135,18 @@ class CliResetSessionTest extends ItopDataTestCase
*/
private function SendHTTPRequestWithCookies($sUri, $aPostFields, $sForcedLoginMode = null): string
{
- $ch = curl_init();
-
- curl_setopt($ch, CURLOPT_COOKIEJAR, $this->sCookieFile);
- curl_setopt($ch, CURLOPT_COOKIEFILE, $this->sCookieFile);
-
- $sUrl = "$this->sUrl/$sUri";
if (!is_null($sForcedLoginMode)) {
- $sUrl .= "?login_mode=$sForcedLoginMode";
+ $sUri .= "?login_mode=$sForcedLoginMode";
}
- curl_setopt($ch, CURLOPT_URL, $sUrl);
- curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
- curl_setopt($ch, CURLOPT_POSTFIELDS, $aPostFields);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 1);
- // Force disable of certificate check as most of dev / test env have a self-signed certificate
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- $sResponse = curl_exec($ch);
+ $aCurlOptions = [
+ CURLOPT_COOKIEJAR => $this->sCookieFile,
+ CURLOPT_COOKIEFILE => $this->sCookieFile,
+ CURLOPT_HEADER => 1,
+ ];
+
+ $sResponse = $this->CallItopUri($sUri, $aPostFields, $aCurlOptions);
+ var_dump($this->aLastCurlGetInfo);
/** $sResponse example
* "HTTP/1.1 200 OK
Date: Wed, 07 Jun 2023 05:00:40 GMT
@@ -177,16 +154,15 @@ class CliResetSessionTest extends ItopDataTestCase
Set-Cookie: itop-2e83d2e9b00e354fdc528621cac532ac=q7ldcjq0rvbn33ccr9q8u8e953; path=/
*/
//var_dump($sResponse);
- $iHeaderSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
+ $iHeaderSize = $this->aLastCurlGetInfo['header_size'] ?? 0;
$sBody = substr($sResponse, $iHeaderSize);
//$iHttpCode = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));
if (preg_match('/HTTP.* (\d*) /', $sResponse, $aMatches)) {
$sHttpCode = $aMatches[1];
} else {
- $sHttpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+ $sHttpCode = $this->aLastCurlGetInfo['http_code'] ?? -1;
}
- curl_close($ch);
$this->assertEquals(200, $sHttpCode, "The test logic assumes that the HTTP request is correctly handled");
return $sBody;
diff --git a/tests/php-unit-tests/unitary-tests/webservices/RestTest.php b/tests/php-unit-tests/unitary-tests/webservices/RestTest.php
index e13035b36..57d323c92 100644
--- a/tests/php-unit-tests/unitary-tests/webservices/RestTest.php
+++ b/tests/php-unit-tests/unitary-tests/webservices/RestTest.php
@@ -17,7 +17,6 @@ class RestTest extends ItopDataTestCase
public const USE_TRANSACTION = false;
public const CREATE_TEST_ORG = false;
- private static $sUrl;
private static $sLogin;
private static $sPassword = "Iuytrez9876543ç_è-(";
@@ -44,7 +43,6 @@ class RestTest extends ItopDataTestCase
{
parent::setUp();
- static::$sUrl = MetaModel::GetConfig()->Get('app_root_url');
static::$sLogin = "rest-user-".date('dmYHis');
$this->CreateTestOrganization();
@@ -297,16 +295,7 @@ JSON;
$aPostFields['callback'] = $sCallbackName;
}
- curl_setopt($ch, CURLOPT_URL, static::$sUrl."/webservices/rest.php");
- curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
- curl_setopt($ch, CURLOPT_POSTFIELDS, $aPostFields);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- // Force disable of certificate check as most of dev / test env have a self-signed certificate
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
-
- $sJson = curl_exec($ch);
- curl_close($ch);
+ $sJson = $this->CallItopUri('webservices/rest.php', $aPostFields);
if (!is_null($sTmpFile)) {
unlink($sTmpFile);