N°8796 - Add PHP code style validation in iTop and extensions - format whole code base

This commit is contained in:
odain
2025-11-07 15:39:53 +01:00
parent 12f23113f5
commit 890a2568c8
2110 changed files with 53099 additions and 63885 deletions

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -6,7 +7,7 @@
class ApplicationObjectExtensionTest extends \Combodo\iTop\Test\UnitTest\ItopDataTestCase
{
const CREATE_TEST_ORG = true;
public const CREATE_TEST_ORG = true;
// Count the calls by name
private static array $aCalls = [];
@@ -85,7 +86,6 @@ class ApplicationObjectExtensionTest extends \Combodo\iTop\Test\UnitTest\ItopDat
$this->assertEquals(2, self::$iCalls);
}
public function testModificationsOnInsertWith2Extensions()
{
self::ResetCallCount();
@@ -100,4 +100,4 @@ class ApplicationObjectExtensionTest extends \Combodo\iTop\Test\UnitTest\ItopDat
$this->assertEquals(6, self::$iCalls);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2013-2024 Combodo SAS
*
@@ -31,20 +32,20 @@ class DashboardLayoutTest extends ItopTestCase
*/
public function GetDashletCoordinatesProvider()
{
return array(
'OneColLayout-Cell0' => array('DashboardLayoutOneCol', 0, array(0, 0)),
'OneColLayout-Cell1' => array('DashboardLayoutOneCol', 1, array(0, 1)),
'TwoColsLayout-Cell0' => array('DashboardLayoutTwoCols', 0, array(0, 0)),
'TwoColsLayout-Cell1' => array('DashboardLayoutTwoCols', 1, array(1, 0)),
'TwoColsLayout-Cell2' => array('DashboardLayoutTwoCols', 2, array(0, 1)),
'TwoColsLayout-Cell3' => array('DashboardLayoutTwoCols', 3, array(1, 1)),
'ThreeColsLayout-Cell0' => array('DashboardLayoutThreeCols', 0, array(0, 0)),
'ThreeColsLayout-Cell1' => array('DashboardLayoutThreeCols', 1, array(1, 0)),
'ThreeColsLayout-Cell2' => array('DashboardLayoutThreeCols', 2, array(2, 0)),
'ThreeColsLayout-Cell3' => array('DashboardLayoutThreeCols', 3, array(0, 1)),
'ThreeColsLayout-Cell4' => array('DashboardLayoutThreeCols', 4, array(1, 1)),
'ThreeColsLayout-Cell5' => array('DashboardLayoutThreeCols', 5, array(2, 1)),
);
return [
'OneColLayout-Cell0' => ['DashboardLayoutOneCol', 0, [0, 0]],
'OneColLayout-Cell1' => ['DashboardLayoutOneCol', 1, [0, 1]],
'TwoColsLayout-Cell0' => ['DashboardLayoutTwoCols', 0, [0, 0]],
'TwoColsLayout-Cell1' => ['DashboardLayoutTwoCols', 1, [1, 0]],
'TwoColsLayout-Cell2' => ['DashboardLayoutTwoCols', 2, [0, 1]],
'TwoColsLayout-Cell3' => ['DashboardLayoutTwoCols', 3, [1, 1]],
'ThreeColsLayout-Cell0' => ['DashboardLayoutThreeCols', 0, [0, 0]],
'ThreeColsLayout-Cell1' => ['DashboardLayoutThreeCols', 1, [1, 0]],
'ThreeColsLayout-Cell2' => ['DashboardLayoutThreeCols', 2, [2, 0]],
'ThreeColsLayout-Cell3' => ['DashboardLayoutThreeCols', 3, [0, 1]],
'ThreeColsLayout-Cell4' => ['DashboardLayoutThreeCols', 4, [1, 1]],
'ThreeColsLayout-Cell5' => ['DashboardLayoutThreeCols', 5, [2, 1]],
];
}
/**
@@ -59,6 +60,6 @@ class DashboardLayoutTest extends ItopTestCase
$oDashboardLayout = new $sDashboardLayoutClass();
$aDashletCoordinates = $oDashboardLayout->GetDashletCoordinates($iCellIdx);
$this->assertEquals($aExpectedCoordinates,$aDashletCoordinates);
$this->assertEquals($aExpectedCoordinates, $aDashletCoordinates);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2018 Dennis Lassiter
*

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SARL
* @license http://opensource.org/licenses/AGPL-3.0
@@ -15,10 +16,10 @@ use UserRequest;
class DisplayBlockTest extends ItopCustomDatamodelTestCase
{
const CREATE_TEST_ORG = true;
public const CREATE_TEST_ORG = true;
public function GetDatamodelDeltaAbsPath(): string
{
return __DIR__ . '/Delta/add-enum-value-with-quote.xml';
return __DIR__.'/Delta/add-enum-value-with-quote.xml';
}
public function renderChartAjaxProvider(): array
@@ -94,4 +95,4 @@ class DisplayBlockTest extends ItopCustomDatamodelTestCase
$this->assertFalse(in_array($sNonExpected, $aJSNames));
$this->assertTrue(in_array($sExpected, $aJSNames));
}
}
}

View File

@@ -1,15 +1,18 @@
<?php
namespace Combodo\iTop\Test\UnitTest\Application;
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
use MetaModel;
class LoginTest extends ItopDataTestCase {
class LoginTest extends ItopDataTestCase
{
protected $sConfigTmpBackupFile;
protected $sConfigPath;
protected $sLoginMode;
protected function setUp(): void {
protected function setUp(): void
{
parent::setUp();
clearstatcache();
@@ -29,8 +32,9 @@ class LoginTest extends ItopDataTestCase {
@chmod($this->sConfigPath, 0444);
}
protected function tearDown(): void {
if (! is_null($this->sConfigTmpBackupFile) && is_file($this->sConfigTmpBackupFile)){
protected function tearDown(): void
{
if (! is_null($this->sConfigTmpBackupFile) && is_file($this->sConfigTmpBackupFile)) {
//put config back
@chmod($this->sConfigPath, 0770);
file_put_contents($this->sConfigPath, file_get_contents($this->sConfigTmpBackupFile));
@@ -40,18 +44,19 @@ class LoginTest extends ItopDataTestCase {
parent::tearDown();
}
protected function CallItopUrlByCurl($sUri, ?array $aPostFields=[]){
protected function CallItopUrlByCurl($sUri, ?array $aPostFields = [])
{
$ch = curl_init();
$sUrl = MetaModel::GetConfig()->Get('app_root_url') . "/$sUri";
$sUrl = MetaModel::GetConfig()->Get('app_root_url')."/$sUri";
curl_setopt($ch, CURLOPT_URL, $sUrl);
if (0 !== sizeof($aPostFields)){
if (0 !== sizeof($aPostFields)) {
curl_setopt($ch, CURLOPT_POST, 1);// set post data to true
curl_setopt($ch, CURLOPT_POSTFIELDS, $aPostFields);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$sOutput = curl_exec($ch);
curl_close ($ch);
curl_close($ch);
return $sOutput;
}

View File

@@ -5,10 +5,12 @@ namespace Combodo\iTop\Test\UnitTest\Application;
use Combodo\iTop\Application\WebPage\WebPage;
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
class MenuNodeTest extends ItopDataTestCase {
class MenuNodeTest extends ItopDataTestCase
{
private \UserRequest $oUR;
protected function setUp(): void {
protected function setUp(): void
{
parent::setUp();
clearstatcache();
@@ -20,7 +22,6 @@ class MenuNodeTest extends ItopDataTestCase {
$this->oUR = $this->CreateUserRequest(666, $aUserRequestCustomParams);
}
public function RenderOQLSearchProvider()
{
$aUseCases = [];
@@ -66,16 +67,16 @@ OQL;
SELECT `UserRequest` FROM UserRequest AS `UserRequest` WHERE (DATE_FORMAT(`UserRequest`.`ttr_escalation_deadline`, '%Y%v') != DATE_FORMAT(NOW(), '%Y%v'))
OQL;
try{
try {
$sContent = $this->CallRenderOQLSearch(true, true, true, $sOql);
$this->assertTrue(false !== strpos($sContent, $this->oUR->Get('title')), $sContent);
} catch(\Exception $e){
} catch (\Exception $e) {
echo($e->getMessage());
$this->fail('Without N°7750 fix Exception raised => TypeError : date(): Argument #2 ($timestamp) must be of type ?int, string given');
}
}
public function CallRenderOQLSearch(bool $bSearchPane, bool $bSearchOpen, bool $bAutoreload, string $sOql) : string
public function CallRenderOQLSearch(bool $bSearchPane, bool $bSearchOpen, bool $bAutoreload, string $sOql): string
{
$sTitle = 'title';
$oPage = new WebPage($sTitle);
@@ -94,4 +95,3 @@ OQL;
return $oResponse->getContent();
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -11,7 +12,6 @@ use utils;
class SCSSCompilationTest extends ItopTestCase
{
/**
* @dataProvider CompileDefaultThemesProvider
* @doesNotPerformAssertions

View File

@@ -85,7 +85,6 @@ class SessionTest extends ItopTestCase
$this->assertEquals('OK', Session::Get('test'));
}
public function testIsSet()
{
$this->assertFalse(Session::IsSet('test'));

View File

@@ -11,19 +11,18 @@ use ThemeHandler;
*/
class ThemeHandlerTest extends ItopTestCase
{
const PATTERN = '|\\\/var[^"]+testimages|';
public const PATTERN = '|\\\/var[^"]+testimages|';
private $oCompileCSSServiceMock;
private $sCompiledThemesDirAbsPath;
private $sCssAbsPath;
private $sDmCssAbsPath;
private $sJsonThemeParamFile;
static private $sTmpDir = null;
static private $aDirsToCleanup = [];
static private $sAbsoluteImagePath;
private static $sTmpDir = null;
private static $aDirsToCleanup = [];
private static $sAbsoluteImagePath;
static function setUpBeforeClass(): void
public static function setUpBeforeClass(): void
{
parent::setUpBeforeClass();
@@ -39,10 +38,9 @@ class ThemeHandlerTest extends ItopTestCase
static::$aDirsToCleanup[] = dirname(static::$sAbsoluteImagePath);
}
static function tearDownAfterClass(): void
public static function tearDownAfterClass(): void
{
foreach (static::$aDirsToCleanup as $sDir)
{
foreach (static::$aDirsToCleanup as $sDir) {
static::RecurseRmdir($sDir);
}
@@ -73,35 +71,36 @@ class ThemeHandlerTest extends ItopTestCase
parent::tearDown();
}
function KeepSignatureDiff($sSignature1, $sSignature2) : string {
public function KeepSignatureDiff($sSignature1, $sSignature2): string
{
$aSignature1 = json_decode($sSignature1, true);
$aSignature2 = json_decode($sSignature2, true);
$aDiffOuput = [];
foreach ($aSignature1 as $sKey => $oVal1){
if (is_array($oVal1) && ! empty($oVal1)){
foreach ($aSignature1 as $sKey => $oVal1) {
if (is_array($oVal1) && ! empty($oVal1)) {
$aCurrentDiffVal = [];
$oVal2 = $aSignature2[$sKey];
if (0 != sizeof($oVal1)){
foreach ($oVal1 as $sKey1 => $sVal1){
if (! array_key_exists($sKey1, $oVal2)){
if (0 != sizeof($oVal1)) {
foreach ($oVal1 as $sKey1 => $sVal1) {
if (! array_key_exists($sKey1, $oVal2)) {
$aCurrentDiffVal[$sKey1] = "Missing";
} else if ($sVal1 !== $oVal2[$sKey1]) {
$aCurrentDiffVal[$sKey1] = "expected:$sVal1 | actual:" . $oVal2[$sKey1];
} elseif ($sVal1 !== $oVal2[$sKey1]) {
$aCurrentDiffVal[$sKey1] = "expected:$sVal1 | actual:".$oVal2[$sKey1];
}
}
}
if (! empty($oVal2)){
foreach ($oVal2 as $sKey2 => $sVal2){
if (! array_key_exists($sKey2, $oVal1)){
if (! empty($oVal2)) {
foreach ($oVal2 as $sKey2 => $sVal2) {
if (! array_key_exists($sKey2, $oVal1)) {
$aCurrentDiffVal[$sKey1] = "Missing";
}
}
}
if (! empty($aCurrentDiffVal)){
if (! empty($aCurrentDiffVal)) {
$aDiffOuput[$sKey] = $aCurrentDiffVal;
}
} else if ($oVal1 !== $aSignature2[$sKey]){
} elseif ($oVal1 !== $aSignature2[$sKey]) {
$aDiffOuput[$sKey] = "expected:$oVal1 | actual:$aSignature2[$sKey]";
}
}
@@ -111,14 +110,12 @@ class ThemeHandlerTest extends ItopTestCase
public static function RecurseMkdir($dir)
{
if (is_dir($dir))
{
if (is_dir($dir)) {
return true;
}
$sParentDir = dirname($dir);
if (!static::RecurseMkdir($sParentDir))
{
if (!static::RecurseMkdir($sParentDir)) {
return false;
}
@@ -128,28 +125,28 @@ class ThemeHandlerTest extends ItopTestCase
public function testGetSignatureWithFileWithoutSignature()
{
$sTmpFile = tempnam(sys_get_temp_dir(), "sig");
file_put_contents($sTmpFile,"ffff");
$this->assertEquals("", ThemeHandler::GetSignature($sTmpFile));
file_put_contents($sTmpFile, "ffff");
$this->assertEquals("", ThemeHandler::GetSignature($sTmpFile));
}
public function testGetSignature()
{
$sSig = ThemeHandler::GetSignature(APPROOT.'tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main.css');
$sExpectedSig=<<<JSON
$sExpectedSig = <<<JSON
{"variables":"37c31105548fce44fecca5cb34e455c9","stylesheets":{"jqueryui":"78cfafc3524dac98e61fc2460918d4e5","main":"52d8a7c5530ceb3a4d777364fa4e1eea"},"variable_imports":{"css-variables":"3c3f5adf98b9dbf893658314436c4b93"},"images":{"css\/ui-lightness\/images\/ui-icons_222222_256x240.png":"3a3c5468f484f07ac4a320d9e22acb8c","css\/ui-lightness\/images\/ui-bg_diagonals-thick_20_666666_40x40.png":"4429d568c67d8dfeb9040273ea0fb8c4","css\/ui-lightness\/images\/ui-icons_E87C1E_256x240.png":"7003dd36cb2aa032c8ec871ce4d4e03d","css\/ui-lightness\/images\/ui-icons_1c94c4_256x240.png":"dbd693dc8e0ef04e90a2f7ac7b390086","css\/ui-lightness\/images\/ui-icons_F26522_256x240.png":"16278ec0c07270be571f4c2e97fcc10c","css\/ui-lightness\/images\/ui-bg_diagonals-thick_18_b81900_40x40.png":"e460a66d4b3e093fc651e62a236267cb","css\/ui-lightness\/images\/ui-icons_ffffff_256x240.png":"41612b0f4a034424f8321c9f824a94da","css\/ui-lightness\/images\/ui-icons_ffd27a_256x240.png":"dda1b6f694b0d196aefc66a1d6d758f6","images\/actions_right.png":"31c8906bd25d27b83a0a2466bf903462","images\/ac-background.gif":"76135f3697b41a15aed787cfd77776c7","images\/green-square.gif":"16ea9a497d72f5e66e4e8ea9ae08024e","images\/tv-item.gif":"719fe2d4566108e73162fb8868d3778c","images\/tv-collapsable.gif":"63a3351ea0d580797c9b8c386aa4f48b","images\/tv-expandable.gif":"a2d1af4128e4a798a7f3390b12a28574","images\/tv-item-last.gif":"2ae7e1d9972ce71e5caa65a086bc5b7e","images\/tv-collapsable-last.gif":"71acaa9d7c2616e9e8b7131a75ca65da","images\/tv-expandable-last.gif":"9d51036b3a8102742709da66789fd0f7","images\/red-header.gif":"c73b8765f0c8c3c183cb6a0c2bb0ec69","images\/green-header.gif":"0e22a09bb8051b2a274b3427ede62e82","images\/orange-header.gif":"ce1f93f0af64431771b4cbd6c99c567b","images\/calendar.png":"ab56e59af3c96ca661821257d376465e","images\/truncated.png":"c6f91108afe8159d417b4dc556cd3b2a","images\/plus.gif":"f00e1e6e1161f48608bb2bbc79b9948c","images\/minus.gif":"6d77c0c0c2f86b6995d1cdf78274eaab","images\/full-screen.png":"b541fadd3f1563856a4b44aeebd9d563","images\/indicator.gif":"03ce3dcc84af110e9da8699a841e5200","images\/delete.png":"93c047549c31a270a037840277cf59d3","images\/info-mini.png":"445c090ed777c5e6a08ac390fa896193","images\/ok.png":"f6973773335fd83d8d2875f9a3c925af","images\/error.png":"1af8a1041016f67669c5fd22dc88c82e","images\/eye-open-555.png":"9940f4e5b1248042c238e1924359fd5e","images\/eye-closed-555.png":"6ad3b0bae791bf61addc9d8ca80a642d","images\/eye-open-fff.png":"b7db2402d4d5c72314c25790a66150d4","images\/eye-closed-fff.png":"f9be7454dbb47b0e0bca3aa370ae7db5"},"utility_imports":[]}
JSON;
$this->assertEquals($sExpectedSig, $sSig);
$this->assertEquals($sExpectedSig, $sSig);
}
public function testGetVarSignature()
{
$sSignature=<<<JSON
$sSignature = <<<JSON
{"variables":"37c31105548fce44fecca5cb34e455c9","stylesheets":{"css-variables":"934888ebb4991d4c76555be6b6d1d5cc","jqueryui":"78cfafc3524dac98e61fc2460918d4e5","main":"52d8a7c5530ceb3a4d777364fa4e1eea"},"variable_imports":[],"utility_imports":[]}
JSON;
$var_sig = ThemeHandler::GetVarSignature($sSignature);
$this->assertEquals("37c31105548fce44fecca5cb34e455c9",$var_sig);
$this->assertEquals("37c31105548fce44fecca5cb34e455c9", $var_sig);
}
/**
@@ -158,19 +155,17 @@ JSON;
* @throws \CoreException
* @dataProvider CompileThemesProviderWithoutCss
*/
public function testCompileThemeWithoutCssFile_FocusOnParamAttribute($readFromParamAttributeFromJson=false)
public function testCompileThemeWithoutCssFile_FocusOnParamAttribute($readFromParamAttributeFromJson = false)
{
static::InitCSSDirectory();
$sExpectJsonFilePath = APPROOT.'tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/theme-parameters.json';
$sExpectedThemeParamJson = file_get_contents($sExpectJsonFilePath);
$aThemeParameters = json_decode($sExpectedThemeParamJson, true);
if (is_file($this->sJsonThemeParamFile))
{
if (is_file($this->sJsonThemeParamFile)) {
unlink($this->sJsonThemeParamFile);
}
if (is_file($this->sCssAbsPath))
{
if (is_file($this->sCssAbsPath)) {
unlink($this->sCssAbsPath);
}
@@ -178,25 +173,22 @@ JSON;
->method("CompileCSSFromSASS")
->willReturn("====CSSCOMPILEDCONTENT====");
if($readFromParamAttributeFromJson)
{
if ($readFromParamAttributeFromJson) {
copy($sExpectJsonFilePath, $this->sJsonThemeParamFile);
$this->assertTrue(ThemeHandler::CompileTheme('basque-red', true, "COMPILATIONTIMESTAMP", null, [static::$sTmpDir.'/branding/themes/'], static::$sTmpDir));
}
else
{
} else {
$this->assertTrue(ThemeHandler::CompileTheme('basque-red', true, "COMPILATIONTIMESTAMP", $aThemeParameters, [static::$sTmpDir.'/branding/themes/'], static::$sTmpDir));
}
$this->assertTrue(is_file($this->sCssAbsPath));
$this->assertEquals($sExpectedThemeParamJson, file_get_contents($this->sJsonThemeParamFile));
$this->assertEquals(file_get_contents(APPROOT . 'tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main.css'), file_get_contents($this->sCssAbsPath));
$this->assertEquals(file_get_contents(APPROOT.'tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main.css'), file_get_contents($this->sCssAbsPath));
}
public function CompileThemesProviderWithoutCss()
{
return [
"pass ParamAttributes and Save them in Json" => [false],
"use them from saved json" => [true]
"use them from saved json" => [true],
];
}
@@ -208,23 +200,23 @@ JSON;
* @throws \CoreException
* @dataProvider CompileThemesProviderEmptyArray
*/
public function testCompileThemesEmptyArray($ThemeParametersJson, $CompileCount=0)
public function testCompileThemesEmptyArray($ThemeParametersJson, $CompileCount = 0)
{
$sCssPath = static::$sTmpDir . '/branding/themes/basque-red/main.css';
copy(APPROOT . 'tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main.css', $sCssPath);
$sCssPath = static::$sTmpDir.'/branding/themes/basque-red/main.css';
copy(APPROOT.'tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main.css', $sCssPath);
$this->oCompileCSSServiceMock->expects($this->exactly($CompileCount))
->method("CompileCSSFromSASS")
->willReturn("====CSSCOMPILEDCONTENT====");
$this->assertEquals($CompileCount!=0,ThemeHandler::CompileTheme('basque-red', true, "COMPILATIONTIMESTAMP", json_decode($ThemeParametersJson, true), [static::$sTmpDir.'/branding/themes/'], static::$sTmpDir));
$this->assertEquals($CompileCount != 0, ThemeHandler::CompileTheme('basque-red', true, "COMPILATIONTIMESTAMP", json_decode($ThemeParametersJson, true), [static::$sTmpDir.'/branding/themes/'], static::$sTmpDir));
}
public function CompileThemesProviderEmptyArray()
{
$aEmptyImports = '{"variables":{"brand-primary":"#C53030","hover-background-color":"#F6F6F6","icons-filter":"grayscale(1)","search-form-container-bg-color":"#4A5568"},"utility_imports":[],"variable_imports":[],"stylesheets":{"jqueryui":"..\/css\/ui-lightness\/DO_NOT_CHANGE.jqueryui.scss","main":"..\/css\/DO_NOT_CHANGE.light-grey.scss"}}';
$aEmptyStyleSheets='{"variables":{"brand-primary":"#C53030","hover-background-color":"#F6F6F6","icons-filter":"grayscale(1)","search-form-container-bg-color":"#4A5568"},"utility_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"variable_imports":[],"stylesheets":[]}';
$aEmptyVars='{"variables":[],"utility_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"variable_imports":[],"stylesheets":{"jqueryui":"..\/css\/ui-lightness\/DO_NOT_CHANGE.jqueryui.scss","main":"..\/css\/DO_NOT_CHANGE.light-grey.scss"}}';
$aEmptyStyleSheets = '{"variables":{"brand-primary":"#C53030","hover-background-color":"#F6F6F6","icons-filter":"grayscale(1)","search-form-container-bg-color":"#4A5568"},"utility_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"variable_imports":[],"stylesheets":[]}';
$aEmptyVars = '{"variables":[],"utility_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"variable_imports":[],"stylesheets":{"jqueryui":"..\/css\/ui-lightness\/DO_NOT_CHANGE.jqueryui.scss","main":"..\/css\/DO_NOT_CHANGE.light-grey.scss"}}';
return [
"empty imports" => [$aEmptyImports],
"empty styles" => [$aEmptyStyleSheets],
@@ -245,13 +237,13 @@ JSON;
*/
public function CompileThemesProvider()
{
$sModifiedVariableThemeParameterJson='{"variables":{"brand-primary1":"#C53030","hover-background-color":"#F6F6F6","icons-filter":"grayscale(1)","search-form-container-bg-color":"#4A5568"},"variable_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"stylesheets":{"jqueryui":"..\/css\/ui-lightness\/DO_NOT_CHANGE.jqueryui.scss","main":"..\/css\/DO_NOT_CHANGE.light-grey.scss"},"utility_imports":[]}';
$sInitialThemeParamJson='{"variables":{"brand-primary":"#C53030","hover-background-color":"#F6F6F6","icons-filter":"grayscale(1)","search-form-container-bg-color":"#4A5568"},"variable_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"stylesheets":{"jqueryui":"..\/css\/ui-lightness\/DO_NOT_CHANGE.jqueryui.scss","main":"..\/css\/DO_NOT_CHANGE.light-grey.scss"},"utility_imports":[]}';
$sModifiedVariableThemeParameterJson = '{"variables":{"brand-primary1":"#C53030","hover-background-color":"#F6F6F6","icons-filter":"grayscale(1)","search-form-container-bg-color":"#4A5568"},"variable_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"stylesheets":{"jqueryui":"..\/css\/ui-lightness\/DO_NOT_CHANGE.jqueryui.scss","main":"..\/css\/DO_NOT_CHANGE.light-grey.scss"},"utility_imports":[]}';
$sInitialThemeParamJson = '{"variables":{"brand-primary":"#C53030","hover-background-color":"#F6F6F6","icons-filter":"grayscale(1)","search-form-container-bg-color":"#4A5568"},"variable_imports":{"css-variables":"..\/css\/DO_NOT_CHANGE.css-variables.scss"},"stylesheets":{"jqueryui":"..\/css\/ui-lightness\/DO_NOT_CHANGE.jqueryui.scss","main":"..\/css\/DO_NOT_CHANGE.light-grey.scss"},"utility_imports":[]}';
$sImportFilePath = '/branding/css/DO_NOT_CHANGE.css-variables.scss';
$sVarChangedMainCssPath="tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_varchanged.css";
$sStylesheetMainCssPath="tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_stylesheet.css";
$sImageMainCssPath="tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_imagemodified.css";
$sImportModifiedMainCssPath="tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_importmodified.css";
$sVarChangedMainCssPath = "tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_varchanged.css";
$sStylesheetMainCssPath = "tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_stylesheet.css";
$sImageMainCssPath = "tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_imagemodified.css";
$sImportModifiedMainCssPath = "tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_importmodified.css";
$sStylesheetFilePath = '/branding/css/DO_NOT_CHANGE.light-grey.scss';
$sImageFilePath = 'tests/php-unit-tests/unitary-tests/application/theme-handler/copied/testimages/images/green-header.gif';
return [
@@ -273,7 +265,6 @@ JSON;
];
}
/**
* @param $ThemeParametersJson
* @param int $iCompileCSSFromSASSCount
@@ -287,13 +278,12 @@ JSON;
* @throws \CoreException
* @dataProvider CompileThemesProvider
*/
public function testCompileThemes($ThemeParametersJson, $iCompileCSSFromSASSCount, $bMissingFile=false, $bFilesTouchedRecently=false, $bFileMd5sumModified=false, $sFileToTest=null, $sExpectedMainCssPath=null, $bSetup=true)
public function testCompileThemes($ThemeParametersJson, $iCompileCSSFromSASSCount, $bMissingFile = false, $bFilesTouchedRecently = false, $bFileMd5sumModified = false, $sFileToTest = null, $sExpectedMainCssPath = null, $bSetup = true)
{
static::InitCSSDirectory();
$sAfterReplacementCssVariableMd5sum='';
if (is_file(static::$sTmpDir.'/'.$sFileToTest))
{
$sAfterReplacementCssVariableMd5sum = '';
if (is_file(static::$sTmpDir.'/'.$sFileToTest)) {
$sFileToTest = static::$sTmpDir.'/'.$sFileToTest;
} else {
$sFileToTest = APPROOT.'/'.$sFileToTest;
@@ -309,14 +299,12 @@ JSON;
$sLine = '$approot-relative: "'.static::$sAbsoluteImagePath.'" !default;';
$sCssVariableContent = preg_replace("/\\\$approot-relative: \"(.*)\"/", $sLine, $sCssVariableContent);
file_put_contents($sCssVarPath, $sCssVariableContent);
if ($bMissingFile)
{
if ($bMissingFile) {
$sAfterReplacementCssVariableMd5sum = $sBeforeReplacementCssVariableMd5sum;
unlink($sFileToTest);
}
if (is_file($sCssVarPath))
{
if (is_file($sCssVarPath)) {
$sAfterReplacementCssVariableMd5sum = md5_file($sCssVarPath);
}
@@ -324,26 +312,23 @@ JSON;
$sMainCssContent = file_get_contents(APPROOT."tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/main_testcompilethemes.css");
$sMainCssContent = preg_replace('/MD5SUM/', $sAfterReplacementCssVariableMd5sum, $sMainCssContent);
$sReplacement = rtrim(static::$sAbsoluteImagePath, '/');
$sReplacement=preg_replace('|\/|', '\/', $sReplacement);
$sMainCssContent = preg_replace(static::PATTERN, $sReplacement, $sMainCssContent);
$cssPath = static::$sTmpDir . '/branding/themes/basque-red/main.css';
$sReplacement = preg_replace('|\/|', '\/', $sReplacement);
$sMainCssContent = preg_replace(static::PATTERN, $sReplacement, $sMainCssContent);
$cssPath = static::$sTmpDir.'/branding/themes/basque-red/main.css';
file_put_contents($cssPath, $sMainCssContent);
//should be after main.css modification to make sure precompilation check will be performed
if ($bFilesTouchedRecently)
{
if ($bFilesTouchedRecently) {
touch($sFileToTest, time() + 2, time() + 2);
}
//same: it should be after main.css modification
if ($bFileMd5sumModified)
{
if ($bFileMd5sumModified) {
file_put_contents($sFileToTest, "###\n".file_get_contents($sFileToTest));
touch($sFileToTest, time() + 2, time() + 2);
}
if (is_file($sCssVarPath))
{
if (is_file($sCssVarPath)) {
$sAfterReplacementCssVariableMd5sum = md5_file($sCssVarPath);
}
@@ -352,10 +337,9 @@ JSON;
->willReturn("====CSSCOMPILEDCONTENT====");
$aThemeParameters = json_decode($ThemeParametersJson, true);
$this->assertEquals($iCompileCSSFromSASSCount!=0, ThemeHandler::CompileTheme('basque-red', $bSetup, "COMPILATIONTIMESTAMP", $aThemeParameters, [static::$sTmpDir.'/branding/themes/'], static::$sTmpDir));
$this->assertEquals($iCompileCSSFromSASSCount != 0, ThemeHandler::CompileTheme('basque-red', $bSetup, "COMPILATIONTIMESTAMP", $aThemeParameters, [static::$sTmpDir.'/branding/themes/'], static::$sTmpDir));
if ($iCompileCSSFromSASSCount==1)
{
if ($iCompileCSSFromSASSCount == 1) {
$sExpectedMainCssFile = APPROOT.$sExpectedMainCssPath;
if (!is_file($sExpectedMainCssFile)) {
$this->assertTrue(false, "Cannot find expected main css file $sExpectedMainCssFile");
@@ -379,19 +363,18 @@ JSON;
$sActualContent = file_get_contents($sActualCssFile);
//replace absolute path to fix it in any envt
$sExpectedContent = preg_replace($aPatterns, $aReplacements, file_get_contents($sExpectedCssFile));
$sExpectedContent = preg_replace($aPatterns, $aReplacements, file_get_contents($sExpectedCssFile));
//echo($sExpectedContent);
if ($sExpectedContent != $sActualContent)
{
if ($sExpectedContent != $sActualContent) {
//try to have inner json diff failure
/** @var array $aExpectedJson */
//replace absolute path to fix it in any envt
$sExpectedJson = preg_replace($aPatterns, $aReplacements, ThemeHandler::GetSignature($sExpectedCssFile));
$sExpectedJson = preg_replace($aPatterns, $aReplacements, ThemeHandler::GetSignature($sExpectedCssFile));
$aExpectedJson = json_decode($sExpectedJson, true);
/** @var array $aActualJson */
$aActualJson = json_decode(ThemeHandler::GetSignature($sActualCssFile), true);
echo (ThemeHandler::GetSignature($sActualCssFile));
echo(ThemeHandler::GetSignature($sActualCssFile));
$this->assertEquals($aExpectedJson, $aActualJson, "CSS file dont match ($sExpectedCssFile / $sActualCssFile)");
}
@@ -405,14 +388,16 @@ JSON;
*/
public function testGetAllUrlFromScss($sScssFile)
{
$aIncludedUrls = ThemeHandler::GetAllUrlFromScss(['attr' => "123"],APPROOT.$sScssFile);
$aIncludedUrls = ThemeHandler::GetAllUrlFromScss(['attr' => "123"], APPROOT.$sScssFile);
$this->assertEquals(['approot-relative', 'version', 'version1'], array_values($aIncludedUrls['aMissingVariables']));
$this->assertEquals(["attr"=>"123"],
$aIncludedUrls['aFoundVariables']);
$this->assertEquals(
["attr" => "123"],
$aIncludedUrls['aFoundVariables']
);
$aExpectedCompletedUrls = [
'css/ui-lightness/images/tutu.jpg',
"css/ui-lightness/images/tata.jpeg",
"css/ui-lightness/images/tete.jpeg?g=123"
"css/ui-lightness/images/tete.jpeg?g=123",
];
$aExpectedToCompleteUrls = [
'\'abc/\'+ $approot-relative + "css/ui-lightness/images/toutou.png?v=" + $version',
@@ -467,7 +452,8 @@ SCSS;
$this->assertEquals(['gray-darker', 'brand-primary', 'brand-primary-lightest'], $aMissingVariables);
}
public function testGetVariablesFromFile(){
public function testGetVariablesFromFile()
{
$sContent = <<< 'SCSS'
$approot-relative: "../../../../../" !default; // relative to env-***/branding/themes/***/main.css
$approot-relative2: "../../" !default; // relative to env-***/branding/themes/***/main.css
@@ -482,7 +468,7 @@ $icons-filter: hue-rotate(0deg) !default;
$toto : titi;
SCSS;
file_put_contents(static::$sTmpDir . DIRECTORY_SEPARATOR . 'css-variable.scss', $sContent);
file_put_contents(static::$sTmpDir.DIRECTORY_SEPARATOR.'css-variable.scss', $sContent);
$aVariables = ThemeHandler::GetVariablesFromFile(
[ 'css-variable.scss' ],
[ static::$sTmpDir ]
@@ -504,7 +490,8 @@ SCSS;
$this->assertEquals(
$aExpectedVariables,
$aVariables);
$aVariables
);
}
/**
@@ -522,13 +509,13 @@ SCSS;
public function ResolveUrlProvider()
{
return [
'XXX + $key1 UNresolved' => ["abc/'+ \$key1", ['key'=>'123'], false],
'$key1 + XXX UNresolved' => ["\$key1 + abs", ['key'=>'123'], false],
'XXX + $key UNresolved' => ["abc/'+ \$unknownkey", ['key'=>'123'], false],
'XXX + $key resolved' => ["abc/'+ \$key", ['key'=>'123'], "abc/123"],
'XXX + $key1 resolved' => ["abc/'+ \$key1", ['key1'=>'123'], "abc/123"],
'$key + XXX resolved' => ["\$key + \"/abc", ['key'=>'123'], "123/abc"],
'XXX + $key + YYY resolved' => ["abc/'+ \$key + '/def", ['key'=>'123'], "abc/123/def"],
'XXX + $key1 UNresolved' => ["abc/'+ \$key1", ['key' => '123'], false],
'$key1 + XXX UNresolved' => ["\$key1 + abs", ['key' => '123'], false],
'XXX + $key UNresolved' => ["abc/'+ \$unknownkey", ['key' => '123'], false],
'XXX + $key resolved' => ["abc/'+ \$key", ['key' => '123'], "abc/123"],
'XXX + $key1 resolved' => ["abc/'+ \$key1", ['key1' => '123'], "abc/123"],
'$key + XXX resolved' => ["\$key + \"/abc", ['key' => '123'], "123/abc"],
'XXX + $key + YYY resolved' => ["abc/'+ \$key + '/def", ['key' => '123'], "abc/123/def"],
];
}
@@ -536,8 +523,8 @@ SCSS;
{
static::InitCSSDirectory();
$aStylesheetFile=glob(static::$sTmpDir."/branding/css/*.scss");
$aStylesheetFile[]=static::$sTmpDir."/branding/css/ui-lightness/DO_NOT_CHANGE.jqueryui.scss";
$aStylesheetFile = glob(static::$sTmpDir."/branding/css/*.scss");
$aStylesheetFile[] = static::$sTmpDir."/branding/css/ui-lightness/DO_NOT_CHANGE.jqueryui.scss";
$expectJsonFilePath = APPROOT.'tests/php-unit-tests/unitary-tests/application/theme-handler/expected/themes/basque-red/theme-parameters.json';
$expectedThemeParamJson = file_get_contents($expectJsonFilePath);
$aThemeParametersVariables = json_decode($expectedThemeParamJson, true);
@@ -549,8 +536,7 @@ SCSS;
$aExpectedUris = json_decode(file_get_contents(APPROOT.'tests/php-unit-tests/unitary-tests/application/theme-handler/getimages/expected-getimages.json'), true);
$aExpectedImages = [];
foreach ($aExpectedUris as $sExpectedUri)
{
foreach ($aExpectedUris as $sExpectedUri) {
$aExpectedImages[] = ThemeHandler::GetAppRootWithSlashes().$sExpectedUri;
}
@@ -561,7 +547,8 @@ SCSS;
* @dataProvider FindStylesheetFileProvider
* @throws \Exception
*/
public function testFindStylesheetFile(string $sFileToFind, array $aAllImports){
public function testFindStylesheetFile(string $sFileToFind, array $aAllImports)
{
$sImportsPath = static::$sTmpDir.'branding/';
// Windows compat O:)
@@ -575,7 +562,6 @@ SCSS;
}
}
$oFindStylesheetObject = new FindStylesheetObject();
ThemeHandler::FindStylesheetFile($sFileToFind, [$sImportsPath], $oFindStylesheetObject);
@@ -607,15 +593,15 @@ SCSS;
],
"scss with multi @imports" => [
"sFileToFind" => $sFileToFind3,
"aAllImports" => [$sFileToFind4, $sFileToFind5]
"aAllImports" => [$sFileToFind4, $sFileToFind5],
],
"scss with simple @imports in another folder" => [
"sFileToFind" => "css/simple_import2.scss",
"aAllImports" => [$sFileToFind5]
"aAllImports" => [$sFileToFind5],
],
"scss with @imports shortcut included_file3 => _included_file3.scss" => [
"sFileToFind" => "css/shortcut.scss",
"aAllImports" => ["css/_included_file3.scss", "css/included_scss/included_file4.scss"]
"aAllImports" => ["css/_included_file3.scss", "css/included_scss/included_file4.scss"],
],
"scss with @imports shortcut same file and folder names => feature1/_feature1.scss" => [
"sFileToFind" => "css/shortcut2.scss",
@@ -656,7 +642,7 @@ SCSS;
return [
[ '/var/www/html/iTop/images/itop-logo-2.png', '/var/www/html/iTop/env-production/branding/themes/light-grey/../../../../images/itop-logo-2.png' ],
[ '/var/www/html/iTop/env-production/branding/themes/light-grey/images/', '/var/www/html/iTop/env-production/branding/themes/light-grey/images/' ],
[ '/var/www/html/iTop/css/ui-lightness/images/ui-icons_222222_256x240.png', '/var/www/html/iTop/env-production//branding/themes/light-grey//../../../../css/ui-lightness/images/ui-icons_222222_256x240.png' ]
[ '/var/www/html/iTop/css/ui-lightness/images/ui-icons_222222_256x240.png', '/var/www/html/iTop/env-production//branding/themes/light-grey//../../../../css/ui-lightness/images/ui-icons_222222_256x240.png' ],
];
}
}
}

View File

@@ -13,8 +13,10 @@ use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
*
* @package UI\Base\Layout
*/
class NavigationMenuTest extends ItopDataTestCase {
public function IsAllowedProvider(){
class NavigationMenuTest extends ItopDataTestCase
{
public function IsAllowedProvider()
{
return [
'show menu' => [ true ],
'hide menu' => [ false ],
@@ -25,17 +27,20 @@ class NavigationMenuTest extends ItopDataTestCase {
* @dataProvider IsAllowedProvider
* test used to make sure backward compatibility is ensured
*/
public function testIsAllowed($bExpectedIsAllowed=true){
public function testIsAllowed($bExpectedIsAllowed = true)
{
\MetaModel::GetConfig()->Set('navigation_menu.show_organization_filter', $bExpectedIsAllowed);
$oNavigationMenu = new NavigationMenu(
$this->createMock(ApplicationContext::class),
$this->createMock(PopoverMenu::class));
$this->createMock(PopoverMenu::class)
);
$isAllowed = $oNavigationMenu->IsSiloSelectionEnabled();
$this->assertEquals($bExpectedIsAllowed, $isAllowed);
}
public function testIsAllowed_BackwardCompatibility_NoVariableInConfFile(){
public function testIsAllowed_BackwardCompatibility_NoVariableInConfFile()
{
\MetaModel::GetConfig()->Set('navigation_menu.show_organization_filter', false);
$sTmpFilePath = tempnam(sys_get_temp_dir(), 'test_');
@@ -45,7 +50,7 @@ class NavigationMenuTest extends ItopDataTestCase {
//remove variable for the test
$aLines = file($sTmpFilePath);
$aRows = array();
$aRows = [];
foreach ($aLines as $key => $sLine) {
if (!preg_match('/navigation_menu.show_organization_filter/', $sLine)) {

View File

@@ -21,12 +21,12 @@ class WelcomePopupTest extends ItopDataTestCase
$bResult = usort($aProvidersMessagesData, [WelcomePopupService::class, 'SortOnImportance']);
$this->assertTrue($bResult);
$aMessageIdsSorted = array_map(function($aItem) {
$aMessageIdsSorted = array_map(function ($aItem) {
return $aItem['message']->GetId();
}, $aProvidersMessagesData);
$this->assertEquals($aExpected, $aMessageIdsSorted);
}
/**
* Data provider for testSortOnImportance
* @return array[][]|string[][][][]|number[][][][]
@@ -76,10 +76,10 @@ class WelcomePopupTest extends ItopDataTestCase
{
$oService = WelcomePopupService::GetInstance();
$this->InvokeNonPublicMethod(WelcomePopupService::class, 'SetAcknowledgedMessagesCache', $oService, [$aCache]);
$this->assertEquals($bExpected, $this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, [$sMessageId]));
}
public function isMessageAcknowledgedDataProvider()
{
return [
@@ -94,7 +94,7 @@ class WelcomePopupTest extends ItopDataTestCase
],
];
}
public function testProcessMessages()
{
// Mock a WelcomePopup message provider, with a fixed class name
@@ -103,7 +103,7 @@ class WelcomePopupTest extends ItopDataTestCase
new Message('123', 'foo', '<p>Hello Foo</p>', null, [], 0),
new Message('456', 'bar', '<p>Hello Bar</p>', null, [], 1), // Already acknowledged will be skipped
]);
// Mock another WelcomePopup message provider, with a different class name
$oProvider2 = $this->getMockBuilder(iWelcomePopupExtension::class)->setMockClassName('Provider2')->getMock();
$oProvider2->expects($this->once())->method('GetMessages')->willReturn([
@@ -113,7 +113,7 @@ class WelcomePopupTest extends ItopDataTestCase
$oService = WelcomePopupService::GetInstance();
$this->InvokeNonPublicMethod(WelcomePopupService::class, 'SetAcknowledgedMessagesCache', $oService, [[get_class($oProvider1).'::456']]);
$this->InvokeNonPublicMethod(WelcomePopupService::class, 'SetMessagesProviders', $oService, [[$oProvider1, $oProvider2]]);
$aProvidersMessagesData = $this->InvokeNonPublicMethod(WelcomePopupService::class, 'ProcessMessages', $oService, []);
$this->assertEquals(
[
@@ -141,11 +141,11 @@ class WelcomePopupTest extends ItopDataTestCase
{
self::CreateUser('admin-testAcknowledgeMessage', 1, '-Passw0rd!Complex-');
UserRights::Login('admin-testAcknowledgeMessage');
// Mock a WelcomePopup message provider, with a fixed class name
$oProvider1 = $this->getMockBuilder(iWelcomePopupExtension::class)->setMockClassName('Provider1')->getMock();
$oProvider1->expects($this->exactly(2))->method('AcknowledgeMessage');
// Mock another WelcomePopup message provider, with a different class name
$oProvider2 = $this->getMockBuilder(iWelcomePopupExtension::class)->setMockClassName('Provider2')->getMock();
$oProvider2->expects($this->exactly(1))->method('AcknowledgeMessage');
@@ -154,24 +154,24 @@ class WelcomePopupTest extends ItopDataTestCase
$sMessageUUID2 = get_class($oProvider1).'::456789';
$sMessageUUID3 = get_class($oProvider2).'::456789'; // Same message id but different provider / UUID
$oService = WelcomePopupService::GetInstance();
$this->InvokeNonPublicMethod(WelcomePopupService::class, 'SetMessagesProviders', $oService, [[$oProvider1, $oProvider2]]);
$oService->AcknowledgeMessage($sMessageUUID1);
$this->assertTrue($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, [$sMessageUUID1]));
$this->assertFalse($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, ['-This-Message-Id-Is-Not-Ack0ledg3dged!']));
$this->assertFalse($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, [$sMessageUUID3]));
$oService->AcknowledgeMessage($sMessageUUID2);
$this->assertTrue($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, [$sMessageUUID1]));
$this->assertTrue($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, [$sMessageUUID2]));
$this->assertFalse($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, ['-This-Message-Id-Is-Not-Ack0ledg3dged!']));
$this->assertFalse($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, [$sMessageUUID3]));
$oService->AcknowledgeMessage($sMessageUUID3);
$this->assertTrue($this->InvokeNonPublicMethod(WelcomePopupService::class, 'IsMessageAcknowledged', $oService, [$sMessageUUID3]));
}
/**
* @dataProvider makeStringFitInProvider
*/
@@ -182,7 +182,7 @@ class WelcomePopupTest extends ItopDataTestCase
$this->assertTrue(mb_strlen($sFitted) <= $iLimit);
$this->assertEquals($sExpected, $sFitted);
}
public function makeStringFitInProvider()
{
return [
@@ -193,4 +193,3 @@ class WelcomePopupTest extends ItopDataTestCase
}
}

View File

@@ -23,4 +23,4 @@ class ApplicationContextTest extends \Combodo\iTop\Test\UnitTest\ItopTestCase
$this->assertEquals($sExpected, $sActual, 'Query parameters string should not start with & when $bIncludeAmpersand is false');
}
}
}

View File

@@ -4,11 +4,10 @@ namespace applicationContext;
class MockApplicationContext extends \ApplicationContext
{
public function __construct(array $applicationContextConfig)
{
parent::__construct();
$this->aValues = $applicationContextConfig;
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/*
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -25,7 +26,7 @@ class ApplicationExtensionTest extends ItopCustomDatamodelTestCase
*/
public function GetDatamodelDeltaAbsPath(): string
{
return __DIR__ . '/Delta/application-extension-usages-in-snippets.xml';
return __DIR__.'/Delta/application-extension-usages-in-snippets.xml';
}
/**

View File

@@ -1,4 +1,5 @@
<?php
/**
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -14,7 +15,6 @@ class MockApplicationObjectExtensionForTest1 extends AbstractApplicationObjectEx
protected static $sAttCodeToModify;
protected static $callBack;
public function __construct()
{
}
@@ -72,4 +72,4 @@ class MockApplicationObjectExtensionForTest1 extends AbstractApplicationObjectEx
$oObject->DBUpdate();
}
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* @copyright Copyright (C) 2010-2024 Combodo SAS
* @license http://opensource.org/licenses/AGPL-3.0
@@ -14,7 +15,6 @@ class MockApplicationObjectExtensionForTest2 extends AbstractApplicationObjectEx
protected static $sAttCodeToModify;
protected static $callBack;
public function __construct()
{
}
@@ -72,4 +72,4 @@ class MockApplicationObjectExtensionForTest2 extends AbstractApplicationObjectEx
$oObject->DBUpdate();
}
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2013-2024 Combodo SAS
*
@@ -32,9 +33,9 @@ use UserRights;
class privUITransactionFileTest extends ItopDataTestCase
{
/** @var int ID of the "support agent" pofile in the sample data */
const SAMPLE_DATA_SUPPORT_PROFILE_ID = 5;
const USER1_TEST_LOGIN = 'user1_support_test_privUITransaction';
const USER2_TEST_LOGIN = 'user2_support_test_privUITransaction';
public const SAMPLE_DATA_SUPPORT_PROFILE_ID = 5;
public const USER1_TEST_LOGIN = 'user1_support_test_privUITransaction';
public const USER2_TEST_LOGIN = 'user2_support_test_privUITransaction';
/**
* @dataProvider cleanupOldTransactionsProvider
@@ -43,7 +44,7 @@ class privUITransactionFileTest extends ItopDataTestCase
{
MetaModel::GetConfig()->Set('transactions_gc_threshold', 100);
$iBaseLimit = time() - 24*3600; //24h
$iBaseLimit = time() - 24 * 3600; //24h
$sBaseDir = sys_get_temp_dir();
$sDir = "$sBaseDir/privUITransactionFileTest/cleanupOldTransactions";
@@ -53,10 +54,10 @@ class privUITransactionFileTest extends ItopDataTestCase
mkdir("$sDir", 0777, true);
for ($i = 0; $i < $iCleanableCreated; $i++) {
touch("$sDir/{$sCleanablePrefix}$i", $iBaseLimit - 10*60);
touch("$sDir/{$sCleanablePrefix}$i", $iBaseLimit - 10 * 60);
}
for ($i = 0; $i < $iPreservableCreated; $i++) {
touch("$sDir/{$sPreservablePrefix}$i", $iBaseLimit + 10*60);
touch("$sDir/{$sPreservablePrefix}$i", $iBaseLimit + 10 * 60);
}
$iCleanableCount = count(glob("$sDir/{$sCleanablePrefix}*"));
@@ -123,7 +124,8 @@ class privUITransactionFileTest extends ItopDataTestCase
];
}
public function rm($sDir) {
public function rm($sDir)
{
$aFiles = array_diff(scandir($sDir), ['.','..']);
foreach ($aFiles as $sFile) {
if ((is_dir("$sDir/$sFile"))) {
@@ -135,7 +137,7 @@ class privUITransactionFileTest extends ItopDataTestCase
return rmdir($sDir);
}
const USER_TEST_LOGIN = 'support_test_privUITransaction';
public const USER_TEST_LOGIN = 'support_test_privUITransaction';
/**
* @throws \SecurityException

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2018 Dennis Lassiter
*
@@ -38,11 +39,11 @@ use utils;
class QueryTest extends ItopDataTestCase
{
// disable transaction to avoid data inconsistency between test and call to export (outside test scope)
const USE_TRANSACTION = false;
public const USE_TRANSACTION = false;
// user for exportation process
const USER = 'dani2';
const PASSWORD = '1TopCombodo+';
public const USER = 'dani2';
public const PASSWORD = '1TopCombodo+';
private $oUser;
/** @inheritDoc */
@@ -60,7 +61,7 @@ class QueryTest extends ItopDataTestCase
*/
private function CreateExportUser()
{
$oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", array('name' => 'Administrator'), true);
$oAdminProfile = MetaModel::GetObjectFromOQL("SELECT URP_Profiles WHERE name = :name", ['name' => 'Administrator'], true);
$this->oUser = $this->CreateUser(self::USER, $oAdminProfile->GetKey(), self::PASSWORD);
}
@@ -72,14 +73,14 @@ class QueryTest extends ItopDataTestCase
* @param string $sOql query oql phrase
* @param string|null $sFields fields to export
*/
private function CreateQueryOQL(string $sName, string $sDescription, string $sOql, string $sFields = null) : QueryOQL
private function CreateQueryOQL(string $sName, string $sDescription, string $sOql, string $sFields = null): QueryOQL
{
$oQuery = new QueryOQL();
$oQuery->Set('name', $sName);
$oQuery->Set('description', $sDescription);
$oQuery->Set('oql', $sOql);
if($sFields != null){
if ($sFields != null) {
$oQuery->Set('fields', $sFields);
}
@@ -154,10 +155,10 @@ class QueryTest extends ItopDataTestCase
*/
public function getQueryProvider()
{
return array(
'Export #1' => array('query without params', 'SELECT Person'),
'Export #2' => array('query with params', "SELECT Person WHERE first_name LIKE 'B%'")
);
return [
'Export #1' => ['query without params', 'SELECT Person'],
'Export #2' => ['query with params', "SELECT Person WHERE first_name LIKE 'B%'"],
];
}
/**
@@ -177,7 +178,7 @@ class QueryTest extends ItopDataTestCase
// curl options
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, self::USER . ':' . self::PASSWORD);
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

View File

@@ -1,10 +1,12 @@
<?php
namespace Combodo\iTop\Application\TwigBase\Controller;
use Combodo\iTop\Test\UnitTest\ItopDataTestCase;
use MetaModel;
class ControllerTest extends ItopDataTestCase {
class ControllerTest extends ItopDataTestCase
{
protected function setUp(): void
{
parent::setUp();
@@ -12,7 +14,8 @@ class ControllerTest extends ItopDataTestCase {
$this->RequireOnceUnitTestFile('FakeController.php');
}
public function CheckAccessProvider() {
public function CheckAccessProvider()
{
return [
'simple token access OK' => [
'access_token' => 'toto123',
@@ -42,7 +45,8 @@ class ControllerTest extends ItopDataTestCase {
* Fix N°7147
* @dataProvider CheckAccessProvider
*/
public function testCheckAccess($sConfiguredAccessToken, $sHttpAccessToken, $bSuccess, $bPost=false){
public function testCheckAccess($sConfiguredAccessToken, $sHttpAccessToken, $bSuccess, $bPost = false)
{
$sModuleName = "MyModule";
$sTokenParamName = "access_token_conf_param";
@@ -51,7 +55,7 @@ class ControllerTest extends ItopDataTestCase {
$_REQUEST = [];
$_REQUEST['exec_module'] = $sModuleName;
if ($bPost){
if ($bPost) {
$_POST[$sTokenParamName] = $sHttpAccessToken;
} else {
$_REQUEST[$sTokenParamName] = $sHttpAccessToken;
@@ -62,13 +66,13 @@ class ControllerTest extends ItopDataTestCase {
MetaModel::GetConfig()->SetModuleSetting($sModuleName, $sTokenParamName, $sConfiguredAccessToken);
if (! $bSuccess){
if (! $bSuccess) {
$this->expectExceptionMessage("Invalid token");
}
$this->InvokeNonPublicMethod(FakeController::class, "CheckAccess", $oController);
if ($bSuccess){
if ($bSuccess) {
$this->assertTrue(true, "no issue encountered");
}
}

View File

@@ -1,5 +1,7 @@
<?php
namespace Combodo\iTop\Application\TwigBase\Controller;
class FakeController extends Controller {
class FakeController extends Controller
{
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* Copyright (C) 2018 Dennis Lassiter
*
@@ -42,7 +43,6 @@ class utilsTest extends ItopTestCase
parent::tearDown();
}
public function testEndsWith()
{
$this->assertFalse(utils::EndsWith('a', 'bbbb'));
@@ -87,8 +87,7 @@ class utilsTest extends ItopTestCase
$sSep = DIRECTORY_SEPARATOR;
$sItopRootRealPath = realpath($sAppRoot).$sSep;
$sLicenseFileName = 'license.txt';
if (!is_file($sAppRoot.$sLicenseFileName))
{
if (!is_file($sAppRoot.$sLicenseFileName)) {
$sLicenseFileName = 'LICENSE';
}
@@ -96,7 +95,7 @@ class utilsTest extends ItopTestCase
$sLicenseFileName => [$sAppRoot.$sLicenseFileName, $sAppRoot, $sItopRootRealPath.$sLicenseFileName],
'unexisting file' => [$sAppRoot.'license_DOES_NOT_EXIST.txt', $sAppRoot, false],
'/'.$sLicenseFileName => [$sAppRoot.$sSep.$sLicenseFileName, $sAppRoot, $sItopRootRealPath.$sLicenseFileName],
'%2f'.$sLicenseFileName => [$sAppRoot.'%2f'. $sLicenseFileName, $sAppRoot, false],
'%2f'.$sLicenseFileName => [$sAppRoot.'%2f'.$sLicenseFileName, $sAppRoot, false],
'../'.$sLicenseFileName => [$sAppRoot.'..'.$sSep.$sLicenseFileName, $sAppRoot, false],
'%2e%2e%2f'.$sLicenseFileName => [$sAppRoot.'%2e%2e%2f'.$sLicenseFileName, $sAppRoot, false],
'application/utils.inc.php with basepath=APPROOT' => [
@@ -132,32 +131,32 @@ class utilsTest extends ItopTestCase
public function LocalPathProvider()
{
$sAppRoot = static::GetAppRoot();
return array(
'index.php' => array(
return [
'index.php' => [
'sAbsolutePath' => $sAppRoot.'index.php',
'expected' => 'index.php',
),
'non existing' => array(
],
'non existing' => [
'sAbsolutePath' => $sAppRoot.'nonexisting/nonexisting',
'expected' => false,
),
'outside' => array(
],
'outside' => [
'sAbsolutePath' => '/tmp',
'expected' => false,
),
'application/cmdbabstract.class.inc.php' => array(
],
'application/cmdbabstract.class.inc.php' => [
'sAbsolutePath' => $sAppRoot.'application/cmdbabstract.class.inc.php',
'expected' => 'application/cmdbabstract.class.inc.php',
),
'dir' => array(
],
'dir' => [
'sAbsolutePath' => $sAppRoot.'application/.',
'expected' => 'application',
),
'root' => array(
],
'root' => [
'sAbsolutePath' => $sAppRoot.'.',
'expected' => '',
),
);
],
];
}
/**
@@ -171,14 +170,15 @@ class utilsTest extends ItopTestCase
public function appRootUrlProvider()
{
return array(
'Setup index (windows antislash)' => array('http://localhost/', 'C:\Dev\wamp64\www\itop-dev\setup\index.php', 'C:\Dev\wamp64\www\itop-dev', 'http://localhost/setup/'),
'Setup index (windows slash)' => array('http://127.0.0.1/', 'C:/web/setup/index.php', 'C:/web', 'http://127.0.0.1/setup/'),
'Setup index (windows slash, drive letter case difference)' => array('http://127.0.0.1/', 'c:/web/setup/index.php', 'C:/web', 'http://127.0.0.1/setup/'),
);
return [
'Setup index (windows antislash)' => ['http://localhost/', 'C:\Dev\wamp64\www\itop-dev\setup\index.php', 'C:\Dev\wamp64\www\itop-dev', 'http://localhost/setup/'],
'Setup index (windows slash)' => ['http://127.0.0.1/', 'C:/web/setup/index.php', 'C:/web', 'http://127.0.0.1/setup/'],
'Setup index (windows slash, drive letter case difference)' => ['http://127.0.0.1/', 'c:/web/setup/index.php', 'C:/web', 'http://127.0.0.1/setup/'],
];
}
public function GetAbsoluteUrlAppRootPersistency() {
public function GetAbsoluteUrlAppRootPersistency()
{
$this->setUp();
return [
@@ -260,7 +260,7 @@ class utilsTest extends ItopTestCase
/**
* @dataProvider GetAbsoluteUrlAppRootPersistency
*/
public function testGetAbsoluteUrlAppRootPersistency($bBehindReverseProxy,$bForceTrustProxy1 ,$sExpectedAppRootUrl1,$bForceTrustProxy2 , $sExpectedAppRootUrl2,$bForceTrustProxy3 , $sExpectedAppRootUrl3)
public function testGetAbsoluteUrlAppRootPersistency($bBehindReverseProxy, $bForceTrustProxy1, $sExpectedAppRootUrl1, $bForceTrustProxy2, $sExpectedAppRootUrl2, $bForceTrustProxy3, $sExpectedAppRootUrl3)
{
// resetting static property for each test pass
$this->SetNonPublicStaticProperty(utils::class, 'sAbsoluteUrlAppRootCache', null);
@@ -291,7 +291,6 @@ class utilsTest extends ItopTestCase
$this->assertEquals($sExpectedAppRootUrl3, utils::GetAbsoluteUrlAppRoot($bForceTrustProxy3));
}
/**
* @dataProvider GetDefaultUrlAppRootProvider
*/
@@ -923,78 +922,78 @@ HTML,
'Basic positional with enough args' => [
'Format: %1$s, %2$d, %3$s',
['Hello', 42, 'World'],
'Format: Hello, 42, World'
'Format: Hello, 42, World',
],
'Basic positional with args in different order' => [
'Format: %2$s, %1$d, %3$s',
[42, 'Hello', 'World'],
'Format: Hello, 42, World'
'Format: Hello, 42, World',
],
'Positional with reused specifiers' => [
'Format: %1$s, %2$d, %1$s again',
['Hello', 42],
'Format: Hello, 42, Hello again'
'Format: Hello, 42, Hello again',
],
// Missing arguments tests
'Missing one positional arg' => [
'Format: %1$s, %2$d, %3$s',
['Hello', 42],
'Format: Hello, 42, %3$s'
'Format: Hello, 42, %3$s',
],
'Missing multiple positional args' => [
'Format: %1$s, %2$s, %3$s, %4$s',
['Hello'],
'Format: Hello, %2$s, %3$s, %4$s'
'Format: Hello, %2$s, %3$s, %4$s',
],
'Missing first positional arg' => [
'Format: %1$s, %2$s, %3$s',
[],
'Format: %1$s, %2$s, %3$s'
'Format: %1$s, %2$s, %3$s',
],
// Edge cases
'Positional with larger numbers' => [
'Format: %2$s, %1$d, %3$s, %2$s again',
[123456, 'Hello', 'World'],
'Format: Hello, 123456, World, Hello again'
'Format: Hello, 123456, World, Hello again',
],
'Positional specifiers with non-sequential indexes' => [
'Format: %3$s then %1$s and %5$d',
['first', 'second', 'third', 'fourth', 42],
'Format: third then first and 42'
'Format: third then first and 42',
],
// More complex format specifiers
'Positional with format modifiers' => [
'Format: %1$\'*10s, %2$04d',
['Hello', 42],
'Format: *****Hello, 0042'
'Format: *****Hello, 0042',
],
'Positional with various types' => [
'Format: String: %1$s, Integer: %2$d, Char: %3$c',
['Hello', 42, 65],
'Format: String: Hello, Integer: 42, Char: A'
'Format: String: Hello, Integer: 42, Char: A',
],
// Testing with non-Latin characters
'Positional with UTF-8 characters' => [
'Format: %1$s %2$s %3$s',
['こんにちは', 'Здравствуйте', '你好'],
'Format: こんにちは Здравствуйте 你好'
'Format: こんにちは Здравствуйте 你好',
],
// Mixed formats
'Mixed positional with complex specifiers' => [
'Format: %1$-10s | %2$+d',
['Hello', 42],
'Format: Hello | +42'
'Format: Hello | +42',
],
'Reused positional indexes with some missing' => [
'Format: %1$s %2$d %1$s %3$s %2$d',
['Hello', 42],
'Format: Hello 42 Hello %3$s 42'
]
'Format: Hello 42 Hello %3$s 42',
],
];
}
}