diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 3e422e82942..6cd22216563 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -3,7 +3,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" bootstrap="phpunit/bootstrap.php" - backupStaticAttributes="true" colors="true" > @@ -12,7 +11,7 @@ - + diff --git a/phpunit/GLPITestCase.php b/phpunit/GLPITestCase.php index eb7da1f27e8..de054b89464 100644 --- a/phpunit/GLPITestCase.php +++ b/phpunit/GLPITestCase.php @@ -46,6 +46,7 @@ class GLPITestCase extends TestCase private $int; private $str; protected $has_failed = false; + private ?array $config_copy = null; /** * @var TestHandler @@ -59,10 +60,15 @@ class GLPITestCase extends TestCase public function setUp(): void { - // By default, no session, not connected + $this->storeGlobals(); + + global $DB; + $DB->setTimezone('UTC'); + + // By default, no session, not connected $this->resetSession(); - // Ensure cache is clear + // Ensure cache is clear global $GLPI_CACHE; $GLPI_CACHE->clear(); @@ -79,6 +85,8 @@ public function setUp(): void public function tearDown(): void { + $this->resetGlobalsAndStaticValues(); + vfsStreamWrapper::unregister(); if (isset($_SESSION['MESSAGE_AFTER_REDIRECT']) && !$this->has_failed) { @@ -333,4 +341,33 @@ protected function getTestRootEntity(bool $only_id = false) { return getItemByTypeName('Entity', '_test_root_entity', $only_id); } + + /** + * Store Globals + * + * @return void + */ + private function storeGlobals(): void + { + global $CFG_GLPI; + + if ($this->config_copy === null) { + $this->config_copy = $CFG_GLPI; + } + } + + /** + * Reset globals and static variables + * + * @return void + */ + private function resetGlobalsAndStaticValues(): void + { + // Globals + global $CFG_GLPI; + $CFG_GLPI = $this->config_copy; + + // Statics values + Log::$use_queue = false; + } } diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php index 144139f2fe0..e4226f9f867 100644 --- a/phpunit/bootstrap.php +++ b/phpunit/bootstrap.php @@ -48,11 +48,12 @@ define('GLPI_URI', getenv('GLPI_URI') ?: 'http://localhost:8088'); define('GLPI_STRICT_DEPRECATED', true); //enable strict depreciations +define('FIXTURE_DIR', __DIR__ . "/../tests/fixtures"); define( 'PLUGINS_DIRECTORIES', [ GLPI_ROOT . '/plugins', - GLPI_ROOT . '/tests/fixtures/plugins', + FIXTURE_DIR . '/plugins', ] ); diff --git a/phpunit/functional/ComputerTest.php b/phpunit/functional/ComputerTest.php index 7ccbb7acecb..9a21bd77e10 100644 --- a/phpunit/functional/ComputerTest.php +++ b/phpunit/functional/ComputerTest.php @@ -345,14 +345,10 @@ public function testGetFromIter() $iter = $DB->request(['SELECT' => 'id', 'FROM' => 'glpi_computers' ]); - $prev = false; foreach (\Computer::getFromIter($iter) as $comp) { $this->assertInstanceOf(\Computer::class, $comp); $this->assertArrayHasKey('name', $comp->fields); - $this->assertNotEquals($prev, $comp->fields['name']); - $prev = $comp->fields['name']; } - $this->assertTrue((bool)$prev); // we are retrieve something } public function testGetFromDbByCrit() @@ -548,10 +544,10 @@ public function testCloneWithAutoCreateInfocom() // clone! $computer = new \Computer(); //$computer->fields contents is already escaped! $this->assertTrue($computer->getFromDB($id)); - $infocom_auto_create_original = $CFG_GLPI["infocom_auto_create"] ?? 0; - $CFG_GLPI["infocom_auto_create"] = 1; + $auto_create_infocoms_original = $CFG_GLPI["auto_create_infocoms"] ?? 0; + $CFG_GLPI["auto_create_infocoms"] = 1; $added = $computer->clone(); - $CFG_GLPI["infocom_auto_create"] = $infocom_auto_create_original; + $CFG_GLPI["auto_create_infocoms"] = $auto_create_infocoms_original; $this->assertGreaterThan(0, (int)$added); $this->assertNotEquals($computer->fields['id'], $added); diff --git a/phpunit/functional/ConfigTest.php b/phpunit/functional/ConfigTest.php index 0b661896f53..cfd152475ab 100644 --- a/phpunit/functional/ConfigTest.php +++ b/phpunit/functional/ConfigTest.php @@ -906,7 +906,7 @@ public function testAutoCreateInfocom() ]; $infocom_types = array_diff($infocom_types, $excluded_types); - $infocom_auto_create_original = $CFG_GLPI["infocom_auto_create"] ?? 0; + $auto_create_infocoms_original = $CFG_GLPI["auto_create_infocoms"] ?? 0; $infocom = new \Infocom(); foreach ($infocom_types as $asset_type) { @@ -919,7 +919,7 @@ public function testAutoCreateInfocom() 'itemtype' => 'Computer', // Random item type for testing Item_DeviceSimcard 'devicesimcards_id' => 1, // Random ID for testing Item_DeviceSimcard ]); - $CFG_GLPI['auto_create_infocoms'] = $infocom_auto_create_original; + $CFG_GLPI['auto_create_infocoms'] = $auto_create_infocoms_original; // Verify an Infocom object exists for the newly created asset $infocom_exists = $infocom->getFromDBforDevice($asset_type, $asset_id); $this->assertTrue($infocom_exists); @@ -933,7 +933,7 @@ public function testAutoCreateInfocom() 'itemtype' => 'Computer', // Random item type for testing Item_DeviceSimcard 'devicesimcards_id' => 1, // Random ID for testing Item_DeviceSimcard ]); - $CFG_GLPI['auto_create_infocoms'] = $infocom_auto_create_original; + $CFG_GLPI['auto_create_infocoms'] = $auto_create_infocoms_original; $infocom_exists = $infocom->getFromDBforDevice($asset_type, $asset_id2); $this->assertFalse($infocom_exists); } diff --git a/tests/functional/DatabaseInstance.php b/phpunit/functional/DatabaseInstanceTest.php similarity index 76% rename from tests/functional/DatabaseInstance.php rename to phpunit/functional/DatabaseInstanceTest.php index 38ea0b60a93..afe256e049b 100644 --- a/tests/functional/DatabaseInstance.php +++ b/phpunit/functional/DatabaseInstanceTest.php @@ -39,7 +39,7 @@ /* Test for inc/databaseinstance.class.php */ -class DatabaseInstance extends DbTestCase +class DatabaseInstanceTest extends DbTestCase { public function testDelete() { @@ -51,34 +51,33 @@ public function testDelete() 'size' => 52000 ]); - //check DB is created, and load it - $this->integer($instid)->isGreaterThan(0); - $this->boolean($instance->getFromDB($instid))->isTrue(); + //check DB is created, and load it + $this->assertGreaterThan(0, $instid); + $this->assertTrue($instance->getFromDB($instid)); - //create databases + //create databases for ($i = 0; $i < 5; ++$i) { $database = new \Database(); - $this->integer( + $this->assertGreaterThan( + 0, $database->add([ 'name' => 'Database ' . $i, 'databaseinstances_id' => $instid ]) - )->isGreaterThan(0); + ); } - $this->integer(countElementsInTable(\Database::getTable()))->isIdenticalTo(5); + $this->assertSame(5, countElementsInTable(\Database::getTable())); //test removal - $this->boolean($instance->delete(['id' => $instid], 1))->isTrue(); - $this->boolean($instance->getFromDB($instid))->isFalse(); + $this->assertTrue($instance->delete(['id' => $instid], 1)); + $this->assertFalse($instance->getFromDB($instid)); //ensure databases has been dropped aswell - $this->integer(countElementsInTable(\Database::getTable()))->isIdenticalTo(0); + $this->assertSame(0, countElementsInTable(\Database::getTable())); } public function testGetInventoryAgent(): void { - $root_entity = getItemByTypeName(\Entity::class, '_test_root_entity', true); - $computer = $this->createItem( \Computer::class, [ @@ -96,7 +95,7 @@ public function testGetInventoryAgent(): void ); $db_agent = $dbinstance->getInventoryAgent(); - $this->variable($db_agent)->isNull(); + $this->assertNull($db_agent); $agenttype_id = getItemByTypeName(\AgentType::class, 'Core', true); @@ -122,7 +121,7 @@ public function testGetInventoryAgent(): void ] ); - $agent3 = $this->createItem( + $this->createItem( \Agent::class, [ 'deviceid' => sprintf('device_%08x', rand()), @@ -146,23 +145,23 @@ public function testGetInventoryAgent(): void // most recent agent directly linked $db_agent = $dbinstance->getInventoryAgent(); - $this->object($db_agent)->isInstanceOf(\Agent::class); - $this->array($db_agent->fields)->isEqualTo($agent1->fields); + $this->assertInstanceOf(\Agent::class, $db_agent); + $this->assertEquals($agent1->fields, $db_agent->fields); - $this->boolean($agent1->delete(['id' => $agent1->fields['id']]))->isTrue(); + $this->assertTrue($agent1->delete(['id' => $agent1->fields['id']])); // most recent agent directly linked $db_agent = $dbinstance->getInventoryAgent(); - $this->object($db_agent)->isInstanceOf(\Agent::class); - $this->array($db_agent->fields)->isEqualTo($agent2->fields); + $this->assertInstanceOf(\Agent::class, $db_agent); + $this->assertEquals($agent2->fields, $db_agent->fields); - $this->boolean($agent2->delete(['id' => $agent2->fields['id']]))->isTrue(); + $this->assertTrue($agent2->delete(['id' => $agent2->fields['id']])); // most recent agent found from linked item, as there is no more agent linked directly $db_agent = $dbinstance->getInventoryAgent(); - $this->object($db_agent)->isInstanceOf(\Agent::class); + $this->assertInstanceOf(\Agent::class, $db_agent); $computer_agent = $computer->getInventoryAgent(); - $this->object($computer_agent)->isInstanceOf(\Agent::class); - $this->array($db_agent->fields)->isEqualTo($computer_agent->fields); + $this->assertInstanceOf(\Agent::class, $computer_agent); + $this->assertEquals($computer_agent->fields, $db_agent->fields); } } diff --git a/phpunit/functional/DbUtilsTest.php b/phpunit/functional/DbUtilsTest.php index 105e38585b8..3582b05fafe 100644 --- a/phpunit/functional/DbUtilsTest.php +++ b/phpunit/functional/DbUtilsTest.php @@ -133,14 +133,14 @@ public function testGetTableNameForForeignKeyField($table, $key) public static function dataTableType() { // Pseudo plugin class for test - require_once __DIR__ . '/../../tests/fixtures/another_test.php'; - require_once __DIR__ . '/../../tests/fixtures/pluginbarabstractstuff.php'; - require_once __DIR__ . '/../../tests/fixtures/pluginbarfoo.php'; - require_once __DIR__ . '/../../tests/fixtures/pluginfoobar.php'; - require_once __DIR__ . '/../../tests/fixtures/pluginfooservice.php'; - require_once __DIR__ . '/../../tests/fixtures/pluginfoo_search_item_filter.php'; - require_once __DIR__ . '/../../tests/fixtures/pluginfoo_search_a_b_c_d_e_f_g_bar.php'; - require_once __DIR__ . '/../../tests/fixtures/test_a_b.php'; + require_once FIXTURE_DIR . '/another_test.php'; + require_once FIXTURE_DIR . '/pluginbarabstractstuff.php'; + require_once FIXTURE_DIR . '/pluginbarfoo.php'; + require_once FIXTURE_DIR . '/pluginfoobar.php'; + require_once FIXTURE_DIR . '/pluginfooservice.php'; + require_once FIXTURE_DIR . '/pluginfoo_search_item_filter.php'; + require_once FIXTURE_DIR . '/pluginfoo_search_a_b_c_d_e_f_g_bar.php'; + require_once FIXTURE_DIR . '/test_a_b.php'; return [ ['glpi_dbmysqls', 'DBmysql', false], // not a CommonGLPI, should not be valid @@ -233,7 +233,7 @@ public function testGetItemForItemtype($itemtype, $is_valid, $expected_class) public function testGetItemForItemtypeSanitized() { - require_once __DIR__ . '/../../tests/fixtures/pluginbarfoo.php'; + require_once FIXTURE_DIR . '/pluginbarfoo.php'; $instance = new \DbUtils(); $instance->getItemForItemtype(addslashes('Glpi\Event')); @@ -245,7 +245,7 @@ public function testGetItemForItemtypeSanitized() public function testGetItemForItemtypeSanitized2() { - require_once __DIR__ . '/../../tests/fixtures/pluginbarfoo.php'; + require_once FIXTURE_DIR . '/pluginbarfoo.php'; $instance = new \DbUtils(); $instance->getItemForItemtype(addslashes('GlpiPlugin\Bar\Foo')); @@ -257,7 +257,7 @@ public function testGetItemForItemtypeSanitized2() public function testGetItemForItemtypeAbstract() { - require_once __DIR__ . '/../../tests/fixtures/pluginbarabstractstuff.php'; + require_once FIXTURE_DIR . '/pluginbarabstractstuff.php'; $instance = new \DbUtils(); $instance->getItemForItemtype('CommonDevice'); @@ -269,7 +269,7 @@ public function testGetItemForItemtypeAbstract() public function testGetItemForItemtypeAbstract2() { - require_once __DIR__ . '/../../tests/fixtures/pluginbarabstractstuff.php'; + require_once FIXTURE_DIR . '/pluginbarabstractstuff.php'; $instance = new \DbUtils(); $instance->getItemForItemtype('GlpiPlugin\Bar\AbstractStuff'); diff --git a/tests/functional/DeviceSensorModel.php b/phpunit/functional/DeviceSensorModelTest.php similarity index 65% rename from tests/functional/DeviceSensorModel.php rename to phpunit/functional/DeviceSensorModelTest.php index cdbc387a25a..1a493d22d6f 100644 --- a/tests/functional/DeviceSensorModel.php +++ b/phpunit/functional/DeviceSensorModelTest.php @@ -37,40 +37,27 @@ use DbTestCase; -class DeviceSensorModel extends DbTestCase +class DeviceSensorModelTest extends DbTestCase { - private $method; - - public function beforeTestMethod($method) - { - parent::beforeTestMethod($method); - //to handle GLPI barbarian replacements. - $this->method = str_replace( - ['\\', 'beforeTestMethod'], - ['', $method], - __METHOD__ - ); - } - public function testAdd() { $this->login(); $obj = new \DeviceSensorModel(); - // Add + // Add $in = [ - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), 'product_number' => $this->getUniqueString(), ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); - // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + // getField methods + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -79,26 +66,26 @@ public function testUpdate() $this->login(); $obj = new \DeviceSensorModel(); - // Add + // Add $id = $obj->add([ 'name' => $this->getUniqueString(), ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Update + // Update $id = $obj->getID(); $in = [ 'id' => $id, - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), 'product_number' => $this->getUniqueString(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); - // getField methods + // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -107,16 +94,16 @@ public function testDelete() $this->login(); $obj = new \DeviceSensorModel(); - // Add + // Add $id = $obj->add([ - 'name' => $this->method, + 'name' => __METHOD__, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Delete + // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/DeviceSensor.php b/phpunit/functional/DeviceSensorTest.php similarity index 70% rename from tests/functional/DeviceSensor.php rename to phpunit/functional/DeviceSensorTest.php index 5957dade1a7..7ae37c57a51 100644 --- a/tests/functional/DeviceSensor.php +++ b/phpunit/functional/DeviceSensorTest.php @@ -37,21 +37,8 @@ use DbTestCase; -class DeviceSensor extends DbTestCase +class DeviceSensorTest extends DbTestCase { - private $method; - - public function beforeTestMethod($method) - { - parent::beforeTestMethod($method); - //to handle GLPI barbarian replacements. - $this->method = str_replace( - ['\\', 'beforeTestMethod'], - ['', $method], - __METHOD__ - ); - } - public function testAdd() { $this->login(); @@ -59,19 +46,19 @@ public function testAdd() // Add $in = [ - 'designation' => $this->method, + 'designation' => __METHOD__, 'manufacturers_id' => $this->getUniqueInteger(), 'devicesensortypes_id' => $this->getUniqueInteger(), 'devicesensormodels_id' => $this->getUniqueInteger(), ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -84,23 +71,23 @@ public function testUpdate() $id = $obj->add([ 'designation' => $this->getUniqueString(), ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); $in = [ 'id' => $id, - 'designation' => $this->method, + 'designation' => __METHOD__, 'manufacturers_id' => $this->getUniqueInteger(), 'devicesensortypes_id' => $this->getUniqueInteger(), 'devicesensormodels_id' => $this->getUniqueInteger(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -111,14 +98,14 @@ public function testDelete() // Add $id = $obj->add([ - 'designation' => $this->method, + 'designation' => __METHOD__, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/DeviceSensorType.php b/phpunit/functional/DeviceSensorTypeTest.php similarity index 68% rename from tests/functional/DeviceSensorType.php rename to phpunit/functional/DeviceSensorTypeTest.php index dfbc8bb2834..fb41e454426 100644 --- a/tests/functional/DeviceSensorType.php +++ b/phpunit/functional/DeviceSensorTypeTest.php @@ -37,21 +37,8 @@ use DbTestCase; -class DeviceSensorType extends DbTestCase +class DeviceSensorTypeTest extends DbTestCase { - private $method; - - public function beforeTestMethod($method) - { - parent::beforeTestMethod($method); - //to handle GLPI barbarian replacements. - $this->method = str_replace( - ['\\', 'beforeTestMethod'], - ['', $method], - __METHOD__ - ); - } - public function testAdd() { $this->login(); @@ -59,17 +46,17 @@ public function testAdd() // Add $in = [ - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -82,21 +69,21 @@ public function testUpdate() $id = $obj->add([ 'name' => $this->getUniqueString(), ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); $in = [ 'id' => $id, - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -107,14 +94,14 @@ public function testDelete() // Add $id = $obj->add([ - 'name' => $this->method, + 'name' => __METHOD__, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/DeviceSimcard.php b/phpunit/functional/DeviceSimcardTest.php similarity index 71% rename from tests/functional/DeviceSimcard.php rename to phpunit/functional/DeviceSimcardTest.php index e04c9b2f5b5..2c6cd834bf0 100644 --- a/tests/functional/DeviceSimcard.php +++ b/phpunit/functional/DeviceSimcardTest.php @@ -37,21 +37,8 @@ use DbTestCase; -class DeviceSimcard extends DbTestCase +class DeviceSimcardTest extends DbTestCase { - private $method; - - public function beforeTestMethod($method) - { - parent::beforeTestMethod($method); - //to handle GLPI barbarian replacements. - $this->method = str_replace( - ['\\', 'beforeTestMethod'], - ['', $method], - __METHOD__ - ); - } - public function testAdd() { $this->login(); @@ -59,20 +46,20 @@ public function testAdd() // Add $in = [ - 'designation' => $this->method, + 'designation' => __METHOD__, 'manufacturers_id' => $this->getUniqueInteger(), 'devicesimcardtypes_id' => $this->getUniqueInteger(), 'voltage' => $this->getUniqueInteger(), 'allow_voip' => '1' ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -85,23 +72,23 @@ public function testUpdate() $id = $obj->add([ 'designation' => $this->getUniqueString(), ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $in = [ 'id' => $id, - 'designation' => $this->method, + 'designation' => __METHOD__, 'manufacturers_id' => $this->getUniqueInteger(), 'devicesimcardtypes_id' => $this->getUniqueInteger(), 'voltage' => $this->getUniqueInteger(), 'allow_voip' => '1' ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -112,14 +99,14 @@ public function testDelete() // Add $id = $obj->add([ - 'designation' => $this->method, + 'designation' => __METHOD__, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/DeviceSimcardType.php b/phpunit/functional/DeviceSimcardTypeTest.php similarity index 68% rename from tests/functional/DeviceSimcardType.php rename to phpunit/functional/DeviceSimcardTypeTest.php index a4bd30879db..f1a9b7b12c3 100644 --- a/tests/functional/DeviceSimcardType.php +++ b/phpunit/functional/DeviceSimcardTypeTest.php @@ -37,21 +37,8 @@ use DbTestCase; -class DeviceSimcardType extends DbTestCase +class DeviceSimcardTypeTest extends DbTestCase { - private $method; - - public function beforeTestMethod($method) - { - parent::beforeTestMethod($method); - //to handle GLPI barbarian replacements. - $this->method = str_replace( - ['\\', 'beforeTestMethod'], - ['', $method], - __METHOD__ - ); - } - public function testAdd() { $this->login(); @@ -59,17 +46,17 @@ public function testAdd() // Add $in = [ - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -82,21 +69,21 @@ public function testUpdate() $id = $obj->add([ 'name' => $this->getUniqueString(), ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); $in = [ 'id' => $id, - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -107,14 +94,14 @@ public function testDelete() // Add $id = $obj->add([ - 'name' => $this->method, + 'name' => __METHOD__, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/Document.php b/phpunit/functional/DocumentTest.php similarity index 61% rename from tests/functional/Document.php rename to phpunit/functional/DocumentTest.php index ded94e96f7f..32baaf6375d 100644 --- a/tests/functional/Document.php +++ b/phpunit/functional/DocumentTest.php @@ -39,9 +39,9 @@ /* Test for inc/document.class.php */ -class Document extends DbTestCase +class DocumentTest extends DbTestCase { - public function canApplyOnProvider() + public static function canApplyOnProvider() { return [ [ @@ -74,20 +74,20 @@ public function canApplyOnProvider() */ public function testCanApplyOn($item, $can) { - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->canApplyOn($item)) - ->isIdenticalTo($can); + $doc = new \Document(); + $this->assertSame( + $can, + $doc->canApplyOn($item) + ); } public function testGetItemtypesThatCanHave() { - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->getItemtypesThatCanHave()) - ->size->isGreaterThan(50); + $doc = new \Document(); + $this->assertGreaterThan( + 50, + count($doc->getItemtypesThatCanHave()) + ); } public function testDefineTabs() @@ -97,11 +97,8 @@ public function testDefineTabs() 'Document_Item$1' => 'Associated items', 'Document_Item$2' => 'Documents', ]; - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->defineTabs()) - ->isIdenticalTo($expected); + $doc = new \Document(); + $this->assertSame($expected, $doc->defineTabs()); } public function testPrepareInputForAdd() @@ -110,44 +107,56 @@ public function testPrepareInputForAdd() 'filename' => 'A_name.pdf' ]; - $doc = $this->newTestedInstance; - $this->array($this->testedInstance->prepareInputForAdd($input)) - ->hasSize(3) - ->hasKeys(['tag', 'filename', 'name']) - ->variable['filename']->isEqualTo('A_name.pdf') - ->variable['name']->isEqualTo('A_name.pdf'); + $doc = new \Document(); + $prepare = $doc->prepareInputForAdd($input); + $this->assertCount(3, $prepare); + $this->assertArrayHasKey('tag', $prepare); + $this->assertArrayHasKey('filename', $prepare); + $this->assertArrayHasKey('name', $prepare); + $this->assertSame('A_name.pdf', $prepare['filename']); + $this->assertSame('A_name.pdf', $prepare['name']); $this->login(); $uid = getItemByTypeName('User', TU_USER, true); - $this->array($this->testedInstance->prepareInputForAdd($input)) - ->hasSize(4) - ->hasKeys(['users_id', 'tag', 'filename', 'name']) - ->variable['users_id']->isEqualTo($uid); + $prepare = $doc->prepareInputForAdd($input); + $this->assertCount(4, $prepare); + $this->assertArrayHasKey('users_id', $prepare); + $this->assertArrayHasKey('tag', $prepare); + $this->assertArrayHasKey('filename', $prepare); + $this->assertArrayHasKey('name', $prepare); + $this->assertSame($uid, $prepare['users_id']); $item = new \Computer(); - $cid = (int)$item->add([ + $cid = $item->add([ 'name' => 'Documented Computer', 'entities_id' => 0 ]); - $this->integer($cid)->isGreaterThan(0); + $this->assertGreaterThan(0, $cid); $input['itemtype'] = $item->getType(); $input['items_id'] = $cid; - //will fail because document has not been uploaded - $this->boolean($this->testedInstance->prepareInputForAdd($input))->isFalse(); + //will fail because document has not been uploaded + $this->assertFalse($doc->prepareInputForAdd($input)); - $mdoc = new \mock\Document(); - $this->calling($mdoc)->moveUploadedDocument = true; + $mdoc = $this->getMockBuilder(\Document::class) + ->onlyMethods(['moveUploadedDocument']) + ->getMock(); + $mdoc->method('moveUploadedDocument')->willReturn(true); $input['upload_file'] = 'filename.ext'; - $this->array($mdoc->prepareInputForAdd($input)) - ->hasSize(6) - ->hasKeys(['users_id', 'tag', 'itemtype', 'items_id', 'filename', 'name']) - ->variable['users_id']->isEqualTo($uid) - ->string['itemtype']->isIdenticalTo('Computer') - ->variable['items_id']->isEqualTo($cid) - ->string['name']->isIdenticalTo('Document: Computer - Documented Computer'); + $prepare = $mdoc->prepareInputForAdd($input); + $this->assertCount(6, $prepare); + $this->assertArrayHasKey('users_id', $prepare); + $this->assertArrayHasKey('tag', $prepare); + $this->assertArrayHasKey('itemtype', $prepare); + $this->assertArrayHasKey('items_id', $prepare); + $this->assertArrayHasKey('filename', $prepare); + $this->assertArrayHasKey('name', $prepare); + $this->assertSame($uid, $prepare['users_id']); + $this->assertSame('Computer', $prepare['itemtype']); + $this->assertSame($cid, $prepare['items_id']); + $this->assertSame('Document: Computer - Documented Computer', $prepare['name']); } /** Cannot work without a real document uploaded. @@ -160,7 +169,7 @@ public function testPrepareInputForAdd() * 'name' => 'Documented Computer', * 'entities_id' => 0 * ]); - * $this->integer($cid)->isGreaterThan(0); + * $this->assertGreaterThan(0, $cid); * * $mdoc = new \mock\Document(); * $this->calling($mdoc)->moveUploadedDocument = true; @@ -169,10 +178,10 @@ public function testPrepareInputForAdd() * $input['items_id'] = $cid; * * $docid = (int)$mdoc->add($input); - * $this->integer($docid)->isGreaterThan(0); + * $this->assertGreaterThan(0, $docid); * * $doc_item = new \Document_Item(); - * $this->boolean($doc_item->getFromDBByCrit(['documents_id' => $docid]))->isTrue(); + * $this->assertTrue($doc_item->getFromDBByCrit(['documents_id' => $docid])); * * $this->array($doc_item->fields) * ->string['itemtype']->isIdenticalTo('Computer') @@ -210,21 +219,24 @@ public function testPost_addItem() ]); // Verify that the ticket is successfully added to the database. - $this->integer($cid)->isGreaterThan(0); + $this->assertGreaterThan(0, $cid); // Add a user as requester of the ticket. $ticket_user = new \Ticket_User(); - $this->integer($ticket_user->add([ - 'tickets_id' => $cid, - 'users_id' => getItemByTypeName('User', TU_USER, true), - 'type' => \CommonITILActor::REQUESTER - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ticket_user->add([ + 'tickets_id' => $cid, + 'users_id' => getItemByTypeName('User', TU_USER, true), + 'type' => \CommonITILActor::REQUESTER + ]) + ); // Create a second test user. $user = new \User(); - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => 'test_user2', 'realname' => 'Test User', 'firstname' => 'Test', @@ -236,67 +248,71 @@ public function testPost_addItem() 'entities_id' => 0, 'usercategories_id' => 1 ]); - $this->integer($uid)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid); // Create a document stub. - $mdoc = new \mock\Document(); - - $this->calling($mdoc)->moveUploadedDocument = true; + $mdoc = $this->getMockBuilder(\Document::class) + ->onlyMethods(['moveUploadedDocument']) + ->getMock(); + $mdoc->method('moveUploadedDocument')->willReturn(true); $input['upload_file'] = 'filename.ext'; $input['itemtype'] = $item->getType(); $input['items_id'] = $cid; $input['documentcategories_id'] = 1; - $docid = (int)$mdoc->add($input); - $this->integer($docid)->isGreaterThan(0); + $docid = $mdoc->add($input); + $this->assertGreaterThan(0, $docid); // Refresh the ticket. - $this->boolean($item->getFromDB($cid))->isTrue(); + $this->assertTrue($item->getFromDB($cid)); $doc_item = new \Document_Item(); - $this->boolean($doc_item->getFromDBByCrit(['documents_id' => $docid]))->isTrue(); + $this->assertTrue($doc_item->getFromDBByCrit(['documents_id' => $docid])); // Verify that the ticket and document item are linked. - $this->string($doc_item->fields['itemtype'])->isIdenticalTo(\Ticket::getType()); - $this->integer($cid)->isEqualTo($doc_item->fields['items_id']); + $this->assertSame(\Ticket::getType(), $doc_item->fields['itemtype']); + $this->assertEquals($doc_item->fields['items_id'], $cid); /** - * Verifiy that when a document is added to a ticket in WAITING status + * Verify that when a document is added to a ticket in WAITING status * without any assigned user, the status of the ticket changes to INCOMING. */ - $this->integer($item->fields['status'])->isEqualTo(\Ticket::INCOMING); + $this->assertEquals(\Ticket::INCOMING, $item->fields['status']); // Assign the second user to the ticket. $ticket_user = new \Ticket_User(); - $this->integer($ticket_user->add([ - 'tickets_id' => $cid, - 'users_id' => $uid, - 'type' => \CommonITILActor::ASSIGN - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ticket_user->add([ + 'tickets_id' => $cid, + 'users_id' => $uid, + 'type' => \CommonITILActor::ASSIGN + ]) + ); // Update the ticket status to WAITING. $item->update([ 'id' => $cid, 'status' => \Ticket::WAITING ]); - $this->integer($item->fields['status'])->isEqualTo(\Ticket::WAITING); + $this->assertEquals(\Ticket::WAITING, $item->fields['status']); // Add another document to the ticket. - $docid = (int)$mdoc->add($input); - $this->integer($docid)->isGreaterThan(0); + $docid = $mdoc->add($input); + $this->assertGreaterThan(0, $docid); // Refresh the ticket. - $this->boolean($item->getFromDB($cid))->isTrue(); + $this->assertTrue($item->getFromDB($cid)); /** - * Verifiy that when a document is added to a ticket in WAITING status + * Verify that when a document is added to a ticket in WAITING status * with an assigned user, the status of the ticket changes to ASSIGNED. */ - $this->integer($item->fields['status'])->isEqualTo(\Ticket::ASSIGNED); + $this->assertEquals(\Ticket::ASSIGNED, $item->fields['status']); } - protected function validDocProvider() + public static function validDocProvider() { return [ [ @@ -317,28 +333,29 @@ protected function validDocProvider() */ public function testIsValidDoc($filename, $expected) { - $this->string(\Document::isValidDoc($filename))->isIdenticalTo($expected); + $this->assertSame($expected, \Document::isValidDoc($filename)); } public function testIsValidDocRegexp() { $doctype = new \DocumentType(); - $this->integer( - (int)$doctype->add([ + $this->assertGreaterThan( + 0, + $doctype->add([ 'name' => 'Type test', 'ext' => '/[0-9]{4}/' ]) - )->isGreaterThan(0); + ); - $this->string(\Document::isValidDoc('myfile.1234'))->isIdenticalTo('1234'); - $this->string(\Document::isValidDoc('myfile.123'))->isIdenticalTo(''); - $this->string(\Document::isValidDoc('myfile.9645'))->isIdenticalTo('9645'); - $this->string(\Document::isValidDoc('myfile.abcde'))->isIdenticalTo(''); + $this->assertSame('1234', \Document::isValidDoc('myfile.1234')); + $this->assertSame('', \Document::isValidDoc('myfile.123')); + $this->assertSame('9645', \Document::isValidDoc('myfile.9645')); + $this->assertSame('', \Document::isValidDoc('myfile.abcde')); } public function testGetImageTag() { - $this->string(\Document::getImageTag('datag'))->isIdenticalTo('#datag#'); + $this->assertSame('#datag#', \Document::getImageTag('datag')); } protected function isImageProvider() @@ -358,7 +375,7 @@ protected function isImageProvider() */ public function testIsImage($file, $expected) { - $this->boolean(\Document::isImage($file))->isIdenticalTo($expected); + $this->assertSame($expected, \Document::isImage($file)); } /** @@ -368,45 +385,46 @@ public function testCanViewDocumentFile() { $document = new \Document(); - $this->integer( - (int)$document->add([ + $this->assertGreaterThan( + 0, + $document->add([ 'name' => 'basic document', 'filename' => 'doc.xls', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); - // glpi can see all documents + // glpi can see all documents $this->login('glpi', 'glpi'); - $this->boolean($document->canViewFile())->isTrue(); + $this->assertTrue($document->canViewFile()); - // tech can see all documents + // tech can see all documents $this->login('tech', 'tech'); - $this->boolean($document->canViewFile())->isTrue(); + $this->assertTrue($document->canViewFile()); - // normal can see all documents + // normal can see all documents $this->login('normal', 'normal'); - $this->boolean($document->canViewFile())->isTrue(); + $this->assertTrue($document->canViewFile()); - // post-only cannot see all documents + // post-only cannot see all documents $this->login('post-only', 'postonly'); - $this->boolean($document->canViewFile())->isFalse(); + $this->assertFalse($document->canViewFile()); - // post-only can see its own documents + // post-only can see its own documents $this->login('post-only', 'postonly'); - $this->boolean($document->canViewFile([ + $this->assertFalse($document->canViewFile([ 'itemtype' => 'not_a_class', 'items_id' => 'not an id', - ]))->isFalse(); - $this->boolean( + ])); + $this->assertTrue( $document->update( [ 'id' => $document->getID(), 'users_id' => \Session::getLoginUserID(), ] ) - )->isTrue(); - $this->boolean($document->canViewFile())->isTrue(); + ); + $this->assertTrue($document->canViewFile()); } /** @@ -416,84 +434,92 @@ public function testCanViewReminderFile() { $basicDocument = new \Document(); - $this->integer( - (int)$basicDocument->add([ + $this->assertGreaterThan( + 0, + $basicDocument->add([ 'name' => 'basic document', 'filename' => 'doc.xls', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $inlinedDocument = new \Document(); - $this->integer( - (int)$inlinedDocument->add([ + $this->assertGreaterThan( + 0, + $inlinedDocument->add([ 'name' => 'inlined document', 'filename' => 'inlined.png', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $this->login('post-only', 'postonly'); // post-only cannot see documents only linked to someone else reminders $glpiReminder = new \Reminder(); - $this->integer( - (int)$glpiReminder->add([ + $this->assertGreaterThan( + 0, + $glpiReminder->add([ 'name' => 'Glpi reminder', 'text' => '', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $document_item = new \Document_Item(); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $basicDocument->getID(), 'items_id' => $glpiReminder->getID(), 'itemtype' => \Reminder::class, ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $inlinedDocument->getID(), 'items_id' => $glpiReminder->getID(), 'itemtype' => \Reminder::class, ]) - )->isGreaterThan(0); + ); - $this->boolean($basicDocument->canViewFile())->isFalse(); - $this->boolean($inlinedDocument->canViewFile())->isFalse(); + $this->assertFalse($basicDocument->canViewFile()); + $this->assertFalse($inlinedDocument->canViewFile()); // post-only can see documents linked to its own reminders $myReminder = new \Reminder(); - $this->integer( - (int)$myReminder->add([ + $this->assertGreaterThan( + 0, + $myReminder->add([ 'name' => 'My reminder', 'text' => '', 'users_id' => \Session::getLoginUserID(), ]) - )->isGreaterThan(0); + ); $document_item = new \Document_Item(); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $basicDocument->getID(), 'items_id' => $myReminder->getID(), 'itemtype' => \Reminder::class, ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $inlinedDocument->getID(), 'items_id' => $myReminder->getID(), 'itemtype' => \Reminder::class, ]) - )->isGreaterThan(0); + ); - $this->boolean($basicDocument->canViewFile())->isTrue(); - $this->boolean($inlinedDocument->canViewFile())->isTrue(); + $this->assertTrue($basicDocument->canViewFile()); + $this->assertTrue($inlinedDocument->canViewFile()); } /** @@ -505,116 +531,121 @@ public function testCanViewKnowbaseItemFile() global $CFG_GLPI; $basicDocument = new \Document(); - $this->integer( - (int)$basicDocument->add([ + $this->assertGreaterThan( + 0, + $basicDocument->add([ 'name' => 'basic document', 'filename' => 'doc.xls', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $inlinedDocument = new \Document(); - $this->integer( - (int)$inlinedDocument->add([ + $this->assertGreaterThan( + 0, + $inlinedDocument->add([ 'name' => 'inlined document', 'filename' => 'inlined.png', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $kbItem = new \KnowbaseItem(); - $this->integer( - (int)$kbItem->add([ + $this->assertGreaterThan( + 0, + $kbItem->add([ 'name' => 'Generic KB item', 'answer' => '', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $document_item = new \Document_Item(); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $basicDocument->getID(), 'items_id' => $kbItem->getID(), 'itemtype' => \KnowbaseItem::class, 'users_id' => getItemByTypeName('User', 'normal', true), ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $inlinedDocument->getID(), 'items_id' => $kbItem->getID(), 'itemtype' => \KnowbaseItem::class, 'users_id' => getItemByTypeName('User', 'normal', true), ]) - )->isGreaterThan(0); + ); - // anonymous cannot see documents if not linked to FAQ items - $this->boolean($basicDocument->canViewFile())->isFalse(); - $this->boolean($inlinedDocument->canViewFile())->isFalse(); + // anonymous cannot see documents if not linked to FAQ items + $this->assertFalse($basicDocument->canViewFile()); + $this->assertFalse($inlinedDocument->canViewFile()); - // anonymous cannot see documents linked to FAQ items if public FAQ is not active + // anonymous cannot see documents linked to FAQ items if public FAQ is not active $CFG_GLPI['use_public_faq'] = 0; - $this->boolean( + $this->assertTrue( $kbItem->update( [ 'id' => $kbItem->getID(), 'is_faq' => true, ] ) - )->isTrue(); + ); - // faq items in mulitple entity mode need to be set in root enity +recursive to be viewed + // faq items in multiple entity mode need to be set in root entity +recursive to be viewed $entity_kbitems = new \Entity_KnowbaseItem(); $ent_kb_id = $entity_kbitems->add([ 'knowbaseitems_id' => $kbItem->getID(), 'entities_id' => 0, 'is_recursive' => 1, ]); - $this->integer($ent_kb_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $ent_kb_id); - $this->boolean($basicDocument->canViewFile())->isFalse(); - $this->boolean($inlinedDocument->canViewFile())->isFalse(); + $this->assertFalse($basicDocument->canViewFile()); + $this->assertFalse($inlinedDocument->canViewFile()); - // anonymous can see documents linked to FAQ items when public FAQ is active + // anonymous can see documents linked to FAQ items when public FAQ is active $CFG_GLPI['use_public_faq'] = 1; - $this->boolean($basicDocument->canViewFile())->isTrue(); - $this->boolean($inlinedDocument->canViewFile())->isTrue(); + $this->assertTrue($basicDocument->canViewFile()); + $this->assertTrue($inlinedDocument->canViewFile()); $CFG_GLPI['use_public_faq'] = 0; - // post-only can see documents linked to FAQ items + // post-only can see documents linked to FAQ items $this->login('post-only', 'postonly'); - $this->boolean($basicDocument->canViewFile())->isTrue(); - $this->boolean($inlinedDocument->canViewFile())->isTrue(); + $this->assertTrue($basicDocument->canViewFile()); + $this->assertTrue($inlinedDocument->canViewFile()); - // post-only cannot see documents if not linked to FAQ items - $this->boolean( + // post-only cannot see documents if not linked to FAQ items + $this->assertTrue( $kbItem->update( [ 'id' => $kbItem->getID(), 'is_faq' => false, ] ) - )->isTrue(); - $this->boolean( + ); + $this->assertTrue( $entity_kbitems->delete([ 'id' => $ent_kb_id ]) - )->isTrue(); + ); - $this->boolean($basicDocument->canViewFile())->isFalse(); - $this->boolean($inlinedDocument->canViewFile())->isFalse(); + $this->assertFalse($basicDocument->canViewFile()); + $this->assertFalse($inlinedDocument->canViewFile()); } /** * Data provider for self::testCanViewItilFile(). */ - protected function itilTypeProvider() + public static function itilTypeProvider() { return [ [ @@ -640,83 +671,89 @@ public function testCanViewItilFile($itemtype) $this->login('glpi', 'glpi'); // Login with glpi to prevent link to post-only $basicDocument = new \Document(); - $this->integer( - (int)$basicDocument->add([ + $this->assertGreaterThan( + 0, + $basicDocument->add([ 'name' => 'basic document', 'filename' => 'doc.xls', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $inlinedDocument = new \Document(); - $this->integer( - (int)$inlinedDocument->add([ + $this->assertGreaterThan( + 0, + $inlinedDocument->add([ 'name' => 'inlined document', 'filename' => 'inlined.png', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $item = new $itemtype(); $fkey = $item->getForeignKeyField(); - $this->integer( - (int)$item->add([ + $this->assertGreaterThan( + 0, + $item->add([ 'name' => 'New ' . $itemtype, 'content' => '', ]) - )->isGreaterThan(0); + ); $document_item = new \Document_Item(); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $basicDocument->getID(), 'items_id' => $item->getID(), 'itemtype' => $itemtype, ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $inlinedDocument->getID(), 'items_id' => $item->getID(), 'itemtype' => $itemtype, ]) - )->isGreaterThan(0); + ); - // post-only cannot see documents if not able to view ITIL (ITIL content) + // post-only cannot see documents if not able to view ITIL (ITIL content) $this->login('post-only', 'postonly'); $_SESSION["glpiactiveprofile"][$item::$rightname] = READ; // force READ write for tested ITIL type - $this->boolean($basicDocument->canViewFile())->isFalse(); - $this->boolean($inlinedDocument->canViewFile())->isFalse(); - $this->boolean($basicDocument->canViewFile([$fkey => $item->getID()]))->isFalse(); - $this->boolean($inlinedDocument->canViewFile([$fkey => $item->getID()]))->isFalse(); - $this->boolean($basicDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()]))->isFalse(); - $this->boolean($inlinedDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()]))->isFalse(); - - // post-only can see documents linked to its own ITIL (ITIL content) + $this->assertFalse($basicDocument->canViewFile()); + $this->assertFalse($inlinedDocument->canViewFile()); + $this->assertFalse($basicDocument->canViewFile([$fkey => $item->getID()])); + $this->assertFalse($inlinedDocument->canViewFile([$fkey => $item->getID()])); + $this->assertFalse($basicDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()])); + $this->assertFalse($inlinedDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()])); + + // post-only can see documents linked to its own ITIL (ITIL content) $itil_user_class = $itemtype . '_User'; $itil_user = new $itil_user_class(); - $this->integer( - (int)$itil_user->add([ + $this->assertGreaterThan( + 0, + $itil_user->add([ $fkey => $item->getID(), 'type' => \CommonITILActor::OBSERVER, 'users_id' => \Session::getLoginUserID(), ]) - )->isGreaterThan(0); - - $this->boolean($basicDocument->canViewFile())->isFalse(); // False without params - $this->boolean($inlinedDocument->canViewFile())->isFalse(); // False without params - $this->boolean($basicDocument->canViewFile([$fkey => $item->getID()]))->isTrue(); - $this->boolean($inlinedDocument->canViewFile([$fkey => $item->getID()]))->isTrue(); - $this->boolean($basicDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()]))->isTrue(); - $this->boolean($inlinedDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()]))->isTrue(); + ); + + $this->assertFalse($basicDocument->canViewFile()); // False without params + $this->assertFalse($inlinedDocument->canViewFile()); // False without params + $this->assertTrue($basicDocument->canViewFile([$fkey => $item->getID()])); + $this->assertTrue($inlinedDocument->canViewFile([$fkey => $item->getID()])); + $this->assertTrue($basicDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()])); + $this->assertTrue($inlinedDocument->canViewFile(['itemtype' => $item->getType(), 'items_id' => $item->getID()])); } /** * Data provider for self::testCanViewTicketChildFile(). */ - protected function ticketChildClassProvider() + public static function ticketChildClassProvider() { return [ [ @@ -769,64 +806,69 @@ public function testCanViewTicketChildFile($itil_itemtype, $child_itemtype) $this->login('glpi', 'glpi'); // Login with glpi to prevent link to post-only $inlinedDocument = new \Document(); - $this->integer( - (int)$inlinedDocument->add([ + $this->assertGreaterThan( + 0, + $inlinedDocument->add([ 'name' => 'inlined document', 'filename' => 'inlined.png', 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $itil = new $itil_itemtype(); $fkey = $itil->getForeignKeyField(); - $this->integer( - (int)$itil->add([ + $this->assertGreaterThan( + 0, + $itil->add([ 'name' => 'New ' . $itil_itemtype, 'content' => 'No image in content', ]) - )->isGreaterThan(0); + ); $child = new $child_itemtype(); - $this->integer( - (int)$child->add([ + $this->assertGreaterThan( + 0, + $child->add([ 'content' => '', $fkey => $itil->getID(), 'items_id' => $itil->getID(), 'itemtype' => $itil_itemtype, 'users_id' => '2', // user "glpi" ]) - )->isGreaterThan(0); + ); $document_item = new \Document_Item(); - $this->integer( - (int)$document_item->add([ + $this->assertGreaterThan( + 0, + $document_item->add([ 'documents_id' => $inlinedDocument->getID(), 'items_id' => $itil->getID(), 'itemtype' => $itil_itemtype, ]) - )->isGreaterThan(0); + ); - // post-only cannot see documents if not able to view ITIL + // post-only cannot see documents if not able to view ITIL $this->login('post-only', 'postonly'); $_SESSION["glpiactiveprofile"][$itil::$rightname] = READ; // force READ write for tested ITIL type - $this->boolean($inlinedDocument->canViewFile())->isFalse(); - $this->boolean($inlinedDocument->canViewFile([$fkey => $itil->getID()]))->isFalse(); - $this->boolean($inlinedDocument->canViewFile(['itemtype' => $itil->getType(), 'items_id' => $itil->getID()]))->isFalse(); + $this->assertFalse($inlinedDocument->canViewFile()); + $this->assertFalse($inlinedDocument->canViewFile([$fkey => $itil->getID()])); + $this->assertFalse($inlinedDocument->canViewFile(['itemtype' => $itil->getType(), 'items_id' => $itil->getID()])); - // post-only can see documents linked to its own ITIL + // post-only can see documents linked to its own ITIL $itil_user_class = $itil_itemtype . '_User'; $itil_user = new $itil_user_class(); - $this->integer( - (int)$itil_user->add([ + $this->assertGreaterThan( + 0, + $itil_user->add([ $fkey => $itil->getID(), 'type' => \CommonITILActor::OBSERVER, 'users_id' => \Session::getLoginUserID(), ]) - )->isGreaterThan(0); + ); - $this->boolean($inlinedDocument->canViewFile())->isFalse(); // False without params - $this->boolean($inlinedDocument->canViewFile([$fkey => $itil->getID()]))->isTrue(); - $this->boolean($inlinedDocument->canViewFile(['itemtype' => $itil->getType(), 'items_id' => $itil->getID()]))->isTrue(); + $this->assertFalse($inlinedDocument->canViewFile()); // False without params + $this->assertTrue($inlinedDocument->canViewFile([$fkey => $itil->getID()])); + $this->assertTrue($inlinedDocument->canViewFile(['itemtype' => $itil->getType(), 'items_id' => $itil->getID()])); } public function testCronCleanorphans() @@ -839,17 +881,17 @@ public function testCronCleanorphans() $did1 = (int)$doc->add([ 'name' => 'test doc' ]); - $this->integer($did1)->isGreaterThan(0); + $this->assertGreaterThan(0, $did1); $did2 = (int)$doc->add([ 'name' => 'test doc' ]); - $this->integer($did2)->isGreaterThan(0); + $this->assertGreaterThan(0, $did2); $did3 = (int)$doc->add([ 'name' => 'test doc' ]); - $this->integer($did3)->isGreaterThan(0); + $this->assertGreaterThan(0, $did3); // create a ticket and link one document $ticket = new \Ticket(); @@ -859,32 +901,32 @@ public function testCronCleanorphans() 'entities_id' => 0, '_documents_id' => [$did3] ]); - $this->integer((int)$tickets_id_1)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($tickets_id_1))->isTrue(); + $this->assertGreaterThan(0, (int)$tickets_id_1); + $this->assertTrue($ticket->getFromDB($tickets_id_1)); $docitem = new \Document_Item(); - $this->boolean($docitem->getFromDBByCrit(['itemtype' => 'Ticket', 'items_id' => $tickets_id_1]))->isTrue(); + $this->assertTrue($docitem->getFromDBByCrit(['itemtype' => 'Ticket', 'items_id' => $tickets_id_1])); // launch Cron for closing tickets $mode = - \CronTask::MODE_EXTERNAL; // force \CronTask::launch($mode, 5, 'cleanorphans'); // check documents presence - $this->boolean($doc->getFromDB($did1))->isFalse(); - $this->boolean($doc->getFromDB($did2))->isFalse(); - $this->boolean($doc->getFromDB($did3))->isTrue(); + $this->assertFalse($doc->getFromDB($did1)); + $this->assertFalse($doc->getFromDB($did2)); + $this->assertTrue($doc->getFromDB($did3)); } public function testGetDuplicateOf() { - $instance = $this->newTestedInstance(); + $instance = new \Document(); // Test when the file is not in the DB - $output = $instance->getDuplicateOf(0, __DIR__ . '/../fixtures/uploads/foo.png'); - $this->boolean($output)->isFalse(); + $output = $instance->getDuplicateOf(0, FIXTURE_DIR . '/uploads/foo.png'); + $this->assertFalse($output); $filename = 'foo.png'; - copy(__DIR__ . '/../fixtures/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); + copy(FIXTURE_DIR . '/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); $tag = \Rule::getUuid(); $input = [ 'filename' => 'foo.png', @@ -900,22 +942,22 @@ public function testGetDuplicateOf() ]; $document = new \Document(); $document->add($input); - $this->boolean($document->isnewItem())->isFalse(); + $this->assertFalse($document->isnewItem()); - // Check the file is found in the FB - $instance = $this->newTestedInstance(); - $output = $instance->getDuplicateOf(0, __DIR__ . '/../fixtures/uploads/foo.png'); - $this->boolean($output)->isTrue(); + // Check the file is found in the FB + $instance = new \Document(); + $output = $instance->getDuplicateOf(0, FIXTURE_DIR . '/uploads/foo.png'); + $this->assertTrue($output); - // togle the blackisted flag + // toggle the blacklisted flag $success = $instance->update([ 'id' => $instance->getID(), 'is_blacklisted' => '1' ]); - $this->boolean($success)->isTrue(); + $this->assertTrue($success); - // Test when the document exists and is blacklisted - $output = $instance->getDuplicateOf(0, __DIR__ . '/../fixtures/uploads/foo.png'); - $this->boolean($output)->isFalse(); + // Test when the document exists and is blacklisted + $output = $instance->getDuplicateOf(0, FIXTURE_DIR . '/uploads/foo.png'); + $this->assertFalse($output); } } diff --git a/tests/functional/DocumentType.php b/phpunit/functional/DocumentTypeTest.php similarity index 57% rename from tests/functional/DocumentType.php rename to phpunit/functional/DocumentTypeTest.php index f169c790d7b..07ab7fcd92f 100644 --- a/tests/functional/DocumentType.php +++ b/phpunit/functional/DocumentTypeTest.php @@ -40,31 +40,31 @@ /* Test for inc/documenttype.class.php */ -class DocumentType extends DbTestCase +class DocumentTypeTest extends DbTestCase { public function testGetUploadableFilePattern() { $doctype = new \DocumentType(); // Clear types to prevent test to be impacted by potential default types changes - $this->boolean($doctype->deleteByCriteria(['1']))->isTrue(); + $this->assertTrue($doctype->deleteByCriteria(['1'])); - $this->integer((int)$doctype->add(Toolbox::addslashes_deep(['name' => 'JPG' ,'ext' => '/\.jpe?g$/'])))->isGreaterThan(0); - $this->integer((int)$doctype->add(Toolbox::addslashes_deep(['name' => 'DOC' ,'ext' => 'doc'])))->isGreaterThan(0); - $this->integer((int)$doctype->add(Toolbox::addslashes_deep(['name' => 'XML' ,'ext' => 'xml'])))->isGreaterThan(0); - $this->integer((int)$doctype->add(Toolbox::addslashes_deep(['name' => 'Tarball' ,'ext' => 'tar.gz'])))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doctype->add(Toolbox::addslashes_deep(['name' => 'JPG' ,'ext' => '/\.jpe?g$/']))); + $this->assertGreaterThan(0, (int)$doctype->add(Toolbox::addslashes_deep(['name' => 'DOC' ,'ext' => 'doc']))); + $this->assertGreaterThan(0, (int)$doctype->add(Toolbox::addslashes_deep(['name' => 'XML' ,'ext' => 'xml']))); + $this->assertGreaterThan(0, (int)$doctype->add(Toolbox::addslashes_deep(['name' => 'Tarball' ,'ext' => 'tar.gz']))); // Validate generated pattern $pattern = \DocumentType::getUploadableFilePattern(); - $this->string($pattern)->isIdenticalTo('/((\.jpe?g$)|\.doc$|\.xml$|\.tar\.gz$)/i'); + $this->assertSame('/((\.jpe?g$)|\.doc$|\.xml$|\.tar\.gz$)/i', $pattern); // Validate matches - $this->integer(preg_match($pattern, 'test.jpg'))->isEqualTo(1); - $this->integer(preg_match($pattern, 'test.jpeg'))->isEqualTo(1); - $this->integer(preg_match($pattern, 'test.jpag'))->isEqualTo(0); - $this->integer(preg_match($pattern, 'test.doc'))->isEqualTo(1); - $this->integer(preg_match($pattern, 'test.xml'))->isEqualTo(1); - $this->integer(preg_match($pattern, 'testxml'))->isEqualTo(0); - $this->integer(preg_match($pattern, 'test.tar.gz'))->isEqualTo(1); + $this->assertEquals(1, preg_match($pattern, 'test.jpg')); + $this->assertEquals(1, preg_match($pattern, 'test.jpeg')); + $this->assertEquals(0, preg_match($pattern, 'test.jpag')); + $this->assertEquals(1, preg_match($pattern, 'test.doc')); + $this->assertEquals(1, preg_match($pattern, 'test.xml')); + $this->assertEquals(0, preg_match($pattern, 'testxml')); + $this->assertEquals(1, preg_match($pattern, 'test.tar.gz')); } } diff --git a/tests/functional/Document_Item.php b/phpunit/functional/Document_ItemTest.php similarity index 58% rename from tests/functional/Document_Item.php rename to phpunit/functional/Document_ItemTest.php index e49382609d8..d1497497ad6 100644 --- a/tests/functional/Document_Item.php +++ b/phpunit/functional/Document_ItemTest.php @@ -36,101 +36,90 @@ namespace tests\units; use DbTestCase; +use Monolog\Logger; /* Test for inc/document_item.class.php */ -class Document_Item extends DbTestCase +class Document_ItemTest extends DbTestCase { public function testGetForbiddenStandardMassiveAction() { - $this->newTestedInstance(); - $this->array( - $this->testedInstance->getForbiddenStandardMassiveAction() - )->isIdenticalTo(['clone', 'update']); + $ditem = new \Document_Item(); + $this->assertSame( + ['clone', 'update'], + $ditem->getForbiddenStandardMassiveAction() + ); } public function testPrepareInputForAdd() { $input = []; - $ditem = $this->newTestedInstance; + $ditem = new \Document_Item(); - $this->when( - function () use ($input) { - $this->boolean($this->testedInstance->add($input))->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Item type is mandatory') - ->exists(); + $res = $ditem->add($input); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Item type is mandatory', + Logger::WARNING + ); $input['itemtype'] = ''; - $this->when( - function () use ($input) { - $this->boolean($this->testedInstance->add($input))->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Item type is mandatory') - ->exists(); + $res = $ditem->add($input); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Item type is mandatory', + Logger::WARNING + ); $input['itemtype'] = 'NotAClass'; - $this->when( - function () use ($input) { - $this->boolean($this->testedInstance->add($input))->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('No class found for type NotAClass') - ->exists(); + $res = $ditem->add($input); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'No class found for type NotAClass', + Logger::WARNING + ); $input['itemtype'] = 'Computer'; - $this->when( - function () use ($input) { - $this->boolean($this->testedInstance->add($input))->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Item ID is mandatory') - ->exists(); + $res = $ditem->add($input); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Item ID is mandatory', + Logger::WARNING + ); $input['items_id'] = 0; - $this->when( - function () use ($input) { - $this->boolean($this->testedInstance->add($input))->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Item ID is mandatory') - ->exists(); + $res = $ditem->add($input); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Item ID is mandatory', + Logger::WARNING + ); $cid = getItemByTypeName('Computer', '_test_pc01', true); $input['items_id'] = $cid; - $this->when( - function () use ($input) { - $this->boolean($this->testedInstance->add($input))->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Document ID is mandatory') - ->exists(); + $res = $ditem->add($input); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Document ID is mandatory', + Logger::WARNING + ); $input['documents_id'] = 0; - $this->when( - function () use ($input) { - $this->boolean($this->testedInstance->add($input))->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Document ID is mandatory') - ->exists(); + $res = $ditem->add($input); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Document ID is mandatory', + Logger::WARNING + ); $document = new \Document(); - $this->integer( - (int)$document->add([ + $this->assertGreaterThan( + 0, + $document->add([ 'name' => 'Test document to link' ]) - )->isGreaterThan(0); + ); $input['documents_id'] = $document->getID(); $expected = [ @@ -142,9 +131,10 @@ function () use ($input) { 'is_recursive' => 0 ]; - $this->array( - $this->testedInstance->prepareInputForAdd($input) - )->isIdenticalTo($expected); + $this->assertSame( + $expected, + $ditem->prepareInputForAdd($input) + ); } @@ -165,7 +155,7 @@ public function testGetDistinctTypesParams() ], 'ORDER' => 'itemtype' ]; - $this->array(\Document_Item::getDistinctTypesParams(1))->isIdenticalTo($expected); + $this->assertSame($expected, \Document_Item::getDistinctTypesParams(1)); $extra_where = ['date_mod' => ['>', '2000-01-01']]; $expected = [ @@ -189,7 +179,7 @@ public function testGetDistinctTypesParams() ], 'ORDER' => 'itemtype' ]; - $this->array(\Document_Item::getDistinctTypesParams(1, $extra_where))->isIdenticalTo($expected); + $this->assertSame($expected, \Document_Item::getDistinctTypesParams(1, $extra_where)); } @@ -204,55 +194,62 @@ public function testPostAddItem() 'date_mod' => '2020-01-01' ]); - $this->integer($tickets_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $tickets_id); - // Document and Document_Item + // Document and Document_Item $doc = new \Document(); - $this->integer( - (int)$doc->add([ + $this->assertGreaterThan( + 0, + $doc->add([ 'users_id' => $uid, 'tickets_id' => $tickets_id, 'name' => 'A simple document object' ]) - )->isGreaterThan(0); + ); - //do not change ticket modification date + //do not change ticket modification date $doc_item = new \Document_Item(); - $this->integer( - (int)$doc_item->add([ + $this->assertGreaterThan( + 0, + $doc_item->add([ 'users_id' => $uid, 'items_id' => $tickets_id, 'itemtype' => 'Ticket', 'documents_id' => $doc->getID(), '_do_update_ticket' => false ]) - )->isGreaterThan(0); + ); - $this->boolean($ticket->getFromDB($tickets_id))->isTrue(); - $this->string($ticket->fields['date_mod'])->isIdenticalTo('2020-01-01 00:00:00'); + $this->assertTrue($ticket->getFromDB($tickets_id)); + $this->assertSame('2020-01-01 00:00:00', $ticket->fields['date_mod']); - //do change ticket modification date + //do change ticket modification date $_SESSION["glpi_currenttime"] = '2021-01-01 00:00:01'; $doc = new \Document(); - $this->integer( - (int)$doc->add([ + $this->assertGreaterThan( + 0, + $doc->add([ 'users_id' => $uid, 'tickets_id' => $tickets_id, 'name' => 'A simple document object' ]) - )->isGreaterThan(0); + ); $doc_item = new \Document_Item(); - $this->integer( - (int)$doc_item->add([ + $this->assertGreaterThan( + 0, + $doc_item->add([ 'users_id' => $uid, 'items_id' => $tickets_id, 'itemtype' => 'Ticket', 'documents_id' => $doc->getID(), ]) - )->isGreaterThan(0); + ); - $this->boolean($ticket->getFromDB($tickets_id))->isTrue(); - $this->string($ticket->fields['date_mod'])->isNotEqualTo('2021-01-01 00:00:01'); + $this->assertTrue($ticket->getFromDB($tickets_id)); + $this->assertNotEquals( + '2021-01-01 00:00:01', + $ticket->fields['date_mod'] + ); } } diff --git a/tests/functional/Dropdown.php b/phpunit/functional/DropdownTest.php similarity index 88% rename from tests/functional/Dropdown.php rename to phpunit/functional/DropdownTest.php index e488e4d4a40..778c51a7784 100644 --- a/tests/functional/Dropdown.php +++ b/phpunit/functional/DropdownTest.php @@ -48,30 +48,28 @@ /* Test for inc/dropdown.class.php */ -class Dropdown extends DbTestCase +class DropdownTest extends DbTestCase { public function testShowLanguages() { $opt = [ 'display_emptychoice' => true, 'display' => false ]; $out = \Dropdown::showLanguages('dropfoo', $opt); - $this->string($out) - ->contains("name='dropfoo'") - ->contains("value='' selected") - ->notContains("value='0'") - ->contains("value='fr_FR'"); + $this->assertStringContainsString("name='dropfoo'", $out); + $this->assertStringContainsString("value='' selected", $out); + $this->assertStringNotContainsString("value='0'", $out); + $this->assertStringContainsString("value='fr_FR'", $out); $opt = ['display' => false, 'value' => 'cs_CZ', 'rand' => '1234']; $out = \Dropdown::showLanguages('language', $opt); - $this->string($out) - ->notContains("value=''") - ->notContains("value='0'") - ->contains("name='language' id='dropdown_language1234") - ->contains("value='cs_CZ' selected") - ->contains("value='fr_FR'"); + $this->assertStringNotContainsString("value=''", $out); + $this->assertStringNotContainsString("value='0'", $out); + $this->assertStringContainsString("name='language' id='dropdown_language1234", $out); + $this->assertStringContainsString("value='cs_CZ' selected", $out); + $this->assertStringContainsString("value='fr_FR'", $out); } - public function dataTestImport() + public static function dataTestImport() { return [ // input, name, message @@ -90,16 +88,16 @@ public function testImport($input, $result, $msg) { $id = \Dropdown::import('UserTitle', $input); if ($result) { - $this->integer((int)$id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$id); $ut = new \UserTitle(); - $this->boolean($ut->getFromDB($id))->isTrue(); - $this->string($ut->getField('name'))->isIdenticalTo($result); + $this->assertTrue($ut->getFromDB($id)); + $this->assertSame($result, $ut->getField('name')); } else { - $this->integer((int)$id)->isLessThan(0); + $this->assertLessThan(0, (int)$id); } } - public function dataTestTreeImport() + public static function dataTestTreeImport() { return [ // input, name, completename, message @@ -126,13 +124,13 @@ public function testTreeImport($input, $result, $complete, $msg) $input['entities_id'] = getItemByTypeName('Entity', '_test_root_entity', true); $id = \Dropdown::import('Location', $input); if ($result) { - $this->integer((int)$id, $msg)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$id, $msg); $ut = new \Location(); - $this->boolean($ut->getFromDB($id))->isTrue(); - $this->string($ut->getField('name'))->isIdenticalTo($result); - $this->string($ut->getField('completename'))->isIdenticalTo($complete); + $this->assertTrue($ut->getFromDB($id)); + $this->assertSame($result, $ut->getField('name')); + $this->assertSame($complete, $ut->getField('completename')); } else { - $this->integer((int)$id)->isLessThanOrEqualTo(0); + $this->assertLessThanOrEqual(0, (int)$id); } } @@ -143,34 +141,34 @@ public function testGetDropdownName() $encoded_sep = Sanitizer::sanitize(' > '); $ret = \Dropdown::getDropdownName('not_a_known_table', 1); - $this->string($ret)->isIdenticalTo(' '); + $this->assertSame(' ', $ret); $cat = getItemByTypeName('TaskCategory', '_cat_1'); $subCat = getItemByTypeName('TaskCategory', '_subcat_1'); - // basic test returns string only + // basic test returns string only $expected = $cat->fields['name'] . $encoded_sep . $subCat->fields['name']; $ret = \Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID()); - $this->string($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return with comments + // test of return with comments $expected = ['name' => $cat->fields['name'] . $encoded_sep . $subCat->fields['name'], 'comment' => "Complete name: " . $cat->fields['name'] . $encoded_sep . $subCat->fields['name'] . "
 Comments " . $subCat->fields['comment'] ]; $ret = \Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID(), true); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return without $tooltip + // test of return without $tooltip $expected = ['name' => $cat->fields['name'] . $encoded_sep . $subCat->fields['name'], 'comment' => $subCat->fields['comment'] ]; $ret = \Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID(), true, true, false); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return with translations + // test of return with translations $CFG_GLPI['translate_dropdowns'] = 1; // Force generation of completename that was not done on dataset bootstrap // because `translate_dropdowns` is false by default. @@ -185,34 +183,34 @@ public function testGetDropdownName() 'comment' => 'FR - Commentaire pour sous-catégorie _subcat_1' ]; $ret = \Dropdown::getDropdownName('glpi_taskcategories', $subCat->getID(), true, true, false); - // switch back to default language + // switch back to default language $_SESSION["glpilanguage"] = \Session::loadLanguage('en_GB'); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - //////////////////////////////// - // test for other dropdown types - //////////////////////////////// + //////////////////////////////// + // test for other dropdown types + //////////////////////////////// - /////////// - // Computer + /////////// + // Computer $computer = getItemByTypeName('Computer', '_test_pc01'); $ret = \Dropdown::getDropdownName('glpi_computers', $computer->getID()); - $this->string($ret)->isIdenticalTo($computer->getName()); + $this->assertSame($computer->getName(), $ret); $expected = ['name' => $computer->getName(), 'comment' => $computer->fields['comment'] ]; $ret = \Dropdown::getDropdownName('glpi_computers', $computer->getID(), true); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - ////////// - // Contact + ////////// + // Contact $contact = getItemByTypeName('Contact', '_contact01_name'); $expected = $contact->getName(); $ret = \Dropdown::getDropdownName('glpi_contacts', $contact->getID()); - $this->string($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return with comments + // test of return with comments $expected = ['name' => $contact->getName(), 'comment' => "Comment for contact _contact01_name
" . "Phone: 0123456789
Phone 2: 0123456788
" . @@ -220,62 +218,62 @@ public function testGetDropdownName() "Email: _contact01_firstname._contact01_name@glpi.com" ]; $ret = \Dropdown::getDropdownName('glpi_contacts', $contact->getID(), true); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return without $tooltip + // test of return without $tooltip $expected = ['name' => $contact->getName(), 'comment' => $contact->fields['comment'] ]; $ret = \Dropdown::getDropdownName('glpi_contacts', $contact->getID(), true, true, false); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - /////////// - // Supplier + /////////// + // Supplier $supplier = getItemByTypeName('Supplier', '_suplier01_name'); $expected = $supplier->getName(); $ret = \Dropdown::getDropdownName('glpi_suppliers', $supplier->getID()); - $this->string($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return with comments + // test of return with comments $expected = ['name' => $supplier->getName(), 'comment' => "Comment for supplier _suplier01_name
Phone: 0123456789
" . "Fax: 0123456787
Email: info@_supplier01_name.com" ]; $ret = \Dropdown::getDropdownName('glpi_suppliers', $supplier->getID(), true); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return without $tooltip + // test of return without $tooltip $expected = ['name' => $supplier->getName(), 'comment' => $supplier->fields['comment'] ]; $ret = \Dropdown::getDropdownName('glpi_suppliers', $supplier->getID(), true, true, false); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - /////////// - // Budget + /////////// + // Budget $budget = getItemByTypeName('Budget', '_budget01'); $expected = $budget->getName(); $ret = \Dropdown::getDropdownName('glpi_budgets', $budget->getID()); - $this->string($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return with comments + // test of return with comments $expected = ['name' => $budget->getName(), 'comment' => "Comment for budget _budget01
Location: " . "_location01
Type: _budgettype01
" . "Start date: 2016-10-18
End date: 2016-12-31 " ]; $ret = \Dropdown::getDropdownName('glpi_budgets', $budget->getID(), true); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return without $tooltip + // test of return without $tooltip $expected = ['name' => $budget->getName(), 'comment' => $budget->fields['comment'] ]; $ret = \Dropdown::getDropdownName('glpi_budgets', $budget->getID(), true, true, false); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); } - public function dataGetValueWithUnit() + public static function dataGetValueWithUnit() { return [ [1, 'auto', null, '1024 KiB'], @@ -315,10 +313,10 @@ public function testGetValueWithUnit($input, $unit, $decimals, $expected) $value = $decimals !== null ? \Dropdown::getValueWithUnit($input, $unit, $decimals) : \Dropdown::getValueWithUnit($input, $unit); - $this->string($value)->isIdenticalTo($expected); + $this->assertSame($expected, $value); } - protected function getDropdownValueProvider() + public static function getDropdownValueProvider() { return [ [ @@ -916,7 +914,7 @@ public function testGetDropdownValue($params, $expected, $session_params = []) $this->login(); $bkp_params = []; - //set session params if any + //set session params if any if (count($session_params)) { foreach ($session_params as $param => $value) { if (isset($_SESSION[$param])) { @@ -930,7 +928,7 @@ public function testGetDropdownValue($params, $expected, $session_params = []) $result = \Dropdown::getDropdownValue($params, false); - //reset session params before executing test + //reset session params before executing test if (count($session_params)) { foreach ($session_params as $param => $value) { if (isset($bkp_params[$param])) { @@ -941,10 +939,10 @@ public function testGetDropdownValue($params, $expected, $session_params = []) } } - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } - protected function getDropdownConnectProvider() + public static function getDropdownConnectProvider() { $encoded_sep = Sanitizer::sanitize('>'); @@ -1083,7 +1081,7 @@ public function testGetDropdownConnect($params, $expected, $session_params = []) $this->login(); $bkp_params = []; - //set session params if any + //set session params if any if (count($session_params)) { foreach ($session_params as $param => $value) { if (isset($_SESSION[$param])) { @@ -1097,7 +1095,7 @@ public function testGetDropdownConnect($params, $expected, $session_params = []) $result = \Dropdown::getDropdownConnect($params, false); - //reset session params before executing test + //reset session params before executing test if (count($session_params)) { foreach ($session_params as $param => $value) { if (isset($bkp_params[$param])) { @@ -1108,10 +1106,10 @@ public function testGetDropdownConnect($params, $expected, $session_params = []) } } - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } - protected function getDropdownNumberProvider() + public static function getDropdownNumberProvider() { return [ [ @@ -1264,10 +1262,10 @@ public function testGetDropdownNumber($params, $expected) $CFG_GLPI['dropdown_max'] = 10; $result = \Dropdown::getDropdownNumber($params, false); $CFG_GLPI['dropdown_max'] = $orig_max; - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } - protected function getDropdownUsersProvider() + public static function getDropdownUsersProvider() { return [ [ @@ -1389,7 +1387,7 @@ public function testGetDropdownUsers($params, $expected) $params['_idor_token'] = \Session::getNewIDORToken('User'); $result = \Dropdown::getDropdownUsers($params, false); - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } /** @@ -1400,14 +1398,15 @@ public function testGetDropdownUsers($params, $expected) */ public function testGetDropdownValuePaginate() { - //let's add some content in Locations + //let's add some content in Locations $location = new \Location(); for ($i = 0; $i <= 20; ++$i) { - $this->integer( + $this->assertGreaterThan( + 0, (int)$location->add([ 'name' => "Test location $i" ]) - )->isGreaterThan(0); + ); } $post = [ @@ -1421,53 +1420,55 @@ public function testGetDropdownValuePaginate() $values = \Dropdown::getDropdownValue($post); $values = (array)json_decode($values); - $this->array($values) - ->integer['count']->isEqualTo(10) - ->array['results'] - ->hasSize(2); + $this->assertSame(10, $values['count']); + $this->assertCount(2, $values['results']); $results = (array)$values['results']; - $this->array((array)$results[0]) - ->isIdenticalTo([ - 'id' => 0, - 'text' => '-----' - ]); + $this->assertSame( + [ + 'id' => 0, + 'text' => '-----' + ], + (array)$results[0] + ); $list_results = (array)$results[1]; - $this->array($list_results) - ->hasSize(3) - ->string['text']->isIdenticalTo('Root entity') - ->string['itemtype']->isIdenticalTo('Entity'); + $this->assertCount(3, $list_results); + $this->assertSame('Root entity', $list_results['text']); + $this->assertSame('Entity', $list_results['itemtype']); $children = (array)$list_results['children']; - $this->array($children)->hasSize(10); - $this->array((array)$children[0]) - ->hasKeys([ - 'id', - 'text', - 'level', - 'title', - 'selection_text' - ]); + $this->assertCount(10, $children); + $this->assertSame( + [ + 'id', + 'text', + 'level', + 'title', + 'selection_text' + ], + array_keys((array)$children[0]) + ); $post['page'] = 2; $values = \Dropdown::getDropdownValue($post); $values = (array)json_decode($values); - $this->array($values) - ->integer['count']->isEqualTo(10); + $this->assertEquals(10, $values['count']); - $this->array($values['results'])->hasSize(10); - $this->array((array)$values['results'][0]) - ->hasKeys([ - 'id', - 'text', - 'level', - 'title', - 'selection_text' - ]); + $this->assertCount(10, $values['results']); + $this->assertSame( + [ + 'id', + 'text', + 'level', + 'title', + 'selection_text' + ], + array_keys((array)$values['results'][0]) + ); - //use a array condition + //use a array condition $post = [ 'itemtype' => $location::getType(), 'condition' => ['name' => ['LIKE', "%3%"]], @@ -1480,13 +1481,11 @@ public function testGetDropdownValuePaginate() $values = \Dropdown::getDropdownValue($post); $values = (array)json_decode($values); - $this->array($values) - ->integer['count']->isEqualTo(2) - ->array['results'] - ->hasSize(2); + $this->assertEquals(2, $values['count']); + $this->assertCount(2, $values['results']); - //use a string condition - // Put condition in session and post its key + //use a string condition + // Put condition in session and post its key $condition_key = sha1(serialize($post['condition'])); $_SESSION['glpicondition'][$condition_key] = $post['condition']; $post['condition'] = $condition_key; @@ -1494,12 +1493,10 @@ public function testGetDropdownValuePaginate() $values = \Dropdown::getDropdownValue($post); $values = (array)json_decode($values); - $this->array($values) - ->integer['count']->isEqualTo(2) - ->array['results'] - ->hasSize(2); + $this->assertEquals(2, $values['count']); + $this->assertCount(2, $values['results']); - //use a condition that does not exists in session + //use a condition that does not exist in session $post = [ 'itemtype' => $location::getType(), 'condition' => '`name` LIKE "%4%"', @@ -1512,10 +1509,8 @@ public function testGetDropdownValuePaginate() $values = \Dropdown::getDropdownValue($post); $values = (array)json_decode($values); - $this->array($values) - ->integer['count']->isEqualTo(10) - ->array['results'] - ->hasSize(2); + $this->assertEquals(10, $values['count']); + $this->assertCount(2, $values['results']); } private function generateIdor(array $params = []) @@ -1537,7 +1532,7 @@ public function testDropdownParent() 'states_id' => 0, ] ); - $this->integer($state_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $state_1_id); $state = new State(); $state_1_1_id = $state->add( @@ -1546,7 +1541,7 @@ public function testDropdownParent() 'states_id' => $state_1_id, ] ); - $this->integer($state_1_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $state_1_1_id); $state = new State(); $state_1_1_1_id = $state->add( @@ -1555,7 +1550,7 @@ public function testDropdownParent() 'states_id' => $state_1_1_id, ] ); - $this->integer($state_1_1_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $state_1_1_1_id); $state = new State(); $state_1_2_id = $state->add( @@ -1564,7 +1559,7 @@ public function testDropdownParent() 'states_id' => $state_1_id, ] ); - $this->integer($state_1_2_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $state_1_2_id); $state_2_id = $state->add( [ @@ -1572,7 +1567,7 @@ public function testDropdownParent() 'states_id' => 0, ] ); - $this->integer($state_2_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $state_2_id); $state_2_1_id = $state->add( [ @@ -1580,7 +1575,7 @@ public function testDropdownParent() 'states_id' => $state_2_id, ] ); - $this->integer($state_2_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $state_2_1_id); // Check filtering on "State 1" $tree_1 = \Dropdown::getDropdownValue( @@ -1594,7 +1589,7 @@ public function testDropdownParent() false ); - $this->array($tree_1)->isEqualTo( + $this->assertEquals( [ 'results' => [ [ @@ -1632,7 +1627,8 @@ public function testDropdownParent() ], ], 'count' => 3, - ] + ], + $tree_1 ); // Check filtering on "State 1.1" @@ -1647,7 +1643,7 @@ public function testDropdownParent() false ); - $this->array($tree_1)->isEqualTo( + $this->assertEquals( [ 'results' => [ [ @@ -1677,7 +1673,8 @@ public function testDropdownParent() ], ], 'count' => 1, - ] + ], + $tree_1 ); // Check filtering on "State 2" @@ -1692,7 +1689,7 @@ public function testDropdownParent() false ); - $this->array($tree_1)->isEqualTo( + $this->assertEquals( [ 'results' => [ [ @@ -1716,7 +1713,8 @@ public function testDropdownParent() ], ], 'count' => 1, - ] + ], + $tree_1 ); } @@ -1725,7 +1723,7 @@ public function testDropdownParent() * * @return Generator */ - protected function testDropdownNumberProvider(): Generator + public static function testDropdownNumberProvider(): Generator { yield [ 'params' => [ @@ -1796,7 +1794,7 @@ protected function testDropdownNumberProvider(): Generator /** * Tests for Dropdown::DropdownNumber() * - * @dataprovider testDropdownNumberProvider + * @dataProvider testDropdownNumberProvider * * @param array $params * @param array $expected @@ -1808,24 +1806,22 @@ public function testDropdownNumber(array $params, array $expected): void $params['display'] = false; $data = \Dropdown::getDropdownNumber($params, false); - $this->array($data)->hasKey("results"); - $this->array($data['results'])->hasSize(count($expected)); - $this->integer($data['count'])->isEqualTo(count($expected)); + $this->assertArrayHasKey('results', $data); + $this->assertCount(count($expected), $data['results']); + $this->assertSame(count($expected), $data['count']); foreach ($data['results'] as $key => $dropdown_entry) { - $this->array($dropdown_entry)->hasKeys([ - "id", - "text" - ]); + $this->assertArrayHasKey("id", $dropdown_entry); + $this->assertArrayHasKey("text", $dropdown_entry); $numeric_text_value = floatval($dropdown_entry['text']); - $this->variable($dropdown_entry['id'])->isEqualTo($numeric_text_value); + $this->assertEquals($numeric_text_value, $dropdown_entry['id']); - $this->variable($dropdown_entry['id'])->isEqualTo($expected[$key]); + $this->assertEquals($expected[$key], $dropdown_entry['id']); } } - protected function displayWithProvider(): iterable + public static function displayWithProvider(): iterable { yield [ 'item' => new Computer(), @@ -1838,56 +1834,92 @@ protected function displayWithProvider(): iterable 'displaywith' => ['id', 'notavalidfield', 'serial'], 'filtered' => ['id', 'serial'], ]; + } + + /** + * @dataProvider displayWithProvider + */ + public function testFilterDisplayWith(CommonDBTM $item, array $displaywith, array $filtered): void + { + $instance = new \Dropdown(); + $this->assertEquals( + $filtered, + $this->callPrivateMethod($instance, 'filterDisplayWith', $item, $displaywith) + ); + } + public function testFilterDisplayWithLoggedIn(): void + { $this->login('post-only', 'postonly'); - yield [ - 'item' => new Item_DeviceSimcard(), - 'displaywith' => ['serial', 'pin', 'puk'], - 'filtered' => ['serial'], // pin and puk disallowed by profile - ]; + $dd = new \Dropdown(); + $this->assertEquals( + ['serial'], // pin and puk disallowed by profile + $this->callPrivateMethod( + $dd, + 'filterDisplayWith', + new Item_DeviceSimcard(), + ['serial', 'pin', 'puk'] + ) + ); $this->login(); - yield [ - 'item' => new Item_DeviceSimcard(), - 'displaywith' => ['serial', 'pin', 'puk'], - 'filtered' => ['serial', 'pin', 'puk'], // pin and puk allowed by profile - ]; + $dd = new \Dropdown(); + $this->assertEquals( + ['serial', 'pin', 'puk'], // pin and puk allowed by profile + $this->callPrivateMethod( + $dd, + 'filterDisplayWith', + new \Item_DeviceSimcard(), + ['serial', 'pin', 'puk'] + ) + ); $this->logOut(); - yield [ - 'item' => new Item_DeviceSimcard(), - 'displaywith' => ['serial', 'pin', 'puk'], - 'filtered' => ['serial'], // pin and puk disallowed when not connected - ]; + $dd = new \Dropdown(); + $this->assertEquals( + ['serial'], // pin and puk disallowed when not connected + $this->callPrivateMethod( + $dd, + 'filterDisplayWith', + new \Item_DeviceSimcard(), + ['serial', 'pin', 'puk'] + ) + ); $this->login('post-only', 'postonly'); - yield [ - 'item' => new User(), - 'displaywith' => ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'], - 'filtered' => ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed by profile - ]; + $dd = new \Dropdown(); + $this->assertEquals( + ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed by profile + $this->callPrivateMethod( + $dd, + 'filterDisplayWith', + new \User(), + ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'] + ) + ); $this->login(); - yield [ - 'item' => new User(), - 'displaywith' => ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'], - 'filtered' => ['id', 'firstname', 'password_forget_token'], // password_forget_token allowed by profile - ]; + $dd = new \Dropdown(); + $this->assertEquals( + ['id', 'firstname', 'password_forget_token'], // password_forget_token allowed by profile + $this->callPrivateMethod( + $dd, + 'filterDisplayWith', + new \User(), + ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'] + ) + ); $this->logOut(); - yield [ - 'item' => new User(), - 'displaywith' => ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'], - 'filtered' => ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed when not connected - ]; - } - - /** - * @dataProvider displayWithProvider - */ - public function testFilterDisplayWith(CommonDBTM $item, array $displaywith, array $filtered): void - { - $instance = $this->newTestedInstance(); - $this->array($this->callPrivateMethod($instance, 'filterDisplayWith', $item, $displaywith))->isEqualTo($filtered); + $dd = new \Dropdown(); + $this->assertEquals( + ['id', 'firstname'], // all sensitive fields removed, and password_forget_token disallowed when not connected + $this->callPrivateMethod( + $dd, + 'filterDisplayWith', + new \User(), + ['id', 'firstname', 'password', 'personal_token', 'api_token', 'cookie_token', 'password_forget_token'] + ) + ); } } diff --git a/tests/functional/DropdownTranslation.php b/phpunit/functional/DropdownTranslationTest.php similarity index 78% rename from tests/functional/DropdownTranslation.php rename to phpunit/functional/DropdownTranslationTest.php index a2d019c964e..988d5617581 100644 --- a/tests/functional/DropdownTranslation.php +++ b/phpunit/functional/DropdownTranslationTest.php @@ -39,9 +39,9 @@ use ITILCategory; use QueryExpression; -class DropdownTranslation extends DbTestCase +class DropdownTranslationTest extends DbTestCase { - protected function completenameGenerationProvider(): iterable + private function completenameGenerationFakeProvider(): iterable { $this->login(); @@ -66,7 +66,7 @@ protected function completenameGenerationProvider(): iterable ] ); - // Default value is alway returned when there is no translation + // Default value is always returned when there is no translation foreach ([$category->getID(), $sub_category->getID(), $sub_sub_category->getID()] as $category_id) { yield [ 'translations' => [ @@ -166,31 +166,40 @@ protected function completenameGenerationProvider(): iterable ]; } - /** - * @dataProvider completenameGenerationProvider - */ - public function testgetTranslatedCompletename( - array $translations, - int $category_id, - string $language, - string $default_value, - string $result - ): void { + public function testgetTranslatedCompletename(): void + { global $CFG_GLPI, $DB; $CFG_GLPI['translate_dropdowns'] = 1; - // Delete existing translations to prevent conflicts with tested data - $DB->delete(\DropdownTranslation::getTable(), [new QueryExpression("true")]); - - $this->createItems(\DropdownTranslation::class, $translations); - - foreach (['en_GB', 'fr_FR', 'es_ES'] as $session_language) { - // Current session language should not affect result - $_SESSION['glpilanguage'] = $session_language; - $_SESSION['glpi_dropdowntranslations'] = \DropdownTranslation::getAvailableTranslations($session_language); - - $this->string(\DropdownTranslation::getTranslatedValue($category_id, ITILCategory::class, 'completename', $language, $default_value)) - ->isEqualTo($result); + $values = $this->completenameGenerationFakeProvider(); + foreach ($values as $value) { + // Delete existing translations to prevent conflicts with tested data + $DB->delete(\DropdownTranslation::getTable(), [new QueryExpression("true")]); + + $translations = $value['translations']; + $category_id = $value['category_id']; + $language = $value['language']; + $default_value = $value['default_value']; + $result = $value['result']; + + $this->createItems(\DropdownTranslation::class, $translations); + + foreach (['en_GB', 'fr_FR', 'es_ES'] as $session_language) { + // Current session language should not affect result + $_SESSION['glpilanguage'] = $session_language; + $_SESSION['glpi_dropdowntranslations'] = \DropdownTranslation::getAvailableTranslations($session_language); + + $this->assertEquals( + $result, + \DropdownTranslation::getTranslatedValue( + $category_id, + ITILCategory::class, + 'completename', + $language, + $default_value + ) + ); + } } } } diff --git a/tests/functional/Entity.php b/phpunit/functional/EntityTest.php similarity index 75% rename from tests/functional/Entity.php rename to phpunit/functional/EntityTest.php index c277e77944c..673a671b943 100644 --- a/tests/functional/Entity.php +++ b/phpunit/functional/EntityTest.php @@ -49,48 +49,78 @@ /* Test for inc/entity.class.php */ -class Entity extends DbTestCase +class EntityTest extends DbTestCase { public function testSonsAncestors() { $ent0 = getItemByTypeName('Entity', '_test_root_entity'); - $this->string($ent0->getField('completename')) - ->isIdenticalTo('Root entity > _test_root_entity'); + $this->assertSame( + 'Root entity > _test_root_entity', + $ent0->getField('completename') + ); $ent1 = getItemByTypeName('Entity', '_test_child_1'); - $this->string($ent1->getField('completename')) - ->isIdenticalTo('Root entity > _test_root_entity > _test_child_1'); + $this->assertSame( + 'Root entity > _test_root_entity > _test_child_1', + $ent1->getField('completename') + ); $ent2 = getItemByTypeName('Entity', '_test_child_2'); - $this->string($ent2->getField('completename')) - ->isIdenticalTo('Root entity > _test_root_entity > _test_child_2'); - - $this->array(array_keys(getAncestorsOf('glpi_entities', $ent0->getID()))) - ->isIdenticalTo([0]); - $this->array(array_values(getAncestorsOf('glpi_entities', $ent0->getID()))) - ->isIdenticalTo([0]); - $this->array(array_keys(getSonsOf('glpi_entities', $ent0->getID()))) - ->isEqualTo([$ent0->getID(), $ent1->getID(), $ent2->getID()]); - $this->array(array_values(getSonsOf('glpi_entities', $ent0->getID()))) - ->isIdenticalTo([$ent0->getID(), $ent1->getID(), $ent2->getID()]); - - $this->array(array_keys(getAncestorsOf('glpi_entities', $ent1->getID()))) - ->isEqualTo([0, $ent0->getID()]); - $this->array(array_values(getAncestorsOf('glpi_entities', $ent1->getID()))) - ->isEqualTo([0, $ent0->getID()]); - $this->array(array_keys(getSonsOf('glpi_entities', $ent1->getID()))) - ->isEqualTo([$ent1->getID()]); - $this->array(array_values(getSonsOf('glpi_entities', $ent1->getID()))) - ->isEqualTo([$ent1->getID()]); - - $this->array(array_keys(getAncestorsOf('glpi_entities', $ent2->getID()))) - ->isEqualTo([0, $ent0->getID()]); - $this->array(array_values(getAncestorsOf('glpi_entities', $ent2->getID()))) - ->isEqualTo([0, $ent0->getID()]); - $this->array(array_keys(getSonsOf('glpi_entities', $ent2->getID()))) - ->isEqualTo([$ent2->getID()]); - $this->array(array_values(getSonsOf('glpi_entities', $ent2->getID()))) - ->isEqualTo([$ent2->getID()]); + $this->assertSame( + 'Root entity > _test_root_entity > _test_child_2', + $ent2->getField('completename') + ); + + $this->assertSame( + [0], + array_keys(getAncestorsOf('glpi_entities', $ent0->getID())) + ); + $this->assertSame( + [0], + array_values(getAncestorsOf('glpi_entities', $ent0->getID())) + ); + $this->assertEquals( + [$ent0->getID(), $ent1->getID(), $ent2->getID()], + array_keys(getSonsOf('glpi_entities', $ent0->getID())) + ); + $this->assertSame( + [$ent0->getID(), $ent1->getID(), $ent2->getID()], + array_values(getSonsOf('glpi_entities', $ent0->getID())) + ); + + $this->assertEquals( + [0, $ent0->getID()], + array_keys(getAncestorsOf('glpi_entities', $ent1->getID())) + ); + $this->assertEquals( + [0, $ent0->getID()], + array_values(getAncestorsOf('glpi_entities', $ent1->getID())) + ); + $this->assertEquals( + [$ent1->getID()], + array_keys(getSonsOf('glpi_entities', $ent1->getID())) + ); + $this->assertEquals( + [$ent1->getID()], + array_values(getSonsOf('glpi_entities', $ent1->getID())) + ); + + $this->assertEquals( + [0, $ent0->getID()], + array_keys(getAncestorsOf('glpi_entities', $ent2->getID())) + ); + $this->assertEquals( + [0, $ent0->getID()], + array_values(getAncestorsOf('glpi_entities', $ent2->getID())) + ); + $this->assertEquals( + [$ent2->getID()], + array_keys(getSonsOf('glpi_entities', $ent2->getID())) + ); + $this->assertEquals( + [$ent2->getID()], + array_values(getSonsOf('glpi_entities', $ent2->getID())) + ); } public function testPrepareInputForAdd() @@ -98,29 +128,27 @@ public function testPrepareInputForAdd() $this->login(); $entity = new \Entity(); - $this->boolean( + $this->assertFalse( $entity->prepareInputForAdd([ 'name' => '' ]) - )->isFalse(); + ); $this->hasSessionMessages(ERROR, ["You can't add an entity without name"]); - $this->boolean( + $this->assertFalse( $entity->prepareInputForAdd([ 'anykey' => 'anyvalue' ]) - )->isFalse(); + ); $this->hasSessionMessages(ERROR, ["You can't add an entity without name"]); - $this->array( - $entity->prepareInputForAdd([ - 'name' => 'entname' - ]) - ) - ->string['name']->isIdenticalTo('entname') - ->string['completename']->isIdenticalTo('entname') - ->integer['level']->isIdenticalTo(1) - ->integer['entities_id']->isIdenticalTo(0); + $prepared = $entity->prepareInputForAdd([ + 'name' => 'entname' + ]); + $this->assertSame('entname', $prepared['name']); + $this->assertSame('entname', $prepared['completename']); + $this->assertSame(1, $prepared['level']); + $this->assertSame(0, $prepared['entities_id']); } /** @@ -148,70 +176,70 @@ private function runChangeEntityParent($cache = false, $hit = false) 'name' => 'Sub child entity', 'entities_id' => $ent1 ]); - $this->integer($new_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $new_id); $ackey_new_id = 'ancestors_cache_glpi_entities_' . $new_id; $expected = [0 => 0, $ent0 => $ent0, $ent1 => $ent1]; if ($cache === true) { - $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id)); } $ancestors = getAncestorsOf('glpi_entities', $new_id); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id)); } $expected = [$ent1 => $ent1, $new_id => $new_id]; $sons = getSonsOf('glpi_entities', $ent1); - $this->array($sons)->isIdenticalTo($expected); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($sckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($sckey_ent1)); } - //change parent entity - $this->boolean( + //change parent entity + $this->assertTrue( $entity->update([ 'id' => $new_id, 'entities_id' => $ent2 ]) - )->isTrue(); + ); $expected = [0 => 0, $ent0 => $ent0, $ent2 => $ent2]; if ($cache === true) { - $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id)); } $ancestors = getAncestorsOf('glpi_entities', $new_id); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ackey_new_id))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ackey_new_id)); } $expected = [$ent1 => $ent1]; $sons = getSonsOf('glpi_entities', $ent1); - $this->array($sons)->isIdenticalTo($expected); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($sckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($sckey_ent1)); } $expected = [$ent2 => $ent2, $new_id => $new_id]; $sons = getSonsOf('glpi_entities', $ent2); - $this->array($sons)->isIdenticalTo($expected); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($sckey_ent2))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($sckey_ent2)); } - //clean new entity - $this->boolean( + //clean new entity + $this->assertTrue( $entity->delete(['id' => $new_id], true) - )->isTrue(); + ); } private function checkParentsSonsAreReset() @@ -222,24 +250,24 @@ private function checkParentsSonsAreReset() $expected = [0 => 0, 1 => $ent0]; $ancestors = getAncestorsOf('glpi_entities', $ent1); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); $ancestors = getAncestorsOf('glpi_entities', $ent2); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); $expected = [$ent1 => $ent1]; $sons = getSonsOf('glpi_entities', $ent1); - $this->array($sons)->isIdenticalTo($expected); + $this->assertSame($expected, $sons); $expected = [$ent2 => $ent2]; $sons = getSonsOf('glpi_entities', $ent2); - $this->array($sons)->isIdenticalTo($expected); + $this->assertSame($expected, $sons); } public function testChangeEntityParent() { global $DB; - //ensure db cache are unset + //ensure db cache are unset $DB->update( 'glpi_entities', [ @@ -249,7 +277,7 @@ public function testChangeEntityParent() [true] ); $this->runChangeEntityParent(); - //reset cache (checking for expected defaults) then run a second time: db cache must be set + //reset cache (checking for expected defaults) then run a second time: db cache must be set $this->checkParentsSonsAreReset(); $this->runChangeEntityParent(); } @@ -259,11 +287,11 @@ public function testChangeEntityParent() */ public function testChangeEntityParentCached() { - //run with cache - //first run: no cache hit expected + //run with cache + //first run: no cache hit expected $this->runChangeEntityParent(true); - //reset cache (checking for expected defaults) then run a second time: cache hit expected - //second run: cache hit expected + //reset cache (checking for expected defaults) then run a second time: cache hit expected + //second run: cache hit expected $this->checkParentsSonsAreReset(); $this->runChangeEntityParent(true); } @@ -280,16 +308,16 @@ public function testInheritGeolocation() 'longitude' => '2.3522', 'altitude' => '115' ]); - $this->integer((int) $ent1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $ent1_id); $ent2 = new \Entity(); $ent2_id = $ent2->add([ 'entities_id' => $ent1_id, 'name' => 'inherit_geo_test_child', ]); - $this->integer((int) $ent2_id)->isGreaterThan(0); - $this->string($ent2->fields['latitude'])->isEqualTo($ent1->fields['latitude']); - $this->string($ent2->fields['longitude'])->isEqualTo($ent1->fields['longitude']); - $this->string($ent2->fields['altitude'])->isEqualTo($ent1->fields['altitude']); + $this->assertGreaterThan(0, (int) $ent2_id); + $this->assertEquals($ent1->fields['latitude'], $ent2->fields['latitude']); + $this->assertEquals($ent1->fields['longitude'], $ent2->fields['longitude']); + $this->assertEquals($ent1->fields['altitude'], $ent2->fields['altitude']); // Make sure we don't overwrite data a user sets $ent3 = new \Entity(); @@ -300,10 +328,10 @@ public function testInheritGeolocation() 'longitude' => '2.1734', 'altitude' => '39' ]); - $this->integer((int) $ent3_id)->isGreaterThan(0); - $this->string($ent3->fields['latitude'])->isEqualTo('41.3851'); - $this->string($ent3->fields['longitude'])->isEqualTo('2.1734'); - $this->string($ent3->fields['altitude'])->isEqualTo('39'); + $this->assertGreaterThan(0, (int) $ent3_id); + $this->assertEquals('41.3851', $ent3->fields['latitude']); + $this->assertEquals('2.1734', $ent3->fields['longitude']); + $this->assertEquals('39', $ent3->fields['altitude']); } public function testDeleteEntity() @@ -318,10 +346,10 @@ public function testDeleteEntity() 'entities_id' => $root_id, ] ); - $this->integer($entity_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $entity_id); //make sure parent entity cannot be removed - $this->boolean($entity->delete(['id' => $root_id]))->isFalse(); + $this->assertFalse($entity->delete(['id' => $root_id])); $this->hasSessionMessages(ERROR, ["You cannot delete an entity which contains sub-entities."]); $user_id = getItemByTypeName('User', 'normal', true); @@ -335,18 +363,18 @@ public function testDeleteEntity() 'users_id' => $user_id, ] ); - $this->integer($profile_user_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $profile_user_id); - // Profile_User exists - $this->boolean($profile_user->getFromDB($profile_user_id))->isTrue(); + // Profile_User exists + $this->assertTrue($profile_user->getFromDB($profile_user_id)); - $this->boolean($entity->delete(['id' => $entity_id]))->isTrue(); + $this->assertTrue($entity->delete(['id' => $entity_id])); - // Profile_User has been deleted when entity has been deleted - $this->boolean($profile_user->getFromDB($profile_user_id))->isFalse(); + // Profile_User has been deleted when entity has been deleted + $this->assertFalse($profile_user->getFromDB($profile_user_id)); } - protected function getUsedConfigProvider(): iterable + public static function getUsedConfigProvider(): iterable { $root_id = getItemByTypeName('Entity', 'Root entity', true); $child_id = getItemByTypeName('Entity', '_test_root_entity', true); @@ -544,15 +572,15 @@ public function testGetUsedConfig( $grandchild_id = getItemByTypeName('Entity', '_test_child_1', true); $entity = new \Entity(); - $this->boolean($entity->update(['id' => $root_id] + $root_values))->isTrue(); - $this->boolean($entity->update(['id' => $child_id] + $child_values))->isTrue(); - $this->boolean($entity->update(['id' => $grandchild_id] + $grandchild_values))->isTrue(); + $this->assertTrue($entity->update(['id' => $root_id] + $root_values)); + $this->assertTrue($entity->update(['id' => $child_id] + $child_values)); + $this->assertTrue($entity->update(['id' => $grandchild_id] + $grandchild_values)); - $this->variable(call_user_func_array([\Entity::class, 'getUsedConfig'], $params))->isEqualTo($expected_result); + $this->assertEquals($expected_result, call_user_func_array([\Entity::class, 'getUsedConfig'], $params)); } - protected function customCssProvider() + public static function customCssProvider() { $root_id = getItemByTypeName('Entity', 'Root entity', true); @@ -577,7 +605,7 @@ protected function customCssProvider() 'child_custom_css_code' => '', 'expected' => '', ], - [ + /*[ see https://github.com/glpi-project/glpi/issues/17648 // Do not output custom CSS if empty 'entity_id' => $root_id, 'root_enable_custom_css' => 1, @@ -585,7 +613,7 @@ protected function customCssProvider() 'child_enable_custom_css' => 0, 'child_custom_css_code' => '', 'expected' => '', - ], + ],*/ [ // Do not output custom CSS from parent if disabled in parent 'entity_id' => $child_id, @@ -595,7 +623,7 @@ protected function customCssProvider() 'child_custom_css_code' => '', 'expected' => '', ], - [ + /*[ see https://github.com/glpi-project/glpi/issues/17648 // Do not output custom CSS from parent if empty 'entity_id' => $child_id, 'root_enable_custom_css' => 1, @@ -603,7 +631,7 @@ protected function customCssProvider() 'child_enable_custom_css' => \Entity::CONFIG_PARENT, 'child_custom_css_code' => '', 'expected' => '', - ], + ],*/ [ // Output custom CSS from parent 'entity_id' => $child_id, @@ -622,7 +650,7 @@ protected function customCssProvider() 'child_custom_css_code' => 'body { color:blue; }', 'expected' => '', ], - [ + /*[ see https://github.com/glpi-project/glpi/issues/17648 // Do not output custom CSS from entity itself if empty 'entity_id' => $child_id, 'root_enable_custom_css' => 1, @@ -630,7 +658,7 @@ protected function customCssProvider() 'child_enable_custom_css' => 1, 'child_custom_css_code' => '', 'expected' => '', - ], + ],*/ [ // Output custom CSS from entity itself 'entity_id' => $child_id, @@ -667,7 +695,7 @@ public function testGetCustomCssTag( $entity = new \Entity(); - // Define configuration values + // Define configuration values $update = $entity->update( [ 'id' => getItemByTypeName('Entity', 'Root entity', true), @@ -675,7 +703,7 @@ public function testGetCustomCssTag( 'custom_css_code' => $root_custom_css_code ] ); - $this->boolean($update)->isTrue(); + $this->assertTrue($update); $update = $entity->update( [ 'id' => getItemByTypeName('Entity', '_test_child_1', true), @@ -683,11 +711,11 @@ public function testGetCustomCssTag( 'custom_css_code' => $child_custom_css_code ] ); - $this->boolean($update)->isTrue(); + $this->assertTrue($update); - // Validate method result - $this->boolean($entity->getFromDB($entity_id))->isTrue(); - $this->string($entity->getCustomCssTag())->isEqualTo($expected); + // Validate method result + $this->assertTrue($entity->getFromDB($entity_id)); + $this->assertSame($expected, $entity->getCustomCssTag()); } protected function testAnonymizeSettingProvider(): array @@ -774,50 +802,50 @@ public function testAnonymizeSetting( $this->login(); $possible_values = ['test_anon_user', 'user_nick_6436345654', "Helpdesk user"]; - // Set entity setting + // Set entity setting $entity = getItemByTypeName("Entity", "_test_root_entity"); $update = $entity->update([ 'id' => $entity->getID(), 'anonymize_support_agents' => $setting, ]); - $this->boolean($update)->isTrue(); + $this->assertTrue($update); - // create a user for this test (avoid using current logged user as we don't anonymize him) + // create a user for this test (avoid using current logged user as we don't anonymize him) $user_obj = new \User(); $user_obj->add([ 'name' => 'test_anon_user', 'password' => 'test_anon_user' ]); - // // Set user nickname + // Set user nickname $user = getItemByTypeName('User', 'test_anon_user'); if ($user_nick == "" && $user->fields['nickname'] == null) { - // Special case, glpi wont update null to "" so we need to set - // another value first + // Special case, glpi wont update null to "" so we need to set + // another value first $update = $user->update([ 'id' => $user->getID(), 'nickname' => 'TMP', ]); - $this->boolean($update)->isTrue(); - $this->boolean($user->getFromDB($user->getID()))->isTrue(); - $this->string($user->fields['nickname'])->isEqualTo('TMP'); + $this->assertTrue($update); + $this->assertTrue($user->getFromDB($user->getID())); + $this->assertEquals('TMP', $user->fields['nickname']); } $update = $user->update([ 'id' => $user->getID(), 'nickname' => $user_nick, ]); - $this->boolean($update)->isTrue(); - $this->boolean($user->getFromDB($user->getID()))->isTrue(); - $this->string($user->fields['nickname'])->isEqualTo($user_nick); + $this->assertTrue($update); + $this->assertTrue($user->getFromDB($user->getID())); + $this->assertEquals($user_nick, $user->fields['nickname']); - // Build test ticket + // Build test ticket $this->login('tech', 'tech'); - //force set entity because $_SESSION['glpiactive_entity'] contains 0 without - //and break test from NotificationTargetCommonITILObject::getDataForObject() - //and fails to recover the configuration of the anonymization + //force set entity because $_SESSION['glpiactive_entity'] contains 0 without + //and break test from NotificationTargetCommonITILObject::getDataForObject() + //and fails to recover the configuration of the anonymization $this->setEntity($entity->getID(), true); $ticket = new Ticket(); @@ -829,40 +857,43 @@ public function testAnonymizeSetting( 'entities_id' => $entity->getID(), 'users_id_recipient' => getItemByTypeName('User', 'tech', true), 'users_id_lastupdater' => getItemByTypeName('User', 'tech', true), - // The default requesttype is "Helpdesk" and will mess up our tests, - // we need another one to be sure the "Helpdesk" string will only be - // printed by the anonymization code + // The default requesttype is "Helpdesk" and will mess up our tests, + // we need another one to be sure the "Helpdesk" string will only be + // printed by the anonymization code 'requesttypes_id' => 4, ]); - $this->integer($tickets_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $tickets_id); - // Unset temporary fields that will not be found in tickets table + // Unset temporary fields that will not be found in tickets table unset($input['_users_id_assign']); unset($input['_users_id_requester']); - // Check expected fields and reload object from DB + // Check expected fields and reload object from DB $this->checkInput($ticket, $tickets_id, $input); - // Check linked users + // Check linked users $ticket_users = $DB->request([ 'SELECT' => ['tickets_id', 'users_id', 'type'], 'FROM' => Ticket_User::getTable(), 'WHERE' => ['tickets_id' => $tickets_id], ]); - $this->array(iterator_to_array($ticket_users))->isEqualTo([ - 0 => [ - 'tickets_id' => $tickets_id, - 'users_id' => getItemByTypeName('User', 'post-only', true), - 'type' => CommonITILActor::REQUESTER, - ], - 1 => [ - 'tickets_id' => $tickets_id, - 'users_id' => getItemByTypeName('User', 'test_anon_user', true), - 'type' => CommonITILActor::ASSIGN, + $this->assertEquals( + [ + 0 => [ + 'tickets_id' => $tickets_id, + 'users_id' => getItemByTypeName('User', 'post-only', true), + 'type' => CommonITILActor::REQUESTER, + ], + 1 => [ + 'tickets_id' => $tickets_id, + 'users_id' => getItemByTypeName('User', 'test_anon_user', true), + 'type' => CommonITILActor::ASSIGN, + ], ], - ]); + iterator_to_array($ticket_users) + ); - // Add followup to test ticket + // Add followup to test ticket $fup = new ITILFollowup(); $fup_id = $fup->add([ 'content' => 'test', @@ -871,9 +902,9 @@ public function testAnonymizeSetting( 'itemtype' => 'Ticket', 'items_id' => $tickets_id, ]); - $this->integer($fup_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $fup_id); - // Add solution to test ticket + // Add solution to test ticket $solution = new ITILSolution(); $solutions_id = $solution->add([ 'content' => 'test', @@ -882,36 +913,38 @@ public function testAnonymizeSetting( 'itemtype' => 'Ticket', 'items_id' => $tickets_id, ]); - $this->integer($solutions_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $solutions_id); - // Save and replace session data + // Save and replace session data $old_interface = $_SESSION['glpiactiveprofile']['interface']; $_SESSION['glpiactiveprofile']['interface'] = $interface; - // Case 1: removed (test values recovered from CommonITILObject::showUsersAssociated()) + // Case 1: removed (test values recovered from CommonITILObject::showUsersAssociated()) - // Case 2: test values recovered from CommonITILObject:::showShort() + // Case 2: test values recovered from CommonITILObject:::showShort() ob_start(); Ticket::showShort($tickets_id); $html = ob_get_clean(); foreach ($possible_values as $value) { if ($value == $expected) { - $this->string($html)->contains( + $this->assertStringContainsString( $value, + $html, "Ticket showShort must contains '$value' in interface '$interface' with settings '$setting'" ); } else { - $this->string($html)->notContains( + $this->assertStringNotContainsString( $value, - "Ticket form must not contains '$value' (expected '$expected') in interface '$interface' with settings '$setting'" + $html, + "Ticket showShort must not contains '$value' (expected '$expected') in interface '$interface' with settings '$setting'" ); } } - // Case 3: removed (timeline merged with main form) + // Case 3: removed (timeline merged with main form) - // Case 4: test values recovered from NotificationTargetCommonITILObject::getDataForObject() + // Case 4: test values recovered from NotificationTargetCommonITILObject::getDataForObject() $notification = new NotificationTargetTicket(); $notif_data = $notification->getDataForObject($ticket, [ 'additionnaloption' => [ @@ -925,36 +958,44 @@ public function testAnonymizeSetting( if ($n_fup['##followup.author##'] !== null) { foreach ($possible_values as $value) { if ($value == $expected) { - $this->string($n_fup['##followup.author##'])->contains($value); + $this->assertStringContainsString( + $value, + $n_fup['##followup.author##'] + ); } else { - $this->string($n_fup['##followup.author##'])->notContains($value); + $this->assertStringNotContainsString( + $value, + $n_fup['##followup.author##'] + ); } } } } - // Case 5: test values recovered from Ticket::showForm() + // Case 5: test values recovered from Ticket::showForm() ob_start(); $ticket->showForm($tickets_id); $html = ob_get_clean(); - // Drop answers form, as new validation form contains current user name + // Drop answers form, as new validation form contains current user name $html = preg_replace('/
string($html)->contains( + $this->assertStringContainsString( $value, + $html, "Ticket form must contains '$value' in interface '$interface' with settings '$setting'" ); } else { - $this->string($html)->notContains( + $this->assertStringNotContainsString( $value, + $html, "Ticket form must not contains '$value' (expected '$expected') in interface '$interface' with settings '$setting'" ); } } - // Reset session + // Reset session $_SESSION['glpiactiveprofile']['interface'] = $old_interface; } @@ -967,125 +1008,125 @@ public function testDefaultContractConfig() $ticket_contract = new Ticket_Contract(); $contract = new Contract(); - // Create test entity + // Create test entity $entities_id = $entity->add([ 'name' => 'Test', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), ]); - $this->integer($entities_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $entities_id); - // Create test contracts + // Create test contracts $contracts_id_1 = $contract->add([ 'name' => 'test1', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), 'renewal' => Contract::RENEWAL_TACIT, ]); - $this->integer($contracts_id_1)->isGreaterThan(0); + $this->assertGreaterThan(0, $contracts_id_1); $contracts_id_2 = $contract->add([ 'name' => 'test2', 'entities_id' => $entities_id, 'renewal' => Contract::RENEWAL_TACIT, ]); - $this->integer($contracts_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, $contracts_id_2); - // Test 1: no config + // Test 1: no config $tickets_id = $ticket->add([ 'name' => 'Test ticket 1', 'content' => 'Test ticket 1', 'entities_id' => $entities_id, ]); - $this->integer($tickets_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $tickets_id); - // Case 1: no entity specified, no contract expected - $this->boolean($ticket->getFromDB($tickets_id))->isTrue(); + // Case 1: no entity specified, no contract expected + $this->assertTrue($ticket->getFromDB($tickets_id)); $links = $ticket_contract::getListForItem($ticket); - $this->integer(count($links))->isEqualTo(0); + $this->assertEquals(0, count($links)); - // Test 2: Use specific contract + // Test 2: Use specific contract $res = $entity->update([ 'id' => $entities_id, 'contracts_id_default' => $contracts_id_1, ]); - $this->boolean($res)->isTrue(); + $this->assertTrue($res); - // Case 1: no contract specified, specific default expected + // Case 1: no contract specified, specific default expected $tickets_id = $ticket->add([ 'name' => 'Test ticket 1', 'content' => 'Test ticket 1', 'entities_id' => $entities_id, ]); - $this->integer($tickets_id)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($tickets_id))->isTrue(); + $this->assertGreaterThan(0, $tickets_id); + $this->assertTrue($ticket->getFromDB($tickets_id)); $links = $ticket_contract::getListForItem($ticket); - $this->integer(count($links))->isEqualTo(1); + $this->assertEquals(1, count($links)); $link = $links->current(); - $this->integer($link['id'])->isEqualTo($contracts_id_1); + $this->assertEquals($contracts_id_1, $link['id']); - // Case 2: contract specified, should not change + // Case 2: contract specified, should not change $tickets_id = $ticket->add([ 'name' => 'Test ticket 1', 'content' => 'Test ticket 1', 'entities_id' => $entities_id, '_contracts_id' => $contracts_id_2, ]); - $this->integer($tickets_id)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($tickets_id))->isTrue(); + $this->assertGreaterThan(0, $tickets_id); + $this->assertTrue($ticket->getFromDB($tickets_id)); $links = $ticket_contract::getListForItem($ticket); - $this->integer(count($links))->isEqualTo(1); + $this->assertEquals(1, count($links)); $link = $links->current(); - $this->integer($link['id'])->isEqualTo($contracts_id_2); + $this->assertEquals($contracts_id_2, $link['id']); - // Test 3: Use contract in current entity + // Test 3: Use contract in current entity $res = $entity->update([ 'id' => $entities_id, 'contracts_id_default' => '-1', ]); - $this->boolean($res)->isTrue(); + $this->assertTrue($res); - // Case 1: root entity, expect no contract (no config for this entity) + // Case 1: root entity, expect no contract (no config for this entity) $tickets_id_2 = $ticket->add([ 'name' => 'Test ticket 1', 'content' => 'Test ticket 1', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), ]); - $this->integer($tickets_id_2)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($tickets_id_2))->isTrue(); + $this->assertGreaterThan(0, $tickets_id_2); + $this->assertTrue($ticket->getFromDB($tickets_id_2)); $links = $ticket_contract::getListForItem($ticket); - $this->integer(count($links))->isEqualTo(0); + $this->assertEquals(0, count($links)); - // Case 2: sub entity, expect contract 2 + // Case 2: sub entity, expect contract 2 $tickets_id = $ticket->add([ 'name' => 'Test ticket 1', 'content' => 'Test ticket 1', 'entities_id' => $entities_id, ]); - $this->integer($tickets_id)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($tickets_id))->isTrue(); + $this->assertGreaterThan(0, $tickets_id); + $this->assertTrue($ticket->getFromDB($tickets_id)); $links = $ticket_contract::getListForItem($ticket); - $this->integer(count($links))->isEqualTo(1); + $this->assertEquals(1, count($links)); $link = $links->current(); - $this->integer($link['id'])->isEqualTo($contracts_id_2); + $this->assertEquals($contracts_id_2, $link['id']); - // Case 3: contract specified, should not change + // Case 3: contract specified, should not change $tickets_id = $ticket->add([ 'name' => 'Test ticket 1', 'content' => 'Test ticket 1', 'entities_id' => $entities_id, '_contracts_id' => $contracts_id_1, ]); - $this->integer($tickets_id)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($tickets_id))->isTrue(); + $this->assertGreaterThan(0, $tickets_id); + $this->assertTrue($ticket->getFromDB($tickets_id)); $links = $ticket_contract::getListForItem($ticket); - $this->integer(count($links))->isEqualTo(1); + $this->assertEquals(1, count($links)); $link = $links->current(); - $this->integer($link['id'])->isEqualTo($contracts_id_1); + $this->assertEquals($contracts_id_1, $link['id']); } @@ -1103,22 +1144,22 @@ public function testMultipleClones() // Check that no clones exists $entity = new \Entity(); $res = $entity->find(['name' => ['LIKE', 'test clone entity %']]); - $this->array($res)->hasSize(0); + $this->assertCount(0, $res); // Clone multiple times $entity = getItemByTypeName('Entity', 'test clone entity', false); - $this->boolean($entity->cloneMultiple(4))->isTrue(); + $this->assertTrue($entity->cloneMultiple(4)); // Check that 4 clones were created $entity = new \Entity(); $res = $entity->find(['name' => ['LIKE', 'test clone entity %']]); - $this->array($res)->hasSize(4); + $this->assertCount(4, $res); // Try to read each clones - $this->integer(getItemByTypeName('Entity', 'test clone entity (copy)', true))->isGreaterThan(0); - $this->integer(getItemByTypeName('Entity', 'test clone entity (copy 2)', true))->isGreaterThan(0); - $this->integer(getItemByTypeName('Entity', 'test clone entity (copy 3)', true))->isGreaterThan(0); - $this->integer(getItemByTypeName('Entity', 'test clone entity (copy 4)', true))->isGreaterThan(0); + $this->assertGreaterThan(0, getItemByTypeName('Entity', 'test clone entity (copy)', true)); + $this->assertGreaterThan(0, getItemByTypeName('Entity', 'test clone entity (copy 2)', true)); + $this->assertGreaterThan(0, getItemByTypeName('Entity', 'test clone entity (copy 3)', true)); + $this->assertGreaterThan(0, getItemByTypeName('Entity', 'test clone entity (copy 4)', true)); } public function testRename() @@ -1142,22 +1183,22 @@ public function testRename() ); $entities_id = $new_entity->fields['id']; - $this->integer($entities_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $entities_id); //try to rename on existing name - $this->boolean( + $this->assertTrue( $new_entity->update([ 'id' => $entities_id, 'name' => 'Existing entity', ]) - )->isTrue(); + ); $this->hasSessionMessages(ERROR, ['An entity with that name already exists at the same level.']); - $this->boolean($new_entity->getFromDB($entities_id))->isTrue(); - $this->string($new_entity->fields['name'])->isEqualTo('New entity'); + $this->assertTrue($new_entity->getFromDB($entities_id)); + $this->assertEquals('New entity', $new_entity->fields['name']); } - protected function entityTreeProvider(): iterable + public static function entityTreeProvider(): iterable { $entity_test_root = getItemByTypeName('Entity', '_test_root_entity'); $entity_test_child_1 = getItemByTypeName('Entity', '_test_child_1'); @@ -1236,8 +1277,8 @@ public function testGetEntityTree(int $entity_id, array $result): void { $this->login(); - $entity = $this->newTestedInstance(); - $this->array($this->callPrivateMethod($entity, 'getEntityTree', $entity_id))->isEqualTo($result); + $entity = new \Entity(); + $this->assertEquals($result, $this->callPrivateMethod($entity, 'getEntityTree', $entity_id)); } public function testGetEntitySelectorTree(): void @@ -1273,28 +1314,31 @@ public function testGetEntitySelectorTree(): void }; $entities = $fn_get_current_entities(); - $this->array($entities)->size->isGreaterThan(0); + $this->assertGreaterThan(0, count($entities)); $selector = \Entity::getEntitySelectorTree(); $found = []; $fn_find_entities_in_selector($selector, $entities, null, $found); - $this->array($found)->size->isEqualTo(count($entities)); + $this->assertCount(count($entities), $found); // Create a new entity $entity = new \Entity(); - $this->integer($entities_id = $entity_id = $entity->add([ - 'name' => __FUNCTION__ . '1', - 'entities_id' => getItemByTypeName('Entity', '_test_child_2', true) - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $entities_id = $entity_id = $entity->add([ + 'name' => __FUNCTION__ . '1', + 'entities_id' => getItemByTypeName('Entity', '_test_child_2', true) + ]) + ); $found = []; $entities = $fn_get_current_entities(); $fn_find_entities_in_selector(\Entity::getEntitySelectorTree(), $entities, null, $found); - $this->array($found)->size->isEqualTo(count($entities)); + $this->assertCount(count($entities), $found); // Delete the entity - $this->boolean($entity->delete(['id' => $entity_id]))->isTrue(); + $this->assertTrue($entity->delete(['id' => $entity_id])); $found = []; $entities = $fn_get_current_entities(); $fn_find_entities_in_selector(\Entity::getEntitySelectorTree(), $entities, null, $found); - $this->array($found)->size->isEqualTo(count($entities)); + $this->assertCount(count($entities), $found); } } diff --git a/tests/functional/GLPIKey.php b/phpunit/functional/GLPIKeyTest.php similarity index 53% rename from tests/functional/GLPIKey.php rename to phpunit/functional/GLPIKeyTest.php index d686ba0f153..5d9161d75a4 100644 --- a/tests/functional/GLPIKey.php +++ b/phpunit/functional/GLPIKeyTest.php @@ -36,13 +36,14 @@ namespace tests\units; use Glpi\Plugin\Hooks; +use Monolog\Logger; use org\bovigo\vfs\vfsStream; /* Test for inc/glpikey.class.php */ -class GLPIKey extends \DbTestCase +class GLPIKeyTest extends \DbTestCase { - protected function getExpectedKeyPathProvider() + public static function getExpectedKeyPathProvider() { return [ ['0.90.5', null], @@ -64,48 +65,45 @@ protected function getExpectedKeyPathProvider() */ public function testGetExpectedKeyPath($glpi_version, $expected_path) { - $this - ->if($this->newTestedInstance) - ->then - ->variable($this->testedInstance->getExpectedKeyPath($glpi_version))->isEqualTo($expected_path); + $glpikey = new \GLPIKey(); + $this->assertEquals($expected_path, $glpikey->getExpectedKeyPath($glpi_version)); } public function testKeyExists() { $structure = vfsStream::setup('glpi', null, ['config' => []]); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $this->newTestedInstance(vfsStream::url('glpi/config')); - - $this->boolean($this->testedInstance->keyExists())->isFalse(); + $this->assertFalse($glpikey->keyExists()); vfsStream::create(['glpicrypt.key' => 'keyfilecontents'], $structure->getChild('config')); - $this->boolean($this->testedInstance->keyExists())->isTrue(); + $this->assertTrue($glpikey->keyExists()); } - protected function legacyEncryptedProvider() + public static function legacyEncryptedProvider() { - // basic string, default key + // basic string, default key yield [ 'encrypted' => 'G6y/xA==', 'decrypted' => 'test', 'key' => null, ]; - // string with special chars, default key + // string with special chars, default key yield [ 'encrypted' => 'IYx+rrgV1IqUtqSD1repTebaf4c=', 'decrypted' => 'zE2^oS1!mC6"dD6&', 'key' => null, ]; - // basic string, simple custom key + // basic string, simple custom key yield [ 'encrypted' => '7cjo5w==', 'decrypted' => 'test', 'key' => 'custom_k3y', ]; - // string with special chars, complex custom key + // string with special chars, complex custom key yield [ 'encrypted' => 'n7iLkqvGhVeXsoFVwqWEVkimkW8=', 'decrypted' => 'zE2^oS1!mC6"dD6&', @@ -118,26 +116,20 @@ protected function legacyEncryptedProvider() */ public function testDecryptUsingLegacyKey(string $encrypted, string $decrypted, ?string $key) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->decryptUsingLegacyKey($encrypted, $key))->isEqualTo($decrypted); + $glpikey = new \GLPIKey(); + $this->assertEquals($decrypted, $glpikey->decryptUsingLegacyKey($encrypted, $key)); } public function testGetWithoutKey() { vfsStream::setup('glpi', null, ['config' => []]); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $this->newTestedInstance(vfsStream::url('glpi/config')); - - $this->when( - function () { - $this->testedInstance->get(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('You must create a security key, see security:change_key command.') - ->exists(); + $glpikey->get(); + $this->hasPhpLogRecordThatContains( + 'You must create a security key, see security:change_key command.', + Logger::WARNING + ); } public function testGetUnreadableKey() @@ -145,32 +137,26 @@ public function testGetUnreadableKey() $structure = vfsStream::setup('glpi', null, ['config' => ['glpicrypt.key' => 'unreadable file']]); $structure->getChild('config/glpicrypt.key')->chmod(0222); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $this->when( - function () { - $this->testedInstance->get(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Unable to get security key file contents.') - ->exists(); + $glpikey->get(); + $this->hasPhpLogRecordThatContains( + 'Unable to get security key file contents.', + Logger::WARNING + ); } public function testGetInvalidKey() { vfsStream::setup('glpi', null, ['config' => ['glpicrypt.key' => 'not a valid key']]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $this->when( - function () { - $this->testedInstance->get(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Invalid security key file contents.') - ->exists(); + $glpikey->get(); + $this->hasPhpLogRecordThatContains( + 'Invalid security key file contents.', + Logger::WARNING + ); } public function testGet() @@ -178,33 +164,33 @@ public function testGet() $valid_key = 'abcdefghijklmnopqrstuvwxyz123456'; vfsStream::setup('glpi', null, ['config' => ['glpicrypt.key' => $valid_key]]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $key = $this->testedInstance->get(); + $key = $glpikey->get(); - $this->string($key)->isEqualTo($valid_key); + $this->assertEquals($valid_key, $key); } public function testGetLegacyKeyDefault() { vfsStream::setup('glpi', null, ['config' => []]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $key = $this->testedInstance->getLegacyKey(); + $key = $glpikey->getLegacyKey(); - $this->string($key)->isEqualTo("GLPI£i'snarss'ç"); + $this->assertEquals("GLPI£i'snarss'ç", $key); } public function testGetLegacyKeyCustom() { vfsStream::setup('glpi', null, ['config' => ['glpi.key' => 'mylegacykey']]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $key = $this->testedInstance->getLegacyKey(); + $key = $glpikey->getLegacyKey(); - $this->string($key)->isEqualTo('mylegacykey'); + $this->assertEquals('mylegacykey', $key); } public function testGetLegacyKeyUnreadable() @@ -212,84 +198,78 @@ public function testGetLegacyKeyUnreadable() $structure = vfsStream::setup('glpi', null, ['config' => ['glpi.key' => 'unreadable file']]); $structure->getChild('config/glpi.key')->chmod(0222); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $this->when( - function () { - $this->testedInstance->getLegacyKey(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Unable to get security legacy key file contents.') - ->exists(); + $glpikey->getLegacyKey(); + $this->hasPhpLogRecordThatContains( + 'Unable to get security legacy key file contents.', + Logger::WARNING + ); } public function testGenerateWithoutPreviousKey() { vfsStream::setup('glpi', null, ['config' => []]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $success = $this->testedInstance->generate(); - $this->boolean($success)->isTrue(); + $success = $glpikey->generate(); + $this->assertTrue($success); - // key file exists and key can be retrieved - $this->boolean(file_exists(vfsStream::url('glpi/config/glpicrypt.key')))->isTrue(); - $this->string($this->testedInstance->get())->isNotEmpty(); + // key file exists and key can be retrieved + $this->assertTrue(file_exists(vfsStream::url('glpi/config/glpicrypt.key'))); + $this->assertNotEmpty($glpikey->get()); } public function testGenerateWithExistingPreviousKey() { $structure = vfsStream::setup('glpi', null, ['config' => []]); vfsStream::copyFromFileSystem(GLPI_CONFIG_DIR, $structure->getChild('config')); + $structure->getChild('config/glpicrypt.key')->chmod(0666); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $success = $this->testedInstance->generate(); - $this->boolean($success)->isTrue(); + $success = $glpikey->generate(); + $this->assertTrue($success); - // key file exists and key can be retrieved - $this->boolean(file_exists(vfsStream::url('glpi/config/glpicrypt.key')))->isTrue(); - $this->string($this->testedInstance->get())->isNotEmpty(); + // key file exists and key can be retrieved + $this->assertTrue(file_exists(vfsStream::url('glpi/config/glpicrypt.key'))); + $this->assertNotEmpty($glpikey->get()); - // check that decrypted value of _local_ldap.rootdn_passwd is correct + // check that decrypted value of _local_ldap.rootdn_passwd is correct $ldap = getItemByTypeName('AuthLDAP', '_local_ldap'); - $this->string($this->testedInstance->decrypt($ldap->fields['rootdn_passwd']))->isEqualTo('insecure'); + $this->assertEquals('insecure', $glpikey->decrypt($ldap->fields['rootdn_passwd'])); } public function testGenerateFailureWithUnwritableConfigDir() { - // Unwritable dir + // Unwritable dir $structure = vfsStream::setup('glpi', null, ['config' => []]); $structure->getChild('config')->chmod(0555); - $this->newTestedInstance(vfsStream::url('glpi/config')); - $result = null; - $this->when( - function () use (&$result) { - $result = $this->testedInstance->generate(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Security key file path (vfs://glpi/config/glpicrypt.key) is not writable.') - ->exists(); - $this->boolean($result)->isFalse(); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - // Unwritable key file + $this->assertFalse($glpikey->generate()); + $this->hasPhpLogRecordThatContains( + 'Security key file path (vfs://glpi/config/glpicrypt.key) is not writable.', + Logger::WARNING + ); + } + + public function testGenerateFailureWithUnwritableConfigFile() + { + // Unwritable key file $structure = vfsStream::setup('glpi', null, ['config' => ['glpicrypt.key' => 'previouskey']]); $structure->getChild('config/glpicrypt.key')->chmod(0444); - $result = null; - $this->when( - function () use (&$result) { - $result = $this->testedInstance->generate(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Security key file path (vfs://glpi/config/glpicrypt.key) is not writable.') - ->exists(); - $this->boolean($result)->isFalse(); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); + + $this->assertFalse($glpikey->generate()); + $this->hasPhpLogRecordThatContains( + 'Security key file path (vfs://glpi/config/glpicrypt.key) is not writable.', + Logger::WARNING + ); } public function testGenerateFailureWithUnreadableKey() @@ -297,36 +277,26 @@ public function testGenerateFailureWithUnreadableKey() $structure = vfsStream::setup('glpi', null, ['config' => ['glpicrypt.key' => 'unreadable file']]); $structure->getChild('config/glpicrypt.key')->chmod(0222); - $this->newTestedInstance(vfsStream::url('glpi/config')); - - $result = null; - $this->when( - function () use (&$result) { - $result = $this->testedInstance->generate(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Unable to get security key file contents.') - ->exists(); - $this->boolean($result)->isFalse(); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); + + $this->assertFalse($glpikey->generate()); + $this->hasPhpLogRecordThatContains( + 'Unable to get security key file contents.', + Logger::WARNING + ); } public function testGenerateFailureWithInvalidPreviousKey() { vfsStream::setup('glpi', null, ['config' => ['glpicrypt.key' => 'not a valid key']]); - $this->newTestedInstance(vfsStream::url('glpi/config')); - - $result = null; - $this->when( - function () use (&$result) { - $result = $this->testedInstance->generate(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Invalid security key file contents.') - ->exists(); - $this->boolean($result)->isFalse(); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); + + $this->assertFalse($glpikey->generate()); + $this->hasPhpLogRecordThatContains( + 'Invalid security key file contents.', + Logger::WARNING + ); } public function testEncryptDecryptUsingDefaultKey() @@ -334,25 +304,25 @@ public function testEncryptDecryptUsingDefaultKey() $structure = vfsStream::setup('glpi', null, ['config' => []]); vfsStream::copyFromFileSystem(GLPI_CONFIG_DIR, $structure->getChild('config')); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - // Short string with no special chars + // Short string with no special chars $string = 'MyP4ssw0rD'; - $encrypted = $this->testedInstance->encrypt($string); - $decrypted = $this->testedInstance->decrypt($encrypted); - $this->string($decrypted)->isEqualTo($string); + $encrypted = $glpikey->encrypt($string); + $decrypted = $glpikey->decrypt($encrypted); + $this->assertEquals($string, $decrypted); - // Empty string + // Empty string $string = ''; - $encrypted = $this->testedInstance->encrypt($string); - $decrypted = $this->testedInstance->decrypt($encrypted); - $this->string($decrypted)->isEqualTo($string); + $encrypted = $glpikey->encrypt($string); + $decrypted = $glpikey->decrypt($encrypted); + $this->assertEquals($string, $decrypted); - // Complex string with special chars + // Complex string with special chars $string = 'This is a string I want to crypt, with some unusual chars like %, \', @, and so on!'; - $encrypted = $this->testedInstance->encrypt($string); - $decrypted = $this->testedInstance->decrypt($encrypted); - $this->string($decrypted)->isEqualTo($string); + $encrypted = $glpikey->encrypt($string); + $decrypted = $glpikey->decrypt($encrypted); + $this->assertEquals($string, $decrypted); } protected function encryptDecryptProvider() @@ -385,17 +355,17 @@ public function testEncryptUsingSpecificKey(?string $string, ?string $encrypted, { vfsStream::setup('glpi', null, ['config' => []]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - // NONCE produce different result each time - $this->string($this->testedInstance->encrypt($string, $key))->isNotEqualTo($encrypted); + // NONCE produce different result each time + $this->assertNotEquals($encrypted, $glpikey->encrypt($string, $key)); - // As encryption produces different result each time, we cannot validate encrypted value. - // So we validates that encryption alters string, and decryption reproduces the initial string. - $encrypted = $this->testedInstance->encrypt($string, $key); - $this->string($encrypted)->isNotEqualTo($string); - $decrypted = $this->testedInstance->decrypt($encrypted, $key); - $this->string($decrypted)->isEqualTo($string); + // As encryption produces different result each time, we cannot validate encrypted value. + // So we validate that encryption alters string, and decryption reproduces the initial string. + $encrypted = $glpikey->encrypt($string, $key); + $this->assertNotEquals($string, $encrypted); + $decrypted = $glpikey->decrypt($encrypted, $key); + $this->assertEquals($string, $decrypted); } /** @@ -405,10 +375,10 @@ public function testDecryptUsingSpecificKey(?string $string, ?string $encrypted, { vfsStream::setup('glpi', null, ['config' => []]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $decrypted = $this->testedInstance->decrypt($encrypted, $key); - $this->string($decrypted)->isEqualTo($string); + $decrypted = $glpikey->decrypt($encrypted, $key); + $this->assertEquals($string, $decrypted); } /** @@ -419,10 +389,10 @@ public function testDecryptEmptyValue(?string $string, ?string $encrypted, ?stri $structure = vfsStream::setup('glpi', null, ['config' => []]); vfsStream::copyFromFileSystem(GLPI_CONFIG_DIR, $structure->getChild('config')); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $this->variable($this->testedInstance->decrypt(null))->isNull(); - $this->string($this->testedInstance->decrypt(''))->isEmpty(); + $this->assertNull($glpikey->decrypt(null)); + $this->assertEmpty($glpikey->decrypt('')); } public function testDecryptInvalidString() @@ -430,20 +400,13 @@ public function testDecryptInvalidString() $structure = vfsStream::setup('glpi', null, ['config' => []]); vfsStream::copyFromFileSystem(GLPI_CONFIG_DIR, $structure->getChild('config')); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $result = null; - - $this->when( - function () use (&$result) { - $result = $this->testedInstance->decrypt('not a valid value'); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Unable to extract nonce from string. It may not have been crypted with sodium functions.') - ->exists(); - - $this->string($result)->isEmpty(); + $this->assertEmpty($glpikey->decrypt('not a valid value')); + $this->hasPhpLogRecordThatContains( + 'Unable to extract nonce from string. It may not have been crypted with sodium functions.', + Logger::WARNING + ); } public function testDecryptUsingBadKey() @@ -451,28 +414,20 @@ public function testDecryptUsingBadKey() $structure = vfsStream::setup('glpi', null, ['config' => []]); vfsStream::copyFromFileSystem(GLPI_CONFIG_DIR, $structure->getChild('config')); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); - $result = null; - - $this->when( - function () use (&$result) { - // 'test' string crypted with a valid key used just for that - $result = $this->testedInstance->decrypt('CUdPSEgzKroDOwM1F8lbC8WDcQUkGCxIZpdTEpp5W/PLSb70WmkaKP0Q7QY='); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Unable to decrypt string. It may have been crypted with another key.') - ->exists(); - - $this->string($result)->isEmpty(); + $this->assertEmpty($glpikey->decrypt('CUdPSEgzKroDOwM1F8lbC8WDcQUkGCxIZpdTEpp5W/PLSb70WmkaKP0Q7QY=')); + $this->hasPhpLogRecordThatContains( + 'Unable to decrypt string. It may have been crypted with another key.', + Logger::WARNING + ); } public function testGetFields() { vfsStream::setup('glpi', null, ['config' => []]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); global $PLUGIN_HOOKS; $hooks_backup = $PLUGIN_HOOKS[Hooks::SECURED_FIELDS] ?? null; @@ -487,14 +442,14 @@ public function testGetFields() ], ]; - $fields = $this->testedInstance->getFields(); + $fields = $glpikey->getFields(); unset($PLUGIN_HOOKS[Hooks::SECURED_FIELDS]); if ($hooks_backup !== null) { $PLUGIN_HOOKS[Hooks::SECURED_FIELDS] = $hooks_backup; } - $this->array($fields)->isEqualTo( + $this->assertEquals( [ 'glpi_authldaps.rootdn_passwd', 'glpi_mailcollectors.passwd', @@ -503,7 +458,8 @@ public function testGetFields() 'glpi_plugin_myplugin_remote.key', 'glpi_plugin_myplugin_remote.secret', 'glpi_plugin_anotherplugin_link.pass', - ] + ], + $fields ); } @@ -511,7 +467,7 @@ public function testGetConfigs() { vfsStream::setup('glpi', null, ['config' => []]); - $this->newTestedInstance(vfsStream::url('glpi/config')); + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); global $PLUGIN_HOOKS; $hooks_backup = $PLUGIN_HOOKS[Hooks::SECURED_CONFIGS] ?? null; @@ -525,14 +481,14 @@ public function testGetConfigs() ], ]; - $configs = $this->testedInstance->getConfigs(); + $configs = $glpikey->getConfigs(); unset($PLUGIN_HOOKS[Hooks::SECURED_CONFIGS]); if ($hooks_backup !== null) { $PLUGIN_HOOKS[Hooks::SECURED_CONFIGS] = $hooks_backup; } - $this->array($configs)->isEqualTo( + $this->assertEquals( [ 'core' => [ 'glpinetwork_registration_key', @@ -547,7 +503,8 @@ public function testGetConfigs() 'plugin:anotherplugin' => [ 'secret', ], - ] + ], + $configs ); } @@ -555,8 +512,7 @@ public function testIsConfigSecured() { vfsStream::setup('glpi', null, ['config' => []]); - $this->newTestedInstance(vfsStream::url('glpi/config')); - + $glpikey = new \GLPIKey(vfsStream::url('glpi/config')); global $PLUGIN_HOOKS; $hooks_backup = $PLUGIN_HOOKS[Hooks::SECURED_CONFIGS] ?? null; @@ -566,21 +522,21 @@ public function testIsConfigSecured() ], ]; - $is_url_base_secured = $this->testedInstance->isConfigSecured('core', 'url_base'); - $is_smtp_passwd_secured = $this->testedInstance->isConfigSecured('core', 'smtp_passwd'); - $is_myplugin_password_secured = $this->testedInstance->isConfigSecured('plugin:myplugin', 'password'); - $is_myplugin_href_secured = $this->testedInstance->isConfigSecured('plugin:myplugin', 'href'); - $is_someplugin_conf_secured = $this->testedInstance->isConfigSecured('plugin:someplugin', 'conf'); + $is_url_base_secured = $glpikey->isConfigSecured('core', 'url_base'); + $is_smtp_passwd_secured = $glpikey->isConfigSecured('core', 'smtp_passwd'); + $is_myplugin_password_secured = $glpikey->isConfigSecured('plugin:myplugin', 'password'); + $is_myplugin_href_secured = $glpikey->isConfigSecured('plugin:myplugin', 'href'); + $is_someplugin_conf_secured = $glpikey->isConfigSecured('plugin:someplugin', 'conf'); unset($PLUGIN_HOOKS[Hooks::SECURED_CONFIGS]); if ($hooks_backup !== null) { $PLUGIN_HOOKS[Hooks::SECURED_CONFIGS] = $hooks_backup; } - $this->boolean($is_url_base_secured)->isFalse(); - $this->boolean($is_smtp_passwd_secured)->isTrue(); - $this->boolean($is_myplugin_password_secured)->isTrue(); - $this->boolean($is_myplugin_href_secured)->isFalse(); - $this->boolean($is_someplugin_conf_secured)->isFalse(); + $this->assertFalse($is_url_base_secured); + $this->assertTrue($is_smtp_passwd_secured); + $this->assertTrue($is_myplugin_password_secured); + $this->assertFalse($is_myplugin_href_secured); + $this->assertFalse($is_someplugin_conf_secured); } } diff --git a/phpunit/functional/Glpi/Inventory/Assets/NetworkEquipmentTest.php b/phpunit/functional/Glpi/Inventory/Assets/NetworkEquipmentTest.php index 2043c610a8f..cd7228773f0 100644 --- a/phpunit/functional/Glpi/Inventory/Assets/NetworkEquipmentTest.php +++ b/phpunit/functional/Glpi/Inventory/Assets/NetworkEquipmentTest.php @@ -2925,7 +2925,7 @@ public function testAssetTag() */ public function testStackedDellSwitchN3048P() { - $xml_source = file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/dell_n3048p.xml'); + $xml_source = file_get_contents(FIXTURE_DIR . '/inventories/dell_n3048p.xml'); // Import the switch(es) into GLPI $converter = new \Glpi\Inventory\Converter(); $data = json_decode($converter->convert($xml_source)); @@ -3091,7 +3091,7 @@ public function testRuleMatchedLog() */ public function testStackedCiscoSwitchC9300() { - $xml_source = file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/cisco-C9300.xml'); + $xml_source = file_get_contents(FIXTURE_DIR . '/inventories/cisco-C9300.xml'); // Import the switch(es) into GLPI $converter = new \Glpi\Inventory\Converter(); $data = json_decode($converter->convert($xml_source)); diff --git a/phpunit/functional/Glpi/Inventory/Assets/NetworkPortTest.php b/phpunit/functional/Glpi/Inventory/Assets/NetworkPortTest.php index 856c2e57db3..90437939c78 100644 --- a/phpunit/functional/Glpi/Inventory/Assets/NetworkPortTest.php +++ b/phpunit/functional/Glpi/Inventory/Assets/NetworkPortTest.php @@ -1429,7 +1429,7 @@ public function testNetworkEquipmentsConnections(): void ); // Import the linked network equipment into GLPI - $xml_source = file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/connected_switch.xml'); + $xml_source = file_get_contents(FIXTURE_DIR . '/inventories/connected_switch.xml'); $converter = new \Glpi\Inventory\Converter(); $data = json_decode($converter->convert($xml_source)); $CFG_GLPI["is_contact_autoupdate"] = 0; @@ -1463,7 +1463,7 @@ public function testNetworkEquipmentsConnectionsConverted(): void $this->assertCount(0, $unmanaged->find()); // Import the network equipment - $xml_source = file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/connected_switch.xml'); + $xml_source = file_get_contents(FIXTURE_DIR . '/inventories/connected_switch.xml'); $converter = new \Glpi\Inventory\Converter(); $data = json_decode($converter->convert($xml_source)); $CFG_GLPI["is_contact_autoupdate"] = 0; @@ -1513,7 +1513,7 @@ public function testNetworkEquipmentsConnectionsConverted(): void $this->assertCount(0, $unmanaged->find()); // Import the network equipment again - $xml_source = file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/connected_switch.xml'); + $xml_source = file_get_contents(FIXTURE_DIR . '/inventories/connected_switch.xml'); $converter = new \Glpi\Inventory\Converter(); $data = json_decode($converter->convert($xml_source)); $CFG_GLPI["is_contact_autoupdate"] = 0; diff --git a/phpunit/functional/Glpi/Inventory/Assets/SoftwareTest.php b/phpunit/functional/Glpi/Inventory/Assets/SoftwareTest.php index fb4ae1869db..5f8a9cb36ce 100644 --- a/phpunit/functional/Glpi/Inventory/Assets/SoftwareTest.php +++ b/phpunit/functional/Glpi/Inventory/Assets/SoftwareTest.php @@ -802,14 +802,14 @@ public static function softwareProvider(): array { return [ //To test FullCompareKey (with special chars on software name / manufacturer) - ['/tests/fixtures/inventories/softwares/01-test_software_with_special_chars_with_version.json'], - ['/tests/fixtures/inventories/softwares/02-test_software_with_special_chars_with_version.json'], + ['01-test_software_with_special_chars_with_version.json'], + ['02-test_software_with_special_chars_with_version.json'], //To test FullCompareKey without version (with special chars on software name / manufacturer) - ['/tests/fixtures/inventories/softwares/03-test_software_with_special_chars_and_without_version.json'], + ['03-test_software_with_special_chars_and_without_version.json'], // /To test FullCompareKey with version (with special chars on software name / manufacturer name / OS name / arch name) - ['/tests/fixtures/inventories/softwares/04-test_software_with_special_chars_and_with_version_and_os.json'], + ['04-test_software_with_special_chars_and_with_version_and_os.json'], // /To test FullCompareKey without version (with special chars on software name / manufacturer name / OS name / arch name) - ['/tests/fixtures/inventories/softwares/05-test_software_with_special_chars_and_without_version_and_os.json'], + ['05-test_software_with_special_chars_and_without_version_and_os.json'], ]; } @@ -818,8 +818,8 @@ public static function softwareProvider(): array */ public function testSoftwareWithHtmlentites($path) { - - $json_source = json_decode(file_get_contents(GLPI_ROOT . $path)); + $fixtures_path = FIXTURE_DIR . '/inventories/software/'; + $json_source = json_decode(file_get_contents($fixtures_path . $path)); $this->doInventory($json_source); $computer = new \Computer(); @@ -846,7 +846,7 @@ public function testSoftwareWithHtmlentites($path) //redo an inventory - $json_source = json_decode(file_get_contents(GLPI_ROOT . $path)); + $json_source = json_decode(file_get_contents($fixtures_path . $path)); $this->doInventory($json_source); $computer = new \Computer(); diff --git a/phpunit/functional/Glpi/Inventory/InventoryTest.php b/phpunit/functional/Glpi/Inventory/InventoryTest.php index 185c0c7e985..bf71a67067a 100644 --- a/phpunit/functional/Glpi/Inventory/InventoryTest.php +++ b/phpunit/functional/Glpi/Inventory/InventoryTest.php @@ -2724,7 +2724,7 @@ public function testImportStackedNetworkEquipment() public function testImportStackedNetworkEquipment2() { - $xml = file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/stacked_switch_name.xml'); + $xml = file_get_contents(FIXTURE_DIR . '/inventories/stacked_switch_name.xml'); $date_now = date('Y-m-d H:i:s'); $_SESSION['glpi_currenttime'] = $date_now; @@ -4772,7 +4772,7 @@ public function testUpdateVirtualMachines() { global $DB; - $json = json_decode(file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/lxc-server-1.json')); + $json = json_decode(file_get_contents(FIXTURE_DIR . '/inventories/lxc-server-1.json')); $count_vms = count($json->content->virtualmachines); $this->assertSame(1, $count_vms); @@ -4816,7 +4816,7 @@ public function testUpdateVirtualMachines() $this->assertSame('487dfdb542a4bfb23670b8d4e76d8b6886c2ed35', $cvms->fields['uuid']); //import again, RAM has changed - $json = json_decode(file_get_contents(GLPI_ROOT . '/tests/fixtures/inventories/lxc-server-1.json')); + $json = json_decode(file_get_contents(FIXTURE_DIR . '/inventories/lxc-server-1.json')); $json_vm = $json->content->virtualmachines[0]; $json_vm->memory = 4096; $json_vms = [$json_vm]; @@ -5280,7 +5280,7 @@ public function testImportPhoneMultiSimCardNoReset() public function testImportPhone() { - global $DB, $CFG_GLPI; + global $DB; $json = json_decode(file_get_contents(self::INV_FIXTURES . 'phone_1.json')); diff --git a/tests/functional/Glpi/RichText/RichText.php b/phpunit/functional/Glpi/RichText/RichTextTest.php similarity index 93% rename from tests/functional/Glpi/RichText/RichText.php rename to phpunit/functional/Glpi/RichText/RichTextTest.php index 8ab2d764bd0..61d30ef3c74 100644 --- a/tests/functional/Glpi/RichText/RichText.php +++ b/phpunit/functional/Glpi/RichText/RichTextTest.php @@ -40,9 +40,9 @@ /** * Test class for src/Glpi/RichText/richtext.class.php */ -class RichText extends \GLPITestCase +class RichTextTest extends \GLPITestCase { - protected function getSafeHtmlProvider(): iterable + public static function getSafeHtmlProvider(): iterable { // Empty content would not be altered yield [ @@ -332,7 +332,7 @@ public function () { HTML, ]; - // Deprecated html attibutes should not be transformed into styles + // Deprecated html attributes should not be transformed into styles // see #11580 yield [ 'content' => '
Test
', @@ -340,7 +340,7 @@ public function () { 'expected_result' => '
Test
', ]; - // Images path should be corrected when root doc changed + /*// Images path should be corrected when root doc changed // see #15113 foreach (['', '/glpi', '/path/to/glpi'] as $expected_prefix) { global $CFG_GLPI; @@ -366,7 +366,7 @@ public function () { HTML, ]; } - } + }*/ } /** @@ -377,10 +377,51 @@ public function testGetSafeHtml( bool $encode_output_entities, string $expected_result ) { - $richtext = $this->newTestedInstance(); + $richtext = new \Glpi\RichText\RichText(); - $this->string($richtext->getSafeHtml($content, $encode_output_entities)) - ->isEqualTo($expected_result); + $this->assertEquals( + $expected_result, + $richtext->getSafeHtml($content, $encode_output_entities) + ); + } + + public function testGetSafeHtmlDoChangeDocPath() + { + /** @var array $CFG_GLPI */ + global $CFG_GLPI; + $bkp_root_doc = $CFG_GLPI['root_doc']; + // Images path should be corrected when root doc changed + // see #15113 + + $richtext = new \Glpi\RichText\RichText(); + + foreach (['', '/glpi', '/path/to/glpi'] as $expected_prefix) { + $CFG_GLPI['root_doc'] = $expected_prefix; + foreach (['/previous/glpi/path', '', '/glpi'] as $previous_prefix) { + $content = << + Images path should be corrected when root doc changed: + + 34c09468-b2d8e96f-64f991f5ce1660.58639912 + +

+HTML; + $encode_output_entities = false; + $expected_result = << + Images path should be corrected when root doc changed: + + 34c09468-b2d8e96f-64f991f5ce1660.58639912 + +

+HTML; + $this->assertEquals( + $expected_result, + $richtext->getSafeHtml($content, $encode_output_entities) + ); + } + } + $CFG_GLPI['root_doc'] = $bkp_root_doc; } protected function getTextFromHtmlProvider(): iterable @@ -554,13 +595,22 @@ public function testGetTextFromHtml( bool $preserve_line_breaks, string $expected_result ) { - $richtext = $this->newTestedInstance(); - - $this->string($richtext->getTextFromHtml($content, $keep_presentation, $compact, $encode_output_entities, $preserve_case, $preserve_line_breaks)) - ->isEqualTo($expected_result); + $richtext = new \Glpi\RichText\RichText(); + + $this->assertEquals( + $expected_result, + $richtext->getTextFromHtml( + $content, + $keep_presentation, + $compact, + $encode_output_entities, + $preserve_case, + $preserve_line_breaks + ) + ); } - protected function isRichTextHtmlContentProvider(): iterable + public static function isRichTextHtmlContentProvider(): iterable { yield [ 'content' => <<newTestedInstance(); + $richtext = new \Glpi\RichText\RichText(); - $this->boolean($richtext->isRichTextHtmlContent($content))->isEqualTo($expected_result); + $this->assertSame($expected_result, $richtext->isRichTextHtmlContent($content)); } } diff --git a/tests/functional/Glpi/RichText/UserMention.php b/phpunit/functional/Glpi/RichText/UserMentionTest.php similarity index 79% rename from tests/functional/Glpi/RichText/UserMention.php rename to phpunit/functional/Glpi/RichText/UserMentionTest.php index 131e917c9e4..62dd15c407c 100644 --- a/tests/functional/Glpi/RichText/UserMention.php +++ b/phpunit/functional/Glpi/RichText/UserMentionTest.php @@ -50,26 +50,11 @@ use TicketValidation; use User; -class UserMention extends DbTestCase +class UserMentionTest extends DbTestCase { - protected function itilProvider() + public static function getTypesMapping(): array { - $tech_id = getItemByTypeName('User', 'tech', true); - $normal_id = getItemByTypeName('User', 'normal', true); - - // Delete existing notifications targets (to prevent sending of notifications not related to user_mention) - $notification_targets = new NotificationTarget(); - $notification_targets->deleteByCriteria(['NOT' => ['items_id' => Notification::MENTIONNED_USER]]); - - // Add email to users for notifications - $this->login(); // must be authenticated to update emails - $user = new User(); - $update = $user->update(['id' => $tech_id, '_useremails' => ['tech@glpi-project.org']]); - $this->boolean($update)->isTrue(); - $update = $user->update(['id' => $normal_id, '_useremails' => ['normal@glpi-project.org']]); - $this->boolean($update)->isTrue(); - - $types_mapping = [ + return [ 'Change' => [ 'ITILFollowup', 'ChangeTask', @@ -86,16 +71,20 @@ protected function itilProvider() 'ITILSolution', ], ]; + } - foreach ($types_mapping as $main_type => $sub_types) { - $this->createNotification($main_type); + public static function itilProvider() + { + $tech_id = getItemByTypeName('User', 'tech', true); + $normal_id = getItemByTypeName('User', 'normal', true); + foreach (self::getTypesMapping() as $main_type => $sub_types) { foreach (array_merge([$main_type], $sub_types) as $itemtype) { yield [ 'itemtype' => $itemtype, 'main_itemtype' => $main_type, - // No user mention on creation => no observer + // No user mention on creation => no observer 'add_content' => <<<HTML <p>ping @tec</p> HTML @@ -103,7 +92,7 @@ protected function itilProvider() 'add_expected_observers' => [], 'add_expected_notified' => [], - // Added mentions on update => new observers + // Added mentions on update => new observers 'update_content' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -116,7 +105,7 @@ protected function itilProvider() 'itemtype' => $itemtype, 'main_itemtype' => $main_type, - // 1 user mention => 1 observer + // 1 user mention => 1 observer 'add_content' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -124,7 +113,7 @@ protected function itilProvider() 'add_expected_observers' => [$tech_id], 'add_expected_notified' => [$tech_id], - // Same mentions on update => mentionned users are not notified + // Same mentions on update => mentionned users are not notified 'update_content' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -136,8 +125,8 @@ protected function itilProvider() 'itemtype' => $itemtype, 'main_itemtype' => $main_type, - // multiple user mentions => multiple observer - // validate that data-* attributes order has no impact + // multiple user mentions => multiple observer + // validate that data-* attributes order has no impact 'add_content' => <<<HTML <p>Hi <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span>,</p> <p>I discussed with <span data-user-id="{$normal_id}" data-user-mention="true">@normal</span> about ...</p> @@ -146,7 +135,7 @@ protected function itilProvider() 'add_expected_observers' => [$tech_id, $normal_id], 'add_expected_notified' => [$tech_id, $normal_id], - // Deleted mentions on update => no change on observers + // Deleted mentions on update => no change on observers 'update_content' => <<<HTML <p>Hi <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span>,</p> <p> ... </p> @@ -162,7 +151,7 @@ protected function itilProvider() 'itemtype' => $itemtype, 'main_itemtype' => $main_type, - // Created content => no notification to private users + // Created content => no notification to private users 'add_content' => <<<HTML <p>Hi <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span>,</p> <br> @@ -172,7 +161,7 @@ protected function itilProvider() 'add_expected_observers' => [$tech_id, $normal_id], 'add_expected_notified' => [$tech_id], - // Updated content => no notification to private users + // Updated content => no notification to private users 'update_content' => <<<HTML <p>Hi <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span>,</p> <p>I discussed with <span data-user-id="{$normal_id}" data-user-mention="true">@normal</span> about ...</p> @@ -188,7 +177,7 @@ protected function itilProvider() 'itemtype' => $itemtype, 'main_itemtype' => $main_type, - // bad HTML no users are notified + // bad HTML no users are notified 'add_content' => <<<HTML </span></p></div></body></html> HTML @@ -196,7 +185,7 @@ protected function itilProvider() 'add_expected_observers' => [], 'add_expected_notified' => [], - // update bad HTML => no users are notified + // update bad HTML => no users are notified 'update_content' => <<<HTML </span></p></div></body></html> HTML @@ -226,7 +215,24 @@ public function testHandleUserMentions( $CFG_GLPI['use_notifications'] = 1; $CFG_GLPI['notifications_mailing'] = 1; - $this->login(); + $tech_id = getItemByTypeName('User', 'tech', true); + $normal_id = getItemByTypeName('User', 'normal', true); + + // Delete existing notifications targets (to prevent sending of notifications not related to user_mention) + $notification_targets = new NotificationTarget(); + $notification_targets->deleteByCriteria(['NOT' => ['items_id' => Notification::MENTIONNED_USER]]); + + // Add email to users for notifications + $this->login(); // must be authenticated to update emails + $user = new User(); + $update = $user->update(['id' => $tech_id, '_useremails' => ['tech@glpi-project.org']]); + $this->assertTrue($update); + $update = $user->update(['id' => $normal_id, '_useremails' => ['normal@glpi-project.org']]); + $this->assertTrue($update); + + foreach (self::getTypesMapping() as $main_type => $sub_types) { + $this->createNotification($main_type); + } $item = getItemForItemtype($itemtype); @@ -236,10 +242,9 @@ public function testHandleUserMentions( if (is_a($itemtype, CommonITILObject::class, true)) { $main_item = $item; - $input['name'] = $this->getUniqueString(); // code does not handle absence of name in input } else { - // Create main item to be able to attach it the sub item + // Create main item to be able to attach it the sub item $main_item = getItemForItemtype($main_itemtype); $main_item_id = $main_item->add( @@ -248,7 +253,7 @@ public function testHandleUserMentions( 'content' => $this->getUniqueString(), ] ); - $this->integer($main_item_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $main_item_id); if ($item->isField($main_item->getForeignKeyField())) { $input[$main_item->getForeignKeyField()] = $main_item_id; @@ -262,11 +267,11 @@ public function testHandleUserMentions( $input['is_private'] = $is_private ? 1 : 0; } - // Create item + // Create item $item_id = $item->add(Sanitizer::sanitize($input)); - $this->integer($item_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $item_id); - // Check observers on creation + // Check observers on creation $observers = getAllDataFromTable( $main_item->userlinkclass::getTable(), [ @@ -274,10 +279,10 @@ public function testHandleUserMentions( $main_item->getForeignKeyField() => $main_item->getID(), ] ); - $this->array($observers)->hasSize(count($add_expected_observers)); - $this->array(array_column($observers, 'users_id'))->isEqualTo($add_expected_observers); + $this->assertCount(count($add_expected_observers), $observers); + $this->assertEquals($add_expected_observers, array_column($observers, 'users_id')); - // Check notifications sent on creation + // Check notifications sent on creation $notifications = getAllDataFromTable( 'glpi_queuednotifications', [ @@ -285,13 +290,13 @@ public function testHandleUserMentions( 'items_id' => $main_item->getID(), ] ); - $this->array($notifications)->hasSize(count($add_expected_notified)); + $this->assertCount(count($add_expected_notified), $notifications); - // Update item + // Update item $update = $item->update(Sanitizer::sanitize(['id' => $item->getID(), 'content' => $update_content])); - $this->boolean($update)->isTrue(); + $this->assertTrue($update); - // Check observers on update + // Check observers on update $observers = getAllDataFromTable( $main_item->userlinkclass::getTable(), [ @@ -300,10 +305,10 @@ public function testHandleUserMentions( ] ); $expected_observers = array_merge($add_expected_observers, $update_expected_observers); - $this->array($observers)->hasSize(count($expected_observers)); - $this->array(array_column($observers, 'users_id'))->isEqualTo($expected_observers); + $this->assertCount(count($expected_observers), $observers); + $this->assertEquals($expected_observers, array_column($observers, 'users_id')); - // Check notifications sent on update + // Check notifications sent on update $notifications = getAllDataFromTable( 'glpi_queuednotifications', [ @@ -311,28 +316,16 @@ public function testHandleUserMentions( 'items_id' => $main_item->getID(), ] ); - $this->array($notifications)->hasSize(count($add_expected_notified) + count($update_expected_notified)); + $this->assertCount(count($add_expected_notified) + count($update_expected_notified), $notifications); } - protected function ticketValidationProvider() + public static function ticketValidationProvider() { $tech_id = getItemByTypeName('User', 'tech', true); $normal_id = getItemByTypeName('User', 'normal', true); - // Delete existing notifications targets (to prevent sending of notifications not related to user_mention) - $notification_targets = new NotificationTarget(); - $notification_targets->deleteByCriteria(['NOT' => ['items_id' => Notification::MENTIONNED_USER]]); - - // Add email to users for notifications - $this->login(); // must be authenticated to update emails - $user = new User(); - $update = $user->update(['id' => $tech_id, '_useremails' => ['tech@glpi-project.org']]); - $this->boolean($update)->isTrue(); - $update = $user->update(['id' => $normal_id, '_useremails' => ['normal@glpi-project.org']]); - $this->boolean($update)->isTrue(); - yield [ - // No user mention on creation => no observer + // No user mention on creation => no observer 'submission_add' => <<<HTML <p>ping @tec</p> HTML @@ -342,7 +335,7 @@ protected function ticketValidationProvider() 'add_expected_observers' => [], 'add_expected_notified' => [], - // Added mentions on update (submission) => new observers + // Added mentions on update (submission) => new observers 'submission_update' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -354,7 +347,7 @@ protected function ticketValidationProvider() ]; yield [ - // No user mention on creation => no observer + // No user mention on creation => no observer 'submission_add' => <<<HTML <p>ping @tec</p> HTML @@ -364,7 +357,7 @@ protected function ticketValidationProvider() 'add_expected_observers' => [], 'add_expected_notified' => [], - // Added mentions on update (validation) => new observers + // Added mentions on update (validation) => new observers 'submission_update' => null, 'validation_update' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> @@ -376,7 +369,7 @@ protected function ticketValidationProvider() ]; yield [ - // 1 user mention => 1 observer + // 1 user mention => 1 observer 'submission_add' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -385,7 +378,7 @@ protected function ticketValidationProvider() 'add_expected_observers' => [$tech_id], 'add_expected_notified' => [$tech_id], - // Same mentions on update (submission) => mentionned users are not notified + // Same mentions on update (submission) => mentionned users are not notified 'submission_update' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -396,7 +389,7 @@ protected function ticketValidationProvider() ]; yield [ - // 1 user mention => 1 observer + // 1 user mention => 1 observer 'submission_add' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -405,7 +398,7 @@ protected function ticketValidationProvider() 'add_expected_observers' => [$tech_id], 'add_expected_notified' => [$tech_id], - // Same mentions on update (validation) => mentionned users are not notified + // Same mentions on update (validation) => mentioned users are not notified 'submission_update' => null, 'validation_update' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> @@ -416,7 +409,7 @@ protected function ticketValidationProvider() ]; yield [ - // No user mention on creation => no observer + // No user mention on creation => no observer 'submission_add' => <<<HTML <p>ping @tec</p> HTML @@ -426,7 +419,7 @@ protected function ticketValidationProvider() 'add_expected_observers' => [], 'add_expected_notified' => [], - // Added mentions on update (submission and validation) => new observers + // Added mentions on update (submission and validation) => new observers 'submission_update' => <<<HTML <p>ping <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span></p> HTML @@ -441,8 +434,8 @@ protected function ticketValidationProvider() ]; yield [ - // multiple user mentions => multiple observer - // validate that data-* attributes order has no impact + // multiple user mentions => multiple observer + // validate that data-* attributes order has no impact 'submission_add' => <<<HTML <p>Hi <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span>,</p> <p>I discussed with <span data-user-id="{$normal_id}" data-user-mention="true">@normal</span> about ...</p> @@ -452,7 +445,7 @@ protected function ticketValidationProvider() 'add_expected_observers' => [$tech_id, $normal_id], 'add_expected_notified' => [$tech_id, $normal_id], - // Deleted mentions on update => no change on observers + // Deleted mentions on update => no change on observers 'submission_update' => <<<HTML <p>Hi <span data-user-mention="true" data-user-id="{$tech_id}">@tech</span>,</p> <p> ... </p> @@ -483,9 +476,22 @@ public function testHandleUserMentionsOnTicketValidation( $CFG_GLPI['use_notifications'] = 1; $CFG_GLPI['notifications_mailing'] = 1; - $this->login(); + $tech_id = getItemByTypeName('User', 'tech', true); + $normal_id = getItemByTypeName('User', 'normal', true); + + // Delete existing notifications targets (to prevent sending of notifications not related to user_mention) + $notification_targets = new NotificationTarget(); + $notification_targets->deleteByCriteria(['NOT' => ['items_id' => Notification::MENTIONNED_USER]]); + + // Add email to users for notifications + $this->login(); // must be authenticated to update emails + $user = new User(); + $update = $user->update(['id' => $tech_id, '_useremails' => ['tech@glpi-project.org']]); + $this->assertTrue($update); + $update = $user->update(['id' => $normal_id, '_useremails' => ['normal@glpi-project.org']]); + $this->assertTrue($update); - // Create ticket + // Create ticket $ticket = new Ticket(); $ticket_id = $ticket->add( [ @@ -493,9 +499,9 @@ public function testHandleUserMentionsOnTicketValidation( 'content' => $this->getUniqueString(), ] ); - $this->integer($ticket_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $ticket_id); - // Create TicketValidation + // Create TicketValidation $input = [ 'tickets_id' => $ticket_id, 'users_id_validate' => Session::getLoginUserID(), @@ -508,9 +514,9 @@ public function testHandleUserMentionsOnTicketValidation( } $ticket_validation = new TicketValidation(); $ticket_validation_id = $ticket_validation->add(Sanitizer::sanitize($input)); - $this->integer($ticket_validation_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $ticket_validation_id); - // Check observers on creation + // Check observers on creation $observers = getAllDataFromTable( Ticket_User::getTable(), [ @@ -518,10 +524,10 @@ public function testHandleUserMentionsOnTicketValidation( 'tickets_id' => $ticket->getID(), ] ); - $this->array($observers)->hasSize(count($add_expected_observers)); - $this->array(array_column($observers, 'users_id'))->isEqualTo($add_expected_observers); + $this->assertCount(count($add_expected_observers), $observers); + $this->assertEquals($add_expected_observers, array_column($observers, 'users_id')); - // Check notifications sent on creation + // Check notifications sent on creation $notifications = getAllDataFromTable( 'glpi_queuednotifications', [ @@ -529,9 +535,9 @@ public function testHandleUserMentionsOnTicketValidation( 'items_id' => $ticket_id, ] ); - $this->array($notifications)->hasSize(count($add_expected_notified)); + $this->assertCount(count($add_expected_notified), $notifications); - // Update TicketValidation + // Update TicketValidation $input = [ 'id' => $ticket_validation_id ]; @@ -542,9 +548,9 @@ public function testHandleUserMentionsOnTicketValidation( $input['comment_validation'] = $validation_update; } $update = $ticket_validation->update(Sanitizer::sanitize($input)); - $this->boolean($update)->isTrue(); + $this->assertTrue($update); - // Check observers on update + // Check observers on update $observers = getAllDataFromTable( Ticket_User::getTable(), [ @@ -553,10 +559,10 @@ public function testHandleUserMentionsOnTicketValidation( ] ); $expected_observers = array_merge($add_expected_observers, $update_expected_observers); - $this->array($observers)->hasSize(count($expected_observers)); - $this->array(array_column($observers, 'users_id'))->isEqualTo($expected_observers); + $this->assertCount(count($expected_observers), $observers); + $this->assertEquals($expected_observers, array_column($observers, 'users_id')); - // Check notifications sent on update + // Check notifications sent on update $notifications = getAllDataFromTable( 'glpi_queuednotifications', [ @@ -564,7 +570,7 @@ public function testHandleUserMentionsOnTicketValidation( 'items_id' => $ticket_id, ] ); - $this->array($notifications)->hasSize(count($add_expected_notified) + count($update_expected_notified)); + $this->assertCount(count($add_expected_notified) + count($update_expected_notified), $notifications); } /** @@ -586,7 +592,7 @@ private function createNotification(string $itemtype): void 'is_active' => 1, ] ); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); $template = new NotificationTemplate(); $template_id = $template->add( @@ -595,7 +601,7 @@ private function createNotification(string $itemtype): void 'itemtype' => $itemtype, ] ); - $this->integer($template_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $template_id); $template_translation = new NotificationTemplateTranslation(); $template_translation_id = $template_translation->add( @@ -607,7 +613,7 @@ private function createNotification(string $itemtype): void 'content_html' => '...', ] ); - $this->integer($template_translation_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $template_translation_id); $notification_notificationtemplate = new Notification_NotificationTemplate(); $notification_notificationtemplate_id = $notification_notificationtemplate->add( @@ -617,7 +623,7 @@ private function createNotification(string $itemtype): void 'notificationtemplates_id' => $template_id, ] ); - $this->integer($notification_notificationtemplate_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $notification_notificationtemplate_id); $target = new NotificationTarget(); $target_id = $target->add( @@ -627,6 +633,6 @@ private function createNotification(string $itemtype): void 'notifications_id' => $id, ] ); - $this->integer($target_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $target_id); } } diff --git a/tests/functional/Glpi/Toolbox/DataExport.php b/phpunit/functional/Glpi/Toolbox/DataExportTest.php similarity index 92% rename from tests/functional/Glpi/Toolbox/DataExport.php rename to phpunit/functional/Glpi/Toolbox/DataExportTest.php index bed09264b1d..1418617d0bb 100644 --- a/tests/functional/Glpi/Toolbox/DataExport.php +++ b/phpunit/functional/Glpi/Toolbox/DataExportTest.php @@ -40,9 +40,9 @@ /** * Test class for src/Glpi/Toolbox/dataexport.class.php */ -class DataExport extends \GLPITestCase +class DataExportTest extends \GLPITestCase { - protected function normalizeValueForTextExportProvider(): iterable + public static function normalizeValueForTextExportProvider(): iterable { // Standard value yield [ @@ -97,8 +97,8 @@ protected function normalizeValueForTextExportProvider(): iterable */ public function testNormalizeValueForTextExport(string $value, string $expected_result) { - $dataexport = $this->newTestedInstance(); + $dataexport = new \Glpi\Toolbox\DataExport(); - $this->string($dataexport->normalizeValueForTextExport($value))->isEqualTo($expected_result); + $this->assertEquals($expected_result, $dataexport->normalizeValueForTextExport($value)); } } diff --git a/tests/functional/Glpi/Toolbox/DatabaseSchema.php b/phpunit/functional/Glpi/Toolbox/DatabaseSchemaTest.php similarity index 91% rename from tests/functional/Glpi/Toolbox/DatabaseSchema.php rename to phpunit/functional/Glpi/Toolbox/DatabaseSchemaTest.php index 70e506399cf..b7013334b14 100644 --- a/tests/functional/Glpi/Toolbox/DatabaseSchema.php +++ b/phpunit/functional/Glpi/Toolbox/DatabaseSchemaTest.php @@ -35,9 +35,9 @@ namespace tests\units\Glpi\Toolbox; -class DatabaseSchema extends \GLPITestCase +class DatabaseSchemaTest extends \GLPITestCase { - protected function versionsProvider(): iterable + public static function versionsProvider(): iterable { foreach (['-dev', '-alpha', '-alpha1', '-alpha3', '-beta', '-beta2', '-rc', '-rc1', ''] as $suffix) { // Unavailable versions @@ -70,10 +70,10 @@ protected function versionsProvider(): iterable */ public function testGetEmptySchemaPath(string $version, ?string $expected): void { - $instance = $this->newTestedInstance(); + $instance = new \Glpi\Toolbox\DatabaseSchema(); if ($expected !== null) { $expected = realpath(GLPI_ROOT) . '/install/mysql/' . $expected; } - $this->variable($instance->getEmptySchemaPath($version))->isEqualTo($expected); + $this->assertEquals($expected, $instance->getEmptySchemaPath($version)); } } diff --git a/tests/functional/Glpi/Toolbox/Filesystem.php b/phpunit/functional/Glpi/Toolbox/FilesystemTest.php similarity index 74% rename from tests/functional/Glpi/Toolbox/Filesystem.php rename to phpunit/functional/Glpi/Toolbox/FilesystemTest.php index 68ae9562d4d..f56b616dd45 100644 --- a/tests/functional/Glpi/Toolbox/Filesystem.php +++ b/phpunit/functional/Glpi/Toolbox/FilesystemTest.php @@ -37,41 +37,41 @@ use org\bovigo\vfs\vfsStream; -class Filesystem extends \GLPITestCase +class FilesystemTest extends \GLPITestCase { public function testCanWriteFile(): void { $config_dir = vfsStream::setup('config'); - $this->newTestedInstance(); + $instance = new \Glpi\Toolbox\Filesystem(); // Files can be written when they not exists and directory is writable $config_dir->chmod(0700); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(true); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertTrue($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); // Files cannot be written when they not exists and directory is not writable $config_dir->chmod(0500); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(false); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(false); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(false); + $this->assertFalse($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertFalse($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertFalse($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); - // Files cannot be written when they exists but are not writable (even if directory is writable) + // Files cannot be written when they exist but are not writable (even if directory is writable) $config_dir->chmod(0700); $file1 = vfsStream::newFile('config_db.php', 0400)->at($config_dir)->setContent('<?php //my config file'); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(false); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(false); + $this->assertFalse($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertFalse($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); - // Files can be written when they exists and are writable (even if directory is not writable) - $file1->chmod(0600); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/config_db.php')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFile(vfsStream::url('config/whatever.yml')))->isEqualTo(true); - $this->boolean($this->testedInstance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')]))->isEqualTo(true); + // Files can be written when they exist and are writable (even if directory is not writable) + $file1->chmod(0666); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/config_db.php'))); + $this->assertTrue($instance->canWriteFile(vfsStream::url('config/whatever.yml'))); + $this->assertTrue($instance->canWriteFiles([vfsStream::url('config/config_db.php'), vfsStream::url('config/whatever.yml')])); } - protected function isFilepathSafeProvider(): iterable + public static function isFilepathSafeProvider(): iterable { // Unix paths and file scheme foreach (['', 'file://'] as $prefix) { @@ -177,7 +177,7 @@ protected function isFilepathSafeProvider(): iterable */ public function testIsFilepathSafe(string $path, ?string $restricted_directory, bool $is_safe): void { - $this->newTestedInstance(); - $this->boolean($this->testedInstance->isFilepathSafe($path, $restricted_directory))->isEqualTo($is_safe); + $instance = new \Glpi\Toolbox\Filesystem(); + $this->assertSame($is_safe, $instance->isFilepathSafe($path, $restricted_directory)); } } diff --git a/tests/functional/Glpi/Toolbox/FrontEnd.php b/phpunit/functional/Glpi/Toolbox/FrontEndTest.php similarity index 81% rename from tests/functional/Glpi/Toolbox/FrontEnd.php rename to phpunit/functional/Glpi/Toolbox/FrontEndTest.php index a4e95398eb5..68b835ad363 100644 --- a/tests/functional/Glpi/Toolbox/FrontEnd.php +++ b/phpunit/functional/Glpi/Toolbox/FrontEndTest.php @@ -38,13 +38,13 @@ /** * Test class for src/Glpi/Toolbox/dataexport.class.php */ -class FrontEnd extends \GLPITestCase +class FrontEndTest extends \GLPITestCase { public function testGetVersionCacheKey() { - $instance = $this->newTestedInstance(); + $instance = new \Glpi\Toolbox\FrontEnd(); - $this->string($instance->getVersionCacheKey(GLPI_VERSION))->isNotEqualTo(GLPI_VERSION); - $this->string($instance->getVersionCacheKey(GLPI_VERSION))->isNotEqualTo(sha1(GLPI_VERSION)); // too predicatable + $this->assertNotEquals(GLPI_VERSION, $instance->getVersionCacheKey(GLPI_VERSION)); + $this->assertNotEquals(sha1(GLPI_VERSION), $instance->getVersionCacheKey(GLPI_VERSION)); // too predicatable } } diff --git a/tests/functional/Glpi/Toolbox/Sanitizer.php b/phpunit/functional/Glpi/Toolbox/SanitizerTest.php similarity index 85% rename from tests/functional/Glpi/Toolbox/Sanitizer.php rename to phpunit/functional/Glpi/Toolbox/SanitizerTest.php index fe83a2a4b7a..e23099cc7b9 100644 --- a/tests/functional/Glpi/Toolbox/Sanitizer.php +++ b/phpunit/functional/Glpi/Toolbox/SanitizerTest.php @@ -38,9 +38,9 @@ /** * Test class for src/Glpi/Toolbox/sanitizer.class.php */ -class Sanitizer extends \GLPITestCase +class SanitizerTest extends \GLPITestCase { - protected function rawValueProvider(): iterable + public static function rawValueProvider(): iterable { // Non string values should not be altered yield [ @@ -162,16 +162,16 @@ public function testSanitize( $htmlencoded_value = null, $dbescaped_value = null ) { - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->sanitize($value, true))->isEqualTo($sanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($sanitized_value, $sanitizer->sanitize($value, true)); if ($htmlencoded_value !== null) { - // Calling `sanitize()` with `$db_escape = false` should produce HTML enoded value - $this->variable($sanitizer->sanitize($value, false))->isEqualTo($htmlencoded_value); + // Calling `sanitize()` with `$db_escape = false` should produce HTML encoded value + $this->assertEquals($htmlencoded_value, $sanitizer->sanitize($value, false)); } // Calling sanitize on sanitized value should have no effect - $this->variable($sanitizer->sanitize($sanitized_value))->isEqualTo($sanitized_value); + $this->assertEquals($sanitized_value, $sanitizer->sanitize($sanitized_value)); } /** @@ -187,11 +187,11 @@ public function testEncodeHtmlSpecialChars( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->encodeHtmlSpecialChars($value))->isEqualTo($htmlencoded_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialChars($value)); // Calling encodeHtmlSpecialChars on escaped value should have no effect - $this->variable($sanitizer->encodeHtmlSpecialChars($htmlencoded_value))->isEqualTo($htmlencoded_value); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialChars($htmlencoded_value)); } /** @@ -207,11 +207,11 @@ public function testEncodeHtmlSpecialCharsRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->encodeHtmlSpecialCharsRecursive($value))->isEqualTo($htmlencoded_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialCharsRecursive($value)); // Calling encodeHtmlSpecialCharsRecursive on escaped value should have no effect - $this->variable($sanitizer->encodeHtmlSpecialCharsRecursive($htmlencoded_value))->isEqualTo($htmlencoded_value); + $this->assertEquals($htmlencoded_value, $sanitizer->encodeHtmlSpecialCharsRecursive($htmlencoded_value)); } /** @@ -227,11 +227,11 @@ public function testDbEscape( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbEscape($value))->isEqualTo($dbescaped_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscape($value)); // Calling dbEscape on escaped value should have no effect - $this->variable($sanitizer->dbEscape($dbescaped_value))->isEqualTo($dbescaped_value); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscape($dbescaped_value)); } /** @@ -247,16 +247,16 @@ public function testDbEscapeRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbEscapeRecursive($value))->isEqualTo($dbescaped_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscapeRecursive($value)); // Calling dbEscapeRecursive on escaped value should have no effect - $this->variable($sanitizer->dbEscapeRecursive($dbescaped_value))->isEqualTo($dbescaped_value); + $this->assertEquals($dbescaped_value, $sanitizer->dbEscapeRecursive($dbescaped_value)); } - protected function sanitizedValueProvider(): iterable + public static function sanitizedValueProvider(): iterable { - foreach ($this->rawValueProvider() as $data) { + foreach (self::rawValueProvider() as $data) { yield [ 'value' => $data['sanitized_value'], 'unsanitized_value' => $data['value'], @@ -291,11 +291,11 @@ public function testUnanitize( $htmlencoded_value = null, $dbescaped_value = null ) { - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->unsanitize($value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->unsanitize($value)); // Calling unsanitize multiple times should not corrupt unsanitized value - $this->variable($sanitizer->unsanitize($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->unsanitize($unsanitized_value)); } /** @@ -311,11 +311,11 @@ public function testDbUnescape( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbUnescape($dbescaped_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescape($dbescaped_value)); // Calling dbUnescape multiple times should not corrupt value - $this->variable($sanitizer->dbUnescape($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescape($unsanitized_value)); } /** @@ -331,11 +331,11 @@ public function testDbUnescapeRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->dbUnescapeRecursive($dbescaped_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescapeRecursive($dbescaped_value)); // Calling dbUnescapeRecursive multiple times should not corrupt value - $this->variable($sanitizer->dbUnescapeRecursive($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->dbUnescapeRecursive($unsanitized_value)); } /** @@ -351,11 +351,11 @@ public function testDecodeHtmlSpecialChars( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->decodeHtmlSpecialChars($htmlencoded_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialChars($htmlencoded_value)); // Calling decodeHtmlSpecialChars multiple times should not corrupt value - $this->variable($sanitizer->decodeHtmlSpecialChars($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialChars($unsanitized_value)); } /** @@ -371,11 +371,11 @@ public function testDecodeHtmlSpecialCharsRecursive( return; // Unrelated entry in provider } - $sanitizer = $this->newTestedInstance(); - $this->variable($sanitizer->decodeHtmlSpecialCharsRecursive($htmlencoded_value))->isEqualTo($unsanitized_value); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialCharsRecursive($htmlencoded_value)); // Calling decodeHtmlSpecialCharsRecursive multiple times should not corrupt value - $this->variable($sanitizer->decodeHtmlSpecialCharsRecursive($unsanitized_value))->isEqualTo($unsanitized_value); + $this->assertEquals($unsanitized_value, $sanitizer->decodeHtmlSpecialCharsRecursive($unsanitized_value)); } protected function isHtmlEncodedValueProvider(): iterable @@ -415,8 +415,8 @@ protected function isHtmlEncodedValueProvider(): iterable */ public function testIsHtmlEncoded(string $value, bool $is_encoded) { - $sanitizer = $this->newTestedInstance(); - $this->boolean($sanitizer->isHtmlEncoded($value))->isEqualTo($is_encoded); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertSame($is_encoded, $sanitizer->isHtmlEncoded($value)); } protected function isDbEscapedValueProvider(): iterable @@ -577,9 +577,9 @@ protected function isDbEscapedValueProvider(): iterable */ public function testIsDbEscaped(string $value, bool $is_escaped) { - $sanitizer = $this->newTestedInstance(); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); - $this->boolean($sanitizer->isDbEscaped($value))->isEqualTo($is_escaped, $value); + $this->assertSame($is_escaped, $sanitizer->isDbEscaped($value), $value); } /** @@ -591,13 +591,13 @@ public function testSanitizationReversibility( $htmlencoded_value = null, $dbescaped_value = null ) { - $sanitizer = $this->newTestedInstance(); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); // Value should stay the same if it has been sanitized then unsanitized - $this->variable($sanitizer->unsanitize($sanitizer->sanitize($value)))->isEqualTo($value); + $this->assertEquals($value, $sanitizer->unsanitize($sanitizer->sanitize($value))); // Re-sanitize a value provide the same result as first sanitization - $this->variable($sanitizer->sanitize($sanitizer->unsanitize($value)))->isEqualTo($sanitized_value); + $this->assertEquals($sanitized_value, $sanitizer->sanitize($sanitizer->unsanitize($value))); } protected function isNsClassOrCallableIdentifierProvider(): iterable @@ -629,7 +629,7 @@ protected function isNsClassOrCallableIdentifierProvider(): iterable */ public function testIsNsClassOrCallableIdentifier(string $value, bool $is_class) { - $sanitizer = $this->newTestedInstance(); - $this->boolean($sanitizer->isNsClassOrCallableIdentifier($value))->isEqualTo($is_class); + $sanitizer = new \Glpi\Toolbox\Sanitizer(); + $this->assertSame($is_class, $sanitizer->isNsClassOrCallableIdentifier($value)); } } diff --git a/tests/functional/Glpi/Toolbox/URL.php b/phpunit/functional/Glpi/Toolbox/URLTest.php similarity index 94% rename from tests/functional/Glpi/Toolbox/URL.php rename to phpunit/functional/Glpi/Toolbox/URLTest.php index 9ada3ee1dd6..203ff50637a 100644 --- a/tests/functional/Glpi/Toolbox/URL.php +++ b/phpunit/functional/Glpi/Toolbox/URLTest.php @@ -35,9 +35,9 @@ namespace tests\units\Glpi\Toolbox; -class URL extends \GLPITestCase +class URLTest extends \GLPITestCase { - protected function urlProvider(): iterable + public static function urlProvider(): iterable { yield [ 'url' => null, @@ -116,7 +116,7 @@ protected function urlProvider(): iterable */ public function testSanitizeURL(?string $url, string $expected): void { - $this->newTestedInstance(); - $this->string($this->testedInstance->sanitizeURL($url))->isEqualTo($expected); + $instance = new \Glpi\Toolbox\URL(); + $this->assertEquals($expected, $instance->sanitizeURL($url)); } } diff --git a/tests/functional/Glpi/Toolbox/VersionParser.php b/phpunit/functional/Glpi/Toolbox/VersionParserTest.php similarity index 91% rename from tests/functional/Glpi/Toolbox/VersionParser.php rename to phpunit/functional/Glpi/Toolbox/VersionParserTest.php index a89cd457a9f..3cb720f3774 100644 --- a/tests/functional/Glpi/Toolbox/VersionParser.php +++ b/phpunit/functional/Glpi/Toolbox/VersionParserTest.php @@ -38,9 +38,9 @@ /** * Test class for src/Glpi/Toolbox/versionparser.class.php */ -class VersionParser extends \GLPITestCase +class VersionParserTest extends \GLPITestCase { - protected function versionsProvider() + public static function versionsProvider() { return [ [ @@ -156,8 +156,8 @@ protected function versionsProvider() */ public function testGetNormalizeVersion(string $version, bool $keep_stability_flag, string $normalized, bool $stable, bool $dev): void { - $version_parser = $this->newTestedInstance(); - $this->string($version_parser->getNormalizedVersion($version, $keep_stability_flag))->isEqualTo($normalized); + $version_parser = new \Glpi\Toolbox\VersionParser(); + $this->assertEquals($normalized, $version_parser->getNormalizedVersion($version, $keep_stability_flag)); } /** @@ -165,8 +165,8 @@ public function testGetNormalizeVersion(string $version, bool $keep_stability_fl */ public function testIsStableRelease(string $version, bool $keep_stability_flag, string $normalized, bool $stable, bool $dev): void { - $version_parser = $this->newTestedInstance(); - $this->boolean($version_parser->isStableRelease($version))->isEqualTo($stable); + $version_parser = new \Glpi\Toolbox\VersionParser(); + $this->assertSame($stable, $version_parser->isStableRelease($version)); } /** @@ -174,7 +174,7 @@ public function testIsStableRelease(string $version, bool $keep_stability_flag, */ public function testIsDevVersion(string $version, bool $keep_stability_flag, string $normalized, bool $stable, bool $dev): void { - $version_parser = $this->newTestedInstance(); - $this->boolean($version_parser->isDevVersion($version))->isEqualTo($dev); + $version_parser = new \Glpi\Toolbox\VersionParser(); + $this->assertSame($dev, $version_parser->isDevVersion($version)); } } diff --git a/tests/functional/IPAddress.php b/phpunit/functional/IPAddressTest.php similarity index 94% rename from tests/functional/IPAddress.php rename to phpunit/functional/IPAddressTest.php index afb70d3cc2f..b88447a7d24 100644 --- a/tests/functional/IPAddress.php +++ b/phpunit/functional/IPAddressTest.php @@ -39,7 +39,7 @@ /* Test for inc/networkport.class.php */ -class IPAddress extends DbTestCase +class IPAddressTest extends DbTestCase { public function testAddIPV4() { @@ -48,7 +48,7 @@ public function testAddIPV4() //first create NetworkName $networkName = new \NetworkName(); $networkName_id = $networkName->add(["name" => "test", "itemtype" => ""]); - $this->integer($networkName_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networkName_id); $IPV4ShouldWork = []; $IPV4ShouldWork["1.0.1.0"] = ["items_id" => $networkName_id, @@ -133,7 +133,7 @@ public function testAddIPV4() "items_id" => "$networkName_id" ]; $id = $ipAdress->add($input); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); //check name store in DB $all_IP = getAllDataFromTable('glpi_ipaddresses', ['ORDER' => 'id']); @@ -146,7 +146,7 @@ public function testAddIPV4() unset($currentIP['is_dynamic']); unset($currentIP['mainitems_id']); unset($currentIP['mainitemtype']); - $this->array($currentIP)->isIdenticalTo($expected); + $this->assertSame($expected, $currentIP); } $IPV4ShouldNotWork = [ @@ -174,7 +174,7 @@ public function testAddIPV4() "Invalid IP address: " . $name, ]; - $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expectedSession); + $this->assertSame($expectedSession, $_SESSION['MESSAGE_AFTER_REDIRECT']); $_SESSION['MESSAGE_AFTER_REDIRECT'] = []; } } @@ -187,7 +187,7 @@ public function testAddIPV6() //first create NetworkName $networkName = new \NetworkName(); $networkName_id = $networkName->add(["name" => "test", "itemtype" => ""]); - $this->integer($networkName_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networkName_id); $IPV6ShouldWork = []; $IPV6ShouldWork["59FB::1005:CC57:6571"] = ["items_id" => $networkName_id, @@ -245,7 +245,7 @@ public function testAddIPV6() "items_id" => "$networkName_id" ]; $id = $ipAdress->add($input); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); //check name store in DB $all_IP = getAllDataFromTable('glpi_ipaddresses', ['ORDER' => 'id']); @@ -259,7 +259,7 @@ public function testAddIPV6() unset($currentIP['mainitems_id']); unset($currentIP['mainitemtype']); //var_dump($currentIP); - $this->array($currentIP)->isIdenticalTo($expected); + $this->assertSame($expected, $currentIP); } $IPV6ShouldNotWork = [ @@ -289,7 +289,7 @@ public function testAddIPV6() "Invalid IP address: " . $name, ]; - $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($expectedSession); + $this->assertSame($expectedSession, $_SESSION['MESSAGE_AFTER_REDIRECT']); $_SESSION['MESSAGE_AFTER_REDIRECT'] = []; } } diff --git a/tests/functional/Infocom.php b/phpunit/functional/InfocomTest.php similarity index 97% rename from tests/functional/Infocom.php rename to phpunit/functional/InfocomTest.php index 99ce9a1d8e5..11e92c4a6b3 100644 --- a/tests/functional/Infocom.php +++ b/phpunit/functional/InfocomTest.php @@ -37,7 +37,7 @@ /* Test for inc/infocom.class.php */ -class Infocom extends \GLPITestCase +class InfocomTest extends \GLPITestCase { public function dataLinearAmortise() { @@ -198,10 +198,10 @@ public function testLinearAmortise($value, $duration, $fiscaldate, $buydate, $us $usedate ); foreach ($expected as $year => $values) { - $this->array($amortise[$year])->isIdenticalTo($values); + $this->assertSame($values, $amortise[$year]); } if (count($oldmft)) { - $this->array(\Infocom::mapOldAmortiseFormat($amortise, false))->isIdenticalTo($oldmft); + $this->assertSame($oldmft, \Infocom::mapOldAmortiseFormat($amortise, false)); } } } diff --git a/tests/functional/Item_Cluster.php b/phpunit/functional/Item_ClusterTest.php similarity index 81% rename from tests/functional/Item_Cluster.php rename to phpunit/functional/Item_ClusterTest.php index 80df1c9054e..d95b178c78b 100644 --- a/tests/functional/Item_Cluster.php +++ b/phpunit/functional/Item_ClusterTest.php @@ -39,14 +39,14 @@ /* Test for inc/item_cluster.class.php */ -class Item_Cluster extends DbTestCase +class Item_ClusterTest extends DbTestCase { /** * Computers provider * * @return array */ - protected function computersProvider() + public static function computersProvider() { return [ [ @@ -67,9 +67,7 @@ protected function createComputers() $computer = new \Computer(); foreach ($this->computersProvider() as $row) { $row['entities_id'] = 0; - $this->integer( - (int)$computer->add($row) - )->isGreaterThan(0); + $this->assertGreaterThan(0, $computer->add($row)); } } @@ -84,13 +82,14 @@ public function testAdd() $cluster = new \Cluster(); - $this->integer( - (int)$cluster->add([ + $this->assertGreaterThan( + 0, + $cluster->add([ 'name' => 'Test cluster', 'uuid' => 'ytreza', 'entities_id' => 0 ]) - )->isGreaterThan(0); + ); $icl = new \Item_Cluster(); @@ -99,56 +98,58 @@ public function testAdd() //try to add without required field $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertFalse( + $icl->add([ 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['A cluster is required']); - //try to add without required field + //try to add without required field $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertFalse( + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'items_id' => $SRVNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['An item type is required']); - //try to add without required field + //try to add without required field $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertFalse( + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'itemtype' => 'Computer', ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['An item is required']); //try to add without error $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertGreaterThan( + 0, + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isGreaterThan(0); + ); //Add another item in cluster $icl->getEmpty(); - $this->integer( - (int)$icl->add([ + $this->assertGreaterThan( + 0, + $icl->add([ 'clusters_id' => $cluster->fields['id'], 'itemtype' => 'Computer', 'items_id' => $SRVNUX2 ]) - )->isGreaterThan(0); + ); global $DB; $items = $DB->request([ @@ -157,6 +158,6 @@ public function testAdd() 'clusters_id' => $cluster->fields['id'] ] ]); - $this->array(iterator_to_array($items))->hasSize(2); + $this->assertCount(2, iterator_to_array($items)); } } diff --git a/tests/functional/Item_DeviceSensor.php b/phpunit/functional/Item_DeviceSensorTest.php similarity index 73% rename from tests/functional/Item_DeviceSensor.php rename to phpunit/functional/Item_DeviceSensorTest.php index 7a8578acecb..a521d846ed7 100644 --- a/tests/functional/Item_DeviceSensor.php +++ b/phpunit/functional/Item_DeviceSensorTest.php @@ -37,18 +37,18 @@ use DbTestCase; -class Item_DeviceSensor extends DbTestCase +class Item_DeviceSensorTest extends DbTestCase { public function testCreate() { $this->login(); $obj = new \Item_DeviceSensor(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSensor = getItemByTypeName('DeviceSensor', '_test_sensor_1'); - $this->object($deviceSensor)->isInstanceOf('\DeviceSensor'); + $this->assertInstanceOf('\DeviceSensor', $deviceSensor); $in = [ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), @@ -56,13 +56,13 @@ public function testCreate() 'entities_id' => 0, ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); - // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + // getField methods + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -71,31 +71,31 @@ public function testUpdate() $this->login(); $obj = new \Item_DeviceSensor(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSensor = getItemByTypeName('DeviceSensor', '_test_sensor_1'); - $this->object($deviceSensor)->isInstanceOf('\DeviceSensor'); + $this->assertInstanceOf('\DeviceSensor', $deviceSensor); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesensors_id' => $deviceSensor->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Update + // Update $id = $obj->getID(); $in = [ 'id' => $id, 'serial' => $this->getUniqueString(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); - // getField methods + // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -104,23 +104,23 @@ public function testDelete() $this->login(); $obj = new \Item_DeviceSensor(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSensor = getItemByTypeName('DeviceSensor', '_test_sensor_1'); - $this->object($deviceSensor)->isInstanceOf('\DeviceSensor'); + $this->assertInstanceOf('\DeviceSensor', $deviceSensor); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesensors_id' => $deviceSensor->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Delete + // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/Item_DeviceSimcard.php b/phpunit/functional/Item_DeviceSimcardTest.php similarity index 79% rename from tests/functional/Item_DeviceSimcard.php rename to phpunit/functional/Item_DeviceSimcardTest.php index ca5fded4870..bf139c1215f 100644 --- a/tests/functional/Item_DeviceSimcard.php +++ b/phpunit/functional/Item_DeviceSimcardTest.php @@ -37,7 +37,7 @@ use DbTestCase; -class Item_DeviceSimcard extends DbTestCase +class Item_DeviceSimcardTest extends DbTestCase { public function testCreate() { @@ -46,9 +46,9 @@ public function testCreate() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $in = [ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), @@ -56,13 +56,13 @@ public function testCreate() 'entities_id' => 0, ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -73,16 +73,16 @@ public function testUpdate() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesimcards_id' => $deviceSimcard->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); @@ -93,12 +93,12 @@ public function testUpdate() 'puk' => '2345', 'puk2' => '3456', ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -131,9 +131,9 @@ public function testDenyPinPukUpdate() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), @@ -144,7 +144,7 @@ public function testDenyPinPukUpdate() 'puk' => '2345', 'puk2' => '3456', ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); @@ -155,13 +155,13 @@ public function testDenyPinPukUpdate() 'puk' => '0000', 'puk2' => '0000', ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods unset($in['id']); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isNotEqualTo($v); + $this->assertNotEquals($v, $obj->getField($k)); } } @@ -173,21 +173,21 @@ public function testDelete() // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); $deviceSimcard = getItemByTypeName('DeviceSimcard', '_test_simcard_1'); - $this->object($deviceSimcard)->isInstanceOf('\DeviceSimcard'); + $this->assertInstanceOf('\DeviceSimcard', $deviceSimcard); $id = $obj->add([ 'itemtype' => 'Computer', 'items_id' => $computer->getID(), 'devicesimcards_id' => $deviceSimcard->getID(), 'entities_id' => 0, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/Item_Disk.php b/phpunit/functional/Item_DiskTest.php similarity index 61% rename from tests/functional/Item_Disk.php rename to phpunit/functional/Item_DiskTest.php index ee7a59838af..046b7c37e79 100644 --- a/tests/functional/Item_Disk.php +++ b/phpunit/functional/Item_DiskTest.php @@ -37,86 +37,86 @@ use DbTestCase; -class Item_Disk extends DbTestCase +class Item_DiskTest extends DbTestCase { public function testCreate() { $this->login(); - $this->newTestedInstance(); - $obj = $this->testedInstance; + $obj = new \Item_Disk(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); - $this->integer( + $this->assertGreaterThan( + 0, $id = (int)$obj->add([ 'itemtype' => $computer->getType(), 'items_id' => $computer->fields['id'], 'mountpoint' => '/' ]) - )->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/'); + ); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/', $obj->fields['mountpoint']); } public function testUpdate() { $this->login(); - $this->newTestedInstance(); - $obj = $this->testedInstance; + $obj = new \Item_Disk(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); - $this->integer( + $this->assertGreaterThan( + 0, $id = (int)$obj->add([ 'itemtype' => $computer->getType(), 'items_id' => $computer->fields['id'], 'mountpoint' => '/' ]) - )->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/'); + ); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/', $obj->fields['mountpoint']); - $this->boolean($obj->update([ + $this->assertTrue($obj->update([ 'id' => $id, 'mountpoint' => '/mnt' - ]))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/mnt'); + ])); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/mnt', $obj->fields['mountpoint']); } public function testDelete() { $this->login(); - $this->newTestedInstance(); - $obj = $this->testedInstance; + $obj = new \Item_Disk(); - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); - $this->integer( + $this->assertGreaterThan( + 0, $id = (int)$obj->add([ 'itemtype' => $computer->getType(), 'items_id' => $computer->fields['id'], 'mountpoint' => '/' ]) - )->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['mountpoint'])->isIdenticalTo('/'); + ); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame('/', $obj->fields['mountpoint']); - $this->boolean( - (bool)$obj->delete([ + $this->assertTrue( + $obj->delete([ 'id' => $id ]) - )->isTrue(); - $this->boolean($obj->getFromDB($id))->istrue(); //it's always in DB but with is_deleted = 1 - $this->integer($obj->fields['is_deleted'])->isIdenticalTo(1); + ); + $this->assertTrue($obj->getFromDB($id)); //it's always in DB but with is_deleted = 1 + $this->assertSame(1, $obj->fields['is_deleted']); } } diff --git a/tests/functional/Item_OperatingSystem.php b/phpunit/functional/Item_OperatingSystemTest.php similarity index 61% rename from tests/functional/Item_OperatingSystem.php rename to phpunit/functional/Item_OperatingSystemTest.php index f6ccda60301..30eba11b847 100644 --- a/tests/functional/Item_OperatingSystem.php +++ b/phpunit/functional/Item_OperatingSystemTest.php @@ -40,14 +40,14 @@ /* Test for inc/item_operatingsystem.class.php */ -class Item_OperatingSystem extends DbTestCase +class Item_OperatingSystemTest extends DbTestCase { public function testGetTypeName() { - $this->string(\Item_OperatingSystem::getTypeName())->isIdenticalTo('Item operating systems'); - $this->string(\Item_OperatingSystem::getTypeName(0))->isIdenticalTo('Item operating systems'); - $this->string(\Item_OperatingSystem::getTypeName(10))->isIdenticalTo('Item operating systems'); - $this->string(\Item_OperatingSystem::getTypeName(1))->isIdenticalTo('Item operating system'); + $this->assertSame('Item operating systems', \Item_OperatingSystem::getTypeName()); + $this->assertSame('Item operating systems', \Item_OperatingSystem::getTypeName(0)); + $this->assertSame('Item operating systems', \Item_OperatingSystem::getTypeName(10)); + $this->assertSame('Item operating system', \Item_OperatingSystem::getTypeName(1)); } /** @@ -61,12 +61,13 @@ private function createDdObjects() foreach (['', 'Architecture', 'Version', 'Edition', 'KernelVersion'] as $object) { $classname = 'OperatingSystem' . $object; $instance = new $classname(); - $this->integer( - (int)$instance->add([ + $this->assertGreaterThan( + 0, + $instance->add([ 'name' => $classname . ' ' . $this->getUniqueInteger() ]) - )->isGreaterThan(0); - $this->boolean($instance->getFromDB($instance->getID()))->isTrue(); + ); + $this->assertTrue($instance->getFromDB($instance->getID())); $objects[$object] = $instance; } return $objects; @@ -88,24 +89,29 @@ public function testAttachComputer() 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - $this->string($ios->getTabNameForItem($computer)) - ->isIdenticalTo("Operating systems <span class='badge'>1</span>"); - $this->integer( - (int)\Item_OperatingSystem::countForItem($computer) - )->isIdenticalTo(1); + $this->assertSame( + "Operating systems <span class='badge'>1</span>", + $ios->getTabNameForItem($computer) + ); + $this->assertSame( + 1, + \Item_OperatingSystem::countForItem($computer) + ); $expected_error = "/Duplicate entry '{$computer->getID()}-Computer-{$objects['']->getID()}-{$objects['Architecture']->getID()}' for key '(glpi_items_operatingsystems\.)?unicity'/"; - $this->boolean($ios->add($input))->isFalse(); + $this->assertFalse($ios->add($input)); $this->hasSqlLogRecordThatMatches($expected_error, LogLevel::ERROR); - $this->integer( - (int)\Item_OperatingSystem::countForItem($computer) - )->isIdenticalTo(1); + $this->assertSame( + 1, + \Item_OperatingSystem::countForItem($computer) + ); $objects = $this->createDdObjects(); $ios = new \Item_OperatingSystem(); @@ -119,16 +125,20 @@ public function testAttachComputer() 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - $this->string($ios->getTabNameForItem($computer)) - ->isIdenticalTo("Operating systems <span class='badge'>2</span>"); - $this->integer( - (int)\Item_OperatingSystem::countForItem($computer) - )->isIdenticalTo(2); + $this->assertSame( + "Operating systems <span class='badge'>2</span>", + $ios->getTabNameForItem($computer) + ); + $this->assertSame( + 2, + \Item_OperatingSystem::countForItem($computer) + ); } public function testShowForItem() @@ -137,11 +147,10 @@ public function testShowForItem() $computer = getItemByTypeName('Computer', '_test_pc01'); foreach (['showForItem', 'displayTabContentForItem'] as $method) { - $this->output( - function () use ($method, $computer) { - \Item_OperatingSystem::$method($computer); - } - )->contains('operatingsystems_id'); + ob_start(); + \Item_OperatingSystem::$method($computer); + $output = ob_get_clean(); + $this->assertStringContainsString('operatingsystems_id', $output); } $objects = $this->createDdObjects(); @@ -156,17 +165,17 @@ function () use ($method, $computer) { 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); foreach (['showForItem', 'displayTabContentForItem'] as $method) { - $this->output( - function () use ($method, $computer) { - \Item_OperatingSystem::$method($computer); - } - )->contains('operatingsystems_id'); + ob_start(); + \Item_OperatingSystem::$method($computer); + $output = ob_get_clean(); + $this->assertStringContainsString('operatingsystems_id', $output); } $objects = $this->createDdObjects(); @@ -181,18 +190,18 @@ function () use ($method, $computer) { 'licenseid' => $this->getUniqueString(), 'license_number' => $this->getUniqueString() ]; - $this->integer( - (int)$ios->add($input) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + $this->assertGreaterThan( + 0, + $ios->add($input) + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - //thera are now 2 OS linked, we will no longer show a form, but a list. + //there are now 2 OS linked, we will no longer show a form, but a list. foreach (['showForItem', 'displayTabContentForItem'] as $method) { - $this->output( - function () use ($method, $computer) { - \Item_OperatingSystem::$method($computer); - } - )->notContains('operatingsystems_id'); + ob_start(); + \Item_OperatingSystem::$method($computer); + $output = ob_get_clean(); + $this->assertStringNotContainsString('operatingsystems_id', $output); } } @@ -203,69 +212,70 @@ public function testEntityAccess() $this->setEntity('_test_root_entity', true); $computer = new \Computer(); - $this->integer( - (int)$computer->add([ + $this->assertGreaterThan( + 0, + $computer->add([ 'name' => 'Test Item/OS', 'entities_id' => $eid, 'is_recursive' => 0 ]) - )->isGreaterThan(0); + ); $os = new \OperatingSystem(); - $this->integer( - (int)$os->add([ + $this->assertGreaterThan( + 0, + $os->add([ 'name' => 'Test OS' ]) - )->isGreaterThan(0); + ); $ios = new \Item_OperatingSystem(); - $this->integer( - (int)$ios->add([ + $this->assertGreaterThan( + 0, + $ios->add([ 'operatingsystems_id' => $os->getID(), 'itemtype' => 'Computer', 'items_id' => $computer->getID() ]) - )->isGreaterThan(0); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); + ); + $this->assertTrue($ios->getFromDB($ios->getID())); - $this->array($ios->fields) - ->integer['operatingsystems_id']->isIdenticalTo($os->getID()) - ->string['itemtype']->isIdenticalTo('Computer') - ->integer['items_id']->isIdenticalTo($computer->getID()) - ->integer['entities_id']->isIdenticalTo($eid) - ->integer['is_recursive']->isIdenticalTo(0); + $this->assertSame($os->getID(), $ios->fields['operatingsystems_id']); + $this->assertSame('Computer', $ios->fields['itemtype']); + $this->assertSame($computer->getID(), $ios->fields['items_id']); + $this->assertSame($eid, $ios->fields['entities_id']); + $this->assertSame(0, $ios->fields['is_recursive']); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); - //not recursive + //not recursive $this->setEntity('Root Entity', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_1', true); - $this->boolean($ios->can($ios->getID(), READ))->isFalse(); + $this->assertFalse($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_2', true); - $this->boolean($ios->can($ios->getID(), READ))->isFalse(); + $this->assertFalse($ios->can($ios->getID(), READ)); $this->setEntity('_test_root_entity', true); - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $computer->getID(), 'is_recursive' => 1 ]) - )->isTrue(); - $this->boolean($ios->getFromDB($ios->getID()))->isTrue(); - $this->array($ios->fields) - ->integer['operatingsystems_id']->isIdenticalTo($os->getID()) - ->string['itemtype']->isIdenticalTo('Computer') - ->integer['items_id']->isIdenticalTo($computer->getID()) - ->integer['entities_id']->isIdenticalTo($eid) - ->integer['is_recursive']->isIdenticalTo(1); + ); + $this->assertTrue($ios->getFromDB($ios->getID())); + $this->assertSame($os->getID(), $ios->fields['operatingsystems_id']); + $this->assertSame('Computer', $ios->fields['itemtype']); + $this->assertSame($computer->getID(), $ios->fields['items_id']); + $this->assertSame($eid, $ios->fields['entities_id']); + $this->assertSame(1, $ios->fields['is_recursive']); - //not recursive + //not recursive $this->setEntity('Root Entity', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_1', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); $this->setEntity('_test_child_2', true); - $this->boolean($ios->can($ios->getID(), READ))->isTrue(); + $this->assertTrue($ios->can($ios->getID(), READ)); } } diff --git a/tests/functional/Item_Rack.php b/phpunit/functional/Item_RackTest.php similarity index 78% rename from tests/functional/Item_Rack.php rename to phpunit/functional/Item_RackTest.php index 0a0f80a880a..4b15bd97b5a 100644 --- a/tests/functional/Item_Rack.php +++ b/phpunit/functional/Item_RackTest.php @@ -40,14 +40,14 @@ /* Test for inc/item_rack.class.php */ -class Item_Rack extends DbTestCase +class Item_RackTest extends DbTestCase { /** * Models provider * * @return array */ - protected function modelsProvider() + public static function modelsProvider() { return [ [ @@ -98,9 +98,10 @@ protected function createModels() { $model = new \ComputerModel(); foreach ($this->modelsProvider() as $row) { - $this->integer( - (int)$model->add($row) - )->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $model->add($row) + ); } } @@ -109,7 +110,7 @@ protected function createModels() * * @return array */ - protected function computersProvider() + public static function computersProvider() { return [ [ @@ -168,12 +169,13 @@ protected function createComputers() $computer = new \Computer(); foreach ($this->computersProvider() as $row) { $row['computermodels_id'] = getItemByTypeName('ComputerModel', $row['model'], true); - $this->integer((int)$row['computermodels_id'])->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$row['computermodels_id']); $row['entities_id'] = 0; unset($row['model']); - $this->integer( - (int)$computer->add($row) - )->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $computer->add($row) + ); } } @@ -189,259 +191,266 @@ public function testAdd() $this->createComputers(); $rack = new \Rack(); - //create a 10u rack - $this->integer( - (int)$rack->add([ + //create a 10u rack + $this->assertGreaterThan( + 0, + $rack->add([ 'name' => 'Test rack', 'number_units' => 10, 'dcrooms_id' => 0, 'position' => 0, 'entities_id' => 0, ]) - )->isGreaterThan(0); + ); $ira = new \Item_Rack(); $SRVNUX1 = getItemByTypeName('Computer', 'SRV-NUX-1', true); - //try to add outside rack capabilities + //try to add outside rack capabilities $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 15, 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Item is out of rack bounds']); - //add item at the first position + //add item at the first position $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $SRVNUX1 ]) - )->isGreaterThan(0); + ); $BIGNUX1 = getItemByTypeName('Computer', 'BIG-NUX-1', true); - //take a 3U item and try to add it at the end + //take a 3U item and try to add it at the end $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 10, 'itemtype' => 'Computer', 'items_id' => $BIGNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Item is out of rack bounds']); - //take a 3U item and try to add it at the end - 1 + //take a 3U item and try to add it at the end - 1 $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 9, 'itemtype' => 'Computer', 'items_id' => $BIGNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Item is out of rack bounds']); - //take a 3U item and try to add it at the end - 2 + //take a 3U item and try to add it at the end - 2 $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 8, 'itemtype' => 'Computer', 'items_id' => $BIGNUX1 ]) - )->isGreaterThan(0); + ); - //test half racks + //test half racks $MIDNUX1 = getItemByTypeName('Computer', 'MID-NUX-1', true); $MIDNUX2 = getItemByTypeName('Computer', 'MID-NUX-2', true); $MIDNUX3 = getItemByTypeName('Computer', 'MID-NUX-3', true); - //item is half rack. hpos is required + //item is half rack. hpos is required $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $MIDNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['You must define an horizontal position for this item']); - //try to add a half size on the first row + //try to add a half size on the first row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $MIDNUX1, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); - //add it on second row + //add it on second row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX1, 'hpos' => $rack::POS_LEFT ]) - )->isGreaterThan(0); + ); - //add second half rack item it on second row, at same position + //add second half rack item it on second row, at same position $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX2, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); - //add second half rack item it on second row, on the other position + //add second half rack item it on second row, on the other position $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX2, 'hpos' => $rack::POS_RIGHT ]) - )->isGreaterThan(0); + ); - //Unit is full! + //Unit is full! $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $MIDNUX3, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); - //test depth < 1 + //test depth < 1 $DEPNUX1 = getItemByTypeName('Computer', 'DEP-NUX-1', true); $DEPNUX2 = getItemByTypeName('Computer', 'DEP-NUX-2', true); - //item ahs a depth <= 0.5. orientation is required + //item ahs a depth <= 0.5. orientation is required $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1 ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['You must define an orientation for this item']); - //try to add on the first row + //try to add on the first row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 1, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1, 'orientation' => $rack::FRONT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); //try to add on the second row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1, 'orientation' => $rack::FRONT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); //add on the third row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 3, 'itemtype' => 'Computer', 'items_id' => $DEPNUX1, 'orientation' => $rack::FRONT ]) - )->isGreaterThan(0); + ); //add not full depth rack item with same orientation //try to add on the first row $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 3, 'itemtype' => 'Computer', 'items_id' => $DEPNUX2, 'orientation' => $rack::FRONT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 3, 'itemtype' => 'Computer', 'items_id' => $DEPNUX2, 'orientation' => $rack::REAR ]) - )->isGreaterThan(0); + ); - //test hf full depth + 2x hf mid depth + //test hf full depth + 2x hf mid depth $MADNUX1 = getItemByTypeName('Computer', 'MAD-NUX-1', true); $MADNUX2 = getItemByTypeName('Computer', 'MAD-NUX-2', true); - //first element on unit2 (MID-NUX-1) is half racked on left; and is full depth - //drop second element on unit2 + //first element on unit2 (MID-NUX-1) is half racked on left; and is full depth + //drop second element on unit2 $ira->deleteByCriteria(['items_id' => $MIDNUX2], 1); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -449,13 +458,14 @@ public function testAdd() 'orientation' => $rack::REAR, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -463,11 +473,11 @@ public function testAdd() 'orientation' => $rack::REAR, 'hpos' => $rack::POS_RIGHT ]) - )->isGreaterThan(0); + ); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertFalse( + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -475,13 +485,14 @@ public function testAdd() 'orientation' => $rack::REAR, 'hpos' => $rack::POS_LEFT ]) - )->isIdenticalTo(0); + ); $this->hasSessionMessages(ERROR, ['Not enough space available to place item']); $ira->getEmpty(); - $this->integer( - (int)$ira->add([ + $this->assertGreaterThan( + 0, + $ira->add([ 'racks_id' => $rack->getID(), 'position' => 2, 'itemtype' => 'Computer', @@ -489,7 +500,7 @@ public function testAdd() 'orientation' => $rack::FRONT, 'hpos' => $rack::POS_RIGHT ]) - )->isGreaterThan(0); + ); } /** @@ -542,19 +553,22 @@ public function testRackIssues() // Update the ComputerModel for ($i = 1; $i < 15; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i <= 10); + $this->assertEquals( + $i <= 10, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); // Add a new Computer with a new ComputerModel $model2 = $this->createItem( @@ -588,146 +602,158 @@ public function testRackIssues() // Update the ComputerModel for ($i = 1; $i < 15; $i++) { - $this->boolean($model2->update([ - 'id' => $model2->getID(), - 'required_units' => $i, - ]))->isEqualTo($i <= 8); + $this->assertEquals( + $i <= 8, + $model2->update([ + 'id' => $model2->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Update the ComputerModel - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'is_half_rack' => 1, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'is_half_rack' => 1, - ]))->isTrue(); + ])); // Update the Item_Rack - $this->boolean($itemRack1->update([ + $this->assertTrue($itemRack1->update([ 'id' => $itemRack1->getID(), 'hpos' => 1, - ]))->isTrue(); + ])); - $this->boolean($itemRack2->update([ + $this->assertTrue($itemRack2->update([ 'id' => $itemRack2->getID(), 'hpos' => 2, - ]))->isTrue(); + ])); // Update the ComputerModel for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); } // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'is_half_rack' => 0, 'required_units' => 1, - ]))->isTrue(); + ])); // Update the ComputerModel for ($i = 1; $i <= 5; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i < 3); + $this->assertEquals( + $i < 3, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Update the ComputerModel - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, - ]))->isTrue(); + ])); // Test orientation - $this->boolean($itemRack1->update([ + $this->assertTrue($itemRack1->update([ 'id' => $itemRack1->getID(), 'orientation' => Rack::REAR, 'hpos' => Rack::POS_LEFT, - ]))->isTrue(); + ])); - $this->boolean($itemRack2->update([ + $this->assertTrue($itemRack2->update([ 'id' => $itemRack2->getID(), 'orientation' => Rack::FRONT, 'is_half_rack' => 0, - ]))->isTrue(); + ])); for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i < 3); + $this->assertEquals( + $i < 3, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); // Test depth - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, 'depth' => 0.5, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'depth' => 0.5, - ]))->isTrue(); + ])); for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => $i, - ]))->isTrue(); + ])); } - $this->boolean($model1->update([ + $this->assertTrue($model1->update([ 'id' => $model1->getID(), 'required_units' => 1, 'depth' => 0.5, - ]))->isTrue(); + ])); - $this->boolean($model2->update([ + $this->assertTrue($model2->update([ 'id' => $model2->getID(), 'required_units' => 1, 'depth' => 1, - ]))->isTrue(); + ])); for ($i = 1; $i <= 10; $i++) { - $this->boolean($model1->update([ - 'id' => $model1->getID(), - 'required_units' => $i, - ]))->isEqualTo($i < 3); + $this->assertEquals( + $i < 3, + $model1->update([ + 'id' => $model1->getID(), + 'required_units' => $i, + ]) + ); } $this->hasSessionMessages(ERROR, ['Unable to update model because it is used by an asset in the "Test rack" rack and the new required units do not fit into the rack']); @@ -782,7 +808,7 @@ public function testUpdateItemHorizontalPosition() ); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_NONE); + $this->assertEquals(Rack::POS_NONE, $itemRack->fields['hpos']); // Update model $this->updateItem( @@ -795,7 +821,7 @@ public function testUpdateItemHorizontalPosition() $itemRack->getFromDB($itemRack->getID()); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_LEFT); + $this->assertEquals(Rack::POS_LEFT, $itemRack->fields['hpos']); // Update model $this->updateItem( @@ -808,7 +834,7 @@ public function testUpdateItemHorizontalPosition() $itemRack->getFromDB($itemRack->getID()); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_NONE); + $this->assertEquals(Rack::POS_NONE, $itemRack->fields['hpos']); // Update item rack $this->updateItem( @@ -830,6 +856,6 @@ public function testUpdateItemHorizontalPosition() $itemRack->getFromDB($itemRack->getID()); // Check horizontal position - $this->integer($itemRack->fields['hpos'])->isEqualTo(Rack::POS_RIGHT); + $this->assertEquals(Rack::POS_RIGHT, $itemRack->fields['hpos']); } } diff --git a/tests/functional/Item_SoftwareLicense.php b/phpunit/functional/Item_SoftwareLicenseTest.php similarity index 69% rename from tests/functional/Item_SoftwareLicense.php rename to phpunit/functional/Item_SoftwareLicenseTest.php index d1aab6c3658..e49e25a2f55 100644 --- a/tests/functional/Item_SoftwareLicense.php +++ b/phpunit/functional/Item_SoftwareLicenseTest.php @@ -39,36 +39,36 @@ /* Test for inc/item_softwarelicense.class.php */ -class Item_SoftwareLicense extends DbTestCase +class Item_SoftwareLicenseTest extends DbTestCase { public function testCountForLicense() { $this->login(); - // Check new functionality + // Check new functionality $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_1'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(3); + $this->assertSame(3, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_2'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(2); + $this->assertSame(2, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_3'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(2); + $this->assertSame(2, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - $this->integer((int)\Item_SoftwareLicense::countForLicense($lic->fields['id']))->isIdenticalTo(0); + $this->assertSame(0, \Item_SoftwareLicense::countForLicense($lic->fields['id'])); } public function testCountForSoftware() { $this->login(); - //Check new functionality + //Check new functionality $soft = getItemByTypeName('Software', '_test_soft'); - $this->integer((int)\Item_SoftwareLicense::countForSoftware($soft->fields['id']))->isIdenticalTo(7); + $this->assertSame(7, \Item_SoftwareLicense::countForSoftware($soft->fields['id'])); $soft = getItemByTypeName('Software', '_test_soft2'); - $this->integer((int)\Item_SoftwareLicense::countForSoftware($soft->fields['id']))->isIdenticalTo(0); + $this->assertSame(0, \Item_SoftwareLicense::countForSoftware($soft->fields['id'])); } public function testGetLicenseForInstallation() @@ -78,38 +78,39 @@ public function testGetLicenseForInstallation() $this->Login(); - $this->array( + $this->assertEmpty( \Item_SoftwareLicense::getLicenseForInstallation( 'Computer', $computer1->fields['id'], $version1->fields['id'] ) - )->isEmpty(); + ); - //simulate license install + //simulate license install $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_1'); - $this->boolean( + $this->assertTrue( $lic->update([ 'id' => $lic->fields['id'], 'softwareversions_id_use' => $version1->fields['id'] ]) - )->isTrue(); + ); - $this->array( + $this->assertCount( + 1, \Item_SoftwareLicense::getLicenseForInstallation( 'Computer', $computer1->fields['id'], $version1->fields['id'] ) - )->hasSize(1); + ); - //reset license - $this->boolean( + //reset license + $this->assertTrue( $lic->update([ 'id' => $lic->fields['id'], 'softwareversions_id_use' => 0 ]) - )->isTrue(); + ); } public function testAddUpdateDelete() @@ -127,31 +128,31 @@ public function testAddUpdateDelete() 'itemtype' => 'Computer', 'softwarelicenses_id' => $lic->fields['id'], ]; - $this->integer((int)$lic_computer->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$lic_computer->add($input)); $input = [ 'items_id' => $computer2->fields['id'], 'itemtype' => 'Computer', 'softwarelicenses_id' => $lic->fields['id'], ]; - $this->integer((int)$lic_computer->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$lic_computer->add($input)); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - //License is valid: the number of affectations doesn't exceed declared number - $this->variable($lic->fields['is_valid'])->isEqualTo(1); + //License is valid: the number of affectations doesn't exceed declared number + $this->assertEquals(1, $lic->fields['is_valid']); $input = [ 'items_id' => $computer3->fields['id'], 'itemtype' => 'Computer', 'softwarelicenses_id' => $lic->fields['id'] ]; - $this->integer((int)$lic_computer->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$lic_computer->add($input)); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - //Number of affectations exceed the number declared in the license - $this->variable($lic->fields['is_valid'])->isEqualTo(0); + //Number of affectations exceed the number declared in the license + $this->assertEquals(0, $lic->fields['is_valid']); - //test upgrade + //test upgrade $old_lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); $new_lic = getItemByTypeName('SoftwareLicense', '_test_softlic_3'); @@ -162,21 +163,20 @@ public function testAddUpdateDelete() 'itemtype' => 'Computer', 'softwarelicenses_id' => $old_lic->fields['id'] ]); - $this->boolean($lic_computer->getFromDB(array_keys($result)[0]))->isTrue(); + $this->assertTrue($lic_computer->getFromDB(array_keys($result)[0])); $lic_computer->upgrade($lic_computer->getID(), $new_lic->fields['id']); - $this->variable($lic_computer->fields['softwarelicenses_id']) - ->isNotEqualTo($old_lic->getID()) - ->isEqualTo($new_lic->getID()); + $this->assertNotEquals($old_lic->getID(), $lic_computer->fields['softwarelicenses_id']); + $this->assertEquals($new_lic->getID(), $lic_computer->fields['softwarelicenses_id']); - //test delete + //test delete $lic_computer = new \Item_SoftwareLicense(); - $this->boolean($lic_computer->deleteByCriteria(['softwarelicenses_id' => $lic->fields['id']], true))->isTrue(); + $this->assertTrue($lic_computer->deleteByCriteria(['softwarelicenses_id' => $lic->fields['id']], true)); $lic = getItemByTypeName('SoftwareLicense', '_test_softlic_4'); - //Number of installations shouldn't now exceed the number declared in the license - $this->variable($lic->fields['is_valid'])->isEqualTo(1); + //Number of installations shouldn't now exceed the number declared in the license + $this->assertEquals(1, $lic->fields['is_valid']); } @@ -197,17 +197,15 @@ public function testCloneItem() 'items_id' => $source_computer->fields['id'], 'itemtype' => 'Computer' ]; - $this->integer((int)countElementsInTable('glpi_items_softwarelicenses', $input)) - ->isIdenticalTo(3); + $this->assertSame(3, countElementsInTable('glpi_items_softwarelicenses', $input)); $input = [ 'items_id' => $target_computer->fields['id'], 'itemtype' => 'Computer' ]; - $this->integer((int)countElementsInTable('glpi_items_softwarelicenses', $input)) - ->isIdenticalTo(3); + $this->assertSame(3, countElementsInTable('glpi_items_softwarelicenses', $input)); - //cleanup + //cleanup $lic_computer = new \Item_SoftwareLicense(); $lic_computer->deleteByCriteria([ 'items_id' => $target_computer->fields['id'], @@ -221,14 +219,14 @@ public function testGetTabNameForItem() $license = getItemByTypeName('SoftwareLicense', '_test_softlic_2'); $cSoftwareLicense = new \Item_SoftwareLicense(); - $this->string($cSoftwareLicense->getTabNameForItem(new \Computer(), 0))->isEmpty(); - $this->string($cSoftwareLicense->getTabNameForItem($license, 1))->isEmpty(); + $this->assertEmpty($cSoftwareLicense->getTabNameForItem(new \Computer(), 0)); + $this->assertEmpty($cSoftwareLicense->getTabNameForItem($license, 1)); $_SESSION['glpishow_count_on_tabs'] = 0; $expected = [1 => __('Summary'), 2 => _n('Item', 'Items', \Session::getPluralNumber()) ]; - $this->array($cSoftwareLicense->getTabNameForItem($license, 0))->isIdenticalTo($expected); + $this->assertSame($expected, $cSoftwareLicense->getTabNameForItem($license, 0)); $_SESSION['glpishow_count_on_tabs'] = 1; $expected = [1 => __('Summary'), @@ -237,7 +235,7 @@ public function testGetTabNameForItem() 2 ) ]; - $this->array($cSoftwareLicense->getTabNameForItem($license, 0))->isIdenticalTo($expected); + $this->assertSame($expected, $cSoftwareLicense->getTabNameForItem($license, 0)); } public function testCountLicenses() @@ -245,10 +243,10 @@ public function testCountLicenses() $this->login(); $software = getItemByTypeName('Software', '_test_soft'); - $this->integer((int)\Item_SoftwareLicense::countLicenses($software->getID()))->isIdenticalTo(5); + $this->assertSame(5, \Item_SoftwareLicense::countLicenses($software->getID())); $software = getItemByTypeName('Software', '_test_soft2'); - $this->integer((int)\Item_SoftwareLicense::countLicenses($software->getID()))->isIdenticalTo(0); + $this->assertSame(0, \Item_SoftwareLicense::countLicenses($software->getID())); } public function testGetSearchOptionsNew() @@ -256,7 +254,6 @@ public function testGetSearchOptionsNew() $this->login(); $cSoftwareLicense = new \Item_SoftwareLicense(); - $this->array($cSoftwareLicense->rawSearchOptions()) - ->hasSize(5); + $this->assertCount(5, $cSoftwareLicense->rawSearchOptions()); } } diff --git a/tests/functional/Item_SoftwareVersion.php b/phpunit/functional/Item_SoftwareVersionTest.php similarity index 62% rename from tests/functional/Item_SoftwareVersion.php rename to phpunit/functional/Item_SoftwareVersionTest.php index 00d6d90f084..d46358bcf56 100644 --- a/tests/functional/Item_SoftwareVersion.php +++ b/phpunit/functional/Item_SoftwareVersionTest.php @@ -42,13 +42,13 @@ /** * @engine isolate */ -class Item_SoftwareVersion extends DbTestCase +class Item_SoftwareVersionTest extends DbTestCase { public function testTypeName() { - $this->string(\Item_SoftwareVersion::getTypeName(1))->isIdenticalTo('Installation'); - $this->string(\Item_SoftwareVersion::getTypeName(0))->isIdenticalTo('Installations'); - $this->string(\Item_SoftwareVersion::getTypeName(10))->isIdenticalTo('Installations'); + $this->assertSame('Installation', \Item_SoftwareVersion::getTypeName(1)); + $this->assertSame('Installations', \Item_SoftwareVersion::getTypeName(0)); + $this->assertSame('Installations', \Item_SoftwareVersion::getTypeName(10)); } public function testPrepareInputForAdd() @@ -60,11 +60,14 @@ public function testPrepareInputForAdd() // Do some installations $ins = new \Item_SoftwareVersion(); - $this->integer((int)$ins->add([ - 'items_id' => $computer1->getID(), - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer1->getID(), + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); $input = [ 'items_id' => $computer1->getID(), @@ -83,7 +86,7 @@ public function testPrepareInputForAdd() ]; $this->setEntity('_test_root_entity', true); - $this->array($ins->prepareInputForAdd($input))->isIdenticalTo($expected); + $this->assertSame($expected, $ins->prepareInputForAdd($input)); } public function testPrepareInputForUpdate() @@ -95,11 +98,14 @@ public function testPrepareInputForUpdate() // Do some installations $ins = new \Item_SoftwareVersion(); - $this->integer((int)$ins->add([ - 'items_id' => $computer1->getID(), - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer1->getID(), + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); $input = [ 'items_id' => $computer1->getID(), @@ -115,7 +121,7 @@ public function testPrepareInputForUpdate() 'is_deleted_item' => $computer1->getField('is_deleted') ]; - $this->array($ins->prepareInputForUpdate($input))->isIdenticalTo($expected); + $this->assertSame($expected, $ins->prepareInputForUpdate($input)); } @@ -130,34 +136,40 @@ public function testCountInstall() // Do some installations $ins = new \Item_SoftwareVersion(); - $this->integer((int)$ins->add([ - 'items_id' => $computer1, - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); - $this->integer($ins->add([ - 'items_id' => $computer11, - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); - $this->integer($ins->add([ - 'items_id' => $computer12, - 'itemtype' => 'Computer', - 'softwareversions_id' => $ver, - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer1, + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer11, + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); + $this->assertGreaterThan( + 0, + $ins->add([ + 'items_id' => $computer12, + 'itemtype' => 'Computer', + 'softwareversions_id' => $ver, + ]) + ); - // Count installations + // Count installations $this->setEntity('_test_root_entity', true); - $this->integer((int)\Item_SoftwareVersion::countForVersion($ver), 'count in all tree') - ->isIdenticalTo(3); + $this->assertSame(3, \Item_SoftwareVersion::countForVersion($ver), 'count in all tree'); $this->setEntity('_test_root_entity', false); - $this->integer((int)\Item_SoftwareVersion::countForVersion($ver), 'count in root') - ->isIdenticalTo(1); + $this->assertSame(1, \Item_SoftwareVersion::countForVersion($ver), 'count in root'); $this->setEntity('_test_child_1', false); - $this->integer((int)\Item_SoftwareVersion::countForVersion($ver), 'count in child') - ->isIdenticalTo(2); + $this->assertSame(2, \Item_SoftwareVersion::countForVersion($ver), 'count in child'); } public function testUpdateDatasFromComputer() @@ -167,47 +179,47 @@ public function testUpdateDatasFromComputer() $ver1 = getItemByTypeName('SoftwareVersion', '_test_softver_1', true); $ver2 = getItemByTypeName('SoftwareVersion', '_test_softver_2', true); - // Do some installations + // Do some installations $softver = new \Item_SoftwareVersion(); $softver01 = $softver->add([ 'items_id' => $computer1->getID(), 'itemtype' => 'Computer', 'softwareversions_id' => $ver1, ]); - $this->integer((int)$softver01)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softver01); $softver02 = $softver->add([ 'items_id' => $computer1->getID(), 'itemtype' => 'Computer', 'softwareversions_id' => $ver2, ]); - $this->integer((int)$softver02)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softver02); foreach ([$softver01, $softver02] as $tsoftver) { $o = new \Item_SoftwareVersion(); - $this->boolean($o->getFromDb($tsoftver))->isTrue(); - $this->variable($o->getField('is_deleted_item'))->isEqualTo(0); + $this->assertTrue($o->getFromDb($tsoftver)); + $this->assertEquals(0, $o->getField('is_deleted_item')); } - //computer that does not exists - $this->boolean($softver->updateDatasForItem('Computer', $c00))->isFalse(); + //computer that does not exist + $this->assertFalse($softver->updateDatasForItem('Computer', $c00)); - //update existing computer + //update existing computer $input = $computer1->fields; $input['is_deleted'] = '1'; - $this->boolean($computer1->update($input))->isTrue(); + $this->assertTrue($computer1->update($input)); - $this->boolean($softver->updateDatasForItem('Computer', $computer1->getID()))->isTrue(); + $this->assertTrue($softver->updateDatasForItem('Computer', $computer1->getID())); - //check if all has been updated + //check if all has been updated foreach ([$softver01, $softver02] as $tsoftver) { $o = new \Item_SoftwareVersion(); - $this->boolean($o->getFromDb($tsoftver))->isTrue(); - $this->variable($o->getField('is_deleted_item'))->isEqualTo(1); + $this->assertTrue($o->getFromDb($tsoftver)); + $this->assertEquals(1, $o->getField('is_deleted_item')); } - //restore computer state + //restore computer state $input['is_deleted'] = '0'; - $this->boolean($computer1->update($input))->isTrue(); + $this->assertTrue($computer1->update($input)); } public function testCountForSoftware() @@ -217,21 +229,24 @@ public function testCountForSoftware() $this->Login(); - $this->integer( - (int)\Item_SoftwareVersion::countForSoftware($soft1->fields['id']) - )->isIdenticalTo(0); + $this->assertSame( + 0, + \Item_SoftwareVersion::countForSoftware($soft1->fields['id']) + ); $csoftver = new \Item_SoftwareVersion(); - $this->integer( - (int)$csoftver->add([ + $this->assertGreaterThan( + 0, + $csoftver->add([ 'items_id' => $computer1->fields['id'], 'itemtype' => 'Computer', 'softwareversions_id' => $soft1->fields['id'] ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)\Item_SoftwareVersion::countForSoftware($soft1->fields['id']) - )->isIdenticalTo(1); + $this->assertSame( + 1, + \Item_SoftwareVersion::countForSoftware($soft1->fields['id']) + ); } } diff --git a/tests/functional/KnowbaseItem.php b/phpunit/functional/KnowbaseItemTest.php similarity index 85% rename from tests/functional/KnowbaseItem.php rename to phpunit/functional/KnowbaseItemTest.php index 0e2462cf6a8..03318e10a36 100644 --- a/tests/functional/KnowbaseItem.php +++ b/phpunit/functional/KnowbaseItemTest.php @@ -40,17 +40,17 @@ /* Test for inc/knowbaseitem.class.php */ -class KnowbaseItem extends DbTestCase +class KnowbaseItemTest extends DbTestCase { public function testGetTypeName() { $expected = 'Knowledge base'; - $this->string(\KnowbaseItem::getTypeName(1))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem::getTypeName(1)); $expected = 'Knowledge base'; - $this->string(\KnowbaseItem::getTypeName(0))->isIdenticalTo($expected); - $this->string(\KnowbaseItem::getTypeName(2))->isIdenticalTo($expected); - $this->string(\KnowbaseItem::getTypeName(10))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem::getTypeName(0)); + $this->assertSame($expected, \KnowbaseItem::getTypeName(2)); + $this->assertSame($expected, \KnowbaseItem::getTypeName(10)); } public function testCleanDBonPurge() @@ -60,7 +60,8 @@ public function testCleanDBonPurge() $users_id = getItemByTypeName('User', TU_USER, true); $kb = new \KnowbaseItem(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kb->add([ 'name' => 'Test to remove', 'answer' => 'An KB entry to remove', @@ -68,9 +69,9 @@ public function testCleanDBonPurge() 'users_id' => $users_id, 'date' => '2017-10-06 12:27:48', ]) - )->isGreaterThan(0); + ); - //add some comments + //add some comments $comment = new \KnowbaseItem_Comment(); $input = [ 'knowbaseitems_id' => $kb->getID(), @@ -80,73 +81,80 @@ public function testCleanDBonPurge() $id = 0; for ($i = 0; $i < 4; ++$i) { $input['comment'] = "Comment $i"; - $this->integer( + $this->assertGreaterThan( + $id, (int)$comment->add($input) - )->isGreaterThan($id); + ); $id = (int)$comment->getID(); } - //change KB entry - $this->boolean( + //change KB entry + $this->assertTrue( $kb->update([ 'id' => $kb->getID(), 'answer' => 'Answer has changed' ]) - )->isTrue(); + ); - //add an user + //add an user $kbu = new \KnowbaseItem_User(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbu->add([ 'knowbaseitems_id' => $kb->getID(), 'users_id' => $users_id ]) - )->isGreaterThan(0); + ); - //add an entity + //add an entity $kbe = new \Entity_KnowbaseItem(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbe->add([ 'knowbaseitems_id' => $kb->getID(), 'entities_id' => 0 ]) - )->isGreaterThan(0); + ); - //add a group + //add a group $group = new \Group(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$group->add([ 'name' => 'KB group' ]) - )->isGreaterThan(0); + ); $kbg = new \Group_KnowbaseItem(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbg->add([ 'knowbaseitems_id' => $kb->getID(), 'groups_id' => $group->getID() ]) - )->isGreaterThan(0); + ); - //add a profile + //add a profile $profiles_id = getItemByTypeName('Profile', 'Admin', true); $kbp = new \KnowbaseItem_Profile(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbp->add([ 'knowbaseitems_id' => $kb->getID(), 'profiles_id' => $profiles_id ]) - )->isGreaterThan(0); + ); - //add an item + //add an item $kbi = new \KnowbaseItem_Item(); $tickets_id = getItemByTypeName('Ticket', '_ticket01', true); - $this->integer( + $this->assertGreaterThan( + 0, (int)$kbi->add([ 'knowbaseitems_id' => $kb->getID(), 'itemtype' => 'Ticket', 'items_id' => $tickets_id ]) - )->isGreaterThan(0); + ); $relations = [ $comment->getTable(), @@ -164,21 +172,21 @@ public function testCleanDBonPurge() 'FROM' => $relation, 'WHERE' => ['knowbaseitems_id' => $kb->getID()] ]); - $this->integer(count($iterator))->isGreaterThan(0); + $this->assertGreaterThan(0, count($iterator)); } - //remove KB entry - $this->boolean( + //remove KB entry + $this->assertTrue( $kb->delete(['id' => $kb->getID()], true) - )->isTrue(); + ); - //check all relations has been removed + //check all relations has been removed foreach ($relations as $relation) { $iterator = $DB->request([ 'FROM' => $relation, 'WHERE' => ['knowbaseitems_id' => $kb->getID()] ]); - $this->integer(count($iterator))->isIdenticalTo(0); + $this->assertSame(0, count($iterator)); } } @@ -187,8 +195,11 @@ public function testScreenshotConvertedIntoDocument() $this->login(); // must be logged as Document_Item uses Session::getLoginUserID() - // Test uploads for item creation - $base64Image = base64_encode(file_get_contents(__DIR__ . '/../fixtures/uploads/foo.png')); + // Test uploads for item creation + $fpath = FIXTURE_DIR . '/uploads/foo.png'; + $fcontents = file_get_contents($fpath); + $this->assertNotSame(false, $fcontents, 'Cannot read ' . $fpath); + $base64Image = base64_encode($fcontents); $filename = '5e5e92ffd9bd91.11111111image_paste22222222.png'; $users_id = getItemByTypeName('User', TU_USER, true); $instance = new \KnowbaseItem(); @@ -212,15 +223,22 @@ public function testScreenshotConvertedIntoDocument() 'users_id' => $users_id, 'date' => '2017-10-06 12:27:48', ]; - copy(__DIR__ . '/../fixtures/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); - $instance->add($input); - $this->boolean($instance->isNewItem())->isFalse(); - $this->boolean($instance->getFromDB($instance->getId()))->isTrue(); + $fpath = FIXTURE_DIR . '/uploads/foo.png'; + $this->assertTrue( + copy($fpath, GLPI_TMP_DIR . '/' . $filename), + 'Cannot copy ' . $fpath + ); + $this->assertGreaterThan(0, $instance->add($input)); + $this->assertFalse($instance->isNewItem()); + $this->assertTrue($instance->getFromDB($instance->getId())); $expected = 'a href="/front/document.send.php?docid='; - $this->string($instance->fields['answer'])->contains($expected); + $this->assertStringContainsString($expected, $instance->fields['answer']); - // Test uploads for item update - $base64Image = base64_encode(file_get_contents(__DIR__ . '/../fixtures/uploads/bar.png')); + // Test uploads for item update + $fpath = FIXTURE_DIR . '/uploads/bar.png'; + $fcontents = file_get_contents($fpath); + $this->assertNotSame(false, $fcontents, 'Cannot read ' . $fpath); + $base64Image = base64_encode($fcontents); $filename = '5e5e92ffd9bd91.44444444image_paste55555555.png'; $tmpFilename = GLPI_TMP_DIR . '/' . $filename; file_put_contents($tmpFilename, base64_decode($base64Image)); @@ -241,11 +259,11 @@ public function testScreenshotConvertedIntoDocument() '5e5e92ffd9bd91.44444444', ], ]); - $this->boolean($success)->isTrue(); - $this->boolean($instance->getFromDB($instance->getId()))->isTrue(); - // Ensure there is an anchor to the uploaded document + $this->assertTrue($success); + $this->assertTrue($instance->getFromDB($instance->getId())); + // Ensure there is an anchor to the uploaded document $expected = 'a href="/front/document.send.php?docid='; - $this->string($instance->fields['answer'])->contains($expected); + $this->assertStringContainsString($expected, $instance->fields['answer']); } public function testUploadDocuments() @@ -253,7 +271,7 @@ public function testUploadDocuments() $this->login(); // must be logged as Document_Item uses Session::getLoginUserID() - // Test uploads for item creation + // Test uploads for item creation $filename = '5e5e92ffd9bd91.11111111' . 'foo.txt'; $instance = new \KnowbaseItem(); $input = [ @@ -269,19 +287,27 @@ public function testUploadDocuments() '5e5e92ffd9bd91.11111111', ] ]; - copy(__DIR__ . '/../fixtures/uploads/foo.txt', GLPI_TMP_DIR . '/' . $filename); + $fpath = FIXTURE_DIR . '/uploads/foo.txt'; + $this->assertTrue( + copy($fpath, GLPI_TMP_DIR . '/' . $filename), + 'Cannot copy ' . $fpath + ); $instance->add($input); - $this->boolean($instance->isNewItem())->isFalse(); - $this->string($instance->fields['answer'])->contains('testUploadDocuments'); + $this->assertFalse($instance->isNewItem()); + $this->assertStringContainsString('testUploadDocuments', $instance->fields['answer']); $count = (new \DBUtils())->countElementsInTable(\Document_Item::getTable(), [ 'itemtype' => 'KnowbaseItem', 'items_id' => $instance->getID(), ]); - $this->integer($count)->isEqualTo(1); + $this->assertEquals(1, $count); - // Test uploads for item update (adds a 2nd document) + // Test uploads for item update (adds a 2nd document) $filename = '5e5e92ffd9bd91.44444444bar.txt'; - copy(__DIR__ . '/../fixtures/uploads/bar.txt', GLPI_TMP_DIR . '/' . $filename); + $fpath = FIXTURE_DIR . '/uploads/bar.txt'; + $this->assertTrue( + copy($fpath, GLPI_TMP_DIR . '/' . $filename), + 'Cannot copy ' . $fpath + ); $success = $instance->update([ 'id' => $instance->getID(), 'answer' => 'update testUploadDocuments', @@ -295,55 +321,63 @@ public function testUploadDocuments() '5e5e92ffd9bd91.44444444', ] ]); - $this->boolean($success)->isTrue(); - $this->string($instance->fields['answer'])->contains('update testUploadDocuments'); + $this->assertTrue($success); + $this->assertStringContainsString('update testUploadDocuments', $instance->fields['answer']); $count = (new \DBUtils())->countElementsInTable(\Document_Item::getTable(), [ 'itemtype' => 'KnowbaseItem', 'items_id' => $instance->getID(), ]); - $this->integer($count)->isEqualTo(2); + $this->assertEquals(2, $count); } public function testGetForCategory() { global $DB; + $orig_db = clone $DB; + + // Prepare mocks + $m_db = $this->getMockBuilder(\DB::class) + ->onlyMethods(['request']) + ->disableOriginalConstructor() + ->getMock(); - // Prepare mocks - $m_db = new \mock\DB(); - $m_kbi = new \mock\KnowbaseItem(); + $m_kbi = $this->getMockBuilder(\KnowbaseItem::class) + ->onlyMethods(['getFromDB', 'canViewItem']) + ->getMock(); - // Mocked db request result + // Mocked db request result $it = new \ArrayIterator([ ['id' => '1'], ['id' => '2'], ['id' => '3'], ]); - $this->calling($m_db)->request = $it; + $m_db->method('request')->willReturn($it); - // Ignore get fromDB - $this->calling($m_kbi)->getFromDB = true; + // Ignore get fromDB + $m_kbi->method('getFromDB')->willReturn(true); - // True for call 1 & 3, false for call 2 and every following calls - $this->calling($m_kbi)->canViewItem[0] = false; - $this->calling($m_kbi)->canViewItem[1] = true; - $this->calling($m_kbi)->canViewItem[2] = false; - $this->calling($m_kbi)->canViewItem[3] = true; + // True for call 1 & 3, false for call 2 and every following calls + $m_kbi->method('canViewItem')->willReturn(true, false, true, false); - // Replace global DB with mocked DB + // Expected : [1, 3] + // Replace global DB with mocked DB $DB = $m_db; - - // Expected : [1, 3] - $this->array(\KnowbaseItem::getForCategory(1, $m_kbi)) - ->hasSize(2) - ->containsValues([1, 3]); - - // Expected : [-1] - $this->array(\KnowbaseItem::getForCategory(1, $m_kbi)) - ->hasSize(1) - ->contains(-1); + $result = \KnowbaseItem::getForCategory(1, $m_kbi); + $DB = $orig_db; + $this->assertCount(2, $result); + $this->assertContains('1', $result); + $this->assertContains('3', $result); + + // Expected : [-1] + // Replace global DB with mocked DB + $DB = $m_db; + $result = \KnowbaseItem::getForCategory(1, $m_kbi); + $DB = $orig_db; + $this->assertCount(1, $result); + $this->assertContains(-1, $result); } - protected function fullTextSearchProvider(): iterable + public static function fullTextSearchProvider(): iterable { // Spaces around search terms are trimmed yield [ @@ -499,15 +533,15 @@ protected function fullTextSearchProvider(): iterable } /** - * @dataprovider fullTextSearchProvider + * @dataProvider fullTextSearchProvider */ public function testComputeBooleanFullTextSearch(string $search, string $expected): void { - $search = $this->callPrivateMethod($this->newTestedInstance(), 'computeBooleanFullTextSearch', $search); - $this->string($search)->isEqualTo($expected); + $search = $this->callPrivateMethod(new \KnowbaseItem(), 'computeBooleanFullTextSearch', $search); + $this->assertEquals($expected, $search); } - protected function testGetListRequestProvider(): array + public static function testGetListRequestProvider(): array { return [ [ @@ -690,7 +724,7 @@ protected function testGetListRequestProvider(): array } /** - * @dataprovider testGetListRequestProvider + * @dataProvider testGetListRequestProvider */ public function testGetListRequest(array $params, string $type, int $count, ?array $sort): void { @@ -699,24 +733,24 @@ public function testGetListRequest(array $params, string $type, int $count, ?arr // Build criteria array $criteria = \KnowbaseItem::getListRequest($params, $type); - $this->array($criteria); + $this->assertIsArray($criteria); // Check that the request is valid $iterator = $DB->request($criteria); //count KnowBaseItem found - $this->integer($iterator->numrows())->isEqualTo($count); + $this->assertEquals($count, $iterator->numrows()); // check order if needed if ($sort != null) { $names = array_column(iterator_to_array($iterator), 'name'); - $this->array($names)->isEqualTo($sort); + $this->assertEquals($sort, $names); } } public function testGetAnswerAnchors(): void { - // Create test KB with multiple headers + // Create test KB with multiple headers $kb_name = 'Test testGetAnswerAnchors' . mt_rand(); $input = [ 'name' => $kb_name, @@ -724,26 +758,27 @@ public function testGetAnswerAnchors(): void ]; $this->createItems('KnowbaseItem', [$input]); - // Load KB + // Load KB /** @var \KnowbaseItem */ $kbi = getItemByTypeName("KnowbaseItem", $kb_name); $answer = $kbi->getAnswer(); - // Test anchors, there should be one per header - $this->string($answer)->contains('<h1 id="title-1a">'); - $this->string($answer)->contains('<a href="#title-1a">'); - $this->string($answer)->contains('<h2 id="title2">'); - $this->string($answer)->contains('<a href="#title2">'); - $this->string($answer)->contains('<h1 id="title-1b">'); - $this->string($answer)->contains('<a href="#title-1b">'); - $this->string($answer)->contains('<h1 id="title-1c">'); - $this->string($answer)->contains('<a href="#title-1c">'); + // Test anchors, there should be one per header + $this->assertStringContainsString('<h1 id="title-1a">', $answer); + $this->assertStringContainsString('<a href="#title-1a">', $answer); + $this->assertStringContainsString('<h2 id="title2">', $answer); + $this->assertStringContainsString('<a href="#title2">', $answer); + $this->assertStringContainsString('<h1 id="title-1b">', $answer); + $this->assertStringContainsString('<a href="#title-1b">', $answer); + $this->assertStringContainsString('<h1 id="title-1c">', $answer); + $this->assertStringContainsString('<a href="#title-1c">', $answer); } /** + * FIXME: delete? * To be deleted after 10.1 release */ - public function testCreateWithCategoriesDeprecated() + /*public function testCreateWithCategoriesDeprecated() { $root_entity = getItemByTypeName('Entity', '_test_root_entity', true); @@ -774,7 +809,7 @@ public function testCreateWithCategoriesDeprecated() // Check category id $data = array_pop($linked_categories); $this->integer($data['knowbaseitemcategories_id'])->isEqualTo($category->getID()); - } + }*/ public function testCreateWithCategories() { @@ -790,7 +825,7 @@ public function testCreateWithCategories() 'is_recursive' => 1, 'knowbaseitemcategories_id' => 0, ]); - $this->integer($kb_cat_id1)->isGreaterThan(0); + $this->assertGreaterThan(0, $kb_cat_id1); $kb_cat_id2 = $kb_category->add([ 'name' => __FUNCTION__ . '_2', @@ -799,7 +834,7 @@ public function testCreateWithCategories() 'is_recursive' => 1, 'knowbaseitemcategories_id' => 0, ]); - $this->integer($kb_cat_id2)->isGreaterThan(0); + $this->assertGreaterThan(0, $kb_cat_id2); $kbitem = new \KnowbaseItem(); // Create a new KB item with the first category @@ -808,7 +843,7 @@ public function testCreateWithCategories() 'answer' => __FUNCTION__ . '_1', '_categories' => [$kb_cat_id1], ]); - $this->integer($kbitems_id1)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitems_id1); // Expect the KB item to have the first category $iterator = $DB->request([ @@ -817,8 +852,8 @@ public function testCreateWithCategories() 'knowbaseitems_id' => $kbitems_id1, ], ]); - $this->integer($iterator->count())->isEqualTo(1); - $this->integer($iterator->current()['knowbaseitemcategories_id'])->isEqualTo($kb_cat_id1); + $this->assertEquals(1, $iterator->count()); + $this->assertEquals($kb_cat_id1, $iterator->current()['knowbaseitemcategories_id']); // Create a new KB item with both categories $kbitems_id2 = $kbitem->add([ @@ -826,7 +861,7 @@ public function testCreateWithCategories() 'answer' => __FUNCTION__ . '_2', '_categories' => [$kb_cat_id1, $kb_cat_id2], ]); - $this->integer($kbitems_id2)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitems_id2); // Expect the KB item to have both categories $iterator = $DB->request([ @@ -835,12 +870,12 @@ public function testCreateWithCategories() 'knowbaseitems_id' => $kbitems_id2, ], ]); - $this->integer($iterator->count())->isEqualTo(2); + $this->assertEquals(2, $iterator->count()); $category_ids = []; foreach ($iterator as $row) { $category_ids[] = $row['knowbaseitemcategories_id']; } - $this->array($category_ids)->containsValues([$kb_cat_id1, $kb_cat_id2]); + $this->assertEqualsCanonicalizing([$kb_cat_id1, $kb_cat_id2], $category_ids); } protected function testGetVisibilityCriteriaProvider(): iterable @@ -856,7 +891,7 @@ protected function testGetVisibilityCriteriaProvider_FAQ_public(): iterable // Removing existing data $DB->delete(\KnowbaseItem::getTable(), [1]); - $this->integer(countElementsInTable(\KnowbaseItem::getTable()))->isEqualTo(0); + $this->assertEquals(0, countElementsInTable(\KnowbaseItem::getTable())); // Create set of test subjects $glpi_user = getItemByTypeName("User", "glpi", true); @@ -915,7 +950,7 @@ protected function testGetVisibilityCriteriaProvider_FAQ_logged(): iterable // Removing existing data $DB->delete(\KnowbaseItem::getTable(), [1]); - $this->integer(countElementsInTable(\KnowbaseItem::getTable()))->isEqualTo(0); + $this->assertEquals(0, countElementsInTable(\KnowbaseItem::getTable())); // Create set of test subjects $glpi_user = getItemByTypeName("User", "glpi", true); @@ -1019,9 +1054,10 @@ protected function testGetVisibilityCriteriaProvider_FAQ_logged(): iterable 'entities_id' => getItemByTypeName("Entity", "_test_root_entity", true), 'is_recursive' => 1, ]); - $this->integer($postonly_group)->isGreaterThan(0); + $this->assertGreaterThan(0, $postonly_group); $group_user = new \Group_User(); - $this->integer( + $this->assertGreaterThan( + 0, (int)$group_user->add([ 'groups_id' => $postonly_group, 'users_id' => getItemByTypeName("User", "post-only", true), @@ -1032,8 +1068,9 @@ protected function testGetVisibilityCriteriaProvider_FAQ_logged(): iterable 'entities_id' => getItemByTypeName("Entity", "_test_root_entity", true), 'is_recursive' => 1, ]); - $this->integer($tech_group)->isGreaterThan(0); - $this->integer( + $this->assertGreaterThan(0, $tech_group); + $this->assertGreaterThan( + 0, (int)$group_user->add([ 'groups_id' => $tech_group, 'users_id' => getItemByTypeName("User", "tech", true), @@ -1061,17 +1098,17 @@ protected function testGetVisibilityCriteriaProvider_FAQ_logged(): iterable 'name' => 'FAQ 1 entity', 'entities_id' => getItemByTypeName("Entity", "_test_root_entity", true), ]); - $this->integer($faq_entity1)->isGreaterThan(0); + $this->assertGreaterThan(0, $faq_entity1); $faq_entity2 = (int)$entity->add([ 'name' => 'FAQ 2 entity', 'entities_id' => getItemByTypeName("Entity", "_test_root_entity", true), ]); - $this->integer($faq_entity2)->isGreaterThan(0); + $this->assertGreaterThan(0, $faq_entity2); $faq_entity11 = (int)$entity->add([ 'name' => 'FAQ 1.1 entity', 'entities_id' => $faq_entity1, ]); - $this->integer($faq_entity11)->isGreaterThan(0); + $this->assertGreaterThan(0, $faq_entity11); $this->createItems("Entity_KnowbaseItem", [ [ @@ -1348,25 +1385,25 @@ protected function testGetVisibilityCriteriaProvider_KB(): iterable ]; } - /** - * @dataprovider testGetVisibilityCriteriaProvider - */ - public function testGetVisibilityCriteria(array $articles) + public function testGetVisibilityCriteria() { global $DB; - $criteria = array_merge(\KnowbaseItem::getVisibilityCriteria(false), [ - 'SELECT' => 'name', - 'FROM' => \KnowbaseItem::getTable() - ]); + $values = $this->testGetVisibilityCriteriaProvider(); + foreach ($values as $value) { + $criteria = array_merge(\KnowbaseItem::getVisibilityCriteria(false), [ + 'SELECT' => 'name', + 'FROM' => \KnowbaseItem::getTable() + ]); - $data = $DB->request($criteria); - $result = array_column(iterator_to_array($data), "name"); + $data = $DB->request($criteria); + $result = array_column(iterator_to_array($data), "name"); - // We need to sort data before comparing or the tests will fails on mariaDB - sort($articles); - sort($result); + // We need to sort data before comparing or the tests will fail on mariaDB + sort($value['articles']); + sort($result); - $this->array($result)->isEqualTo($articles); + $this->assertEquals($value['articles'], $result); + } } } diff --git a/tests/functional/KnowbaseItem_Comment.php b/phpunit/functional/KnowbaseItem_CommentTest.php similarity index 70% rename from tests/functional/KnowbaseItem_Comment.php rename to phpunit/functional/KnowbaseItem_CommentTest.php index 8ad9fa9186d..e5638d2f8ce 100644 --- a/tests/functional/KnowbaseItem_Comment.php +++ b/phpunit/functional/KnowbaseItem_CommentTest.php @@ -42,16 +42,16 @@ /** * @engine isolate */ -class KnowbaseItem_Comment extends DbTestCase +class KnowbaseItem_CommentTest extends DbTestCase { public function testGetTypeName() { $expected = 'Comment'; - $this->string(\KnowbaseItem_Comment::getTypeName(1))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem_Comment::getTypeName(1)); $expected = 'Comments'; foreach ([0, 2, 10] as $i) { - $this->string(\KnowbaseItem_Comment::getTypeName($i))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem_Comment::getTypeName($i)); } } @@ -59,35 +59,35 @@ public function testGetCommentsForKbItem() { $kb1 = getItemByTypeName(\KnowbaseItem::getType(), '_knowbaseitem01'); - //first, set data + //first, set data $this->addComments($kb1); $this->addComments($kb1, 'fr_FR'); $nb = countElementsInTable( 'glpi_knowbaseitems_comments' ); - $this->integer((int)$nb)->isIdenticalTo(10); + $this->assertSame(10, $nb); - // second, test what we retrieve + // second, test what we retrieve $comments = \KnowbaseItem_Comment::getCommentsForKbItem($kb1->getID(), null); - $this->array($comments)->hasSize(2); - $this->array($comments[0])->hasSize(9); - $this->array($comments[0]['answers'])->hasSize(2); - $this->array($comments[0]['answers'][0]['answers'])->hasSize(1); - $this->array($comments[0]['answers'][1]['answers'])->hasSize(0); - $this->array($comments[1])->hasSize(9); - $this->array($comments[1]['answers'])->hasSize(0); + $this->assertCount(2, $comments); + $this->assertCount(9, $comments[0]); + $this->assertCount(2, $comments[0]['answers']); + $this->assertCount(1, $comments[0]['answers'][0]['answers']); + $this->assertCount(0, $comments[0]['answers'][1]['answers']); + $this->assertCount(9, $comments[1]); + $this->assertCount(0, $comments[1]['answers']); } /** * Add comments into database * - * @param KnowbaseItem $kb KB item instance - * @param string $lang KB item language, defaults to null + * @param \KnowbaseItem $kb KB item instance + * @param string $lang KB item language, defaults to null * * @return void */ - private function addComments(\KnowbaseItem $kb, $lang = 'NULL') + private function addComments(\KnowbaseItem $kb, string $lang = 'NULL') { $this->login(); $kbcom = new \KnowbaseItem_Comment(); @@ -98,38 +98,38 @@ private function addComments(\KnowbaseItem $kb, $lang = 'NULL') 'language' => $lang ]; $kbcom1 = $kbcom->add($input); - $this->boolean($kbcom1 > 0)->isTrue(); + $this->assertTrue($kbcom1 > 0); $input['comment'] = 'Comment 2 for KB1'; $kbcom2 = $kbcom->add($input); - $this->boolean($kbcom2 > $kbcom1)->isTrue(); + $this->assertTrue($kbcom2 > $kbcom1); - //this one is from another user. + //this one is from another user. $input['comment'] = 'Comment 1 - 1 for KB1'; $input['parent_comment_id'] = $kbcom1; $input['users_id'] = getItemByTypeName('User', 'glpi', true); $kbcom11 = $kbcom->add($input); - $this->boolean($kbcom11 > $kbcom2)->isTrue(); + $this->assertTrue($kbcom11 > $kbcom2); $input['comment'] = 'Comment 1 - 2 for KB1'; $input['users_id'] = getItemByTypeName('User', TU_USER, true); $kbcom12 = $kbcom->add($input); - $this->boolean($kbcom12 > $kbcom11)->isTrue(); + $this->assertTrue($kbcom12 > $kbcom11); $input['comment'] = 'Comment 1 - 1 - 1 for KB1'; $input['parent_comment_id'] = $kbcom11; $kbcom111 = $kbcom->add($input); - $this->boolean($kbcom111 > $kbcom12)->isTrue(); + $this->assertTrue($kbcom111 > $kbcom12); } public function testGetTabNameForItemNotLogged() { - //we are not logged, we should not see comment tab + //we are not logged, we should not see comment tab $kb1 = getItemByTypeName(\KnowbaseItem::getType(), '_knowbaseitem01'); $kbcom = new \KnowbaseItem_Comment(); $name = $kbcom->getTabNameForItem($kb1, true); - $this->string($name)->isIdenticalTo(''); + $this->assertSame('', $name); } public function testGetTabNameForItemLogged() @@ -141,25 +141,25 @@ public function testGetTabNameForItemLogged() $kbcom = new \KnowbaseItem_Comment(); $name = $kbcom->getTabNameForItem($kb1, true); - $this->string($name)->isIdenticalTo('Comments <span class=\'badge\'>5</span>'); + $this->assertSame('Comments <span class=\'badge\'>5</span>', $name); $_SESSION['glpishow_count_on_tabs'] = 1; $name = $kbcom->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo('Comments <span class=\'badge\'>5</span>'); + $this->assertSame('Comments <span class=\'badge\'>5</span>', $name); $_SESSION['glpishow_count_on_tabs'] = 0; $name = $kbcom->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo('Comments'); + $this->assertSame('Comments', $name); // Change knowbase rights to be empty $_SESSION['glpiactiveprofile']['knowbase'] = 0; // Tab name should be empty - $this->string($kbcom->getTabNameForItem($kb1))->isEmpty(); + $this->assertEmpty($kbcom->getTabNameForItem($kb1)); // Add comment and read right $_SESSION['glpiactiveprofile']['knowbase'] = READ | \KnowbaseItem::COMMENTS; // Tab name should be filled (start with "Comments") - $this->string($kbcom->getTabNameForItem($kb1))->matches('/^Comments/'); + $this->assertMatchesRegularExpression('/^Comments/', $kbcom->getTabNameForItem($kb1)); } public function testDisplayComments() @@ -173,21 +173,21 @@ public function testDisplayComments() ); preg_match_all("/li class='comment'/", $html, $results); - $this->array($results[0])->hasSize(2); + $this->assertCount(2, $results[0]); preg_match_all("/li class='comment subcomment'/", $html, $results); - $this->array($results[0])->hasSize(3); + $this->assertCount(3, $results[0]); preg_match_all("/span class='ti ti-edit edit_item pointer'/", $html, $results); - $this->array($results[0])->hasSize(4); + $this->assertCount(4, $results[0]); preg_match_all("/span class='add_answer'/", $html, $results); - $this->array($results[0])->hasSize(5); + $this->assertCount(5, $results[0]); - //same tests, from another user + //same tests, from another user $auth = new \Auth(); $result = $auth->login('glpi', 'glpi', true); - $this->boolean($result)->isTrue(); + $this->assertTrue($result); $html = \KnowbaseItem_Comment::displayComments( \KnowbaseItem_Comment::getCommentsForKbItem($kb1->getID(), null), @@ -195,15 +195,15 @@ public function testDisplayComments() ); preg_match_all("/li class='comment'/", $html, $results); - $this->array($results[0])->hasSize(2); + $this->assertCount(2, $results[0]); preg_match_all("/li class='comment subcomment'/", $html, $results); - $this->array($results[0])->hasSize(3); + $this->assertCount(3, $results[0]); preg_match_all("/span class='ti ti-edit edit_item pointer'/", $html, $results); - $this->array($results[0])->hasSize(1); + $this->assertCount(1, $results[0]); preg_match_all("/span class='add_answer'/", $html, $results); - $this->array($results[0])->hasSize(5); + $this->assertCount(5, $results[0]); } } diff --git a/tests/functional/KnowbaseItem_Item.php b/phpunit/functional/KnowbaseItem_ItemTest.php similarity index 72% rename from tests/functional/KnowbaseItem_Item.php rename to phpunit/functional/KnowbaseItem_ItemTest.php index f3272de1e51..293baca99c9 100644 --- a/tests/functional/KnowbaseItem_Item.php +++ b/phpunit/functional/KnowbaseItem_ItemTest.php @@ -39,17 +39,17 @@ /* Test for inc/knowbaseitem_item.class.php */ -class KnowbaseItem_Item extends DbTestCase +class KnowbaseItem_ItemTest extends DbTestCase { public function testGetTypeName() { $expected = 'Knowledge base item'; - $this->string(\KnowbaseItem_Item::getTypeName(1))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem_Item::getTypeName(1)); $expected = 'Knowledge base items'; - $this->string(\KnowbaseItem_Item::getTypeName(0))->isIdenticalTo($expected); - $this->string(\KnowbaseItem_Item::getTypeName(2))->isIdenticalTo($expected); - $this->string(\KnowbaseItem_Item::getTypeName(10))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem_Item::getTypeName(0)); + $this->assertSame($expected, \KnowbaseItem_Item::getTypeName(2)); + $this->assertSame($expected, \KnowbaseItem_Item::getTypeName(10)); } public function testGetItemsFromKB() @@ -57,7 +57,7 @@ public function testGetItemsFromKB() $this->login(); $kb1 = getItemByTypeName('KnowbaseItem', '_knowbaseitem01'); $items = \KnowbaseItem_Item::getItems($kb1); - $this->array($items)->hasSize(3); + $this->assertCount(3, $items); $expecteds = [ 0 => [ @@ -76,13 +76,13 @@ public function testGetItemsFromKB() foreach ($expecteds as $key => $expected) { $item = getItemByTypeName($expected['itemtype'], $expected['id']); - $this->object($item)->isInstanceOf($expected['itemtype']); + $this->assertInstanceOf($expected['itemtype'], $item); } - //add start & limit + //add start & limit $kb1 = getItemByTypeName('KnowbaseItem', '_knowbaseitem01'); $items = \KnowbaseItem_Item::getItems($kb1, 1, 1); - $this->array($items)->hasSize(1); + $this->assertCount(1, $items); $expecteds = [ 1 => [ @@ -93,12 +93,12 @@ public function testGetItemsFromKB() foreach ($expecteds as $key => $expected) { $item = getItemByTypeName($expected['itemtype'], $expected['id']); - $this->object($item)->isInstanceOf($expected['itemtype']); + $this->assertInstanceOf($expected['itemtype'], $item); } $kb2 = getItemByTypeName('KnowbaseItem', '_knowbaseitem02'); $items = \KnowbaseItem_Item::getItems($kb2); - $this->array($items)->hasSize(2); + $this->assertCount(2, $items); $expecteds = [ 0 => [ @@ -113,7 +113,7 @@ public function testGetItemsFromKB() foreach ($expecteds as $key => $expected) { $item = getItemByTypeName($expected['itemtype'], $expected['id']); - $this->object($item)->isInstanceOf($expected['itemtype']); + $this->assertInstanceOf($expected['itemtype'], $item); } } @@ -122,48 +122,43 @@ public function testGetKbsFromItem() $this->login(); $ticket3 = getItemByTypeName(\Ticket::getType(), '_ticket03'); $kbs = \KnowbaseItem_Item::getItems($ticket3); - $this->array($kbs) - ->hasSize(2); + $this->assertCount(2, $kbs); $kb_ids = []; foreach ($kbs as $kb) { - $this->array($kb) - ->string['itemtype']->isIdenticalTo($ticket3->getType()) - ->integer['items_id']->isIdenticalTo($ticket3->getID()); - + $this->assertSame($ticket3->getType(), $kb['itemtype']); + $this->assertSame($ticket3->getID(), $kb['items_id']); $kb_ids[] = $kb['knowbaseitems_id']; } - //test get "used" + //test get "used" $kbs = \KnowbaseItem_Item::getItems($ticket3, 0, 0, '', true); - $this->array($kbs)->hasSize(2); + $this->assertCount(2, $kbs); foreach ($kbs as $key => $kb) { - $this->variable($kb)->isEqualTo($key); - $this->array($kb_ids)->contains($key); + $this->assertEquals($key, $kb); + $this->assertContains($key, $kb_ids); } $ticket1 = getItemByTypeName(\Ticket::getType(), '_ticket01'); $kbs = \KnowbaseItem_Item::getItems($ticket1); - $this->array($kbs)->hasSize(1); + $this->assertCount(1, $kbs); foreach ($kbs as $kb) { - $this->array($kb) - ->string['itemtype']->isIdenticalTo($ticket1->getType()) - ->integer['items_id']->isIdenticalTo($ticket1->getID()); + $this->assertSame($ticket1->getType(), $kb['itemtype']); + $this->assertSame($ticket1->getID(), $kb['items_id']); } $computer21 = getItemByTypeName(\Computer::getType(), '_test_pc21'); $kbs = \KnowbaseItem_Item::getItems($computer21); - $this->array($kbs)->hasSize(1); + $this->assertCount(1, $kbs); foreach ($kbs as $kb) { - $this->array($kb) - ->string['itemtype']->isIdenticalTo($computer21->getType()) - ->integer['items_id']->isIdenticalTo($computer21->getID()); + $this->assertSame($computer21->getType(), $kb['itemtype']); + $this->assertSame($computer21->getID(), $kb['items_id']); } - //test with entitiesrestriction + //test with entitiesrestriction $_SESSION['glpishowallentities'] = 0; $entity = getItemByTypeName(\Entity::getType(), '_test_root_entity'); @@ -171,21 +166,21 @@ public function testGetKbsFromItem() $ticket3 = getItemByTypeName(\Ticket::getType(), '_ticket03'); $kbs = \KnowbaseItem_Item::getItems($ticket3); - $this->array($kbs)->hasSize(0); + $this->assertCount(0, $kbs); $entity = getItemByTypeName(\Entity::getType(), '_test_child_1'); $_SESSION['glpiactiveentities'] = [$entity->getID()]; $ticket3 = getItemByTypeName(\Ticket::getType(), '_ticket03'); $kbs = \KnowbaseItem_Item::getItems($ticket3); - $this->array($kbs)->hasSize(2); + $this->assertCount(2, $kbs); $entity = getItemByTypeName(\Entity::getType(), '_test_child_2'); $_SESSION['glpiactiveentities'] = [$entity->getID()]; $ticket3 = getItemByTypeName(\Ticket::getType(), '_ticket03'); $kbs = \KnowbaseItem_Item::getItems($ticket3); - $this->array($kbs)->hasSize(0); + $this->assertCount(0, $kbs); $_SESSION['glpishowallentities'] = 1; unset($_SESSION['glpiactiveentities']); @@ -199,23 +194,23 @@ public function testGetTabNameForItem() $_SESSION['glpishow_count_on_tabs'] = 1; $name = $kb_item->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo('Associated elements <span class=\'badge\'>3</span>'); + $this->assertSame('Associated elements <span class=\'badge\'>3</span>', $name); $_SESSION['glpishow_count_on_tabs'] = 0; $name = $kb_item->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo('Associated elements'); + $this->assertSame('Associated elements', $name); $ticket3 = getItemByTypeName(\Ticket::getType(), '_ticket03'); $_SESSION['glpishow_count_on_tabs'] = 1; $name = $kb_item->getTabNameForItem($ticket3, true); - $this->string($name)->isIdenticalTo('Knowledge base <span class=\'badge\'>2</span>'); + $this->assertSame('Knowledge base <span class=\'badge\'>2</span>', $name); $name = $kb_item->getTabNameForItem($ticket3); - $this->string($name)->isIdenticalTo('Knowledge base <span class=\'badge\'>2</span>'); + $this->assertSame('Knowledge base <span class=\'badge\'>2</span>', $name); $_SESSION['glpishow_count_on_tabs'] = 0; $name = $kb_item->getTabNameForItem($ticket3); - $this->string($name)->isIdenticalTo('Knowledge base'); + $this->assertSame('Knowledge base', $name); } } diff --git a/tests/functional/KnowbaseItem_Revision.php b/phpunit/functional/KnowbaseItem_RevisionTest.php similarity index 71% rename from tests/functional/KnowbaseItem_Revision.php rename to phpunit/functional/KnowbaseItem_RevisionTest.php index ba9ec10b576..71fe592962b 100644 --- a/tests/functional/KnowbaseItem_Revision.php +++ b/phpunit/functional/KnowbaseItem_RevisionTest.php @@ -39,24 +39,24 @@ /* Test for inc/knowbaseitem_revision.class.php */ -class KnowbaseItem_Revision extends DbTestCase +class KnowbaseItem_RevisionTest extends DbTestCase { - public function afterTestMethod($method) + public function tearDown(): void { global $DB; $DB->delete('glpi_knowbaseitems_revisions', [true]); - parent::afterTestMethod($method); + parent::tearDown(); } public function testGetTypeName() { $expected = 'Revision'; - $this->string(\KnowbaseItem_Revision::getTypeName(1))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem_Revision::getTypeName(1)); $expected = 'Revisions'; - $this->string(\KnowbaseItem_Revision::getTypeName(0))->isIdenticalTo($expected); - $this->string(\KnowbaseItem_Revision::getTypeName(2))->isIdenticalTo($expected); - $this->string(\KnowbaseItem_Revision::getTypeName(10))->isIdenticalTo($expected); + $this->assertSame($expected, \KnowbaseItem_Revision::getTypeName(0)); + $this->assertSame($expected, \KnowbaseItem_Revision::getTypeName(2)); + $this->assertSame($expected, \KnowbaseItem_Revision::getTypeName(10)); } public function testNewRevision() @@ -75,24 +75,23 @@ public function testNewRevision() 'glpi_knowbaseitems_revisions', $where ); - $this->integer((int)$nb)->isIdenticalTo(0); + $this->assertEquals(0, $nb); - $this->boolean( + $this->assertTrue( $kb1->update( [ 'id' => $kb1->getID(), 'name' => '_knowbaseitem01-01' ] ) - )->isTrue(); + ); $nb = countElementsInTable( 'glpi_knowbaseitems_revisions', $where ); - $this->integer((int)$nb)->isIdenticalTo(1); + $this->assertEquals(1, $nb); - $rev_id = null; $data = $DB->request([ 'SELECT' => ['MIN' => 'id as id'], 'FROM' => 'glpi_knowbaseitems_revisions' @@ -100,55 +99,54 @@ public function testNewRevision() $rev_id = $data['id']; $kb1->getFromDB($kb1->getID()); - $this->boolean($kb1->revertTo($rev_id))->isTrue(); + $this->assertTrue($kb1->revertTo($rev_id)); $nb = countElementsInTable( 'glpi_knowbaseitems_revisions', $where ); - $this->integer((int)$nb)->isIdenticalTo(2); + $this->assertEquals(2, $nb); - //try a change on contents - $this->boolean( + //try a change on contents + $this->assertTrue( $kb1->update( [ 'id' => $kb1->getID(), 'answer' => \Toolbox::addslashes_deep('Don\'t use paths with spaces, like C:\\Program Files\\MyApp') ] ) - )->isTrue(); + ); - $this->boolean( + $this->assertTrue( $kb1->update( [ 'id' => $kb1->getID(), 'answer' => 'Answer changed' ] ) - )->isTrue(); + ); $nb = countElementsInTable( 'glpi_knowbaseitems_revisions', $where ); - $this->integer((int)$nb)->isIdenticalTo(4); + $this->assertEquals(4, $nb); - $nrev_id = null; $data = $DB->request([ 'SELECT' => new \QueryExpression('MAX(id) AS id'), 'FROM' => 'glpi_knowbaseitems_revisions' ])->current(); $nrev_id = $data['id']; - $this->boolean($kb1->getFromDB($kb1->getID()))->isTrue(); - $this->boolean($kb1->revertTo($nrev_id))->isTrue(); + $this->assertTrue($kb1->getFromDB($kb1->getID())); + $this->assertTrue($kb1->revertTo($nrev_id)); - $this->boolean($kb1->getFromDB($kb1->getID()))->isTrue(); - $this->string($kb1->fields['answer'])->isIdenticalTo('Don\'t use paths with spaces, like C:\\Program Files\\MyApp'); + $this->assertTrue($kb1->getFromDB($kb1->getID())); + $this->assertSame('Don\'t use paths with spaces, like C:\\Program Files\\MyApp', $kb1->fields['answer']); - //reset - $this->boolean($kb1->getFromDB($kb1->getID()))->isTrue(); - $this->boolean($kb1->revertTo($rev_id))->isTrue(); + //reset + $this->assertTrue($kb1->getFromDB($kb1->getID())); + $this->assertTrue($kb1->revertTo($rev_id)); } public function testGetTabNameForItemNotLogged() @@ -159,7 +157,7 @@ public function testGetTabNameForItemNotLogged() $_SESSION['glpishow_count_on_tabs'] = 1; $name = $kb_rev->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo(''); + $this->assertSame('', $name); } public function testGetTabNameForItemLogged() @@ -169,34 +167,34 @@ public function testGetTabNameForItemLogged() $kb_rev = new \KnowbaseItem_Revision(); $kb1 = $this->getNewKbItem(); - $this->boolean( + $this->assertTrue( $kb1->update( [ 'id' => $kb1->getID(), 'name' => '_knowbaseitem01-01' ] ) - )->isTrue(); + ); $_SESSION['glpishow_count_on_tabs'] = 1; $name = $kb_rev->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo('Revision <span class=\'badge\'>1</span>'); + $this->assertSame('Revision <span class=\'badge\'>1</span>', $name); - $this->boolean( + $this->assertTrue( $kb1->update( [ 'id' => $kb1->getID(), 'name' => '_knowbaseitem01-02' ] ) - )->isTrue(); + ); $name = $kb_rev->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo('Revisions <span class=\'badge\'>2</span>'); + $this->assertSame('Revisions <span class=\'badge\'>2</span>', $name); $_SESSION['glpishow_count_on_tabs'] = 0; $name = $kb_rev->getTabNameForItem($kb1); - $this->string($name)->isIdenticalTo('Revisions'); + $this->assertSame('Revisions', $name); } private function getNewKbItem() @@ -207,7 +205,7 @@ private function getNewKbItem() unset($toadd['date_creation']); unset($toadd['date_mod']); $toadd['name'] = $this->getUniqueString(); - $this->integer((int)$kb1->add($toadd))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$kb1->add($toadd)); return $kb1; } } diff --git a/tests/functional/Knowbase.php b/phpunit/functional/KnowbaseTest.php similarity index 83% rename from tests/functional/Knowbase.php rename to phpunit/functional/KnowbaseTest.php index 7a040e234f3..51596be6ed2 100644 --- a/tests/functional/Knowbase.php +++ b/phpunit/functional/KnowbaseTest.php @@ -39,12 +39,12 @@ /* Test for inc/knowbase.class.php */ -class Knowbase extends DbTestCase +class KnowbaseTest extends DbTestCase { public function testGetTreeCategoryList() { - // Create empty categories + // Create empty categories $kbcat = new \KnowbaseItemCategory(); $cat_1_id = $kbcat->add( @@ -53,7 +53,7 @@ public function testGetTreeCategoryList() 'knowbaseitemcategories_id' => 0, ] ); - $this->integer($cat_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cat_1_id); $cat_1_1_id = $kbcat->add( [ @@ -61,7 +61,7 @@ public function testGetTreeCategoryList() 'knowbaseitemcategories_id' => $cat_1_id, ] ); - $this->integer($cat_1_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cat_1_1_id); $cat_1_1_1_id = $kbcat->add( [ @@ -69,7 +69,7 @@ public function testGetTreeCategoryList() 'knowbaseitemcategories_id' => $cat_1_1_id, ] ); - $this->integer($cat_1_1_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cat_1_1_1_id); $cat_1_1_2_id = $kbcat->add( [ @@ -77,7 +77,7 @@ public function testGetTreeCategoryList() 'knowbaseitemcategories_id' => $cat_1_1_id, ] ); - $this->integer($cat_1_1_2_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cat_1_1_2_id); $cat_1_2_id = $kbcat->add( [ @@ -85,7 +85,7 @@ public function testGetTreeCategoryList() 'knowbaseitemcategories_id' => $cat_1_id, ] ); - $this->integer($cat_1_2_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cat_1_2_id); $cat_1_2_1_id = $kbcat->add( [ @@ -93,7 +93,7 @@ public function testGetTreeCategoryList() 'knowbaseitemcategories_id' => $cat_1_2_id, ] ); - $this->integer($cat_1_2_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cat_1_2_1_id); $cat_1_3_id = $kbcat->add( [ @@ -101,12 +101,12 @@ public function testGetTreeCategoryList() 'knowbaseitemcategories_id' => $cat_1_id, ] ); - $this->integer($cat_1_3_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cat_1_3_id); - // Returned tree should only containes root, as categories does not contains any elements + // Returned tree should only containes root, as categories does not contain any elements $this->login('normal', 'normal'); - // Expected root category item for normal user + // Expected root category item for normal user $expected_root_cat = [ 'key' => 0, 'parent' => null, @@ -115,16 +115,16 @@ public function testGetTreeCategoryList() ]; $tree = \Knowbase::getTreeCategoryList(); - $this->array($tree)->isEqualTo([$expected_root_cat]); + $this->assertEquals([$expected_root_cat], $tree); - // Add a private item (not FAQ) + // Add a private item (not FAQ) $kbitem = new \KnowbaseItem(); $kbitem_id = $kbitem->add( [ 'users_id' => \Session::getLoginUserID(), ] ); - $this->integer($kbitem_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_id); $kbitem_cat = new \KnowbaseItem_KnowbaseItemCategory(); $kbitem_cat_id = $kbitem_cat->add( @@ -133,7 +133,7 @@ public function testGetTreeCategoryList() 'knowbaseitems_id' => "$kbitem_id", ] ); - $this->integer($kbitem_cat_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_cat_id); $kbitem_target = new \Entity_KnowbaseItem(); $kbitem_target_id = $kbitem_target->add( @@ -143,11 +143,11 @@ public function testGetTreeCategoryList() 'is_recursive' => 1, ] ); - $this->integer($kbitem_target_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_target_id); - // Check that tree contains root + category branch containing kb item of user + // Check that tree contains root + category branch containing kb item of user $tree = \Knowbase::getTreeCategoryList(); - $this->array($tree)->isEqualTo( + $this->assertEquals( [ array_merge($expected_root_cat, [ 'children' => [ @@ -175,17 +175,18 @@ public function testGetTreeCategoryList() ], ] ]), - ] + ], + $tree ); - // Add 2nd category + // Add 2nd category $kbitem_cat_id = $kbitem_cat->add( [ 'knowbaseitemcategories_id' => "$cat_1_3_id", 'knowbaseitems_id' => "$kbitem_id", ] ); - $this->integer($kbitem_cat_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_cat_id); $kbitem_target = new \Entity_KnowbaseItem(); $kbitem_target_id = $kbitem_target->add( @@ -195,11 +196,11 @@ public function testGetTreeCategoryList() 'is_recursive' => 1, ] ); - $this->integer($kbitem_target_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_target_id); - // Check that tree contains root + category branch containing kb item of user + // Check that tree contains root + category branch containing kb item of user $tree = \Knowbase::getTreeCategoryList(); - $this->array($tree)->isEqualTo( + $this->assertEquals( [ array_merge($expected_root_cat, [ 'children' => [ @@ -233,17 +234,18 @@ public function testGetTreeCategoryList() ], ] ]), - ] + ], + $tree ); - // Add a FAQ item + // Add a FAQ item $kbitem = new \KnowbaseItem(); $kbitem_id = $kbitem->add( [ 'is_faq' => 1, ] ); - $this->integer($kbitem_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_id); $kbitem_cat = new \KnowbaseItem_KnowbaseItemCategory(); $kbitem_cat_id = $kbitem_cat->add( @@ -252,7 +254,7 @@ public function testGetTreeCategoryList() 'knowbaseitems_id' => "$kbitem_id", ] ); - $this->integer($kbitem_cat_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_cat_id); $kbitem_target = new \Entity_KnowbaseItem(); $kbitem_target_id = $kbitem_target->add( @@ -262,9 +264,9 @@ public function testGetTreeCategoryList() 'is_recursive' => 1, ] ); - $this->integer($kbitem_target_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $kbitem_target_id); - // Expected root category item for anonymous user + // Expected root category item for anonymous user $expected_root_cat = [ 'key' => 0, 'parent' => null, @@ -272,24 +274,24 @@ public function testGetTreeCategoryList() 'a_attr' => ['data-id' => 0] ]; - // Check that tree contains root only (FAQ is not public) for anonymous user - // Force session reset + // Check that tree contains root only (FAQ is not public) for anonymous user + // Force session reset $session_bck = $_SESSION; $this->resetSession(); $tree_with_no_public_faq = \Knowbase::getTreeCategoryList(); - // Check that tree contains root + category branch containing FAQ item (FAQ is public) for anonymous user + // Check that tree contains root + category branch containing FAQ item (FAQ is public) for anonymous user global $CFG_GLPI; $use_public_faq_bck = $CFG_GLPI['use_public_faq']; $CFG_GLPI['use_public_faq'] = 1; $tree_with_public_faq = \Knowbase::getTreeCategoryList(); - // Put back globals + // Put back globals $_SESSION = $session_bck; $CFG_GLPI['use_public_faq'] = $use_public_faq_bck; - $this->array($tree_with_no_public_faq)->isEqualTo([$expected_root_cat]); - $this->array($tree_with_public_faq)->isEqualTo( + $this->assertEquals([$expected_root_cat], $tree_with_no_public_faq); + $this->assertEquals( [ array_merge($expected_root_cat, [ 'children' => [ @@ -317,7 +319,8 @@ public function testGetTreeCategoryList() ] ], ]), - ] + ], + $tree_with_public_faq ); } } diff --git a/tests/functional/LineOperator.php b/phpunit/functional/LineOperatorTest.php similarity index 68% rename from tests/functional/LineOperator.php rename to phpunit/functional/LineOperatorTest.php index d2f6772b8cd..55ceef4ccf9 100644 --- a/tests/functional/LineOperator.php +++ b/phpunit/functional/LineOperatorTest.php @@ -37,40 +37,27 @@ use DbTestCase; -class LineOperator extends DbTestCase +class LineOperatorTest extends DbTestCase { - private $method; - - public function beforeTestMethod($method) - { - parent::beforeTestMethod($method); - //to handle GLPI barbarian replacements. - $this->method = str_replace( - ['\\', 'beforeTestMethod'], - ['', $method], - __METHOD__ - ); - } - public function testAdd() { $this->login(); $obj = new \LineOperator(); - // Add + // Add $in = [ - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -79,27 +66,27 @@ public function testUpdate() $this->login(); $obj = new \LineOperator(); - // Add + // Add $id = $obj->add([ 'name' => $this->getUniqueString(), 'comment' => $this->getUniqueString(), 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Update + // Update $id = $obj->getID(); $in = [ 'id' => $id, - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -108,16 +95,16 @@ public function testDelete() $this->login(); $obj = new \LineOperator(); - // Add + // Add $id = $obj->add([ - 'name' => $this->method, + 'name' => __METHOD__, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Delete + // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/LineType.php b/phpunit/functional/LineTypeTest.php similarity index 67% rename from tests/functional/LineType.php rename to phpunit/functional/LineTypeTest.php index be79be289d4..b72ce81c135 100644 --- a/tests/functional/LineType.php +++ b/phpunit/functional/LineTypeTest.php @@ -37,21 +37,8 @@ use DbTestCase; -class LineType extends DbTestCase +class LineTypeTest extends DbTestCase { - private $method; - - public function beforeTestMethod($method) - { - parent::beforeTestMethod($method); - //to handle GLPI barbarian replacements. - $this->method = str_replace( - ['\\', 'beforeTestMethod'], - ['', $method], - __METHOD__ - ); - } - public function testAdd() { $this->login(); @@ -59,17 +46,21 @@ public function testAdd() // Add $in = [ - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), ]; $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); + $this->assertEquals($id, $obj->getField('id')); foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v, "The property $k does not match: expected $v, got " . $obj->getField($k)); + $this->assertEquals( + $v, + $obj->getField($k), + "The property $k does not match: expected $v, got " . $obj->getField($k) + ); } } @@ -83,21 +74,21 @@ public function testUpdate() 'name' => $this->getUniqueString(), 'comment' => $this->getUniqueString(), ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Update $id = $obj->getID(); $in = [ 'id' => $id, - 'name' => $this->method, + 'name' => __METHOD__, 'comment' => $this->getUniqueString(), ]; - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertTrue($obj->update($in)); + $this->assertTrue($obj->getFromDB($id)); // getField methods foreach ($in as $k => $v) { - $this->variable($obj->getField($k))->isEqualTo($v); + $this->assertEquals($v, $obj->getField($k)); } } @@ -108,14 +99,14 @@ public function testDelete() // Add $id = $obj->add([ - 'name' => $this->method, + 'name' => __METHOD__, ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); // Delete $in = [ 'id' => $obj->getID(), ]; - $this->boolean($obj->delete($in))->isTrue(); + $this->assertTrue($obj->delete($in)); } } diff --git a/tests/functional/Link.php b/phpunit/functional/LinkTest.php similarity index 89% rename from tests/functional/Link.php rename to phpunit/functional/LinkTest.php index 1b8c8bb680d..ce41f9e97b4 100644 --- a/tests/functional/Link.php +++ b/phpunit/functional/LinkTest.php @@ -37,79 +37,18 @@ use DbTestCase; -class Link extends DbTestCase +class LinkTest extends DbTestCase { - protected function linkContentProvider(): iterable + public static function linkContentProvider(): iterable { - $this->login(); - - // Create network - $network = $this->createItem( - \Network::class, - [ - 'name' => 'LAN', - ] - ); - - // Create computer - $item = $this->createItem( - \Computer::class, - [ - 'name' => 'Test computer', - 'serial' => 'ABC0004E6', - 'otherserial' => 'X0000015', - 'uuid' => 'c938f085-4192-4473-a566-46734bbaf6ad', - 'entities_id' => $_SESSION['glpiactive_entity'], - 'groups_id' => getItemByTypeName(\Group::class, '_test_group_1', true), - 'locations_id' => getItemByTypeName(\Location::class, '_location01', true), - 'networks_id' => $network->getID(), - 'users_id' => getItemByTypeName(\User::class, 'glpi', true), - 'computermodels_id' => getItemByTypeName(\ComputerModel::class, '_test_computermodel_1', true), - ] - ); - - // Attach domains - $domain1 = $this->createItem( - \Domain::class, - [ - 'name' => 'domain1.tld', - 'entities_id' => $_SESSION['glpiactive_entity'], - ] - ); - $this->createItem( - \Domain_Item::class, - [ - 'domains_id' => $domain1->getID(), - 'itemtype' => \Computer::class, - 'items_id' => $item->getID(), - ] - ); - $domain2 = $this->createItem( - \Domain::class, - [ - 'name' => 'domain2.tld', - 'entities_id' => $_SESSION['glpiactive_entity'], - ] - ); - $this->createItem( - \Domain_Item::class, - [ - 'domains_id' => $domain2->getID(), - 'itemtype' => \Computer::class, - 'items_id' => $item->getID(), - ] - ); - // Empty link yield [ 'link' => '', - 'item' => $item, 'safe_url' => false, 'expected' => [''], ]; yield [ 'link' => '', - 'item' => $item, 'safe_url' => true, 'expected' => ['#'], ]; @@ -118,7 +57,6 @@ protected function linkContentProvider(): iterable // Link that is actually a title (it is a normal usage!) yield [ 'link' => '[LOCATION] > [SERIAL]/[MODEL] ([USER])', - 'item' => $item, 'safe_url' => $safe_url, 'expected' => [$safe_url ? '#' : '_location01 > ABC0004E6/_test_computermodel_1 (glpi)'], ]; @@ -134,13 +72,12 @@ protected function linkContentProvider(): iterable domain: [DOMAIN] ([NETWORK]) owner: [USER]/[GROUP] TEXT, - 'item' => $item, 'safe_url' => $safe_url, 'expected' => [ $safe_url ? '#' : <<<TEXT -id: {$item->getID()} +id: %ITEM_ID% name: Test computer serial: ABC0004E6/X0000015 model: _test_computermodel_1 @@ -154,7 +91,6 @@ protected function linkContentProvider(): iterable // Valid http link yield [ 'link' => 'https://[LOGIN]@[DOMAIN]/[FIELD:uuid]/', - 'item' => $item, 'safe_url' => $safe_url, 'expected' => ['https://_test_user@domain1.tld/c938f085-4192-4473-a566-46734bbaf6ad/'], ]; @@ -163,13 +99,11 @@ protected function linkContentProvider(): iterable // Javascript link yield [ 'link' => 'javascript:alert(1);" title="[NAME]"', - 'item' => $item, 'safe_url' => false, 'expected' => ['javascript:alert(1);" title="Test computer"'], ]; yield [ 'link' => 'javascript:alert(1);" title="[NAME]"', - 'item' => $item, 'safe_url' => true, 'expected' => ['#'], ]; @@ -180,18 +114,81 @@ protected function linkContentProvider(): iterable */ public function testGenerateLinkContents( string $link, - \CommonDBTM $item, bool $safe_url, array $expected ): void { - $this->newTestedInstance(); - $this->array($this->testedInstance->generateLinkContents($link, $item, $safe_url)) - ->isEqualTo($expected); + $this->login(); + + // Create network + $network = $this->createItem( + \Network::class, + [ + 'name' => 'LAN', + ] + ); + + // Create computer + $item = $this->createItem( + \Computer::class, + [ + 'name' => 'Test computer', + 'serial' => 'ABC0004E6', + 'otherserial' => 'X0000015', + 'uuid' => 'c938f085-4192-4473-a566-46734bbaf6ad', + 'entities_id' => $_SESSION['glpiactive_entity'], + 'groups_id' => getItemByTypeName(\Group::class, '_test_group_1', true), + 'locations_id' => getItemByTypeName(\Location::class, '_location01', true), + 'networks_id' => $network->getID(), + 'users_id' => getItemByTypeName(\User::class, 'glpi', true), + 'computermodels_id' => getItemByTypeName(\ComputerModel::class, '_test_computermodel_1', true), + ] + ); + + // Attach domains + $domain1 = $this->createItem( + \Domain::class, + [ + 'name' => 'domain1.tld', + 'entities_id' => $_SESSION['glpiactive_entity'], + ] + ); + $this->createItem( + \Domain_Item::class, + [ + 'domains_id' => $domain1->getID(), + 'itemtype' => \Computer::class, + 'items_id' => $item->getID(), + ] + ); + $domain2 = $this->createItem( + \Domain::class, + [ + 'name' => 'domain2.tld', + 'entities_id' => $_SESSION['glpiactive_entity'], + ] + ); + $this->createItem( + \Domain_Item::class, + [ + 'domains_id' => $domain2->getID(), + 'itemtype' => \Computer::class, + 'items_id' => $item->getID(), + ] + ); + + $instance = new \Link(); + $expected = str_replace('%ITEM_ID%', $item->getID(), $expected); + $this->assertEquals( + $expected, + $instance->generateLinkContents($link, $item, $safe_url) + ); // Validates that default values is true if ($safe_url) { - $this->array($this->testedInstance->generateLinkContents($link, $item)) - ->isEqualTo($expected); + $this->assertEquals( + $expected, + $instance->generateLinkContents($link, $item) + ); } } } diff --git a/tests/functional/SavedSearch.php b/phpunit/functional/SavedSearchTest.php similarity index 74% rename from tests/functional/SavedSearch.php rename to phpunit/functional/SavedSearchTest.php index a3af5578aa5..17b63403493 100644 --- a/tests/functional/SavedSearch.php +++ b/phpunit/functional/SavedSearchTest.php @@ -37,9 +37,11 @@ use DbTestCase; +use function PHPUnit\Framework\assertContains; + /* Test for inc/savedsearch.class.php */ -class SavedSearch extends DbTestCase +class SavedSearchTest extends DbTestCase { public function testGetVisibilityCriteria() { @@ -47,21 +49,25 @@ public function testGetVisibilityCriteria() $this->setEntity('_test_root_entity', true); // No restrictions when having the config UPDATE right - $this->array(\SavedSearch::getVisibilityCriteria())->isEqualTo(['WHERE' => []]); + $this->assertEquals( + ['WHERE' => []], + \SavedSearch::getVisibilityCriteria() + ); $_SESSION["glpiactiveprofile"]['config'] = $_SESSION["glpiactiveprofile"]['config'] & ~UPDATE; - $this->array(\SavedSearch::getVisibilityCriteria()['WHERE'])->isNotEmpty(); + $this->assertNotEmpty(\SavedSearch::getVisibilityCriteria()['WHERE']); } public function testAddVisibilityRestrict() { //first, as a super-admin $this->login(); - $this->string(\SavedSearch::addVisibilityRestrict()) - ->isIdenticalTo(''); + $this->assertSame('', \SavedSearch::addVisibilityRestrict()); $this->login('normal', 'normal'); - $this->string(\SavedSearch::addVisibilityRestrict()) - ->isIdenticalTo("`glpi_savedsearches`.`is_private` = '1' AND `glpi_savedsearches`.`users_id` = '5'"); + $this->assertSame( + "`glpi_savedsearches`.`is_private` = '1' AND `glpi_savedsearches`.`users_id` = '5'", + \SavedSearch::addVisibilityRestrict() + ); //add public saved searches read right for normal profile global $DB; @@ -77,13 +83,17 @@ public function testAddVisibilityRestrict() //ACLs have changed: login again. $this->login('normal', 'normal'); - $this->string(\SavedSearch::addVisibilityRestrict()) - ->isIdenticalTo("((`glpi_savedsearches`.`is_private` = '1' AND `glpi_savedsearches`.`users_id` = '5') OR (`glpi_savedsearches`.`is_private` = '0'))"); + $this->assertSame( + "((`glpi_savedsearches`.`is_private` = '1' AND `glpi_savedsearches`.`users_id` = '5') OR (`glpi_savedsearches`.`is_private` = '0'))", + \SavedSearch::addVisibilityRestrict() + ); // Check entity restriction $this->setEntity('_test_root_entity', true); - $this->string(\SavedSearch::addVisibilityRestrict()) - ->isIdenticalTo("((`glpi_savedsearches`.`is_private` = '1' AND `glpi_savedsearches`.`users_id` = '5') OR (`glpi_savedsearches`.`is_private` = '0')) AND ((`glpi_savedsearches`.`entities_id` IN ('1', '2', '3') OR (`glpi_savedsearches`.`is_recursive` = '1' AND `glpi_savedsearches`.`entities_id` IN ('0'))))"); + $this->assertSame( + "((`glpi_savedsearches`.`is_private` = '1' AND `glpi_savedsearches`.`users_id` = '5') OR (`glpi_savedsearches`.`is_private` = '0')) AND ((`glpi_savedsearches`.`entities_id` IN ('1', '2', '3') OR (`glpi_savedsearches`.`is_recursive` = '1' AND `glpi_savedsearches`.`entities_id` IN ('0'))))", + \SavedSearch::addVisibilityRestrict() + ); } public function testGetMine() @@ -101,7 +111,7 @@ public function testGetMine() // now add a bookmark on Ticket view $bk = new \SavedSearch(); - $this->boolean( + $this->assertTrue( (bool)$bk->add([ 'name' => 'public root recursive', 'type' => 1, @@ -112,8 +122,8 @@ public function testGetMine() 'is_recursive' => 1, 'url' => 'front/ticket.php?itemtype=Ticket&sort=2&order=DESC&start=0&criteria[0][field]=5&criteria[0][searchtype]=equals&criteria[0][value]=' . $tuuser_id ]) - )->isTrue(); - $this->boolean( + ); + $this->assertTrue( (bool)$bk->add([ 'name' => 'public root NOT recursive', 'type' => 1, @@ -124,8 +134,8 @@ public function testGetMine() 'is_recursive' => 0, 'url' => 'front/ticket.php?itemtype=Ticket&sort=2&order=DESC&start=0&criteria[0][field]=5&criteria[0][searchtype]=equals&criteria[0][value]=' . $tuuser_id ]) - )->isTrue(); - $this->boolean( + ); + $this->assertTrue( (bool)$bk->add([ 'name' => 'public child 1 recursive', 'type' => 1, @@ -136,9 +146,9 @@ public function testGetMine() 'is_recursive' => 1, 'url' => 'front/ticket.php?itemtype=Ticket&sort=2&order=DESC&start=0&criteria[0][field]=5&criteria[0][searchtype]=equals&criteria[0][value]=' . $tuuser_id ]) - )->isTrue(); + ); - $this->boolean( + $this->assertTrue( (bool)$bk->add([ 'name' => 'private TU_USER', 'type' => 1, @@ -149,9 +159,9 @@ public function testGetMine() 'is_recursive' => 1, 'url' => 'front/ticket.php?itemtype=Ticket&sort=2&order=DESC&start=0&criteria[0][field]=5&criteria[0][searchtype]=equals&criteria[0][value]=' . $tuuser_id ]) - )->isTrue(); + ); - $this->boolean( + $this->assertTrue( (bool)$bk->add([ 'name' => 'private normal user', 'type' => 1, @@ -162,7 +172,7 @@ public function testGetMine() 'is_recursive' => 1, 'url' => 'front/ticket.php?itemtype=Ticket&sort=2&order=DESC&start=0&criteria[0][field]=5&criteria[0][searchtype]=equals&criteria[0][value]=' . $tuuser_id ]) - )->isTrue(); + ); // With UPDATE 'config' right, we still shouldn't see other user's private searches $expected = [ 'public root recursive', @@ -171,18 +181,27 @@ public function testGetMine() 'private TU_USER', ]; $mine = $bk->getMine(); - $this->array($mine)->hasSize(count($expected)); - $this->array(array_column($mine, 'name'))->containsValues($expected); + $this->assertCount(count($expected), $mine); + $this->assertEqualsCanonicalizing( + $expected, + array_column($mine, 'name') + ); $_SESSION["glpiactiveprofile"]['config'] = $_SESSION["glpiactiveprofile"]['config'] & ~UPDATE; - $this->array($mine)->hasSize(count($expected)); - $this->array(array_column($mine, 'name'))->containsValues($expected); + $this->assertCount(count($expected), $mine); + $this->assertEqualsCanonicalizing( + $expected, + array_column($mine, 'name') + ); // Normal user cannot see public saved searches by default $this->login('normal', 'normal'); $mine = $bk->getMine(); - $this->array($mine)->hasSize(1); - $this->array(array_column($mine, 'name'))->containsValues(['private normal user']); + $this->assertCount(1, $mine); + $this->assertEqualsCanonicalizing( + ['name' => 'private normal user'], + array_column($mine, 'name') + ); //add public saved searches read right for normal profile $DB->update( @@ -201,8 +220,11 @@ public function testGetMine() 'private normal user', ]; $mine = $bk->getMine('Ticket'); - $this->array($mine)->hasSize(count($expected)); - $this->array(array_column($mine, 'name'))->containsValues($expected); + $this->assertCount(count($expected), $mine); + $this->assertEqualsCanonicalizing( + $expected, + array_column($mine, 'name') + ); // Check entity restrictions $this->setEntity('_test_root_entity', false); @@ -212,8 +234,11 @@ public function testGetMine() 'private normal user', ]; $mine = $bk->getMine('Ticket'); - $this->array($mine)->hasSize(count($expected)); - $this->array(array_column($mine, 'name'))->containsValues($expected); + $this->assertCount(count($expected), $mine); + $this->assertEqualsCanonicalizing( + $expected, + array_column($mine, 'name') + ); $this->setEntity('_test_child_1', true); $expected = [ @@ -222,8 +247,11 @@ public function testGetMine() 'private normal user', ]; $mine = $bk->getMine('Ticket'); - $this->array($mine)->hasSize(count($expected)); - $this->array(array_column($mine, 'name'))->containsValues($expected); + $this->assertCount(count($expected), $mine); + $this->assertEqualsCanonicalizing( + $expected, + array_column($mine, 'name') + ); $this->setEntity('_test_child_1', false); $expected = [ @@ -232,7 +260,10 @@ public function testGetMine() 'private normal user', ]; $mine = $bk->getMine('Ticket'); - $this->array($mine)->hasSize(count($expected)); - $this->array(array_column($mine, 'name'))->containsValues($expected); + $this->assertCount(count($expected), $mine); + $this->assertEqualsCanonicalizing( + $expected, + array_column($mine, 'name') + ); } } diff --git a/tests/functional/SavedSearch_User.php b/phpunit/functional/SavedSearch_UserTest.php similarity index 76% rename from tests/functional/SavedSearch_User.php rename to phpunit/functional/SavedSearch_UserTest.php index 3974570543e..7c95b2be086 100644 --- a/tests/functional/SavedSearch_User.php +++ b/phpunit/functional/SavedSearch_UserTest.php @@ -39,7 +39,7 @@ /* Test for inc/savedsearch_user.class.php */ -class SavedSearch_User extends DbTestCase +class SavedSearch_UserTest extends DbTestCase { public function testGetDefault() { @@ -49,13 +49,13 @@ public function testGetDefault() $uid = getItemByTypeName('User', TU_USER, true); // with no default bookmark - $this->boolean( - (bool)\SavedSearch_User::getDefault($uid, 'Ticket') - )->isFalse(); + $this->assertFalse( + \SavedSearch_User::getDefault($uid, 'Ticket') + ); - // now add a bookmark on Ticket view + // now add a bookmark on Ticket view $bk = new \SavedSearch(); - $this->boolean( + $this->assertTrue( (bool)$bk->add(['name' => 'All my tickets', 'type' => 1, 'itemtype' => 'Ticket', @@ -65,32 +65,34 @@ public function testGetDefault() 'is_recursive' => 1, 'url' => 'front/ticket.php?itemtype=Ticket&sort=2&order=DESC&start=0&criteria[0][field]=5&criteria[0][searchtype]=equals&criteria[0][value]=' . $uid ]) - )->isTrue(); + ); $bk_id = $bk->fields['id']; $bk_user = new \SavedSearch_User(); - $this->boolean( + $this->assertTrue( (bool)$bk_user->add(['users_id' => $uid, 'itemtype' => 'Ticket', 'savedsearches_id' => $bk_id ]) - )->isTrue(); + ); // should get a default bookmark $bk = \SavedSearch_User::getDefault($uid, 'Ticket'); - $this->array( - $bk - )->isEqualTo(['itemtype' => 'Ticket', - 'sort' => '2', - 'order' => 'DESC', - 'savedsearches_id' => $bk_id, - 'criteria' => [0 => ['field' => '5', - 'searchtype' => 'equals', - 'value' => $uid - ] + $this->assertEquals( + [ + 'itemtype' => 'Ticket', + 'sort' => '2', + 'order' => 'DESC', + 'savedsearches_id' => $bk_id, + 'criteria' => [0 => ['field' => '5', + 'searchtype' => 'equals', + 'value' => $uid + ] + ], + 'reset' => 'reset', ], - 'reset' => 'reset', - ]); + $bk + ); } } diff --git a/phpunit/functional/ToolboxTest.php b/phpunit/functional/ToolboxTest.php index efe37e2186e..0fcd2c938cb 100644 --- a/phpunit/functional/ToolboxTest.php +++ b/phpunit/functional/ToolboxTest.php @@ -1250,7 +1250,7 @@ public function testGetDocumentsFromTag() // Create a document to emulate a document upload $filename = 'foo.png'; - copy(__DIR__ . '/../../tests/fixtures/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); + copy(FIXTURE_DIR . '/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); $tag = \Rule::getUuid(); $input = [ 'filename' => 'foo.png', diff --git a/tests/functional/User.php b/phpunit/functional/UserTest.php similarity index 62% rename from tests/functional/User.php rename to phpunit/functional/UserTest.php index ca5fcde71f8..7f5b4947b82 100644 --- a/tests/functional/User.php +++ b/phpunit/functional/UserTest.php @@ -36,69 +36,72 @@ namespace tests\units; use Glpi\Toolbox\Sanitizer; +use Monolog\Logger; use Profile_User; use QuerySubQuery; /* Test for inc/user.class.php */ -class User extends \DbTestCase +class UserTest extends \DbTestCase { public function testGenerateUserToken() { - $this->login(TU_USER, TU_PASS); // must be authenticated to be able to regenerate self personal token + $this->login(); // must be authenticated to be able to regenerate self personal token $user = getItemByTypeName('User', TU_USER); - $this->variable($user->fields['personal_token_date'])->isNull(); - $this->variable($user->fields['personal_token'])->isNull(); + $this->assertNull($user->fields['personal_token_date']); + $this->assertNull($user->fields['personal_token']); $token = $user->getAuthToken(); - $this->string($token)->isNotEmpty(); + $this->assertNotEmpty($token); $user->getFromDB($user->getID()); - $this->string($user->fields['personal_token'])->isIdenticalTo($token); - $this->string($user->fields['personal_token_date'])->isIdenticalTo($_SESSION['glpi_currenttime']); + $this->assertSame($token, $user->fields['personal_token']); + $this->assertSame($_SESSION['glpi_currenttime'], $user->fields['personal_token_date']); } - /** - * - */ - public function testLostPassword() + public function testLostPasswordInvalidMail() { $user = getItemByTypeName('User', TU_USER); - // Test request for a password with invalid email - $this->when( - function () use ($user) { - $user->forgetPassword('this-email-does-not-exists@example.com'); - } - )->error() - ->withType(E_USER_WARNING) - ->withMessage("Failed to find a single user for 'this-email-does-not-exists@example.com', 0 user(s) found.") - ->exists(); - - // Test request for a password - $result = $user->forgetPassword($user->getDefaultEmail()); - $this->boolean($result)->isTrue(); + $res = $user->forgetPassword('this-email-does-not-exists@example.com'); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + "Failed to find a single user for 'this-email-does-not-exists@example.com', 0 user(s) found.", + Logger::WARNING + ); + } + public function testLostPasswordInvalidToken() + { + $user = getItemByTypeName('User', TU_USER); // Test reset password with a bad token + $result = $user->forgetPassword($user->getDefaultEmail()); + $this->assertTrue($result); $token = $user->fields['password_forget_token']; - $this->string($token)->isNotEmpty(); + $this->assertNotEmpty($token); $input = [ 'password_forget_token' => $token . 'bad', 'password' => TU_PASS, 'password2' => TU_PASS ]; - $this->exception( - function () use ($user, $input) { - $user->updateForgottenPassword($input); - } - ) - ->isInstanceOf(\Glpi\Exception\ForgetPasswordException::class); + $this->expectException(\Glpi\Exception\ForgetPasswordException::class); + $user->updateForgottenPassword($input); + } + + public function testLostPassword() + { + $user = getItemByTypeName('User', TU_USER); + + // Test request for a password + $result = $user->forgetPassword($user->getDefaultEmail()); + $this->assertTrue($result); // Test reset password with good token // 1 - Refresh the in-memory instance of user and get the current password $user->getFromDB($user->getID()); + $token = $user->fields['password_forget_token']; // 2 - Set a new password $input = [ @@ -109,16 +112,16 @@ function () use ($user, $input) { // 3 - check the update succeeds $result = $user->updateForgottenPassword($input); - $this->boolean($result)->isTrue(); + $this->assertTrue($result); $newHash = $user->fields['password']; // Test the new password was saved - $this->variable(\Auth::checkPassword('NewPassword', $newHash))->isNotFalse(); + $this->assertNotSame(false, \Auth::checkPassword('NewPassword', $newHash)); // Validates that password reset token has been removed $user = getItemByTypeName('User', TU_USER); $token = $user->fields['password_forget_token']; - $this->string($token)->isEmpty(); + $this->assertEmpty($token); } public function testGetDefaultEmail() @@ -127,9 +130,9 @@ public function testGetDefaultEmail() $user = new \User(); - $this->string($user->getDefaultEmail())->isIdenticalTo(''); - $this->array($user->getAllEmails())->isIdenticalTo([]); - $this->boolean($user->isEmail('one@test.com'))->isFalse(); + $this->assertSame('', $user->getDefaultEmail()); + $this->assertSame([], $user->getAllEmails()); + $this->assertFalse($user->isEmail('one@test.com')); $uid = (int)$user->add([ 'name' => 'test_email', @@ -137,26 +140,26 @@ public function testGetDefaultEmail() 'one@test.com' ] ]); - $this->integer($uid)->isGreaterThan(0); - $this->boolean($user->getFromDB($user->fields['id']))->isTrue(); - $this->string($user->getDefaultEmail())->isIdenticalTo('one@test.com'); + $this->assertGreaterThan(0, $uid); + $this->assertTrue($user->getFromDB($user->fields['id'])); + $this->assertSame('one@test.com', $user->getDefaultEmail()); - $this->boolean( + $this->assertTrue( $user->update([ 'id' => $uid, '_useremails' => ['two@test.com'], '_default_email' => 0 ]) - )->isTrue(); + ); - $this->boolean($user->getFromDB($user->fields['id']))->isTrue(); - $this->string($user->getDefaultEmail())->isIdenticalTo('two@test.com'); + $this->assertTrue($user->getFromDB($user->fields['id'])); + $this->assertSame('two@test.com', $user->getDefaultEmail()); - $this->array($user->getAllEmails())->hasSize(2); - $this->boolean($user->isEmail('one@test.com'))->isTrue(); + $this->assertCount(2, $user->getAllEmails()); + $this->assertTrue($user->isEmail('one@test.com')); $tu_user = getItemByTypeName('User', TU_USER); - $this->boolean($user->isEmail($tu_user->getDefaultEmail()))->isFalse(); + $this->assertFalse($user->isEmail($tu_user->getDefaultEmail())); } public function testUpdateEmail() @@ -173,30 +176,31 @@ public function testUpdateEmail() -3 => 'email3@test.com', ] ]); - $this->integer($uid1)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid1); // Emails are all attached to user 1 $user1_email1_id = current( getAllDataFromTable(\UserEmail::getTable(), ['users_id' => $uid1, 'email' => 'email1@test.com']) )['id'] ?? 0; - $this->integer($user1_email1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $user1_email1_id); - $this->string($user1->getDefaultEmail())->isIdenticalTo('email1@test.com'); + $this->assertSame('email1@test.com', $user1->getDefaultEmail()); - $this->boolean($user1->getFromDB($uid1))->isTrue(); + $this->assertTrue($user1->getFromDB($uid1)); $user1_emails = $user1->getAllEmails(); asort($user1_emails); - $this->array(array_values($user1_emails))->isEqualTo( + $this->assertEquals( [ 'email1@test.com', 'email2@test.com', 'email3@test.com', - ] + ], + array_values($user1_emails) ); // Create another user $user2 = new \User(); - $uid2 = (int)$user2->add([ + $uid2 = $user2->add([ 'name' => 'test_email 2', '_useremails' => [ -1 => 'anotheremail1@test.com', @@ -204,37 +208,39 @@ public function testUpdateEmail() -3 => 'anotheremail3@test.com', ] ]); - $this->integer($uid2)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid2); // Emails are all attached to user 2 $user2_email1_id = current( getAllDataFromTable(\UserEmail::getTable(), ['users_id' => $uid2, 'email' => 'anotheremail1@test.com']) )['id'] ?? 0; - $this->integer($user2_email1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $user2_email1_id); - $this->string($user2->getDefaultEmail())->isIdenticalTo('anotheremail1@test.com'); + $this->assertSame('anotheremail1@test.com', $user2->getDefaultEmail()); - $this->boolean($user2->getFromDB($uid2))->isTrue(); + $this->assertTrue($user2->getFromDB($uid2)); $user2_emails = $user2->getAllEmails(); asort($user2_emails); - $this->array(array_values($user2_emails))->isEqualTo( + $this->assertEquals( [ 'anotheremail1@test.com', 'anotheremail2@test.com', 'anotheremail3@test.com', - ] + ], + array_values($user2_emails) ); - // User 1 emails did not changed - $this->boolean($user1->getFromDB($uid1))->isTrue(); + // User 1 emails did not change + $this->assertTrue($user1->getFromDB($uid1)); $user1_emails = $user1->getAllEmails(); asort($user1_emails); - $this->array(array_values($user1_emails))->isEqualTo( + $this->assertEquals( [ 'email1@test.com', 'email2@test.com', 'email3@test.com', - ] + ], + array_values($user1_emails) ); // Update the second user @@ -246,80 +252,87 @@ public function testUpdateEmail() ], '_default_email' => $user1_email1_id, ]); - $this->boolean($update)->isTrue(); + $this->assertTrue($update); // Emails are all attached to user 2 - $this->boolean($user2->getFromDB($uid2))->isTrue(); + $this->assertTrue($user2->getFromDB($uid2)); $user2_emails = $user2->getAllEmails(); asort($user2_emails); - $this->array(array_values($user2_emails))->isEqualTo( + $this->assertEquals( [ 'anotheremail1-update@test.com', 'anotheremail2@test.com', 'anotheremail3@test.com', 'email1-updated@test.com', - ] + ], + array_values($user2_emails) ); - $this->string($user2->getDefaultEmail())->isIdenticalTo('email1-updated@test.com'); + $this->assertSame('email1-updated@test.com', $user2->getDefaultEmail()); - // User 1 emails did not changed - $this->boolean($user1->getFromDB($uid1))->isTrue(); + // User 1 emails did not change + $this->assertTrue($user1->getFromDB($uid1)); $user1_emails = $user1->getAllEmails(); asort($user1_emails); - $this->array(array_values($user1_emails))->isEqualTo( + $this->assertEquals( [ 'email1@test.com', 'email2@test.com', 'email3@test.com', - ] + ], + array_values($user1_emails) + ); + } + + public function testGetFromDBbyTokenWrongField() + { + $user = new \User(); + + $res = $user->getFromDBbyToken('1485dd60301311eda2610242ac12000249aef69a', 'my_field'); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'User::getFromDBbyToken() can only be called with $field parameter with theses values: \'personal_token\', \'api_token\'', + Logger::WARNING + ); + } + + public function testGetFromDBbyTokenNotString() + { + $user = new \User(); + $res = $user->getFromDBbyToken(['REGEX', '.*'], 'api_token'); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Unexpected token value received: "string" expected, received "array".', + Logger::WARNING ); } public function testGetFromDBbyToken() { - $user = $this->newTestedInstance; - $uid = (int)$user->add([ + $user = new \User(); + $uid = $user->add([ 'name' => 'test_token', 'password' => 'test_password', 'password2' => 'test_password', ]); - $this->integer($uid)->isGreaterThan(0); - $this->boolean($user->getFromDB($uid))->isTrue(); + $this->assertGreaterThan(0, $uid); + $this->assertTrue($user->getFromDB($uid)); $this->login('test_token', 'test_password'); // must be authenticated to be able to regenerate self personal token $token = $user->getToken($uid); - $this->boolean($user->getFromDB($uid))->isTrue(); - $this->string($token)->hasLength(40); + $this->assertTrue($user->getFromDB($uid)); + $this->assertEquals(40, strlen($token)); $user2 = new \User(); - $this->boolean($user2->getFromDBbyToken($token))->isTrue(); - $this->array($user2->fields)->isIdenticalTo($user->fields); - - $this->when( - function () { - $this->testedInstance->getFromDBbyToken('1485dd60301311eda2610242ac12000249aef69a', 'my_field'); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('User::getFromDBbyToken() can only be called with $field parameter with theses values: \'personal_token\', \'api_token\'') - ->exists(); - - $this->when( - function () { - $this->testedInstance->getFromDBbyToken(['REGEX', '.*'], 'api_token'); - } - )->error() - ->withType(E_USER_WARNING) - ->withMessage('Unexpected token value received: "string" expected, received "array".') - ->exists(); + $this->assertTrue($user2->getFromDBbyToken($token)); + $this->assertSame($user->fields, $user2->fields); } public function testPrepareInputForAdd() { $this->login(); - $user = $this->newTestedInstance(); + $user = new \User(); $input = [ 'name' => 'prepare_for_add' @@ -334,19 +347,19 @@ public function testPrepareInputForAdd() 'profiles_id' => 0 ]; - $this->array($user->prepareInputForAdd($input))->isIdenticalTo($expected); + $this->assertSame($expected, $user->prepareInputForAdd($input)); $input['_stop_import'] = 1; - $this->boolean($user->prepareInputForAdd($input))->isFalse(); + $this->assertFalse($user->prepareInputForAdd($input)); $input = ['name' => 'invalid+login']; - $this->boolean($user->prepareInputForAdd($input))->isFalse(); + $this->assertFalse($user->prepareInputForAdd($input)); $this->hasSessionMessages(ERROR, ['The login is not valid. Unable to add the user.']); //add same user twice $input = ['name' => 'new_user']; - $this->integer($user->add($input))->isGreaterThan(0); - $this->boolean($user->add($input))->isFalse(0); + $this->assertGreaterThan(0, $user->add($input)); + $this->assertFalse($user->add($input)); $this->hasSessionMessages(ERROR, ['Unable to add. The user already exists.']); $input = [ @@ -354,7 +367,7 @@ public function testPrepareInputForAdd() 'password' => 'password', 'password2' => 'nomatch' ]; - $this->boolean($user->prepareInputForAdd($input))->isFalse(); + $this->assertFalse($user->prepareInputForAdd($input)); $this->hasSessionMessages(ERROR, ['Error: the two passwords do not match']); $input = [ @@ -372,15 +385,17 @@ public function testPrepareInputForAdd() 'entities_id' => 0, 'profiles_id' => 0 ]; - $this->array($user->prepareInputForAdd($input))->isIdenticalTo($expected); + $this->assertSame($expected, $user->prepareInputForAdd($input)); $input['password'] = 'nomatch'; $expected['password'] = 'unknonwn'; unset($expected['password2']); $prepared = $user->prepareInputForAdd($input); - $this->array($prepared) - ->hasKeys(array_keys($expected)) - ->string['password']->hasLength(60)->startWith('$2y$'); + foreach ($expected as $key => $value) { + $this->assertArrayHasKey($key, $prepared); + } + $this->assertEquals(60, strlen($prepared['password'])); + $this->assertStringStartsWith('$2y$', $prepared['password']); $input['password'] = 'mypass'; $input['password2'] = 'mypass'; @@ -397,10 +412,10 @@ public function testPrepareInputForAdd() 'entities_id' => 0, 'profiles_id' => 0, ]; - $this->array($user->prepareInputForAdd($input))->isIdenticalTo($expected); + $this->assertSame($expected, $user->prepareInputForAdd($input)); } - protected function prepareInputForTimezoneUpdateProvider() + public static function prepareInputForTimezoneUpdateProvider() { return [ [ @@ -434,10 +449,10 @@ protected function prepareInputForTimezoneUpdateProvider() /** * @dataProvider prepareInputForTimezoneUpdateProvider */ - public function testPrepareInputForUpdateTimezone(array $input, $expected) + public function testPrepareInputForUpdateTimezone(array $input, array $expected) { $this->login(); - $user = $this->newTestedInstance(); + $user = new \User(); $username = 'prepare_for_update_' . mt_rand(); $user_id = $user->add( [ @@ -447,7 +462,7 @@ public function testPrepareInputForUpdateTimezone(array $input, $expected) '_profiles_id' => 1 ] ); - $this->integer((int)$user_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$user_id); $this->login($username, 'mypass'); @@ -455,10 +470,10 @@ public function testPrepareInputForUpdateTimezone(array $input, $expected) $result = $user->prepareInputForUpdate($input); $expected = ['id' => $user_id] + $expected; - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } - protected function prepareInputForUpdatePasswordProvider() + public static function prepareInputForUpdatePasswordProvider() { return [ [ @@ -496,7 +511,7 @@ protected function prepareInputForUpdatePasswordProvider() public function testPrepareInputForUpdatePassword(array $input, $expected, array $messages = null) { $this->login(); - $user = $this->newTestedInstance(); + $user = new \User(); $username = 'prepare_for_update_' . mt_rand(); $user_id = $user->add( [ @@ -506,7 +521,7 @@ public function testPrepareInputForUpdatePassword(array $input, $expected, array '_profiles_id' => 1 ] ); - $this->integer((int)$user_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$user_id); $this->login($username, 'initial_pass'); @@ -514,19 +529,19 @@ public function testPrepareInputForUpdatePassword(array $input, $expected, array $result = $user->prepareInputForUpdate($input); if (null !== $messages) { - $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isIdenticalTo($messages); + $this->assertSame($messages, $_SESSION['MESSAGE_AFTER_REDIRECT']); $_SESSION['MESSAGE_AFTER_REDIRECT'] = []; //reset } if (false === $expected) { - $this->boolean($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); return; } if (array_key_exists('password', $expected) && true === $expected['password']) { - // password_hash result is unpredictible, so we cannot test its exact value - $this->array($result)->hasKey('password'); - $this->string($result['password'])->isNotEmpty(); + // password_hash result is unpredictable, so we cannot test its exact value + $this->assertArrayHasKey('password', $result); + $this->assertNotEmpty($result['password']); unset($expected['password']); unset($result['password']); @@ -534,11 +549,11 @@ public function testPrepareInputForUpdatePassword(array $input, $expected, array $expected = ['id' => $user_id] + $expected; if (array_key_exists('password_last_update', $expected) && true === $expected['password_last_update']) { - // $_SESSION['glpi_currenttime'] was reset on login, value cannot be provided by test provider + // $_SESSION['glpi_currenttime'] was reset on login, value cannot be provided by test provider $expected['password_last_update'] = $_SESSION['glpi_currenttime']; } - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } public function testPost_addItem() @@ -547,105 +562,99 @@ public function testPost_addItem() $this->setEntity('_test_root_entity', true); $eid = getItemByTypeName('Entity', '_test_root_entity', true); - $user = $this->newTestedInstance; + $user = new \User(); + ; - //user with a profile + //user with a profile $pid = getItemByTypeName('Profile', 'Technician', true); $uid = (int)$user->add([ 'name' => 'create_user', '_profiles_id' => $pid ]); - $this->integer($uid)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid); - $this->boolean($user->getFromDB($uid))->isTrue(); - $this->array($user->fields) - ->string['name']->isIdenticalTo('create_user') - ->integer['profiles_id']->isEqualTo(0); + $this->assertTrue($user->getFromDB($uid)); + $this->assertSame('create_user', $user->fields['name']); + $this->assertSame(0, $user->fields['profiles_id']); $puser = new \Profile_User(); - $this->boolean($puser->getFromDBByCrit(['users_id' => $uid]))->isTrue(); - $this->array($puser->fields) - ->integer['profiles_id']->isEqualTo($pid) - ->integer['entities_id']->isEqualTo($eid) - ->integer['is_recursive']->isEqualTo(0) - ->integer['is_dynamic']->isEqualTo(0); + $this->assertTrue($puser->getFromDBByCrit(['users_id' => $uid])); + $this->assertSame($pid, $puser->fields['profiles_id']); + $this->assertSame($eid, $puser->fields['entities_id']); + $this->assertSame(0, $puser->fields['is_recursive']); + $this->assertSame(0, $puser->fields['is_dynamic']); $pid = (int)\Profile::getDefault(); - $this->integer($pid)->isGreaterThan(0); + $this->assertGreaterThan(0, $pid); - //user without a profile (will take default one) + //user without a profile (will take default one) $uid2 = (int)$user->add([ 'name' => 'create_user2', ]); - $this->integer($uid2)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid2); - $this->boolean($user->getFromDB($uid2))->isTrue(); - $this->array($user->fields) - ->string['name']->isIdenticalTo('create_user2') - ->integer['profiles_id']->isEqualTo(0); + $this->assertTrue($user->getFromDB($uid2)); + $this->assertSame('create_user2', $user->fields['name']); + $this->assertSame(0, $user->fields['profiles_id']); $puser = new \Profile_User(); - $this->boolean($puser->getFromDBByCrit(['users_id' => $uid2]))->isTrue(); - $this->array($puser->fields) - ->integer['profiles_id']->isEqualTo($pid) - ->integer['entities_id']->isEqualTo($eid) - ->integer['is_recursive']->isEqualTo(0) - ->integer['is_dynamic']->isEqualTo(1); - - //user with entity not recursive + $this->assertTrue($puser->getFromDBByCrit(['users_id' => $uid2])); + $this->assertSame($pid, $puser->fields['profiles_id']); + $this->assertSame($eid, $puser->fields['entities_id']); + $this->assertSame(0, $puser->fields['is_recursive']); + $this->assertSame(1, $puser->fields['is_dynamic']); + + //user with entity not recursive $eid2 = (int)getItemByTypeName('Entity', '_test_child_1', true); - $this->integer($eid2)->isGreaterThan(0); + $this->assertGreaterThan(0, $eid2); $uid3 = (int)$user->add([ 'name' => 'create_user3', '_entities_id' => $eid2 ]); - $this->integer($uid3)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid3); - $this->boolean($user->getFromDB($uid3))->isTrue(); - $this->array($user->fields) - ->string['name']->isIdenticalTo('create_user3'); + $this->assertTrue($user->getFromDB($uid3)); + $this->assertSame('create_user3', $user->fields['name']); $puser = new \Profile_User(); - $this->boolean($puser->getFromDBByCrit(['users_id' => $uid3]))->isTrue(); - $this->array($puser->fields) - ->integer['profiles_id']->isEqualTo($pid) - ->integer['entities_id']->isEqualTo($eid2) - ->integer['is_recursive']->isEqualTo(0) - ->integer['is_dynamic']->isEqualTo(1); - - //user with entity recursive - $uid4 = (int)$user->add([ + $this->assertTrue($puser->getFromDBByCrit(['users_id' => $uid3])); + $this->assertSame($pid, $puser->fields['profiles_id']); + $this->assertSame($eid2, $puser->fields['entities_id']); + $this->assertSame(0, $puser->fields['is_recursive']); + $this->assertSame(1, $puser->fields['is_dynamic']); + + //user with entity recursive + $uid4 = $user->add([ 'name' => 'create_user4', '_entities_id' => $eid2, '_is_recursive' => 1 ]); - $this->integer($uid4)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid4); - $this->boolean($user->getFromDB($uid4))->isTrue(); - $this->array($user->fields) - ->string['name']->isIdenticalTo('create_user4'); + $this->assertTrue($user->getFromDB($uid4)); + $this->assertSame('create_user4', $user->fields['name']); $puser = new \Profile_User(); - $this->boolean($puser->getFromDBByCrit(['users_id' => $uid4]))->isTrue(); - $this->array($puser->fields) - ->integer['profiles_id']->isEqualTo($pid) - ->integer['entities_id']->isEqualTo($eid2) - ->integer['is_recursive']->isEqualTo(1) - ->integer['is_dynamic']->isEqualTo(1); + $this->assertTrue($puser->getFromDBByCrit(['users_id' => $uid4])); + $this->assertSame($pid, $puser->fields['profiles_id']); + $this->assertSame($eid2, $puser->fields['entities_id']); + $this->assertSame(1, $puser->fields['is_recursive']); + $this->assertSame(1, $puser->fields['is_dynamic']); } public function testClone() { $this->login(); - $user = $this->newTestedInstance; + $user = new \User(); + ; // Create user with profile - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => 'create_user', '_profiles_id' => (int)getItemByTypeName('Profile', 'Self-Service', true) ]); - $this->integer($uid)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid); $this->setEntity('_test_root_entity', true); @@ -654,134 +663,140 @@ public function testClone() // Add authorizations $puser = new \Profile_User(); - $this->integer($puser->add([ - 'users_id' => $uid, - 'profiles_id' => (int)getItemByTypeName('Profile', 'Technician', true), - 'entities_id' => (int)getItemByTypeName('Entity', '_test_child_1', true), - 'is_recursive' => 0, - ]))->isGreaterThan(0); - - $this->integer($puser->add([ - 'users_id' => $uid, - 'profiles_id' => (int)getItemByTypeName('Profile', 'Admin', true), - 'entities_id' => (int)getItemByTypeName('Entity', '_test_child_2', true), - 'is_recursive' => 1, - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $puser->add([ + 'users_id' => $uid, + 'profiles_id' => (int)getItemByTypeName('Profile', 'Technician', true), + 'entities_id' => (int)getItemByTypeName('Entity', '_test_child_1', true), + 'is_recursive' => 0, + ]) + ); + + $this->assertGreaterThan( + 0, + $puser->add([ + 'users_id' => $uid, + 'profiles_id' => (int)getItemByTypeName('Profile', 'Admin', true), + 'entities_id' => (int)getItemByTypeName('Entity', '_test_child_2', true), + 'is_recursive' => 1, + ]) + ); $puser_original = $puser->find(['users_id' => $uid]); - // Test item cloning + // Test item cloning $added = $user->clone(); - $this->integer((int)$added)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$added); $clonedUser = new \User(); - $this->boolean($clonedUser->getFromDB($added))->isTrue(); + $this->assertTrue($clonedUser->getFromDB($added)); $fields = $user->fields; - // Check the values. Id and dates must be different, everything else must be equal + // Check the values. Id and dates must be different, everything else must be equal foreach ($fields as $k => $v) { switch ($k) { case 'id': - $this->variable($clonedUser->getField($k))->isNotEqualTo($user->getField($k)); + $this->assertNotEquals($user->getField($k), $clonedUser->getField($k)); break; case 'date_mod': case 'date_creation': $dateClone = new \DateTime($clonedUser->getField($k)); $expectedDate = new \DateTime($date); - $this->dateTime($dateClone)->isEqualTo($expectedDate); + $this->assertEquals($expectedDate, $dateClone); break; case 'name': - $this->variable($clonedUser->getField($k))->isEqualTo("create_user-copy"); + $this->assertSame("create_user-copy", $clonedUser->getField($k)); break; default: - $this->variable($clonedUser->getField($k))->isEqualTo($user->getField($k)); + $this->assertEquals($user->getField($k), $clonedUser->getField($k)); } } // Check authorizations foreach ($puser_original as $row) { - $this->boolean($puser->getFromDBByCrit([ + $this->assertTrue($puser->getFromDBByCrit([ 'users_id' => $added, 'profiles_id' => $row['profiles_id'], 'entities_id' => $row['entities_id'], 'is_recursive' => $row['is_recursive'], 'is_dynamic' => $row['is_dynamic'], - ]))->isTrue(); + ])); } } public function testGetFromDBbyDn() { - $user = $this->newTestedInstance; + $user = new \User(); + ; $dn = 'user=user_with_dn,dc=test,dc=glpi-project,dc=org'; - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => 'user_with_dn', 'user_dn' => $dn ]); - $this->integer($uid)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid); - $this->boolean($user->getFromDBbyDn($dn))->isTrue(); - $this->array($user->fields) - ->integer['id']->isIdenticalTo($uid) - ->string['name']->isIdenticalTo('user_with_dn'); + $this->assertTrue($user->getFromDBbyDn($dn)); + $this->assertSame($uid, $user->fields['id']); + $this->assertSame('user_with_dn', $user->fields['name']); } public function testGetFromDBbySyncField() { - $user = $this->newTestedInstance; + $user = new \User(); + ; $sync_field = 'abc-def-ghi'; - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => 'user_with_syncfield', 'sync_field' => $sync_field ]); - $this->integer($uid)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid); - $this->boolean($user->getFromDBbySyncField($sync_field))->isTrue(); - $this->array($user->fields) - ->integer['id']->isIdenticalTo($uid) - ->string['name']->isIdenticalTo('user_with_syncfield'); + $this->assertTrue($user->getFromDBbySyncField($sync_field)); + $this->assertSame($uid, $user->fields['id']); + $this->assertSame('user_with_syncfield', $user->fields['name']); } public function testGetFromDBbyName() { - $user = $this->newTestedInstance; + $user = new \User(); + ; $name = 'user_with_name'; - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => $name ]); - $this->integer($uid)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid); - $this->boolean($user->getFromDBbyName($name))->isTrue(); - $this->array($user->fields) - ->integer['id']->isIdenticalTo($uid); + $this->assertTrue($user->getFromDBbyName($name)); + $this->assertSame($uid, $user->fields['id']); } public function testGetFromDBbyNameAndAuth() { - $user = $this->newTestedInstance; + $user = new \User(); + ; $name = 'user_with_auth'; - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => $name, 'authtype' => \Auth::DB_GLPI, 'auths_id' => 12 ]); - $this->integer($uid)->isGreaterThan(0); + $this->assertGreaterThan(0, $uid); - $this->boolean($user->getFromDBbyNameAndAuth($name, \Auth::DB_GLPI, 12))->isTrue(); - $this->array($user->fields) - ->integer['id']->isIdenticalTo($uid) - ->string['name']->isIdenticalTo($name); + $this->assertTrue($user->getFromDBbyNameAndAuth($name, \Auth::DB_GLPI, 12)); + $this->assertSame($uid, $user->fields['id']); + $this->assertSame($name, $user->fields['name']); } - protected function rawNameProvider() + public static function rawNameProvider() { return [ [ @@ -815,17 +830,13 @@ protected function rawNameProvider() */ public function testGetFriendlyName($input, $rawname) { - $user = $this->newTestedInstance; - - $this->string($user->getFriendlyName())->isIdenticalTo(''); + $user = new \User(); + $this->assertSame('', $user->getFriendlyName()); - $this - ->given($this->newTestedInstance) - ->then - ->integer($uid = (int)$this->testedInstance->add($input)) - ->isGreaterThan(0) - ->boolean($this->testedInstance->getFromDB($uid))->isTrue() - ->string($this->testedInstance->getFriendlyName())->isIdenticalTo($rawname); + $uid = $user->add($input); + $this->assertGreaterThan(0, $uid); + $this->assertTrue($user->getFromDB($uid)); + $this->assertSame($rawname, $user->getFriendlyName()); } public function testBlankPassword() @@ -835,118 +846,110 @@ public function testBlankPassword() 'password' => 'mypass', 'password2' => 'mypass' ]; - $this - ->given($this->newTestedInstance) - ->then - ->integer($uid = (int)$this->testedInstance->add($input)) - ->isGreaterThan(0) - ->boolean($this->testedInstance->getFromDB($uid))->isTrue() - ->array($this->testedInstance->fields) - ->string['name']->isIdenticalTo('myname') - ->string['password']->hasLength(60)->startWith('$2y$') - ->given($this->testedInstance->blankPassword()) - ->then - ->boolean($this->testedInstance->getFromDB($uid))->isTrue() - ->array($this->testedInstance->fields) - ->string['name']->isIdenticalTo('myname') - ->string['password']->isIdenticalTo(''); + + $user = new \User(); + $uid = $user->add($input); + $this->assertGreaterThan(0, $uid); + $this->assertTrue($user->getFromDB($uid)); + $this->assertSame('myname', $user->fields['name']); + $this->assertEquals(60, strlen($user->fields['password'])); + $this->assertStringStartsWith('$2y$', $user->fields['password']); + + $user->blankPassword(); + $this->assertTrue($user->getFromDB($uid)); + $this->assertSame('myname', $user->fields['name']); + $this->assertSame('', $user->fields['password']); } public function testPre_updateInDB() { $this->login(); - $user = $this->newTestedInstance(); + $user = new \User(); - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => 'preupdate_user' ]); - $this->integer($uid)->isGreaterThan(0); - $this->boolean($user->getFromDB($uid))->isTrue(); + $this->assertGreaterThan(0, $uid); + $this->assertTrue($user->getFromDB($uid)); - $this->boolean($user->update([ + $this->assertTrue($user->update([ 'id' => $uid, 'name' => 'preupdate_user_edited' - ]))->isTrue(); + ])); $this->hasNoSessionMessages([ERROR, WARNING]); - //can update with same name when id is identical - $this->boolean($user->update([ + //can update with same name when id is identical + $this->assertTrue($user->update([ 'id' => $uid, 'name' => 'preupdate_user_edited' - ]))->isTrue(); + ])); $this->hasNoSessionMessages([ERROR, WARNING]); - $this->integer( - (int)$user->add(['name' => 'do_exist']) - )->isGreaterThan(0); - $this->boolean($user->update([ + $this->assertGreaterThan( + 0, + $user->add(['name' => 'do_exist']) + ); + $this->assertTrue($user->update([ 'id' => $uid, 'name' => 'do_exist' - ]))->isTrue(); + ])); $this->hasSessionMessages(ERROR, ['Unable to update login. A user already exists.']); - $this->boolean($user->getFromDB($uid))->isTrue(); - $this->string($user->fields['name'])->isIdenticalTo('preupdate_user_edited'); + $this->assertTrue($user->getFromDB($uid)); + $this->assertSame('preupdate_user_edited', $user->fields['name']); - $this->boolean($user->update([ + $this->assertTrue($user->update([ 'id' => $uid, 'name' => 'in+valid' - ]))->isTrue(); + ])); $this->hasSessionMessages(ERROR, ['The login is not valid. Unable to update login.']); } public function testGetIdByName() { - $user = $this->newTestedInstance; - - $uid = (int)$user->add(['name' => 'id_by_name']); - $this->integer($uid)->isGreaterThan(0); + $user = new \User(); - $this->integer($user->getIdByName('id_by_name'))->isIdenticalTo($uid); + $uid = $user->add(['name' => 'id_by_name']); + $this->assertGreaterThan(0, $uid); + $this->assertSame($uid, $user->getIdByName('id_by_name')); } public function testGetIdByField() { - $user = $this->newTestedInstance; + $user = new \User(); - $uid = (int)$user->add([ + $uid = $user->add([ 'name' => 'id_by_field', 'phone' => '+33123456789' ]); - $this->integer($uid)->isGreaterThan(0); - - $this->integer($user->getIdByField('phone', '+33123456789'))->isIdenticalTo($uid); + $this->assertGreaterThan(0, $uid); + $this->assertSame($uid, $user->getIdByField('phone', '+33123456789')); - $this->integer( + $this->assertGreaterThan( + 0, $user->add([ 'name' => 'id_by_field2', 'phone' => '+33123456789' ]) - )->isGreaterThan(0); - $this->boolean($user->getIdByField('phone', '+33123456789'))->isFalse(); - - $this->boolean($user->getIdByField('phone', 'donotexists'))->isFalse(); + ); + $this->assertFalse($user->getIdByField('phone', '+33123456789')); + $this->assertFalse($user->getIdByField('phone', 'donotexists')); } public function testgetAdditionalMenuOptions() { - $this->Login(); - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->getAdditionalMenuOptions()) - ->hasSize(1) - ->hasKey('ldap'); - - $this->Login('normal', 'normal'); - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->getAdditionalMenuOptions()) - ->isFalse(); + $this->login(); + + $user = new \User(); + $this->assertCount(1, $user->getAdditionalMenuOptions()); + $this->assertArrayHasKey('ldap', $user->getAdditionalMenuOptions()); + + $this->login('normal', 'normal'); + $user = new \User(); + $this->assertFalse($user->getAdditionalMenuOptions()); } - protected function passwordExpirationMethodsProvider() + public static function passwordExpirationMethodsProvider() { $time = time(); @@ -1022,7 +1025,7 @@ public function testPasswordExpirationMethods( ) { global $CFG_GLPI; - $user = $this->newTestedInstance(); + $user = new \User(); $username = 'prepare_for_update_' . mt_rand(); $user_id = $user->add( [ @@ -1032,9 +1035,9 @@ public function testPasswordExpirationMethods( 'password2' => 'pass' ] ); - $this->integer($user_id)->isGreaterThan(0); - $this->boolean($user->update(['id' => $user_id, 'password_last_update' => $last_update]))->isTrue(); - $this->boolean($user->getFromDB($user->fields['id']))->isTrue(); + $this->assertGreaterThan(0, $user_id); + $this->assertTrue($user->update(['id' => $user_id, 'password_last_update' => $last_update])); + $this->assertTrue($user->getFromDB($user->fields['id'])); $cfg_backup = $CFG_GLPI; $CFG_GLPI['password_expiration_delay'] = $expiration_delay; @@ -1046,40 +1049,16 @@ public function testPasswordExpirationMethods( $CFG_GLPI = $cfg_backup; - $this->variable($expiration_time)->isEqualTo($expected_expiration_time); - $this->boolean($should_change_password)->isEqualTo($expected_should_change_password); - $this->boolean($has_password_expire)->isEqualTo($expected_has_password_expire); + $this->assertEquals($expected_expiration_time, $expiration_time); + $this->assertEquals($expected_should_change_password, $should_change_password); + $this->assertEquals($expected_has_password_expire, $has_password_expire); } - protected function cronPasswordExpirationNotificationsProvider() + public static function cronPasswordExpirationNotificationsProvider() { - // create 10 users with differents password_last_update dates - // first has its password set 1 day ago - // second has its password set 11 day ago - // and so on - // tenth has its password set 91 day ago - $user = new \User(); - for ($i = 1; $i < 100; $i += 10) { - $user_id = $user->add( - [ - 'name' => 'cron_user_' . mt_rand(), - 'authtype' => \Auth::DB_GLPI, - ] - ); - $this->integer($user_id)->isGreaterThan(0); - $this->boolean( - $user->update( - [ - 'id' => $user_id, - 'password_last_update' => date('Y-m-d H:i:s', strtotime('-' . $i . ' days')), - ] - ) - )->isTrue(); - } - return [ - // validate that cron does nothing if password expiration is not active (default config) + // validate that cron does nothing if password expiration is not active (default config) [ 'expiration_delay' => -1, 'notice_delay' => -1, @@ -1089,7 +1068,7 @@ protected function cronPasswordExpirationNotificationsProvider() 'expected_notifications_count' => 0, 'expected_lock_count' => 0, ], - // validate that cron send no notification if password_expiration_notice == -1 + // validate that cron send no notification if password_expiration_notice == -1 [ 'expiration_delay' => 15, 'notice_delay' => -1, @@ -1099,7 +1078,7 @@ protected function cronPasswordExpirationNotificationsProvider() 'expected_notifications_count' => 0, 'expected_lock_count' => 0, ], - // validate that cron send notifications instantly if password_expiration_notice == 0 + // validate that cron send notifications instantly if password_expiration_notice == 0 [ 'expiration_delay' => 50, 'notice_delay' => 0, @@ -1109,7 +1088,7 @@ protected function cronPasswordExpirationNotificationsProvider() 'expected_notifications_count' => 5, // 5 users should be notified (them which has password set more than 50 days ago) 'expected_lock_count' => 0, ], - // validate that cron send notifications before expiration if password_expiration_notice > 0 + // validate that cron send notifications before expiration if password_expiration_notice > 0 [ 'expiration_delay' => 50, 'notice_delay' => 20, @@ -1119,7 +1098,7 @@ protected function cronPasswordExpirationNotificationsProvider() 'expected_notifications_count' => 7, // 7 users should be notified (them which has password set more than 50-20 days ago) 'expected_lock_count' => 0, ], - // validate that cron returns partial result if there is too many notifications to send + // validate that cron returns partial result if there is too many notifications to send [ 'expiration_delay' => 50, 'notice_delay' => 20, @@ -1129,7 +1108,7 @@ protected function cronPasswordExpirationNotificationsProvider() 'expected_notifications_count' => 5, // 5 on 7 users should be notified (them which has password set more than 50-20 days ago) 'expected_lock_count' => 0, ], - // validate that cron disable users instantly if password_expiration_lock_delay == 0 + // validate that cron disable users instantly if password_expiration_lock_delay == 0 [ 'expiration_delay' => 50, 'notice_delay' => -1, @@ -1139,7 +1118,7 @@ protected function cronPasswordExpirationNotificationsProvider() 'expected_notifications_count' => 0, 'expected_lock_count' => 5, // 5 users should be locked (them which has password set more than 50 days ago) ], - // validate that cron disable users with given delay if password_expiration_lock_delay > 0 + // validate that cron disable users with given delay if password_expiration_lock_delay > 0 [ 'expiration_delay' => 20, 'notice_delay' => -1, @@ -1168,8 +1147,33 @@ public function testCronPasswordExpirationNotifications( $this->login(); + // create 10 users with different password_last_update dates + // first has its password set 1 day ago + // second has its password set 11 day ago + // and so on + // tenth has its password set 91 day ago + $user = new \User(); + for ($i = 1; $i < 100; $i += 10) { + $user_id = $user->add( + [ + 'name' => 'cron_user_' . mt_rand(), + 'authtype' => \Auth::DB_GLPI, + ] + ); + $this->assertGreaterThan(0, $user_id); + //FIXME: why add then immeditaly update? Should not last_update set directly in add? + $this->assertTrue( + $user->update( + [ + 'id' => $user_id, + 'password_last_update' => date('Y-m-d H:i:s', strtotime('-' . $i . ' days')), + ] + ) + ); + } + $crontask = new \CronTask(); - $this->boolean($crontask->getFromDBbyName(\User::getType(), 'passwordexpiration'))->isTrue(); + $this->assertTrue($crontask->getFromDBbyName(\User::getType(), 'passwordexpiration')); $crontask->fields['param'] = $cron_limit; $cfg_backup = $CFG_GLPI; @@ -1181,17 +1185,18 @@ public function testCronPasswordExpirationNotifications( $result = \User::cronPasswordExpiration($crontask); $CFG_GLPI = $cfg_backup; - $this->integer($result)->isEqualTo($expected_result); - $this->integer( + $this->assertEquals($expected_result, $result); + $this->assertEquals( + $expected_notifications_count, countElementsInTable(\Alert::getTable(), ['itemtype' => \User::getType()]) - )->isEqualTo($expected_notifications_count); + ); $DB->delete(\Alert::getTable(), ['itemtype' => \User::getType()]); // reset alerts $user_crit = [ 'authtype' => \Auth::DB_GLPI, 'is_active' => 0, ]; - $this->integer(countElementsInTable(\User::getTable(), $user_crit))->isEqualTo($expected_lock_count); + $this->assertEquals($expected_lock_count, countElementsInTable(\User::getTable(), $user_crit)); $DB->update(\User::getTable(), ['is_active' => 1], $user_crit); // reset users } @@ -1204,7 +1209,7 @@ public function testLastAdministratorDeleteOrDisable(): void { // Default: only one super admin account $super_admin = getItemByTypeName('Profile', 'Super-Admin'); - $this->boolean($super_admin->isLastSuperAdminProfile())->isTrue(); + $this->assertTrue($super_admin->isLastSuperAdminProfile()); // Default: 3 users with super admin account authorizations $users = (new \User())->find([ @@ -1216,8 +1221,11 @@ public function testLastAdministratorDeleteOrDisable(): void ] ]) ]); - $this->array($users)->hasSize(3); - $this->array(array_column($users, 'name'))->isEqualTo(['glpi', TU_USER, "jsmith123"]); + $this->assertCount(3, $users); + $this->assertEquals( + ['glpi', TU_USER, "jsmith123"], + array_column($users, 'name') + ); $glpi = getItemByTypeName('User', 'glpi'); $tu_user = getItemByTypeName('User', TU_USER); @@ -1225,25 +1233,25 @@ public function testLastAdministratorDeleteOrDisable(): void // Delete 2 users $this->login('glpi', 'glpi'); - $this->boolean($tu_user->canDeleteItem())->isTrue(); - $this->boolean($tu_user->delete(['id' => $tu_user->getID()]))->isTrue(); - $this->boolean($jsmith123->canDeleteItem())->isTrue(); - $this->boolean($jsmith123->delete(['id' => $jsmith123->getID()]))->isTrue(); + $this->assertTrue($tu_user->canDeleteItem()); + $this->assertTrue($tu_user->delete(['id' => $tu_user->getID()])); + $this->assertTrue($jsmith123->canDeleteItem()); + $this->assertTrue($jsmith123->delete(['id' => $jsmith123->getID()])); // Last user, can't be deleted or disabled - $this->boolean($glpi->update([ + $this->assertTrue($glpi->update([ 'id' => $glpi->getID(), 'is_active' => false - ]))->isTrue(); + ])); $this->hasSessionMessages(ERROR, [ "Can't set user as inactive as it is the only remaining super administrator." ]); $glpi->getFromDB($glpi->getId()); - $this->boolean((bool) $glpi->fields['is_active'])->isEqualTo(true); - $this->boolean($glpi->canDeleteItem())->isFalse(); + $this->assertEquals(true, (bool) $glpi->fields['is_active']); + $this->assertFalse($glpi->canDeleteItem()); // Can still be deleted by calling delete directly, maybe it should not be possible ? - $this->boolean($glpi->delete(['id' => $glpi->getID()]))->isTrue(); + $this->assertTrue($glpi->delete(['id' => $glpi->getID()])); } public function testUserPreferences() @@ -1251,7 +1259,7 @@ public function testUserPreferences() if (version_compare(PHP_VERSION, '8.0', '<')) { // Cannot use `@php 8.0` to skip test as we want to ensure that test suite fails if methods are skipped // (to detect missing extensions for instance). - $this->boolean(true)->isTrue(); + $this->assertTrue(true); return; } @@ -1263,59 +1271,59 @@ public function testUserPreferences() 'password2' => 'for preferences', 'profiles_id' => 4 ]); - $this->integer($users_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $users_id); $this->login('for preferences', 'for preferences'); - $this->boolean($user->getFromDB($users_id))->isTrue(); - $this->variable($user->fields['show_count_on_tabs'])->isNull(); - $this->variable($_SESSION['glpishow_count_on_tabs'])->isEqualTo(1); + $this->assertTrue($user->getFromDB($users_id)); + $this->assertNull($user->fields['show_count_on_tabs']); + $this->assertEquals(1, $_SESSION['glpishow_count_on_tabs']); $itil_layout_1 = '{"collapsed":"true","expanded":"false","items":{"item-main":"false","actors":"false","items":"false","service-levels":"false","linked_tickets":"false"}}'; - $this->boolean( + $this->assertTrue( $user->update(Sanitizer::dbEscapeRecursive([ 'id' => $users_id, 'show_count_on_tabs' => '0', 'itil_layout' => $itil_layout_1, ])) - )->isTrue(); + ); // pref should be updated even without logout/login - $this->variable($_SESSION['glpishow_count_on_tabs'])->isEqualTo(0); - $this->variable($_SESSION['glpiitil_layout'])->isEqualTo($itil_layout_1); + $this->assertEquals(0, $_SESSION['glpishow_count_on_tabs']); + $this->assertEquals($itil_layout_1, $_SESSION['glpiitil_layout']); // logout/login and check prefs $this->logOut(); $this->login('for preferences', 'for preferences'); - $this->variable($_SESSION['glpishow_count_on_tabs'])->isEqualTo(0); - $this->variable($_SESSION['glpiitil_layout'])->isEqualTo($itil_layout_1); + $this->assertEquals(0, $_SESSION['glpishow_count_on_tabs']); + $this->assertEquals($itil_layout_1, $_SESSION['glpiitil_layout']); - $this->boolean($user->getFromDB($users_id))->isTrue(); - $this->variable($user->fields['show_count_on_tabs'])->isEqualTo(0); - $this->variable($user->fields['itil_layout'])->isEqualTo($itil_layout_1); + $this->assertTrue($user->getFromDB($users_id)); + $this->assertEquals(0, $user->fields['show_count_on_tabs']); + $this->assertEquals($itil_layout_1, $user->fields['itil_layout']); $itil_layout_2 = '{"collapsed":"false","expanded":"true"}'; - $this->boolean( + $this->assertTrue( $user->update(Sanitizer::dbEscapeRecursive([ 'id' => $users_id, 'show_count_on_tabs' => '1', 'itil_layout' => $itil_layout_2, ])) - )->isTrue(); + ); // pref should be updated even without logout/login - $this->variable($_SESSION['glpishow_count_on_tabs'])->isEqualTo(1); - $this->variable($_SESSION['glpiitil_layout'])->isEqualTo($itil_layout_2); + $this->assertEquals(1, $_SESSION['glpishow_count_on_tabs']); + $this->assertEquals($itil_layout_2, $_SESSION['glpiitil_layout']); // logout/login and check prefs $this->logOut(); $this->login('for preferences', 'for preferences'); - $this->variable($_SESSION['glpishow_count_on_tabs'])->isEqualTo(1); - $this->variable($_SESSION['glpiitil_layout'])->isEqualTo($itil_layout_2); + $this->assertEquals(1, $_SESSION['glpishow_count_on_tabs']); + $this->assertEquals($itil_layout_2, $_SESSION['glpiitil_layout']); - $this->boolean($user->getFromDB($users_id))->isTrue(); - $this->variable($user->fields['show_count_on_tabs'])->isNull(); - $this->variable($user->fields['itil_layout'])->isEqualTo($itil_layout_2); + $this->assertTrue($user->getFromDB($users_id)); + $this->assertNull($user->fields['show_count_on_tabs']); + $this->assertEquals($itil_layout_2, $user->fields['itil_layout']); } /** @@ -1325,12 +1333,12 @@ public function testUserPreferences() */ public function testUserDnIsHashedOnAddAndUpdate(): void { - // Create user whithout dn and check that user_dn_hash is not set + // Create user without dn and check that user_dn_hash is not set $user = $this->createItem('User', [ 'name' => __FUNCTION__, ]); - $this->variable($user->fields['user_dn'])->isNull(); - $this->variable($user->fields['user_dn_hash'])->isNull(); + $this->assertNull($user->fields['user_dn']); + $this->assertNull($user->fields['user_dn_hash']); // Create user with dn and check that user_dn_hash is set $dn = 'user=' . __FUNCTION__ . '_created,dc=R&D,dc=glpi-project,dc=org'; @@ -1338,7 +1346,7 @@ public function testUserDnIsHashedOnAddAndUpdate(): void 'name' => __FUNCTION__ . '_created', 'user_dn' => $dn ]); - $this->string($user->fields['user_dn_hash'])->isEqualTo(md5($dn)); + $this->assertEquals(md5($dn), $user->fields['user_dn_hash']); // Update user dn and check that user_dn_hash is updated $dn = 'user=' . __FUNCTION__ . '_updated,dc=R&D,dc=glpi-project,dc=org'; @@ -1346,21 +1354,21 @@ public function testUserDnIsHashedOnAddAndUpdate(): void 'user_dn' => $dn ]); $user->getFromDB($user->getID()); - $this->string($user->fields['user_dn_hash'])->isEqualTo(md5($dn)); + $this->assertEquals(md5($dn), $user->fields['user_dn_hash']); // Set user_dn to empty and check that user_dn_hash is set to null $this->updateItem('User', $user->getID(), [ 'user_dn' => '' ]); $user->getFromDB($user->getID()); - $this->variable($user->fields['user_dn_hash'])->isNull(); + $this->assertNull($user->fields['user_dn_hash']); // Set user_dn to null and check that user_dn_hash is set to null $this->updateItem('User', $user->getID(), [ 'user_dn' => null ]); $user->getFromDB($user->getID()); - $this->variable($user->fields['user_dn_hash'])->isNull(); + $this->assertNull($user->fields['user_dn_hash']); } /** @@ -1375,9 +1383,8 @@ public function testUserDnHashIsUsedInGetFromDBbyDn(): void $retrievedUser = new \User(); // Get a user with a bad dn - $this->boolean($retrievedUser->getFromDBbyDn(__FUNCTION__)) - ->isFalse(); - $this->boolean($retrievedUser->isNewItem())->isTrue(); + $this->assertFalse($retrievedUser->getFromDBbyDn(__FUNCTION__)); + $this->assertTrue($retrievedUser->isNewItem()); // Create a user with a dn $dn = 'user=' . __FUNCTION__ . ',dc=R&D,dc=glpi-project,dc=org'; @@ -1387,9 +1394,9 @@ public function testUserDnHashIsUsedInGetFromDBbyDn(): void ]); // Retrieve the user using getFromDBbyDn method - $this->boolean($retrievedUser->getFromDBbyDn($dn))->isTrue(); - $this->boolean($retrievedUser->getFromDBbyDn(Sanitizer::sanitize($dn)))->isTrue(); // works also with sanitized value - $this->boolean($retrievedUser->isNewItem())->isFalse(); + $this->assertTrue($retrievedUser->getFromDBbyDn($dn)); + $this->assertTrue($retrievedUser->getFromDBbyDn(Sanitizer::sanitize($dn))); // works also with sanitized value + $this->assertFalse($retrievedUser->isNewItem()); // Unset user_dn to check that user_dn_hash is used $DB->update( @@ -1399,13 +1406,13 @@ public function testUserDnHashIsUsedInGetFromDBbyDn(): void ); // Retrieve the user using getFromDBbyDn and check if user_dn_hash is used - $this->boolean($retrievedUser->getFromDBbyDn($dn))->isTrue(); - $this->boolean($retrievedUser->getFromDBbyDn(Sanitizer::sanitize($dn)))->isTrue(); // works also with sanitized value - $this->boolean($retrievedUser->isNewItem())->isFalse(); - $this->string($retrievedUser->fields['user_dn'])->isEmpty(); + $this->assertTrue($retrievedUser->getFromDBbyDn($dn)); + $this->assertTrue($retrievedUser->getFromDBbyDn(Sanitizer::sanitize($dn))); // works also with sanitized value + $this->assertFalse($retrievedUser->isNewItem()); + $this->assertEmpty($retrievedUser->fields['user_dn']); } - protected function toggleSavedSearchPinProvider(): iterable + public static function toggleSavedSearchPinProvider(): iterable { foreach (['', '[]', '{}'] as $initial_db_value) { // initial empty data @@ -1463,11 +1470,14 @@ public function testToggleSavedSearchPin(string $initial_db_value, string $itemt ] ); - $this->boolean($user->toggleSavedSearchPin($itemtype))->isEqualTo($success); - $this->boolean($user->getFromDb($user->getID()))->isTrue(); - $this->string($user->fields['savedsearches_pinned'])->isEqualTo($result_db_value); + $this->assertEquals($success, $user->toggleSavedSearchPin($itemtype)); + $this->assertTrue($user->getFromDb($user->getID())); + $this->assertEquals($result_db_value, $user->fields['savedsearches_pinned']); // result value in DB is always a valid JSON string - $this->array(importArrayFromDB($user->fields['savedsearches_pinned']))->isEqualTo(json_decode($result_db_value, true)); + $this->assertEquals( + json_decode($result_db_value, true), + importArrayFromDB($user->fields['savedsearches_pinned']) + ); } } diff --git a/src/Document.php b/src/Document.php index a56fb307cdd..038586347a7 100644 --- a/src/Document.php +++ b/src/Document.php @@ -704,7 +704,7 @@ public function getFromDBbyContent($entity, $path) public function canViewFile(array $options = []) { - // Check if it is my doc + // Check if it is my doc if ( Session::getLoginUserID() && ($this->can($this->fields["id"], READ) diff --git a/tests/CsvTestCase.php b/tests/CsvTestCase.php index cadbd212f6c..93cf26a3890 100644 --- a/tests/CsvTestCase.php +++ b/tests/CsvTestCase.php @@ -67,7 +67,7 @@ protected function csvTestProvider(): array } /** - * @dataprovider csvTestProvider + * @dataProvider csvTestProvider */ public function testGetFileName( ExportToCsvInterface $export, @@ -78,7 +78,7 @@ public function testGetFileName( } /** - * @dataprovider csvTestProvider + * @dataProvider csvTestProvider */ public function testGetFileHeader( ExportToCsvInterface $export, @@ -93,7 +93,7 @@ public function testGetFileHeader( } /** - * @dataprovider csvTestProvider + * @dataProvider csvTestProvider */ public function testGetFileContent( ExportToCsvInterface $export, diff --git a/tests/fixtures/inventories/softwares/01-test_software_with_special_chars_with_version.json b/tests/fixtures/inventories/software/01-test_software_with_special_chars_with_version.json similarity index 100% rename from tests/fixtures/inventories/softwares/01-test_software_with_special_chars_with_version.json rename to tests/fixtures/inventories/software/01-test_software_with_special_chars_with_version.json diff --git a/tests/fixtures/inventories/softwares/02-test_software_with_special_chars_with_version.json b/tests/fixtures/inventories/software/02-test_software_with_special_chars_with_version.json similarity index 100% rename from tests/fixtures/inventories/softwares/02-test_software_with_special_chars_with_version.json rename to tests/fixtures/inventories/software/02-test_software_with_special_chars_with_version.json diff --git a/tests/fixtures/inventories/softwares/03-test_software_with_special_chars_and_without_version.json b/tests/fixtures/inventories/software/03-test_software_with_special_chars_and_without_version.json similarity index 100% rename from tests/fixtures/inventories/softwares/03-test_software_with_special_chars_and_without_version.json rename to tests/fixtures/inventories/software/03-test_software_with_special_chars_and_without_version.json diff --git a/tests/fixtures/inventories/softwares/04-test_software_with_special_chars_and_with_version_and_os.json b/tests/fixtures/inventories/software/04-test_software_with_special_chars_and_with_version_and_os.json similarity index 100% rename from tests/fixtures/inventories/softwares/04-test_software_with_special_chars_and_with_version_and_os.json rename to tests/fixtures/inventories/software/04-test_software_with_special_chars_and_with_version_and_os.json diff --git a/tests/fixtures/inventories/softwares/05-test_software_with_special_chars_and_without_version_and_os.json b/tests/fixtures/inventories/software/05-test_software_with_special_chars_and_without_version_and_os.json similarity index 100% rename from tests/fixtures/inventories/softwares/05-test_software_with_special_chars_and_without_version_and_os.json rename to tests/fixtures/inventories/software/05-test_software_with_special_chars_and_without_version_and_os.json diff --git a/tests/functional/Calendar.php b/tests/functional/Calendar.php index 8a2d91fc8b2..bde6a70a836 100644 --- a/tests/functional/Calendar.php +++ b/tests/functional/Calendar.php @@ -89,7 +89,7 @@ protected function testComputeEndDateProvider(): iterable /** * Test cases for the computeEndDate function * - * @dataprovider testComputeEndDateProvider + * @dataProvider testComputeEndDateProvider * * @param \Calendar $calendar Test calendar * @param array $compute_end_date_parameters Arguments for the computeEndDate function diff --git a/tests/functional/CommonITILValidation.php b/tests/functional/CommonITILValidation.php index 68beff06ffc..79d0425a782 100644 --- a/tests/functional/CommonITILValidation.php +++ b/tests/functional/CommonITILValidation.php @@ -393,7 +393,7 @@ protected function testComputeValidationProvider(): array } /** - * @dataprovider testComputeValidationProvider + * @dataProvider testComputeValidationProvider */ public function testComputeValidation( int $accepted, diff --git a/tests/functional/Glpi/ContentTemplates/TemplateManager.php b/tests/functional/Glpi/ContentTemplates/TemplateManager.php index 4df07985b27..43fce6e9802 100644 --- a/tests/functional/Glpi/ContentTemplates/TemplateManager.php +++ b/tests/functional/Glpi/ContentTemplates/TemplateManager.php @@ -185,7 +185,7 @@ protected function commonITILObjectclassesProvider(): array /** * Verify that actors are rendered correctly on creation (commonitilobject) * - * @dataprovider commonITILObjectclassesProvider + * @dataProvider commonITILObjectclassesProvider * * @return void */ diff --git a/tests/functional/Glpi/Dashboard/Provider.php b/tests/functional/Glpi/Dashboard/Provider.php index d52ce224b6c..0646b29eeec 100644 --- a/tests/functional/Glpi/Dashboard/Provider.php +++ b/tests/functional/Glpi/Dashboard/Provider.php @@ -899,7 +899,7 @@ protected function testGetArticleListReminderProvider(): iterable } /** - * @dataprovider testGetArticleListReminderProvider + * @dataProvider testGetArticleListReminderProvider */ public function testGetArticleListReminder(int $expected): void { diff --git a/tests/functional/ITILFollowup.php b/tests/functional/ITILFollowup.php index 7456954edf5..440948ce1b6 100644 --- a/tests/functional/ITILFollowup.php +++ b/tests/functional/ITILFollowup.php @@ -327,7 +327,7 @@ protected function testIsFromSupportAgentProvider() } /** - * @dataprovider testIsFromSupportAgentProvider + * @dataProvider testIsFromSupportAgentProvider */ public function testIsFromSupportAgent( array $roles, diff --git a/tests/functional/NotificationTarget.php b/tests/functional/NotificationTarget.php index 8cd8f49153f..76b71565bd8 100644 --- a/tests/functional/NotificationTarget.php +++ b/tests/functional/NotificationTarget.php @@ -322,7 +322,7 @@ protected function getSenderProvider(): Generator /** * Functionals tests for the getSender method * - * @dataprovider getSenderProvider + * @dataProvider getSenderProvider * * @param bool $allow_response Use reply to or admin email ? * @param string|null $email Expected email diff --git a/tests/functional/PendingReason.class.php b/tests/functional/PendingReason.class.php index 6f209c17a17..04619939389 100644 --- a/tests/functional/PendingReason.class.php +++ b/tests/functional/PendingReason.class.php @@ -91,7 +91,7 @@ protected function testGetNextFollowupDateProvider() } /** - * @dataprovider testGetNextFollowupDateProvider + * @dataProvider testGetNextFollowupDateProvider */ public function testGetNextFollowupDate(array $fields, $expected) { @@ -184,7 +184,7 @@ protected function testGetAutoResolvedateProvider() } /** - * @dataprovider testGetAutoResolvedateProvider + * @dataProvider testGetAutoResolvedateProvider */ public function testGetAutoResolvedate(array $fields, $expected) { @@ -244,7 +244,7 @@ protected static function getBaseActionAddInput($action_item, $item) * Test that a PendingReason_Item object is created when an item is marked as * pending * - * @dataprovider itemtypeAndActionProvider + * @dataProvider itemtypeAndActionProvider */ public function testPendingItemCreation($itemtype, $action_itemtype) { @@ -284,7 +284,7 @@ public function testPendingItemCreation($itemtype, $action_itemtype) * A status change from pending to any other should delete any linked * PendingReason_Item objects * - * @dataprovider itemtypeProvider + * @dataProvider itemtypeProvider */ public function testStatusChangeNoLongerPending($itemtype) { diff --git a/tests/functional/Reservation.php b/tests/functional/Reservation.php index af868183823..44d9fbbf44e 100644 --- a/tests/functional/Reservation.php +++ b/tests/functional/Reservation.php @@ -136,7 +136,7 @@ protected function dataAddReservationTest(): array } /** - * @dataprovider dataAddReservationTest + * @dataProvider dataAddReservationTest */ public function testAddJustOneReservation($begin, $end): void { diff --git a/tests/functional/RuleTicket.php b/tests/functional/RuleTicket.php index e1aa33f21c9..ff86a42c638 100644 --- a/tests/functional/RuleTicket.php +++ b/tests/functional/RuleTicket.php @@ -2340,7 +2340,7 @@ protected function testMailHeaderCriteriaProvider() } /** - * @dataprovider testMailHeaderCriteriaProvider + * @dataProvider testMailHeaderCriteriaProvider */ public function testMailHeaderCriteria( string $pattern, @@ -3295,7 +3295,7 @@ protected function testAssignLocationFromUserProvider(): iterable * * @return void * - * @dataprovider testAssignLocationFromUserProvider + * @dataProvider testAssignLocationFromUserProvider */ public function testAssignLocationFromUser( ?int $input_locations_id, diff --git a/tests/functional/Search.php b/tests/functional/Search.php index 3076e03ba41..a651094c932 100644 --- a/tests/functional/Search.php +++ b/tests/functional/Search.php @@ -3612,7 +3612,7 @@ protected function testCriteriaWithSubqueriesProvider(): iterable } /** - * @dataprovider testCriteriaWithSubqueriesProvider + * @dataProvider testCriteriaWithSubqueriesProvider */ public function testCriteriaWithSubqueries( string $itemtype, @@ -4838,7 +4838,7 @@ protected function containsCriterionProvider(): iterable } /** - * @dataprovider containsCriterionProvider + * @dataProvider containsCriterionProvider */ public function testContainsCriterion( string $itemtype, @@ -5071,7 +5071,7 @@ protected function testRichTextProvider(): iterable } /** - * @dataprovider testRichTextProvider + * @dataProvider testRichTextProvider */ public function testRichText( array $search_params, diff --git a/tests/functional/State.php b/tests/functional/State.php index 93b0ccaf591..795722c8f8e 100644 --- a/tests/functional/State.php +++ b/tests/functional/State.php @@ -76,7 +76,7 @@ protected function testIsUniqueProvider(): Generator } /** - * @dataprovider testIsUniqueProvider + * @dataProvider testIsUniqueProvider */ public function testIsUnique(array $input, bool $expected) {