diff --git a/phpunit.xml.dist b/phpunit.xml.dist index c5248206942..4d711702bbc 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -8,5 +8,8 @@ phpunit/functional/ + + + diff --git a/phpunit/DbTestCase.php b/phpunit/DbTestCase.php index 7deaa7bf308..0861b34c2a3 100644 --- a/phpunit/DbTestCase.php +++ b/phpunit/DbTestCase.php @@ -150,7 +150,7 @@ protected function getClasses($function = false, array $excludes = []) $excludes = array_merge( $excludes, [ - 'TicketFollowup', // Deprecated + '/^TicketFollowup$/', // Deprecated '/^RuleImportComputer.*/', // Deprecated ] ); diff --git a/phpunit/GLPITestCase.php b/phpunit/GLPITestCase.php index c19227b1083..eb7da1f27e8 100644 --- a/phpunit/GLPITestCase.php +++ b/phpunit/GLPITestCase.php @@ -35,6 +35,7 @@ use Glpi\Tests\Log\TestHandler; use Monolog\Logger; +use org\bovigo\vfs\vfsStreamWrapper; use PHPUnit\Framework\TestCase; use Psr\Log\LogLevel; @@ -72,10 +73,14 @@ public function setUp(): void $PHPLOGGER->setHandlers([$this->php_log_handler]); $this->sql_log_handler = new TestHandler(LogLevel::DEBUG); $SQLLOGGER->setHandlers([$this->sql_log_handler]); + + vfsStreamWrapper::register(); } public function tearDown(): void { + vfsStreamWrapper::unregister(); + if (isset($_SESSION['MESSAGE_AFTER_REDIRECT']) && !$this->has_failed) { unset($_SESSION['MESSAGE_AFTER_REDIRECT'][INFO]); $this->assertSame( diff --git a/phpunit/bootstrap.php b/phpunit/bootstrap.php index 7f5161b9699..d3d049b1993 100644 --- a/phpunit/bootstrap.php +++ b/phpunit/bootstrap.php @@ -97,7 +97,7 @@ include_once __DIR__ . '/InventoryTestCase.php'; //include_once __DIR__ . '/functional/CommonITILRecurrent.php'; //include_once __DIR__ . '/functional/Glpi/ContentTemplates/Parameters/AbstractParameters.php'; -//include_once __DIR__ . '/functional/AbstractRightsDropdown.php'; +include_once __DIR__ . '/functional/AbstractRightsDropdown.php'; // check folder exists instead of class_exists('\GuzzleHttp\Client'), to prevent global includes if (file_exists(__DIR__ . '/../vendor/autoload.php') && !file_exists(__DIR__ . '/../vendor/guzzlehttp/guzzle')) { diff --git a/tests/functional/AbstractRightsDropdown.php b/phpunit/functional/AbstractRightsDropdown.php similarity index 94% rename from tests/functional/AbstractRightsDropdown.php rename to phpunit/functional/AbstractRightsDropdown.php index 0eaa55ef702..91c32e8cf94 100644 --- a/tests/functional/AbstractRightsDropdown.php +++ b/phpunit/functional/AbstractRightsDropdown.php @@ -44,7 +44,7 @@ abstract class AbstractRightsDropdown extends \GLPITestCase { - protected function testGetPostedIdsProvider(): Generator + public static function getPostedIdsProvider(): Generator { $flat_values_set = [ 'users_id-3', @@ -91,7 +91,7 @@ protected function testGetPostedIdsProvider(): Generator } /** - * @dataprovider testGetPostedIdsProvider + * @dataProvider getPostedIdsProvider */ public function testGetPostedIds( array $values, @@ -99,6 +99,6 @@ public function testGetPostedIds( array $expected_ids ): void { $ids = \AbstractRightsDropdown::getPostedIds($values, $class); - $this->array($ids)->isEqualTo($expected_ids); + $this->assertSame($expected_ids, $ids); } } diff --git a/phpunit/functional/Agent.php b/phpunit/functional/Agent.php new file mode 100644 index 00000000000..be20acb0b34 --- /dev/null +++ b/phpunit/functional/Agent.php @@ -0,0 +1,490 @@ +. + * + * --------------------------------------------------------------------- + */ + +namespace tests\units; + +use DbTestCase; + +class Agent extends DbTestCase +{ + const INV_FIXTURES = GLPI_ROOT . '/vendor/glpi-project/inventory_format/examples/'; + + public function testDefineTabs() + { + $expected = [ + 'Agent$main' => 'Agent', + 'RuleMatchedLog$0' => 'Import information', + ]; + + $agent = new \Agent(); + $this->assertSame($expected, $agent->defineTabs()); + } + + public function testHandleAgent() + { + $metadata = [ + 'deviceid' => 'glpixps-2018-07-09-09-07-13', + 'version' => 'FusionInventory-Agent_v2.5.2-1.fc31', + 'itemtype' => 'Computer', + 'tag' => '000005', + 'port' => '62354', + 'enabled-tasks' => [ + "inventory", + "netdiscovery", + "netinventory", + "remoteinventory", + "wakeonlan", + ] + ]; + + $agent = new \Agent(); + $this->assertGreaterThan(0, $agent->handleAgent($metadata)); + + // This should also work when inventory type is different than agent linked item type + $metadata['itemtype'] = 'Printer'; + + $agent = new \Agent(); + $this->assertGreaterThan(0, $agent->handleAgent($metadata)); + + // In the case the agent is used to submit another item type, we still + // need to have access to agent tag but no item should be linked + $tag = $agent->fields['tag']; + $port = $agent->fields['port']; + $items_id = $agent->fields['items_id']; + $this->assertSame('000005', $tag); + $this->assertSame('62354', $port); + $this->assertSame(0, $items_id); + + $this->assertSame(1, $agent->fields['use_module_computer_inventory']); + $this->assertSame(1, $agent->fields['use_module_network_discovery']); + $this->assertSame(1, $agent->fields['use_module_network_inventory']); + $this->assertSame(1, $agent->fields['use_module_remote_inventory']); + $this->assertSame(1, $agent->fields['use_module_wake_on_lan']); + $this->assertSame(0, $agent->fields['use_module_esx_remote_inventory']); + $this->assertSame(0, $agent->fields['use_module_package_deployment']); + $this->assertSame(0, $agent->fields['use_module_collect_data']); + } + + public function testHandleAgentWOType() + { + /** @var \DBmysql $DB */ + global $DB; + + //explicitly remove agent type + $this->assertTrue( + $DB->delete( + \AgentType::getTable(), + [ + 'name' => 'Core' + ] + ) + ); + //then rerun tests + $this->testHandleAgent(); + } + + public function testHandleAgentOnUpdate() + { + $metadata = [ + 'deviceid' => 'glpixps-2018-07-09-09-07-13', + 'version' => 'FusionInventory-Agent_v2.5.2-1.fc31', + 'itemtype' => 'Computer', + 'tag' => '000006', + 'port' => '62354', + 'enabled-tasks' => [ + "inventory", + "remoteinventory", + "wakeonlan", + "collect", + "esx", + ] + ]; + + $agent = new \Agent(); + $this->assertGreaterThan(0, $agent->handleAgent($metadata)); + + // This should also work when inventory type is different than agent linked item type + $metadata['itemtype'] = 'Printer'; + + $agent = new \Agent(); + $this->assertGreaterThan(0, $agent->handleAgent($metadata)); + + // In the case the agent is used to submit another item type, we still + // need to have access to agent tag but no item should be linked + $tag = $agent->fields['tag']; + $port = $agent->fields['port']; + $items_id = $agent->fields['items_id']; + $this->assertSame('000006', $tag); + $this->assertSame('62354', $port); + $this->assertSame(0, $items_id); + + $this->assertSame(1, $agent->fields['use_module_computer_inventory']); + $this->assertSame(0, $agent->fields['use_module_network_discovery']); + $this->assertSame(0, $agent->fields['use_module_network_inventory']); + $this->assertSame(1, $agent->fields['use_module_remote_inventory']); + $this->assertSame(1, $agent->fields['use_module_wake_on_lan']); + $this->assertSame(1, $agent->fields['use_module_esx_remote_inventory']); + $this->assertSame(0, $agent->fields['use_module_package_deployment']); + $this->assertSame(1, $agent->fields['use_module_collect_data']); + } + + public function testAgentFeaturesFromItem() + { + //run an inventory + $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); + $inventory = new \Glpi\Inventory\Inventory($json); + + if ($inventory->inError()) { + foreach ($inventory->getErrors() as $error) { + var_dump($error); + } + } + $this->assertFalse($inventory->inError()); + $this->assertSame([], $inventory->getErrors()); + + //check inventory metadata + $metadata = $inventory->getMetadata(); + $this->assertCount(7, $metadata); + $this->assertSame('glpixps-2018-07-09-09-07-13', $metadata['deviceid']); + $this->assertSame('FusionInventory-Agent_v2.5.2-1.fc31', $metadata['version']); + $this->assertSame('Computer', $metadata['itemtype']); + $this->assertSame('inventory', $metadata['action']); + $this->assertNull($metadata['port']); + $this->assertSame('000005', $metadata['tag']); + $this->assertCount(10, $metadata['provider']); + + /** @var \DBmysql $DB */ + global $DB; + //check created agent + $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); + $agents = $DB->request(['FROM' => \Agent::getTable()]); + $this->assertCount(1, $agents); + $current_agent = $agents->current(); + $this->assertSame('glpixps-2018-07-09-09-07-13', $current_agent['deviceid']); + $this->assertSame('glpixps-2018-07-09-09-07-13', $current_agent['name']); + $this->assertSame('2.5.2-1.fc31', $current_agent['version']); + $this->assertSame('Computer', $current_agent['itemtype']); + $this->assertSame($agenttype['id'], $current_agent['agenttypes_id']); + + $agent = new \Agent(); + $this->assertTrue($agent->getFromDB($current_agent['id'])); + + $item = $agent->getLinkedItem(); + $this->assertInstanceOf(\Computer::class, $item); + + $this->assertSame( + [ + 'glpixps', + '192.168.1.142', + '[fe80::b283:4fa3:d3f2:96b1]', + '192.168.1.118', + '[fe80::92a4:26c6:99dd:2d60]', + '192.168.122.1' + ], + $agent->guessAddresses() + ); + + $this->assertSame( + [ + 'http://glpixps:62354', + 'http://192.168.1.142:62354', + 'http://[fe80::b283:4fa3:d3f2:96b1]:62354', + 'http://192.168.1.118:62354', + 'http://[fe80::92a4:26c6:99dd:2d60]:62354', + 'http://192.168.122.1:62354', + 'https://glpixps:62354', + 'https://192.168.1.142:62354', + 'https://[fe80::b283:4fa3:d3f2:96b1]:62354', + 'https://192.168.1.118:62354', + 'https://[fe80::92a4:26c6:99dd:2d60]:62354', + 'https://192.168.122.1:62354' + ], + $agent->getAgentURLs() + ); + + //link a domain to item and see if adresses are still ok + $domain = new \Domain(); + $did = $domain->add([ + 'name' => 'glpi-project.org' + ]); + $this->assertGreaterThan(0, $did); + + $ditem = new \Domain_Item(); + $this->assertGreaterThan( + 0, + $ditem->add([ + 'itemtype' => $item->getType(), + 'items_id' => $item->getID(), + 'domains_id' => $did + ]) + ); + + $this->assertSame( + [ + 'glpixps', + '192.168.1.142', + '[fe80::b283:4fa3:d3f2:96b1]', + '192.168.1.118', + '[fe80::92a4:26c6:99dd:2d60]', + '192.168.122.1', + 'glpixps.glpi-project.org' + ], + $agent->guessAddresses() + ); + } + + public function testAgentHasChanged() + { + //run an inventory + $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); + $inventory = new \Glpi\Inventory\Inventory($json); + + if ($inventory->inError()) { + foreach ($inventory->getErrors() as $error) { + var_dump($error); + } + } + $this->assertFalse($inventory->inError()); + $this->assertSame([], $inventory->getErrors()); + + //check inventory metadata + $metadata = $inventory->getMetadata(); + $this->assertCount(7, $metadata); + $this->assertSame('glpixps-2018-07-09-09-07-13', $metadata['deviceid']); + $this->assertSame('FusionInventory-Agent_v2.5.2-1.fc31', $metadata['version']); + $this->assertSame('Computer', $metadata['itemtype']); + $this->assertSame('inventory', $metadata['action']); + $this->assertNull($metadata['port']); + $this->assertSame('000005', $metadata['tag']); + $this->assertCount(10, $metadata['provider']); + + /** @var \DBmysql $DB */ + global $DB; + //check created agent + $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); + $agents = $DB->request(['FROM' => \Agent::getTable()]); + $this->assertCount(1, $agents); + $current_agent = $agents->current(); + $this->assertSame('glpixps-2018-07-09-09-07-13', $current_agent['deviceid']); + $this->assertSame('glpixps-2018-07-09-09-07-13', $current_agent['name']); + $this->assertSame('2.5.2-1.fc31', $current_agent['version']); + $this->assertSame('Computer', $current_agent['itemtype']); + $this->assertSame('000005', $current_agent['tag']); + $this->assertSame($agenttype['id'], $current_agent['agenttypes_id']); + $old_agents_id = $current_agent['id']; + + $agent = new \Agent(); + $this->assertTrue($agent->getFromDB($current_agent['id'])); + + $item = $agent->getLinkedItem(); + $this->assertInstanceOf(\Computer::class, $item); + + //play an update with changes + $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); + + //change agent and therefore deviceid + $json->content->versionclient = 'GLPI-Agent_v1'; + $json->deviceid = 'glpixps-2022-01-17-11-36-53'; + + $CFG_GLPI["is_contact_autoupdate"] = 0; + $inventory = new \Glpi\Inventory\Inventory($json); + $CFG_GLPI["is_contact_autoupdate"] = 1; //reset to default + + if ($inventory->inError()) { + foreach ($inventory->getErrors() as $error) { + var_dump($error); + } + } + $this->assertFalse($inventory->inError()); + $this->assertSame([], $inventory->getErrors()); + + //check inventory metadata + $metadata = $inventory->getMetadata(); + $this->assertCount(7, $metadata); + $this->assertSame('glpixps-2022-01-17-11-36-53', $metadata['deviceid']); + $this->assertSame('GLPI-Agent_v1', $metadata['version']); + $this->assertSame('Computer', $metadata['itemtype']); + $this->assertSame('inventory', $metadata['action']); + $this->assertNull($metadata['port']); + $this->assertSame('000005', $metadata['tag']); + $this->assertCount(10, $metadata['provider']); + + //check old agent has been dropped + $current_agent = new \Agent(); + $this->assertFalse($current_agent->getFromDB($old_agents_id), 'Old Agent still exists!'); + } + + public function testTagFromXML() + { + //run an inventory + $xml = " + + + + glpixps + 25C1BB60-5BCB-11D9-B18F-5404A6A534C4 + + + 640HP72 + 000 + + + TAG + 000005 + + FusionInventory-Inventory_v2.4.1-2.fc28 + + glpixps.teclib.infra-2018-10-03-08-42-36 + INVENTORY + "; + + $converter = new \Glpi\Inventory\Converter(); + $data = $converter->convert($xml); + $json = json_decode($data); + + $inventory = new \Glpi\Inventory\Inventory($json); + + if ($inventory->inError()) { + foreach ($inventory->getErrors() as $error) { + var_dump($error); + } + } + $this->assertFalse($inventory->inError()); + $this->assertSame([], $inventory->getErrors()); + + //check inventory metadata + $metadata = $inventory->getMetadata(); + $this->assertCount(6, $metadata); + $this->assertSame('Computer', $metadata['itemtype']); + $this->assertSame('inventory', $metadata['action']); + $this->assertNull($metadata['port']); + $this->assertSame('000005', $metadata['tag']); + + /** @var \DBmysql $DB */ + global $DB; + //check created agent + $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); + $agents = $DB->request(['FROM' => \Agent::getTable()]); + $this->assertCount(1, $agents); + $agent = $agents->current(); + $this->assertSame('Computer', $agent['itemtype']); + $this->assertSame('000005', $agent['tag']); + $this->assertSame($agenttype['id'], $agent['agenttypes_id']); + } + + public function testStaleActions() + { + //run an inventory + $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); + $inventory = new \Glpi\Inventory\Inventory($json); + + if ($inventory->inError()) { + foreach ($inventory->getErrors() as $error) { + var_dump($error); + } + } + $this->assertFalse($inventory->inError()); + $this->assertSame([], $inventory->getErrors()); + + //check inventory metadata + $metadata = $inventory->getMetadata(); + $this->assertCount(7, $metadata); + $this->assertSame('glpixps-2018-07-09-09-07-13', $metadata['deviceid']); + $this->assertSame('FusionInventory-Agent_v2.5.2-1.fc31', $metadata['version']); + $this->assertSame('Computer', $metadata['itemtype']); + $this->assertSame('inventory', $metadata['action']); + $this->assertNull($metadata['port']); + $this->assertSame('000005', $metadata['tag']); + $this->assertCount(10, $metadata['provider']); + + /** @var \DBmysql $DB */ + global $DB; + //check created agent + $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); + $agents = $DB->request(['FROM' => \Agent::getTable()]); + $this->assertCount(1, $agents); + $current_agent = $agents->current(); + $this->assertSame('glpixps-2018-07-09-09-07-13', $current_agent['deviceid']); + $this->assertSame('glpixps-2018-07-09-09-07-13', $current_agent['name']); + $this->assertSame('2.5.2-1.fc31', $current_agent['version']); + $this->assertSame('Computer', $current_agent['itemtype']); + $this->assertSame('000005', $current_agent['tag']); + $this->assertSame($agenttype['id'], $current_agent['agenttypes_id']); + $old_agents_id = $current_agent['id']; + + $agent = new \Agent(); + $this->assertTrue($agent->getFromDB($current_agent['id'])); + + $item = $agent->getLinkedItem(); + $this->assertInstanceOf(\Computer::class, $item); + + //check default status + $this->assertSame(0, $item->fields['states_id']); + + //create new status + $state = new \State(); + $states_id = $state->add(['name' => 'Stale']); + $this->assertGreaterThan(0, $states_id); + + //set last agent contact far ago + $DB->update( + \Agent::getTable(), + ['last_contact' => date('Y-m-d H:i:s', strtotime('-1 year'))], + ['id' => $current_agent['id']] + ); + + //define stale agents actions + \Config::setConfigurationValues( + 'inventory', + [ + 'stale_agents_delay' => 1, + 'stale_agents_action' => exportArrayToDB([ + \Glpi\Inventory\Conf::STALE_AGENT_ACTION_STATUS, + \Glpi\Inventory\Conf::STALE_AGENT_ACTION_TRASHBIN + ]), + 'stale_agents_status' => $states_id + ] + ); + + //run crontask + $task = new \CronTask(); + $this->assertSame(1, \Agent::cronCleanoldagents($task)); + + //check item has been updated + $this->assertTrue($item->getFromDB($item->fields['id'])); + $this->assertSame(1, $item->fields['is_deleted']); + $this->assertSame($states_id, $item->fields['states_id']); + } +} diff --git a/tests/functional/Alert.php b/phpunit/functional/Alert.php similarity index 58% rename from tests/functional/Alert.php rename to phpunit/functional/Alert.php index 2f7e01744e5..6e8349e6eca 100644 --- a/tests/functional/Alert.php +++ b/phpunit/functional/Alert.php @@ -44,37 +44,36 @@ class Alert extends DbTestCase public function testAddDelete() { $alert = new \Alert(); - $nb = (int)countElementsInTable($alert->getTable()); + $nb = countElementsInTable($alert->getTable()); $comp = getItemByTypeName('Computer', '_test_pc01'); $date = '2016-09-01 12:34:56'; - // Add + // Add $id = $alert->add([ 'itemtype' => $comp->getType(), 'items_id' => $comp->getID(), 'type' => \Alert::END, 'date' => $date, ]); - $this->integer($id)->isGreaterThan(0); - $this->integer((int)countElementsInTable($alert->getTable()))->isGreaterThan($nb); + $this->assertGreaterThan(0, $id); + $this->assertGreaterThan($nb, countElementsInTable($alert->getTable())); - // Getters - $this->boolean(\Alert::alertExists($comp->getType(), $comp->getID(), \Alert::NOTICE))->isFalse(); - $this->integer((int)\Alert::alertExists($comp->getType(), $comp->getID(), \Alert::END))->isIdenticalTo($id); - $this->string(\Alert::getAlertDate($comp->getType(), $comp->getID(), \Alert::END))->isIdenticalTo($date); + // Getters + $this->assertFalse(\Alert::alertExists($comp->getType(), $comp->getID(), \Alert::NOTICE)); + $this->assertSame($id, (int)\Alert::alertExists($comp->getType(), $comp->getID(), \Alert::END)); + $this->assertSame($date, \Alert::getAlertDate($comp->getType(), $comp->getID(), \Alert::END)); - // Display - $this->output( - function () use ($comp) { - \Alert::displayLastAlert($comp->getType(), $comp->getID()); - } - )->isIdenticalTo(sprintf('Alert sent on %s', \Html::convDateTime($date))); + // Display + ob_start(); + \Alert::displayLastAlert($comp->getType(), $comp->getID()); + $output = ob_get_clean(); + $this->assertSame(sprintf('Alert sent on %s', \Html::convDateTime($date)), $output); - // Delete - $this->boolean($alert->clear($comp->getType(), $comp->getID(), \Alert::END))->isTrue(); - $this->integer((int)countElementsInTable($alert->getTable()))->isIdenticalTo($nb); + // Delete + $this->assertTrue($alert->clear($comp->getType(), $comp->getID(), \Alert::END)); + $this->assertSame(0, countElementsInTable($alert->getTable())); - // Still true, nothing to delete but no error - $this->boolean($alert->clear($comp->getType(), $comp->getID(), \Alert::END))->isTrue(); + // Still true, nothing to delete but no error + $this->assertTrue($alert->clear($comp->getType(), $comp->getID(), \Alert::END)); } } diff --git a/tests/functional/Appliance.php b/phpunit/functional/ApplianceTest.php similarity index 60% rename from tests/functional/Appliance.php rename to phpunit/functional/ApplianceTest.php index bd981bf27a8..6940b620bc6 100644 --- a/tests/functional/Appliance.php +++ b/phpunit/functional/ApplianceTest.php @@ -37,7 +37,7 @@ use DbTestCase; -class Appliance extends DbTestCase +class ApplianceTest extends DbTestCase { public function testDefineTabs() { @@ -46,35 +46,22 @@ public function testDefineTabs() 'Impact$1' => 'Impact analysis', 'ManualLink$1' => 'Links', ]; - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->defineTabs()) - ->isIdenticalTo($expected, print_r($this->testedInstance->defineTabs(), true)); + + $appliance = new \Appliance(); + $this->assertSame($expected, $appliance->defineTabs()); } public function testGetTypes() { + /** @var array $CFG_GLPI */ global $CFG_GLPI; - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->getTypes(true)) - ->isIdenticalTo($CFG_GLPI['appliance_types']); - - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->getTypes()) - ->isIdenticalTo([]); + $appliance = new \Appliance(); + $this->assertSame($CFG_GLPI['appliance_types'], $appliance->getTypes(true)); + $this->assertSame([], $appliance->getTypes()); $this->login(); - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->getTypes()) - ->isIdenticalTo($CFG_GLPI['appliance_types']); + $this->assertSame($CFG_GLPI['appliance_types'], $appliance->getTypes()); } public function testClone() @@ -82,108 +69,112 @@ public function testClone() $this->login(); $app = new \Appliance(); - // Add + // Add $id = $app->add([ 'name' => $this->getUniqueString(), 'entities_id' => 0 ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Update + // Update $id = $app->getID(); - $this->boolean($app->getFromDB($id))->isTrue(); + $this->assertTrue($app->getFromDB($id)); $date = date('Y-m-d H:i:s'); $_SESSION['glpi_currenttime'] = $date; $iapp = new \Appliance_Item(); - $this->integer( + $this->assertGreaterThan( + 0, $iapp->add([ 'appliances_id' => $id, 'itemtype' => 'Computer', 'items_id' => getItemByTypeName('Computer', '_test_pc01', true) ]) - )->isGreaterThan(0); + ); $rapp = new \Appliance_Item_Relation(); - $this->integer( + $this->assertGreaterThan( + 0, $rapp->add([ 'appliances_items_id' => $iapp->fields['id'], 'itemtype' => 'Location', 'items_id' => getItemByTypeName('Location', '_location01', true) ]) - )->isGreaterThan(0); + ); - //add infocom + //add infocom $infocom = new \Infocom(); - $this->integer( + $this->assertGreaterThan( + 0, $infocom->add([ 'itemtype' => 'Appliance', 'items_id' => $id ]) - )->isGreaterThan(0); + ); - //add document + //add document $document = new \Document(); $docid = (int)$document->add(['name' => 'Test link document']); - $this->integer($docid)->isGreaterThan(0); + $this->assertGreaterThan(0, $docid); $docitem = new \Document_Item(); - $this->integer( + $this->assertGreaterThan( + 0, $docitem->add([ 'documents_id' => $docid, 'itemtype' => 'Appliance', 'items_id' => $id ]) - )->isGreaterThan(0); + ); - // Test item cloning + // Test item cloning $added = (int)$app->clone(); - $this->integer($added) - ->isGreaterThan(0) - ->isNotEqualTo($app->fields['id']); + $this->assertGreaterThan(0, $added); + $this->assertNotEquals($app->fields['id'], $added); $clonedApp = new \Appliance(); - $this->boolean($clonedApp->getFromDB($added))->isTrue(); + $this->assertTrue($clonedApp->getFromDB($added)); $fields = $app->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($clonedApp->getField($k))->isNotEqualTo($app->getField($k)); + $this->assertNotEquals($app->getField($k), $clonedApp->getField($k)); break; case 'date_mod': case 'date_creation': $dateClone = new \DateTime($clonedApp->getField($k)); $expectedDate = new \DateTime($date); - $this->dateTime($dateClone)->isEqualTo($expectedDate); + $this->assertEquals($expectedDate, $dateClone); break; case 'name': - $this->variable($clonedApp->getField($k))->isEqualTo("{$app->getField($k)} (copy)"); + $this->assertEquals("{$app->getField($k)} (copy)", $clonedApp->getField($k)); break; default: - $this->variable($clonedApp->getField($k))->isEqualTo($app->getField($k)); + $this->assertEquals($app->getField($k), $clonedApp->getField($k)); } } - //Infocom has been cloned - $this->integer( + //Infocom has been cloned + $this->assertSame( + 1, countElementsInTable( \Infocom::getTable(), ['items_id' => $clonedApp->fields['id']] ) - )->isIdenticalTo(1); + ); - //documents has been cloned - $this->boolean($docitem->getFromDBByCrit(['itemtype' => 'Appliance', 'items_id' => $added]))->isTrue(); + //documents has been cloned + $this->assertTrue($docitem->getFromDBByCrit(['itemtype' => 'Appliance', 'items_id' => $added])); - //items has been cloned - $this->boolean($iapp->getFromDBByCrit(['appliances_id' => $added]))->isTrue(); + //items has been cloned + $this->assertTrue($iapp->getFromDBByCrit(['appliances_id' => $added])); - //relations has been cloned - $this->boolean($rapp->getFromDBByCrit(['appliances_items_id' => $iapp->fields['id']]))->isTrue(); + //relations has been cloned + $this->assertTrue($rapp->getFromDBByCrit(['appliances_items_id' => $iapp->fields['id']])); } public function testMetaSearch() @@ -191,31 +182,44 @@ public function testMetaSearch() $this->login(); $computer = new \Computer(); - $this->integer($computers_id = $computer->add([ + $computers_id = $computer->add([ 'name' => 'Test computer', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ])); + ]); + $this->assertGreaterThan(0, $computers_id); + $cluster = new \Cluster(); - $this->integer($clusters_id = $cluster->add([ + $clusters_id = $cluster->add([ 'name' => 'Test cluster', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ])); + ]); + $this->assertGreaterThan(0, $clusters_id); + $appliance = new \Appliance(); - $this->integer($appliances_id = $appliance->add([ + $appliances_id = $appliance->add([ 'name' => 'Test appliance', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ])); + ]); + $this->assertGreaterThan(0, $appliances_id); + $appliance_item = new \Appliance_Item(); - $this->integer($appliance_item->add([ - 'appliances_id' => $appliances_id, - 'itemtype' => 'Computer', - 'items_id' => $computers_id - ])); - $this->integer($appliance_item->add([ - 'appliances_id' => $appliances_id, - 'itemtype' => 'Cluster', - 'items_id' => $clusters_id - ])); + $this->assertGreaterThan( + 0, + $appliance_item->add([ + 'appliances_id' => $appliances_id, + 'itemtype' => 'Computer', + 'items_id' => $computers_id + ]) + ); + + $this->assertGreaterThan( + 0, + $appliance_item->add([ + 'appliances_id' => $appliances_id, + 'itemtype' => 'Cluster', + 'items_id' => $clusters_id + ]) + ); $criteria = [ [ @@ -230,8 +234,8 @@ public function testMetaSearch() $data = \Search::getDatas('Appliance', [ 'criteria' => $criteria, ]); - $this->integer($data['data']['totalcount'])->isEqualTo(1); - $this->string($data['data']['rows'][0]['Computer_1'][0]['name'])->isEqualTo('Test computer'); + $this->assertSame(1, $data['data']['totalcount']); + $this->assertSame('Test computer', $data['data']['rows'][0]['Computer_1'][0]['name']); $criteria = [ [ @@ -246,7 +250,7 @@ public function testMetaSearch() $data = \Search::getDatas('Appliance', [ 'criteria' => $criteria, ]); - $this->integer($data['data']['totalcount'])->isEqualTo(1); - $this->string($data['data']['rows'][0]['Cluster_1'][0]['name'])->isEqualTo('Test cluster'); + $this->assertSame(1, $data['data']['totalcount']); + $this->assertSame('Test cluster', $data['data']['rows'][0]['Cluster_1'][0]['name']); } } diff --git a/tests/functional/Appliance_Item.php b/phpunit/functional/Appliance_Item.php similarity index 64% rename from tests/functional/Appliance_Item.php rename to phpunit/functional/Appliance_Item.php index c86350d42b5..888eb4650c1 100644 --- a/tests/functional/Appliance_Item.php +++ b/phpunit/functional/Appliance_Item.php @@ -41,14 +41,16 @@ class Appliance_Item extends DbTestCase { public function testGetForbiddenStandardMassiveAction() { - $this->newTestedInstance(); - $this->array( - $this->testedInstance->getForbiddenStandardMassiveAction() - )->isIdenticalTo(['clone', 'update', 'CommonDBConnexity:unaffect', 'CommonDBConnexity:affect']); + $aitem = new \Appliance_Item(); + $this->assertSame( + ['clone', 'update', 'CommonDBConnexity:unaffect', 'CommonDBConnexity:affect'], + $aitem->getForbiddenStandardMassiveAction() + ); } public function testCountForAppliance() { + /** @var \DBmysql $DB */ global $DB; $appliance = new \Appliance(); @@ -56,12 +58,12 @@ public function testCountForAppliance() $appliance_1 = (int)$appliance->add([ 'name' => 'Test appliance' ]); - $this->integer($appliance_1)->isGreaterThan(0); + $this->assertGreaterThan(0, $appliance_1); $appliance_2 = (int)$appliance->add([ 'name' => 'Test appliance' ]); - $this->integer($appliance_2)->isGreaterThan(0); + $this->assertGreaterThan(0, $appliance_2); $itemtypes = [ 'Computer' => '_test_pc01', @@ -72,7 +74,7 @@ public function testCountForAppliance() foreach ($itemtypes as $itemtype => $itemname) { $items_id = getItemByTypeName($itemtype, $itemname, true); foreach ([$appliance_1, $appliance_2] as $app) { - //no printer on appliance_2 + //no printer on appliance_2 if ($itemtype == 'Printer' && $app == $appliance_2) { continue; } @@ -82,34 +84,31 @@ public function testCountForAppliance() 'itemtype' => $itemtype, 'items_id' => $items_id ]; - $this - ->given($this->newTestedInstance) - ->then - ->integer($this->testedInstance->add($input)) - ->isGreaterThan(0); + $aitem = new \Appliance_Item(); + $this->assertGreaterThan(0, $aitem->add($input)); } } - $this->boolean($appliance->getFromDB($appliance_1))->isTrue(); - //not logged, no Appliances types - $this->integer(\Appliance_Item::countForMainItem($appliance))->isIdenticalTo(0); + $this->assertTrue($appliance->getFromDB($appliance_1)); + //not logged, no Appliances types + $this->assertSame(0, \Appliance_Item::countForMainItem($appliance)); $this->login(); - $this->integer(\Appliance_Item::countForMainItem($appliance))->isIdenticalTo(3); + $this->assertSame(3, \Appliance_Item::countForMainItem($appliance)); - $this->boolean($appliance->getFromDB($appliance_2))->isTrue(); - $this->integer(\Appliance_Item::countForMainItem($appliance))->isIdenticalTo(2); + $this->assertTrue($appliance->getFromDB($appliance_2)); + $this->assertSame(2, \Appliance_Item::countForMainItem($appliance)); - $this->boolean($appliance->getFromDB($appliance_1))->isTrue(); - $this->boolean($appliance->delete(['id' => $appliance_1], true))->isTrue(); + $this->assertTrue($appliance->getFromDB($appliance_1)); + $this->assertTrue($appliance->delete(['id' => $appliance_1], true)); - $this->boolean($appliance->getFromDB($appliance_2))->isTrue(); - $this->boolean($appliance->delete(['id' => $appliance_2], true))->isTrue(); + $this->assertTrue($appliance->getFromDB($appliance_2)); + $this->assertTrue($appliance->delete(['id' => $appliance_2], true)); $iterator = $DB->request([ 'FROM' => \Appliance_Item::getTable(), 'WHERE' => ['appliances_id' => [$appliance_1, $appliance_2]] ]); - $this->integer(count($iterator))->isIdenticalTo(0); + $this->assertCount(0, $iterator); } } diff --git a/tests/functional/Appliance_Item_Relation.php b/phpunit/functional/Appliance_Item_Relation.php similarity index 63% rename from tests/functional/Appliance_Item_Relation.php rename to phpunit/functional/Appliance_Item_Relation.php index 6e355882276..3bfa5fd0ef6 100644 --- a/tests/functional/Appliance_Item_Relation.php +++ b/phpunit/functional/Appliance_Item_Relation.php @@ -41,14 +41,16 @@ class Appliance_Item_Relation extends DbTestCase { public function testGetForbiddenStandardMassiveAction() { - $this->newTestedInstance(); - $this->array( - $this->testedInstance->getForbiddenStandardMassiveAction() - )->isIdenticalTo(['clone'/*, 'update', 'CommonDBConnexity:unaffect', 'CommonDBConnexity:affect'*/]); + $aritem = new \Appliance_Item_Relation(); + $this->assertSame( + ['clone'], + $aritem->getForbiddenStandardMassiveAction() + ); } public function testCountForApplianceItem() { + /** @var \DBmysql $DB */ global $DB; $appliance = new \Appliance(); @@ -56,7 +58,7 @@ public function testCountForApplianceItem() $appliances_id = (int)$appliance->add([ 'name' => 'Test appliance' ]); - $this->integer($appliances_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $appliances_id); $items_id = getItemByTypeName('Computer', '_test_pc01', true); $input = [ @@ -66,49 +68,41 @@ public function testCountForApplianceItem() ]; $appitem = new \Appliance_Item(); $appliances_items_id = $appitem->add($input); - $this->integer($appliances_items_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $appliances_items_id); $input = [ 'appliances_items_id' => $appliances_items_id, 'itemtype' => 'Location', 'items_id' => getItemByTypeName('Location', '_location01', true) ]; - $this - ->given($this->newTestedInstance) - ->then - ->integer($this->testedInstance->add($input)) - ->isGreaterThan(0); + $aritem = new \Appliance_Item_Relation(); + $this->assertGreaterThan(0, $aritem->add($input)); - $iterator = $DB->request([ - 'FROM' => \Appliance_Item_Relation::getTable(), - 'WHERE' => ['appliances_items_id' => $appliances_items_id] - ]); - - $this->boolean($appliance->getFromDB($appliances_id))->isTrue(); - $this->boolean($appitem->getFromDB($appliances_items_id))->isTrue(); - //not logged, no Appliances types - $this->integer(\Appliance_Item_Relation::countForMainItem($appitem))->isIdenticalTo(0); + $this->assertTrue($appliance->getFromDB($appliances_id)); + $this->assertTrue($appitem->getFromDB($appliances_items_id)); + //not logged, no Appliances types + $this->assertSame(0, \Appliance_Item_Relation::countForMainItem($appitem)); $this->login(); $this->setEntity(0, true); //locations are in root entity not recursive - $this->integer(\Appliance_Item_Relation::countForMainItem($appitem))->isIdenticalTo(1); + $this->assertSame(1, \Appliance_Item_Relation::countForMainItem($appitem)); $relations = \Appliance_Item_Relation::getForApplianceItem($appliances_items_id); - $this->array($relations)->hasSize(1); - $this->string(array_pop($relations))->contains('_location01'); + $this->assertCount(1, $relations); + $this->assertStringContainsString('_location01', array_pop($relations)); - $this->boolean($appliance->delete(['id' => $appliances_id], true))->isTrue(); + $this->assertTrue($appliance->delete(['id' => $appliances_id], true)); $iterator = $DB->request([ 'FROM' => \Appliance_Item::getTable(), 'WHERE' => ['appliances_id' => $appliances_id] ]); - $this->integer(count($iterator))->isIdenticalTo(0); + $this->assertCount(0, $iterator); $iterator = $DB->request([ 'FROM' => \Appliance_Item_Relation::getTable(), 'WHERE' => ['appliances_items_id' => $appliances_items_id] ]); - $this->integer(count($iterator))->isIdenticalTo(0); + $this->assertCount(0, $iterator); - $this->array(\Appliance_Item_Relation::getForApplianceItem($appliances_items_id))->isEmpty(); + $this->assertSame([], \Appliance_Item_Relation::getForApplianceItem($appliances_items_id)); } } diff --git a/tests/functional/Auth.php b/phpunit/functional/Auth.php similarity index 84% rename from tests/functional/Auth.php rename to phpunit/functional/Auth.php index 35861e59fcd..56a94b4384d 100644 --- a/tests/functional/Auth.php +++ b/phpunit/functional/Auth.php @@ -41,7 +41,7 @@ class Auth extends DbTestCase { - protected function loginProvider() + public static function loginProvider() { return [ ['john', true], @@ -66,7 +66,7 @@ protected function loginProvider() */ public function testIsValidLogin($login, $isvalid) { - $this->boolean(\Auth::isValidLogin($login))->isIdenticalTo($isvalid); + $this->assertSame($isvalid, \Auth::isValidLogin($login)); } public function testGetLoginAuthMethods() @@ -76,7 +76,7 @@ public function testGetLoginAuthMethods() '_default' => 'local', 'local' => 'GLPI internal database' ]; - $this->array($methods)->isIdenticalTo($expected); + $this->assertSame($expected, $methods); } /** @@ -84,11 +84,11 @@ public function testGetLoginAuthMethods() * * @return array */ - protected function lockStrategyProvider() + public static function lockStrategyProvider() { $tests = []; - // test with no password expiration + // test with no password expiration $tests[] = [ 'last_update' => date('Y-m-d H:i:s', strtotime('-10 years')), 'exp_delay' => -1, @@ -96,7 +96,7 @@ protected function lockStrategyProvider() 'expected_lock' => false, ]; - // tests with no lock on password expiration + // tests with no lock on password expiration $cases = [ '-5 days' => false, '-30 days' => false, @@ -110,7 +110,7 @@ protected function lockStrategyProvider() ]; } - // tests with immediate lock on password expiration + // tests with immediate lock on password expiration $cases = [ '-5 days' => false, '-30 days' => true, @@ -124,7 +124,7 @@ protected function lockStrategyProvider() ]; } - // tests with delayed lock on password expiration + // tests with delayed lock on password expiration $cases = [ '-5 days' => false, '-20 days' => false, @@ -149,9 +149,10 @@ protected function lockStrategyProvider() */ public function testAccountLockStrategy(string $last_update, int $exp_delay, int $lock_delay, bool $expected_lock) { + /** @var array $CFG_GLPI */ global $CFG_GLPI; - // reset session to prevent session having less rights to create a user + // reset session to prevent session having less rights to create a user $this->login(); $user = new \User(); @@ -162,8 +163,8 @@ public function testAccountLockStrategy(string $last_update, int $exp_delay, int 'password2' => 'test', '_profiles_id' => 1, ]); - $this->integer($user_id)->isGreaterThan(0); - $this->boolean($user->update(['id' => $user_id, 'password_last_update' => $last_update]))->isTrue(); + $this->assertGreaterThan(0, $user_id); + $this->assertTrue($user->update(['id' => $user_id, 'password_last_update' => $last_update])); $cfg_backup = $CFG_GLPI; $CFG_GLPI['password_expiration_delay'] = $exp_delay; @@ -172,8 +173,8 @@ public function testAccountLockStrategy(string $last_update, int $exp_delay, int $is_logged = $auth->login($username, 'test', true); $CFG_GLPI = $cfg_backup; - $this->boolean($is_logged)->isEqualTo(!$expected_lock); - $this->boolean($user->getFromDB($user->fields['id']))->isTrue(); - $this->boolean((bool)$user->fields['is_active'])->isEqualTo(!$expected_lock); + $this->assertSame(!$expected_lock, $is_logged); + $this->assertTrue($user->getFromDB($user->fields['id'])); + $this->assertSame(!$expected_lock, (bool)$user->fields['is_active']); } } diff --git a/tests/functional/AuthLdapReplicate.php b/phpunit/functional/AuthLdapReplicate.php similarity index 75% rename from tests/functional/AuthLdapReplicate.php rename to phpunit/functional/AuthLdapReplicate.php index 26f96d497dc..c8d2093bf7c 100644 --- a/tests/functional/AuthLdapReplicate.php +++ b/phpunit/functional/AuthLdapReplicate.php @@ -44,25 +44,25 @@ class AuthLdapReplicate extends DbTestCase public function testCanCreate() { $this->login(); - $this->boolean((bool)\AuthLdapReplicate::canCreate())->isTrue(); + $this->assertTrue((bool)\AuthLdapReplicate::canCreate()); $_SESSION['glpiactiveprofile']['config'] = READ; - $this->boolean((bool)\AuthLdapReplicate::canCreate())->isFalse(); + $this->assertFalse((bool)\AuthLdapReplicate::canCreate()); $_SESSION['glpiactiveprofile']['config'] = 0; - $this->boolean((bool)\AuthLdapReplicate::canCreate())->isFalse(); + $this->assertFalse((bool)\AuthLdapReplicate::canCreate()); } public function testCanPurge() { $this->login(); - $this->boolean((bool)\AuthLdapReplicate::canPurge())->isTrue(); + $this->assertTrue((bool)\AuthLdapReplicate::canPurge()); $_SESSION['glpiactiveprofile']['config'] = READ; - $this->boolean((bool)\AuthLdapReplicate::canCreate())->isFalse(); + $this->assertFalse((bool)\AuthLdapReplicate::canCreate()); $_SESSION['glpiactiveprofile']['config'] = 0; - $this->boolean((bool)\AuthLdapReplicate::canCreate())->isFalse(); + $this->assertFalse((bool)\AuthLdapReplicate::canCreate()); } public function testGetForbiddenStandardMassiveAction() @@ -70,7 +70,7 @@ public function testGetForbiddenStandardMassiveAction() $this->login(); $replicate = new \AuthLdapReplicate(); $result = $replicate->getForbiddenStandardMassiveAction(); - $this->array($result)->isIdenticalTo([0 => 'update']); + $this->assertSame([0 => 'update'], $result); } public function testPrepareInputForAddAndUpdate() @@ -78,28 +78,28 @@ public function testPrepareInputForAddAndUpdate() $replicate = new \AuthLdapReplicate(); foreach (['prepareInputForAdd', 'prepareInputForUpdate'] as $method) { - //Do not set a port : no port added + //Do not set a port : no port added $result = $replicate->$method([ 'name' => 'test', 'host' => 'host' ]); - $this->array($result)->nothasKey('port'); + $this->assertArrayNotHasKey('port', $result); - //Port=0, change value to 389 + //Port=0, change value to 389 $result = $replicate->$method([ 'name' => 'test', 'host' => 'host', 'port' => 0 ]); - $this->integer($result['port'])->isIdenticalTo(389); + $this->assertSame(389, $result['port']); - //Port set : do not change it's value + //Port set : do not change its value $result = $replicate->$method([ 'name' => 'test', 'host' => 'host', 'port' => 3389 ]); - $this->integer($result['port'])->isIdenticalTo(3389); + $this->assertSame(3389, $result['port']); } } } diff --git a/tests/functional/Blacklist.php b/phpunit/functional/Blacklist.php similarity index 93% rename from tests/functional/Blacklist.php rename to phpunit/functional/Blacklist.php index 32b6f1fb67d..cde83a442e5 100644 --- a/tests/functional/Blacklist.php +++ b/phpunit/functional/Blacklist.php @@ -53,14 +53,14 @@ public function testGetDefaults() \Blacklist::MANUFACTURER => 1, \Blacklist::IP => 4 ]; - $this->array(array_keys($defaults))->isIdenticalTo(array_keys($expecteds)); + $this->assertSame(array_keys($expecteds), array_keys($defaults)); foreach ($expecteds as $type => $expected) { - $this->array($defaults[$type])->hasSize($expected); + $this->assertCount($expected, $defaults[$type]); } } - protected function processProvider(): array + public static function processProvider(): array { return [ [ @@ -115,6 +115,6 @@ public function testProcess($input, $expected) } $input = (object)$input; $blacklist->processBlackList($input); - $this->object($input)->isEqualTo($expected); + $this->assertEquals($expected, $input); } } diff --git a/tests/functional/Cable.php b/phpunit/functional/Cable.php similarity index 76% rename from tests/functional/Cable.php rename to phpunit/functional/Cable.php index 2343ac0998e..c429e7323b3 100644 --- a/tests/functional/Cable.php +++ b/phpunit/functional/Cable.php @@ -50,30 +50,30 @@ public function testAddSocket() $location = getItemByTypeName('Location', '_location01'); $expected = $socket->getName() . " (" . $location->getName() . ")"; $ret = \Dropdown::getDropdownName('glpi_sockets', $socket->getID()); - $this->string($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return with comments + // test of return with comments $expected = ['name' => $expected, 'comment' => "Comment for socket _socket01" ]; $ret = \Dropdown::getDropdownName('glpi_sockets', $socket->getID(), true); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); - // test of return without $tooltip + // test of return without $tooltip $ret = \Dropdown::getDropdownName('glpi_sockets', $socket->getID(), true, true, false); - $this->array($ret)->isIdenticalTo($expected); + $this->assertSame($expected, $ret); } public function testAddNetworkPortThenSocket() { $this->login(); - //First step add networkport + //First step add networkport $computer1 = getItemByTypeName('Computer', '_test_pc01'); $networkport = new \NetworkPort(); - // Be sure added - $nb_log = (int)countElementsInTable('glpi_logs'); + // Be sure added + $nb_log = countElementsInTable('glpi_logs'); $new_id = $networkport->add([ 'items_id' => $computer1->getID(), 'itemtype' => 'Computer', @@ -84,18 +84,18 @@ public function testAddNetworkPortThenSocket() 'instantiation_type' => 'NetworkPortEthernet', 'name' => 'eth1', ]); - $this->integer((int)$new_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $new_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - //Second step add socket - //add socket model + //Second step add socket + //add socket model $socketModel = new SocketModel(); $nb_log = (int)countElementsInTable('glpi_logs'); $socketModel_id = $socketModel->add([ 'name' => 'socketModel1' ]); - $this->integer((int)$socketModel_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $socketModel_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); $socket = new Socket(); $socket_id = $socket->add([ @@ -109,9 +109,9 @@ public function testAddNetworkPortThenSocket() 'locations_id' => 0, 'comment' => 'comment', ]); - $this->integer((int)$socket_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $socket_id); - // check data in db + // check data in db $all_sockets = getAllDataFromTable('glpi_sockets', ['ORDER' => 'id']); $current_socket = end($all_sockets); unset($current_socket['id']); @@ -129,31 +129,30 @@ public function testAddNetworkPortThenSocket() 'comment' => 'comment', ]; - $this->array($current_socket)->isIdenticalTo($expected); + $this->assertSame($expected, $current_socket); } public function testBackwardCompatibility() { - //test when sockets_id is defined from NetworkPort instanciation (NetworkPortEthernet, NetworkPortFiberChannel) //before it was the NetworkPort instantiation that had the socket reference //now it's the socket that have the networkport reference $this->login(); - //Second step add socket - //add socket model + //Second step add socket + //add socket model $socketModel = new SocketModel(); $nb_log = (int)countElementsInTable('glpi_logs'); $socketModel_id = $socketModel->add([ 'name' => 'socketModel1' ]); - $this->integer((int)$socketModel_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $socketModel_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); $socket = new Socket(); - $nb_log = (int)countElementsInTable('glpi_logs'); + $nb_log = countElementsInTable('glpi_logs'); $socket_id = $socket->add([ 'name' => 'socket1', 'wiring_side' => Socket::FRONT, //default is REAR @@ -162,16 +161,16 @@ public function testBackwardCompatibility() 'locations_id' => 0, 'comment' => 'comment', ]); - $this->integer((int)$socket_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $socket_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - //Second step add networkport - // Do some installations + //Second step add networkport + // Do some installations $computer1 = getItemByTypeName('Computer', '_test_pc01'); $networkport = new \NetworkPort(); - // Be sure added - $nb_log = (int)countElementsInTable('glpi_logs'); + // Be sure added + $nb_log = countElementsInTable('glpi_logs'); $new_id = $networkport->add([ 'items_id' => $computer1->getID(), 'itemtype' => 'Computer', @@ -192,28 +191,28 @@ public function testBackwardCompatibility() 'NetworkName__ipaddresses' => ['-1' => '192.168.20.1'], '_create_children' => true // automatically add instancation, networkname and ipadresses ]); - $this->integer($new_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $new_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - // retrieve NEtworkPortEthernet automatically created + // retrieve NetworkPortEthernet automatically created $all_netportethernets = getAllDataFromTable('glpi_networkportethernets', ['ORDER' => 'id']); $networkportethernet = end($all_netportethernets); $networkPortethernet_id = $networkportethernet['id']; unset($networkportethernet['date_mod']); unset($networkportethernet['date_creation']); - //specify sockets_id and update it + //specify sockets_id and update it $data = $networkportethernet; $data['id'] = $networkPortethernet_id; $data['sockets_id'] = $socket_id; $networkPort_ethernet = new \NetworkPortEthernet(); - $this->boolean($networkPort_ethernet->update($data))->isTrue(); + $this->assertTrue($networkPort_ethernet->update($data)); - //reload socket to check if link to networkports_id is ok (with itemtype and items_id) - $this->boolean($socket->getFromDB($socket_id))->isTrue(); - $this->string($socket->fields['itemtype'])->isIdenticalTo('Computer'); - $this->integer($socket->fields['items_id'])->isIdenticalTo($computer1->getID()); - $this->integer($socket->fields['networkports_id'])->isIdenticalTo($new_id); + //reload socket to check if link to networkports_id is ok (with itemtype and items_id) + $this->assertTrue($socket->getFromDB($socket_id)); + $this->assertSame('Computer', $socket->fields['itemtype']); + $this->assertSame($computer1->getID(), $socket->fields['items_id']); + $this->assertSame($new_id, $socket->fields['networkports_id']); } @@ -221,11 +220,11 @@ public function testAddCable() { $this->login(); - //First step add networkport / socket for computer '_test_pc01' + //First step add networkport / socket for computer '_test_pc01' $computer1 = getItemByTypeName('Computer', '_test_pc01'); $networkport1 = new \NetworkPort(); - // Be sure added + // Be sure added $nb_log = (int)countElementsInTable('glpi_logs'); $new1_id = $networkport1->add([ 'items_id' => $computer1->getID(), @@ -237,19 +236,19 @@ public function testAddCable() 'instantiation_type' => 'NetworkPortEthernet', 'name' => 'eth1', ]); - $this->integer((int)$new1_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $new1_id); + $this->assertGreaterThan($nb_log, (int)countElementsInTable('glpi_logs')); - //add socket model + //add socket model $socketModel1 = new SocketModel(); $nb_log = (int)countElementsInTable('glpi_logs'); $socketModel1_id = $socketModel1->add([ 'name' => 'socketModel1' ]); - $this->integer((int)$socketModel1_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $socketModel1_id); + $this->assertGreaterThan($nb_log, (int)countElementsInTable('glpi_logs')); - //add socket + //add socket $socket1 = new Socket(); $socket1_id = $socket1->add([ 'name' => 'socket1', @@ -262,9 +261,9 @@ public function testAddCable() 'locations_id' => 0, 'comment' => 'comment', ]); - $this->integer((int)$socket1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $socket1_id); - // check data in db + // check data in db $all_sockets = getAllDataFromTable('glpi_sockets', ['ORDER' => 'id']); $current_socket = end($all_sockets); unset($current_socket['id']); @@ -283,14 +282,14 @@ public function testAddCable() 'comment' => 'comment', ]; - $this->array($current_socket)->isIdenticalTo($expected); + $this->assertSame($expected, $current_socket); - //Second step add networkport / socket form switch '_test_pc02' + //Second step add networkport / socket form switch '_test_pc02' $computer2 = getItemByTypeName('Computer', '_test_pc02'); $networkport = new \NetworkPort(); - // Be sure added - $nb_log = (int)countElementsInTable('glpi_logs'); + // Be sure added + $nb_log = countElementsInTable('glpi_logs'); $new2_id = $networkport->add([ 'items_id' => $computer2->getID(), 'itemtype' => 'Computer', @@ -301,19 +300,19 @@ public function testAddCable() 'instantiation_type' => 'NetworkPortEthernet', 'name' => 'eth1', ]); - $this->integer((int)$new2_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $new2_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - //add socket model + //add socket model $socketModel2 = new SocketModel(); $nb_log = (int)countElementsInTable('glpi_logs'); $socketModel2_id = $socketModel2->add([ 'name' => 'socketModel2' ]); - $this->integer((int)$socketModel2_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $socketModel2_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - //add socket + //add socket $socket2 = new Socket(); $socket2_id = $socket2->add([ 'name' => 'socket2', @@ -326,9 +325,9 @@ public function testAddCable() 'locations_id' => 0, 'comment' => 'comment', ]); - $this->integer((int)$socket2_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $socket2_id); - // check data in db + // check data in db $all_sockets = getAllDataFromTable('glpi_sockets', ['ORDER' => 'id']); $current_socket = end($all_sockets); unset($current_socket['id']); @@ -346,37 +345,37 @@ public function testAddCable() 'comment' => 'comment', ]; - $this->array($current_socket)->isIdenticalTo($expected); + $this->assertSame($expected, $current_socket); - //add CableStradn + //add CableStradn $cableStrand = new \CableStrand(); $nb_log = (int)countElementsInTable('glpi_logs'); $cableStrand_id = $cableStrand->add([ 'name' => 'cable_strand' ]); - $this->integer((int)$cableStrand_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $cableStrand_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - //add State + //add State $cableState = new \State(); - $nb_log = (int)countElementsInTable('glpi_logs'); + $nb_log = countElementsInTable('glpi_logs'); $cableState_id = $cableState->add([ 'name' => 'cable_state', 'is_visible_cable' => true, ]); - $this->integer((int)$cableState_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $cableState_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - //add Cabletype + //add Cabletype $cableType = new \CableType(); - $nb_log = (int)countElementsInTable('glpi_logs'); + $nb_log = countElementsInTable('glpi_logs'); $cableType_id = $cableType->add([ 'name' => 'cable_type' ]); - $this->integer((int)$cableType_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $cableType_id); + $this->assertGreaterThan($nb_log, countElementsInTable('glpi_logs')); - //add cable + //add cable $cable = new \Cable(); $cable_id = $cable->add([ 'name' => 'cable', @@ -393,20 +392,20 @@ public function testAddCable() 'cablestrands_id' => $cableStrand_id, 'color' => '#f72f04', 'otherserial' => 'otherserial', - 'sates_id' => $cableState_id, + 'states_id' => $cableState_id, 'users_id_tech' => 2, 'cabletypes_id' => $cableType_id, 'comment' => 'comment', ]); - $this->integer((int)$cable_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cable_id); - // check data in db + // check data in db $all_cables = getAllDataFromTable('glpi_cables', ['ORDER' => 'id']); $current_cable = end($all_cables); - unset($current_cable['id']); unset($current_cable['date_mod']); unset($current_cable['date_creation']); $expected = [ + 'id' => $cable_id, 'name' => 'cable', 'entities_id' => $computer1->fields['entities_id'], 'is_recursive' => 0, @@ -421,10 +420,12 @@ public function testAddCable() 'cablestrands_id' => $cableStrand_id, 'color' => '#f72f04', 'otherserial' => 'otherserial', - 'sates_id' => $cableState_id, + 'states_id' => $cableState_id, 'users_id_tech' => 2, 'cabletypes_id' => $cableType_id, 'comment' => 'comment', + 'is_deleted' => 0 ]; + $this->assertSame($expected, $current_cable); } } diff --git a/tests/functional/Cartridge.php b/phpunit/functional/Cartridge.php similarity index 58% rename from tests/functional/Cartridge.php rename to phpunit/functional/Cartridge.php index 11f941d3183..d689638f0f1 100644 --- a/tests/functional/Cartridge.php +++ b/phpunit/functional/Cartridge.php @@ -48,56 +48,55 @@ public function testInstall() 'name' => 'Test printer', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) ]); - $this->integer((int)$pid)->isGreaterThan(0); - $this->boolean($printer->getFromDB($pid))->isTrue(); + $this->assertGreaterThan(0, $pid); + $this->assertTrue($printer->getFromDB($pid)); $ctype = new \CartridgeItemType(); $tid = $ctype->add([ 'name' => 'Test cartridge type', ]); - $this->integer((int)$tid)->isGreaterThan(0); - $this->boolean($ctype->getFromDB($tid))->isTrue(); + $this->assertGreaterThan(0, $tid); + $this->assertTrue($ctype->getFromDB($tid)); $citem = new \CartridgeItem(); $ciid = $citem->add([ 'name' => 'Test cartridge item', 'cartridgeitemtypes_id' => $tid ]); - $this->integer((int)$ciid)->isGreaterThan(0); - $this->boolean($citem->getFromDB($ciid))->isTrue(); + $this->assertGreaterThan(0, $ciid); + $this->assertTrue($citem->getFromDB($ciid)); $cartridge = new \Cartridge(); $cid = $cartridge->add([ 'name' => 'Test cartridge', 'cartridgeitems_id' => $ciid ]); - $this->integer((int)$cid)->isGreaterThan(0); - $this->boolean($cartridge->getFromDB($cid))->isTrue(); - $this->integer($cartridge->getUsedNumber($ciid))->isIdenticalTo(0); - $this->integer($cartridge->getTotalNumberForPrinter($pid))->isIdenticalTo(0); - - //install - $this->boolean($cartridge->install($pid, $ciid))->isTrue(); - //check install - $this->boolean($cartridge->getFromDB($cid))->isTrue(); - $this->array($cartridge->fields) - ->variable['printers_id']->isEqualTo($pid) - ->string['date_use']->matches('#\d{4}-\d{2}-\d{2}$#'); - $this->variable($cartridge->fields['date_out'])->isNull(); - //already installed - $this->boolean($cartridge->install($pid, $ciid))->isFalse(); + $this->assertGreaterThan(0, $cid); + $this->assertTrue($cartridge->getFromDB($cid)); + $this->assertSame(0, $cartridge->getUsedNumber($ciid)); + $this->assertSame(0, $cartridge->getTotalNumberForPrinter($pid)); + + //install + $this->assertTrue($cartridge->install($pid, $ciid)); + //check install + $this->assertTrue($cartridge->getFromDB($cid)); + $this->assertSame($pid, $cartridge->fields['printers_id']); + $this->assertMatchesRegularExpression('#\d{4}-\d{2}-\d{2}$#', $cartridge->fields['date_use']); + $this->assertNull($cartridge->fields['date_out']); + //already installed + $this->assertFalse($cartridge->install($pid, $ciid)); $this->hasSessionMessages(ERROR, ['No free cartridge']); - $this->integer($cartridge->getUsedNumber($ciid))->isIdenticalTo(1); - $this->integer($cartridge->getTotalNumberForPrinter($pid))->isIdenticalTo(1); + $this->assertSame(1, $cartridge->getUsedNumber($ciid)); + $this->assertSame(1, $cartridge->getTotalNumberForPrinter($pid)); - $this->boolean($cartridge->uninstall($cid))->isTrue(); - //this is not possible... But don't know if this is expected - //$this->boolean($cartridge->install($pid, $ciid))->isTrue(); - //check uninstall - $this->boolean($cartridge->getFromDB($cid))->isTrue(); - $this->string($cartridge->fields['date_out'])->matches('#\d{4}-\d{2}-\d{2}$#'); - $this->integer($cartridge->getUsedNumber($ciid))->isIdenticalTo(0); + $this->assertTrue($cartridge->uninstall($cid)); + //this is not possible... But don't know if this is expected + //$this->assertTrue($cartridge->install($pid, $ciid)); + //check uninstall + $this->assertTrue($cartridge->getFromDB($cid)); + $this->assertMatchesRegularExpression('#\d{4}-\d{2}-\d{2}$#', $cartridge->fields['date_out']); + $this->assertSame(0, $cartridge->getUsedNumber($ciid)); } public function testInfocomInheritance() @@ -108,7 +107,7 @@ public function testInfocomInheritance() $cu_id = (int) $cartridge_item->add([ 'name' => 'Test cartridge item' ]); - $this->integer($cu_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cu_id); $infocom = new \Infocom(); $infocom_id = (int) $infocom->add([ @@ -117,20 +116,20 @@ public function testInfocomInheritance() 'buy_date' => '2020-10-21', 'value' => '500' ]); - $this->integer($infocom_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $infocom_id); $cartridge_id = $cartridge->add([ 'cartridgeitems_id' => $cu_id ]); - $this->integer($cartridge_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $cartridge_id); $infocom2 = new \Infocom(); $infocom2_id = (int) $infocom2->getFromDBByCrit([ 'itemtype' => \Cartridge::getType(), 'items_id' => $cartridge_id ]); - $this->integer($infocom2_id)->isGreaterThan(0); - $this->string($infocom2->fields['buy_date'])->isEqualTo($infocom->fields['buy_date']); - $this->string($infocom2->fields['value'])->isEqualTo($infocom->fields['value']); + $this->assertGreaterThan(0, $infocom2_id); + $this->assertEquals($infocom->fields['buy_date'], $infocom2->fields['buy_date']); + $this->assertEquals($infocom->fields['value'], $infocom2->fields['value']); } } diff --git a/tests/functional/Certificate.php b/phpunit/functional/Certificate.php similarity index 62% rename from tests/functional/Certificate.php rename to phpunit/functional/Certificate.php index 1472f38fdad..d0d92679328 100644 --- a/tests/functional/Certificate.php +++ b/phpunit/functional/Certificate.php @@ -41,34 +41,21 @@ class Certificate 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 \Certificate(); // Add - $in = $this->getIn($this->method); + $in = $this->getIn($this->getUniqueString()); $id = $obj->add($in); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan(0, $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)); } } @@ -77,22 +64,22 @@ public function testUpdate() $this->login(); $obj = new \Certificate(); - // Add + // Add $id = $obj->add([ 'name' => $this->getUniqueString(), 'entities_id' => 0 ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Update + // Update $id = $obj->getID(); - $in = array_merge(['id' => $id], $this->getIn($this->method)); - $this->boolean($obj->update($in))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); + $in = array_merge(['id' => $id], $this->getIn($this->getUniqueString())); + $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)); } } @@ -101,18 +88,18 @@ public function testDelete() $this->login(); $obj = new \Certificate(); - // Add + // Add $id = $obj->add([ - 'name' => $this->method, + 'name' => $this->getUniqueString(), '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)); } public function testClone() @@ -120,48 +107,48 @@ public function testClone() $this->login(); $certificate = new \Certificate(); - // Add + // Add $id = $certificate->add([ 'name' => $this->getUniqueString(), 'entities_id' => 0 ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // Update + // Update $id = $certificate->getID(); - $in = array_merge(['id' => $id], $this->getIn($this->method)); - $this->boolean($certificate->update($in))->isTrue(); - $this->boolean($certificate->getFromDB($id))->isTrue(); + $in = array_merge(['id' => $id], $this->getIn($this->getUniqueString())); + $this->assertTrue($certificate->update($in)); + $this->assertTrue($certificate->getFromDB($id)); $date = date('Y-m-d H:i:s'); $_SESSION['glpi_currenttime'] = $date; - // Test item cloning + // Test item cloning $added = $certificate->clone(); - $this->integer((int)$added)->isGreaterThan(0); + $this->assertGreaterThan(0, $added); $clonedCertificate = new \Certificate(); - $this->boolean($clonedCertificate->getFromDB($added))->isTrue(); + $this->assertTrue($clonedCertificate->getFromDB($added)); $fields = $certificate->fields; - // Check the certificate values. Id and dates must be different, everything else must be equal + // Check the certificate values. ID and dates must be different, everything else must be equal foreach ($fields as $k => $v) { switch ($k) { case 'id': - $this->variable($clonedCertificate->getField($k))->isNotEqualTo($certificate->getField($k)); + $this->assertNotEquals($certificate->getField($k), $clonedCertificate->getField($k)); break; case 'date_mod': case 'date_creation': $dateClone = new \DateTime($clonedCertificate->getField($k)); $expectedDate = new \DateTime($date); - $this->dateTime($dateClone)->isEqualTo($expectedDate); + $this->assertEquals($expectedDate, $dateClone); break; case 'name': - $this->variable($clonedCertificate->getField($k))->isEqualTo("{$certificate->getField($k)} (copy)"); + $this->assertEquals("{$certificate->getField($k)} (copy)", $clonedCertificate->getField($k)); break; default: - $this->variable($clonedCertificate->getField($k))->isEqualTo($certificate->getField($k)); + $this->assertEquals($certificate->getField($k), $clonedCertificate->getField($k)); } } } @@ -199,55 +186,55 @@ public function testCronCertificate() $this->login(); $obj = new \Certificate(); - // Add + // Add $id = $obj->add([ 'name' => $this->getUniqueString(), 'entities_id' => 0, 'date_expiration' => date('Y-m-d', time() - MONTH_TIMESTAMP) ]); - $this->integer($id)->isGreaterThan(0); + $this->assertGreaterThan(0, $id); - // set root entity config for certificates alerts + // set root entity config for certificates alerts $entity = new \Entity(); - $entity->update([ - 'id' => 0, - 'use_certificates_alert' => true, - 'send_certificates_alert_before_delay' => true, - 'certificates_alert_repeat_interval' => 60 - ]); + $this->assertTrue( + $entity->update([ + 'id' => 0, + 'use_certificates_alert' => true, + 'send_certificates_alert_before_delay' => true, + 'certificates_alert_repeat_interval' => 6 * HOUR_TIMESTAMP //60 minutes was not enough with phpunit... + ]) + ); - // force usage of notification (no alert sent otherwise) + // force usage of notification (no alert sent otherwise) $CFG_GLPI['use_notifications'] = true; $CFG_GLPI['notifications_ajax'] = 1; - // lanch glpi cron and force task certificate + // launch glpi cron and force task certificate $crontask = new \CronTask(); $force = -1; $ret = $crontask->launch($force, 1, 'certificate'); + $this->assertNotEquals(false, $ret); - // check presence of the id in alerts table + // check presence of the id in alerts table $alert = new \Alert(); $alerts = $alert->find(); - $this->array($alerts) - ->hasSize(1); + $this->assertCount(1, $alerts); $alert_certificate = array_pop($alerts); - $this->array($alert_certificate) - ->string['itemtype']->isEqualTo('Certificate') - ->integer['items_id']->isEqualTo($id); + $this->assertEquals('Certificate', $alert_certificate['itemtype']); + $this->assertEquals($id, $alert_certificate['items_id']); // No new alert if the last one is less than 1 hour old $alert_id = $alert_certificate['id']; $ret = $crontask->launch($force, 1, 'certificate'); + $this->assertNotEquals(false, $ret); $alerts = $alert->find(); - $this->array($alerts) - ->hasSize(1); + $this->assertCount(1, $alerts); $alert_certificate = array_pop($alerts); - $this->array($alert_certificate) - ->string['itemtype']->isEqualTo('Certificate') - ->integer['items_id']->isEqualTo($id) - ->integer['id']->isEqualTo($alert_id); + $this->assertEquals('Certificate', $alert_certificate['itemtype']); + $this->assertEquals($id, $alert_certificate['items_id']); + $this->assertEquals($alert_id, $alert_certificate['id']); // New alert if the last one is more than 1 hour old $alert_id = $alert_certificate['id']; @@ -256,14 +243,13 @@ public function testCronCertificate() 'date' => date('Y-m-d', time() - DAY_TIMESTAMP) ]); $ret = $crontask->launch($force, 1, 'certificate'); + $this->assertNotEquals(false, $ret); $alerts = $alert->find(); - $this->array($alerts) - ->hasSize(1); + $this->assertCount(1, $alerts); $alert_certificate = array_pop($alerts); - $this->array($alert_certificate) - ->string['itemtype']->isEqualTo('Certificate') - ->integer['items_id']->isEqualTo($id) - ->integer['id']->isEqualTo($alert_id + 1); + $this->assertEquals('Certificate', $alert_certificate['itemtype']); + $this->assertEquals($id, $alert_certificate['items_id']); + $this->assertEquals($alert_id + 1, $alert_certificate['id']); } } diff --git a/tests/functional/Certificate_Item.php b/phpunit/functional/Certificate_Item.php similarity index 53% rename from tests/functional/Certificate_Item.php rename to phpunit/functional/Certificate_Item.php index 9d1ce313e1b..456809d3809 100644 --- a/tests/functional/Certificate_Item.php +++ b/phpunit/functional/Certificate_Item.php @@ -47,36 +47,36 @@ public function testRelations() $root_entity_id = getItemByTypeName('Entity', '_test_root_entity', true); - $this->newTestedInstance(); + $cert_item = new \Certificate_Item(); $cert = new \Certificate(); $input = [ 'name' => 'Test certificate', 'entities_id' => $root_entity_id, ]; - $cid1 = (int)$cert->add($input); - $this->integer($cid1)->isGreaterThan(0); + $cid1 = $cert->add($input); + $this->assertGreaterThan(0, $cid1); $input = [ 'name' => 'Test certificate 2', 'entities_id' => $root_entity_id, ]; - $cid2 = (int)$cert->add($input); - $this->integer($cid2)->isGreaterThan(0); + $cid2 = $cert->add($input); + $this->assertGreaterThan(0, $cid2); $input = [ 'name' => 'Test certificate 3', 'entities_id' => $root_entity_id, ]; - $cid3 = (int)$cert->add($input); - $this->integer($cid3)->isGreaterThan(0); + $cid3 = $cert->add($input); + $this->assertGreaterThan(0, $cid3); $input = [ 'name' => 'Test certificate 4', 'entities_id' => $root_entity_id, ]; - $cid4 = (int)$cert->add($input); - $this->integer($cid4)->isGreaterThan(0); + $cid4 = $cert->add($input); + $this->assertGreaterThan(0, $cid4); $computer = getItemByTypeName('Computer', '_test_pc01'); $printer = getItemByTypeName('Printer', '_test_printer_all'); @@ -86,75 +86,63 @@ public function testRelations() 'itemtype' => 'Computer', 'items_id' => $computer->getID() ]; - $this->integer( - (int)$this->testedInstance->add($input) - )->isGreaterThan(0); + $this->assertGreaterThan(0, $cert_item->add($input)); $input['certificates_id'] = $cid2; - $this->integer( - (int)$this->testedInstance->add($input) - )->isGreaterThan(0); + $this->assertGreaterThan(0, $cert_item->add($input)); $input['certificates_id'] = $cid3; - $this->integer( - (int)$this->testedInstance->add($input) - )->isGreaterThan(0); + $this->assertGreaterThan(0, $cert_item->add($input)); $input = [ 'certificates_id' => $cid1, 'itemtype' => 'Printer', 'items_id' => $printer->getID() ]; - $this->integer( - (int)$this->testedInstance->add($input) - )->isGreaterThan(0); + $this->assertGreaterThan(0, $cert_item->add($input)); $input['certificates_id'] = $cid4; - $this->integer( - (int)$this->testedInstance->add($input) - )->isGreaterThan(0); - - $list_items = iterator_to_array($this->testedInstance->getListForItem($computer)); - $this->array($list_items) - ->hasSize(3) - ->hasKeys([$cid1, $cid2, $cid3]); - - $list_items = iterator_to_array($this->testedInstance->getListForItem($printer)); - $this->array($list_items) - ->hasSize(2) - ->hasKeys([$cid1, $cid4]); - - $this->boolean($cert->getFromDB($cid1))->isTrue(); - $this->exception( - function () use ($cert) { - $this->boolean($this->testedInstance->getListForItem($cert))->isFalse(); - } - )->message->contains('Cannot use getListForItemParams() for a Certificate'); - - $list_types = iterator_to_array($this->testedInstance->getDistinctTypes($cid1)); + $this->assertGreaterThan(0, $cert_item->add($input)); + + $list_items = iterator_to_array($cert_item->getListForItem($computer)); + $this->assertCount(3, $list_items); + $this->assertArrayHasKey($cid1, $list_items); + $this->assertArrayHasKey($cid2, $list_items); + $this->assertArrayHasKey($cid3, $list_items); + + $list_items = iterator_to_array($cert_item->getListForItem($printer)); + $this->assertCount(2, $list_items); + $this->assertArrayHasKey($cid1, $list_items); + $this->assertArrayHasKey($cid4, $list_items); + + $this->assertTrue($cert->getFromDB($cid1)); + + $list_types = iterator_to_array($cert_item->getDistinctTypes($cid1)); $expected = [ ['itemtype' => 'Computer'], ['itemtype' => 'Printer'] ]; - $this->array($list_types)->isIdenticalTo($expected); + $this->assertSame($expected, $list_types); foreach ($list_types as $type) { - $list_items = iterator_to_array($this->testedInstance->getTypeItems($cid1, $type['itemtype'])); - $this->array($list_items)->hasSize(1); + $list_items = iterator_to_array($cert_item->getTypeItems($cid1, $type['itemtype'])); + $this->assertCount(1, $list_items); } - $this->integer($this->testedInstance->countForItem($computer))->isIdenticalTo(3); - $this->integer($this->testedInstance->countForItem($printer))->isIdenticalTo(2); + $this->assertSame(3, $cert_item->countForItem($computer)); + $this->assertSame(2, $cert_item->countForItem($printer)); $computer = getItemByTypeName('Computer', '_test_pc02'); - $this->integer($this->testedInstance->countForItem($computer))->isIdenticalTo(0); + $this->assertSame(0, $cert_item->countForItem($computer)); - $this->exception( - function () use ($cert) { - $this->testedInstance->countForItem($cert); - } - )->message->contains('Cannot use getListForItemParams() for a Certificate'); + $this->assertSame(2, $cert_item->countForMainItem($cert)); + } - $this->integer($this->testedInstance->countForMainItem($cert))->isIdenticalTo(2); + public function testgetListForItemParamsForCertificate() + { + $cert = new \Certificate(); + $cert_item = new \Certificate_Item(); + $this->expectExceptionMessage('Cannot use getListForItemParams() for a Certificate'); + $cert_item->countForItem($cert); } } diff --git a/phpunit/functional/CleanSoftwareCron.php b/phpunit/functional/CleanSoftwareCron.php new file mode 100644 index 00000000000..a527fadcca0 --- /dev/null +++ b/phpunit/functional/CleanSoftwareCron.php @@ -0,0 +1,167 @@ +. + * + * --------------------------------------------------------------------- + */ + +namespace tests\units; + +use DbTestCase; + +class CleanSoftwareCron extends DbTestCase +{ + public function testRun() + { + global $DB; + + $this->login(); + + $software = new \Software(); + $software_version = new \SoftwareVersion(); + + // Delete all existing software and versions + $always_true = [ + new \QueryExpression('1 = 1') + ]; + $this->assertTrue($software->deleteByCriteria($always_true, 1)); + $this->assertTrue($software_version->deleteByCriteria($always_true, 1)); + + // verify all deleted + $this->assertSame( + 0, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \Software::getTable() + ])->current()['cpt'] + ); + $this->assertSame( + 0, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \SoftwareVersion::getTable() + ])->current()['cpt'] + ); + + // Create 100 software with 10 versions each + $entities_id = getItemByTypeName('Entity', '_test_root_entity', true); + for ($i = 0; $i < 100; $i++) { + $software->add([ + 'name' => "Software $i", + 'entities_id' => $entities_id, + ]); + $softwareId = $software->getID(); + $this->assertGreaterThan(0, $softwareId); + for ($j = 0; $j < 10; $j++) { + $this->assertGreaterThan( + 0, + $software_version->add([ + 'name' => "Version $j", + 'softwares_id' => $softwareId, + ]) + ); + } + } + + // verify all created + $this->assertSame( + 100, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \Software::getTable() + ])->current()['cpt'] + ); + $this->assertSame( + 1000, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \SoftwareVersion::getTable() + ])->current()['cpt'] + ); + + // Run cron + \CleanSoftwareCron::run(5); + // Verify only 5 versions were deleted and no software + $this->assertSame( + 100, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \Software::getTable() + ])->current()['cpt'] + ); + $this->assertSame( + 995, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \SoftwareVersion::getTable() + ])->current()['cpt'] + ); + + // Run cron again + \CleanSoftwareCron::run(990); + // Verify only 990 versions were deleted and no software + $this->assertSame( + 100, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \Software::getTable() + ])->current()['cpt'] + ); + $this->assertSame( + 5, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \SoftwareVersion::getTable() + ])->current()['cpt'] + ); + + // Run cron again + \CleanSoftwareCron::run(50); + // All versions should be deleted now and 45 software should be deleted as well + $this->assertSame( + 55, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \Software::getTable(), + 'WHERE' => [ + 'is_deleted' => 0 // cleanup only trashes software, not purges them + ] + ])->current()['cpt'] + ); + $this->assertSame( + 0, + (int)$DB->request([ + 'COUNT' => 'cpt', + 'FROM' => \SoftwareVersion::getTable() + ])->current()['cpt'] + ); + } +} diff --git a/tests/functional/CommonDBTM.php b/phpunit/functional/CommonDBTMTest.php similarity index 62% rename from tests/functional/CommonDBTM.php rename to phpunit/functional/CommonDBTMTest.php index 43b7501dcba..6c153ae1fb0 100644 --- a/tests/functional/CommonDBTM.php +++ b/phpunit/functional/CommonDBTMTest.php @@ -41,15 +41,15 @@ use Document_Item; use Entity; use Glpi\Toolbox\Sanitizer; +use Monolog\Logger; use SoftwareVersion; /* Test for inc/commondbtm.class.php */ -class CommonDBTM extends DbTestCase +class CommonDBTMTest extends DbTestCase { public function testgetIndexNameOtherThanID() { - $networkport = new \NetworkPort(); $networkequipment = new \NetworkEquipment(); $networkportaggregate = new \NetworkPortAggregate(); @@ -58,7 +58,7 @@ public function testgetIndexNameOtherThanID() 'entities_id' => 0, 'name' => 'switch' ]); - $this->integer($ne_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $ne_id); // Add 5 ports $port1 = (int)$networkport->add([ @@ -97,11 +97,11 @@ public function testgetIndexNameOtherThanID() 'entities_id' => 0, ]); - $this->integer($port1)->isGreaterThan(0); - $this->integer($port2)->isGreaterThan(0); - $this->integer($port3)->isGreaterThan(0); - $this->integer($port4)->isGreaterThan(0); - $this->integer($port5)->isGreaterThan(0); + $this->assertGreaterThan(0, $port1); + $this->assertGreaterThan(0, $port2); + $this->assertGreaterThan(0, $port3); + $this->assertGreaterThan(0, $port4); + $this->assertGreaterThan(0, $port5); // add an aggregate port use port 3 and 4 $aggport = (int)$networkportaggregate->add([ @@ -109,18 +109,18 @@ public function testgetIndexNameOtherThanID() 'networkports_id_list' => [$port3, $port4], ]); - $this->integer($aggport)->isGreaterThan(0); + $this->assertGreaterThan(0, $aggport); // Try update to use 2 and 4 - $this->boolean($networkportaggregate->update([ + $this->assertTrue($networkportaggregate->update([ 'networkports_id' => $port5, 'networkports_id_list' => [$port2, $port4], - ]))->isTrue(); + ])); // Try update with id not exist, it will return false - $this->boolean($networkportaggregate->update([ + $this->assertFalse($networkportaggregate->update([ 'networkports_id' => $port3, 'networkports_id_list' => [$port2, $port4], - ]))->isFalse(); + ])); } public function testGetFromDBByRequest() @@ -142,24 +142,19 @@ public function testGetFromDBByRequest() ] ]); // the instance must be populated - $this->boolean($instance->isNewItem())->isFalse(); + $this->assertFalse($instance->isNewItem()); $instance = new \Computer(); - $result = null; - $this->when( - function () use ($instance, &$result) { - $result = $instance->getFromDbByRequest([ - 'WHERE' => ['contact' => 'johndoe'], - ]); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('getFromDBByRequest expects to get one result, 2 found in query "SELECT `glpi_computers`.* FROM `glpi_computers` WHERE `contact` = \'johndoe\'".') - ->exists(); - $this->boolean($result)->isFalse(); - - // the instance must not be populated - $this->boolean($instance->isNewItem())->isTrue(); + $result = $instance->getFromDbByRequest([ + 'WHERE' => ['contact' => 'johndoe'], + ]); + $this->hasPhpLogRecordThatContains( + 'getFromDBByRequest expects to get one result, 2 found in query "SELECT `glpi_computers`.* FROM `glpi_computers` WHERE `contact` = \'johndoe\'".', + Logger::WARNING + ); + $this->assertFalse($result); + // the instance must not be populated + $this->assertTrue($instance->isNewItem()); } public function testGetFromResultSet() @@ -170,37 +165,37 @@ public function testGetFromResultSet() 'LIMIT' => 1 ])->current(); - $this->array($result)->hasKeys(['name', 'uuid']); + $this->assertArrayHasKey('name', $result); + $this->assertArrayHasKey('uuid', $result); $computer = new \Computer(); $computer->getFromResultSet($result); - $this->array($computer->fields)->isIdenticalTo($result); + $this->assertSame($result, $computer->fields); } public function testGetId() { $comp = new \Computer(); - $this->integer($comp->getID())->isIdenticalTo(-1); + $this->assertSame(-1, $comp->getID()); - $this->boolean($comp->getFromDBByCrit(['name' => '_test_pc01']))->isTrue(); - $this->integer((int)$comp->getID())->isGreaterThan(0); + $this->assertTrue($comp->getFromDBByCrit(['name' => '_test_pc01'])); + $this->assertGreaterThan(0, $comp->getID()); } public function testGetEmpty() { $comp = new \Computer(); - $this->array($comp->fields)->isEmpty(); + $this->assertEmpty($comp->fields); - $this->boolean($comp->getEmpty())->isTrue(); - $this->array($comp->fields)->integer['entities_id']->isEqualTo(0); + $this->assertTrue($comp->getEmpty()); + $this->assertSame(0, $comp->fields['entities_id']); $_SESSION["glpiactive_entity"] = 12; - $this->boolean($comp->getEmpty())->isTrue(); + $this->assertTrue($comp->getEmpty()); unset($_SESSION['glpiactive_entity']); - $this->array($comp->fields) - ->integer['entities_id']->isIdenticalTo(12); + $this->assertSame(12, $comp->fields['entities_id']); } /** @@ -210,7 +205,6 @@ public function testGetEmpty() */ protected function getTableProvider() { - return [ [\DBConnection::class, ''], // "static protected $notable = true;" case [\Item_Devices::class, ''], // "static protected $notable = true;" case @@ -228,10 +222,8 @@ protected function getTableProvider() */ public function testGetTable($classname, $tablename) { - - $this->string($classname::getTable()) - ->isEqualTo(\CommonDBTM::getTable($classname)) - ->isEqualTo($tablename); + $this->assertSame($tablename, $classname::getTable()); + $this->assertSame($tablename, \CommonDBTM::getTable($classname)); } /** @@ -241,39 +233,44 @@ public function testGetTable($classname, $tablename) */ public function testGetTableField() { + // Base case + $this->assertSame('glpi_computers.serial', \Computer::getTableField('serial')); + $this->assertSame('glpi_computers.serial', \CommonDBTM::getTableField('serial', \Computer::class)); - // Exception if field argument is empty - $this->exception( - function () { - \Computer::getTableField(''); - } - )->isInstanceOf(\InvalidArgumentException::class) - ->hasMessage('Argument $field cannot be empty.'); + // Wildcard case + $this->assertSame('glpi_configs.*', \Config::getTableField('*')); + $this->assertSame('glpi_configs.*', \CommonDBTM::getTableField('*', \Config::class)); + } - // Exception if class has no table - $this->exception( - function () { - \Item_Devices::getTableField('id'); - } - )->isInstanceOf(\LogicException::class) - ->hasMessage('Invalid table name.'); - - // Base case - $this->string(\Computer::getTableField('serial')) - ->isEqualTo(\CommonDBTM::getTableField('serial', \Computer::class)) - ->isEqualTo('glpi_computers.serial'); - - // Wildcard case - $this->string(\Config::getTableField('*')) - ->isEqualTo(\CommonDBTM::getTableField('*', \Config::class)) - ->isEqualTo('glpi_configs.*'); + /** + * Test CommonDBTM::getTableField() method. + * + * @return void + */ + public function testGetTableFieldEmpty() + { + // Exception if field argument is empty + $this->expectExceptionMessage('Argument $field cannot be empty.'); + \Computer::getTableField(''); + } + + /** + * Test CommonDBTM::getTableField() method. + * + * @return void + */ + public function testGetTableFieldNoTable() + { + // Exception if class has no table + $this->expectExceptionMessage('Invalid table name.'); + \Item_Devices::getTableField('id'); } public function testupdateOrInsert() { global $DB; - //insert case + //insert case $res = (int)$DB->updateOrInsert( \Computer::getTable(), [ @@ -284,16 +281,15 @@ public function testupdateOrInsert() 'name' => 'serial-to-change' ] ); - $this->integer($res)->isGreaterThan(0); + $this->assertGreaterThan(0, $res); $check = $DB->request([ 'FROM' => \Computer::getTable(), 'WHERE' => ['name' => 'serial-to-change'] ])->current(); - $this->array($check) - ->string['serial']->isIdenticalTo('serial-one'); + $this->assertSame('serial-one', $check['serial']); - //update case + //update case $res = $DB->updateOrInsert( \Computer::getTable(), [ @@ -304,43 +300,23 @@ public function testupdateOrInsert() 'name' => 'serial-to-change' ] ); - $this->boolean($res)->isTrue(); + $this->assertTrue($res); $check = $DB->request([ 'FROM' => \Computer::getTable(), 'WHERE' => ['name' => 'serial-to-change'] ])->current(); - $this->array($check) - ->string['serial']->isIdenticalTo('serial-changed'); + $this->assertSame('serial-changed', $check['serial']); - $this->integer( + $this->assertGreaterThan( + 0, (int)$DB->insert( \Computer::getTable(), ['name' => 'serial-to-change'] ) - )->isGreaterThan(0); - - //multiple update case - $this->when( - function () use ($DB) { - $res = $DB->updateOrInsert( - \Computer::getTable(), - [ - 'name' => 'serial-to-change', - 'serial' => 'serial-changed' - ], - [ - 'name' => 'serial-to-change' - ] - ); - $this->boolean($res)->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Update would change too many rows!') - ->exists(); + ); - //allow multiples + //allow multiples $res = $DB->updateOrInsert( \Computer::getTable(), [ @@ -352,14 +328,31 @@ function () use ($DB) { ], false ); - $this->boolean($res)->isTrue(); + $this->assertTrue($res); + + //multiple update case + $res = $DB->updateOrInsert( + \Computer::getTable(), + [ + 'name' => 'serial-to-change', + 'serial' => 'serial-changed' + ], + [ + 'name' => 'serial-to-change' + ] + ); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Update would change too many rows!', + Logger::WARNING + ); } public function testupdateOrInsertMerged() { global $DB; - //insert case + //insert case $res = (int)$DB->updateOrInsert( \Computer::getTable(), [ @@ -369,16 +362,15 @@ public function testupdateOrInsertMerged() 'name' => 'serial-to-change' ] ); - $this->integer($res)->isGreaterThan(0); + $this->assertGreaterThan(0, $res); $check = $DB->request([ 'FROM' => \Computer::getTable(), 'WHERE' => ['name' => 'serial-to-change'] ])->current(); - $this->array($check) - ->string['serial']->isIdenticalTo('serial-one'); + $this->assertSame('serial-one', $check['serial']); - //update case + //update case $res = $DB->updateOrInsert( \Computer::getTable(), [ @@ -388,42 +380,23 @@ public function testupdateOrInsertMerged() 'name' => 'serial-to-change' ] ); - $this->boolean($res)->isTrue(); + $this->assertTrue($res); $check = $DB->request([ 'FROM' => \Computer::getTable(), 'WHERE' => ['name' => 'serial-to-change'] ])->current(); - $this->array($check) - ->string['serial']->isIdenticalTo('serial-changed'); + $this->assertSame('serial-changed', $check['serial']); - $this->integer( + $this->assertGreaterThan( + 0, (int)$DB->insert( \Computer::getTable(), ['name' => 'serial-to-change'] ) - )->isGreaterThan(0); - - //multiple update case - $this->when( - function () use ($DB) { - $res = $DB->updateOrInsert( - \Computer::getTable(), - [ - 'serial' => 'serial-changed' - ], - [ - 'name' => 'serial-to-change' - ] - ); - $this->boolean($res)->isFalse(); - } - )->error - ->withType(E_USER_WARNING) - ->withMessage('Update would change too many rows!') - ->exists(); + ); - //allow multiples + //allow multiples $res = $DB->updateOrInsert( \Computer::getTable(), [ @@ -434,8 +407,25 @@ function () use ($DB) { ], false ); - $this->boolean($res)->isTrue(); + $this->assertTrue($res); + + //multiple update case + $res = $DB->updateOrInsert( + \Computer::getTable(), + [ + 'serial' => 'serial-changed' + ], + [ + 'name' => 'serial-to-change' + ] + ); + $this->assertFalse($res); + $this->hasPhpLogRecordThatContains( + 'Update would change too many rows!', + Logger::WARNING + ); } + /** * Check right on Recursive object * @@ -456,84 +446,84 @@ public function testRecursiveObjectChecks() 'entities_id' => $ent0, 'is_recursive' => 0 ]); - $this->integer($id[0])->isGreaterThan(0); + $this->assertGreaterThan(0, $id[0]); $id[1] = (int)$printer->add([ 'name' => "Printer 2", 'entities_id' => $ent0, 'is_recursive' => 1 ]); - $this->integer($id[1])->isGreaterThan(0); + $this->assertGreaterThan(0, $id[1]); $id[2] = (int)$printer->add([ 'name' => "Printer 3", 'entities_id' => $ent1, 'is_recursive' => 1 ]); - $this->integer($id[2])->isGreaterThan(0); + $this->assertGreaterThan(0, $id[2]); $id[3] = (int)$printer->add([ 'name' => "Printer 4", 'entities_id' => $ent2 ]); - $this->integer($id[3])->isGreaterThan(0); + $this->assertGreaterThan(0, $id[3]); - // Super admin + // Super admin $this->login('glpi', 'glpi'); - $this->variable($_SESSION['glpiactiveprofile']['id'])->isEqualTo(4); - $this->variable($_SESSION['glpiactiveprofile']['printer'])->isEqualTo(255); - - // See all - $this->boolean(\Session::changeActiveEntities('all'))->isTrue(); - - $this->boolean($printer->can($id[0], READ))->isTrue("Fail can read Printer 1"); - $this->boolean($printer->can($id[1], READ))->isTrue("Fail can read Printer 2"); - $this->boolean($printer->can($id[2], READ))->isTrue("Fail can read Printer 3"); - $this->boolean($printer->can($id[3], READ))->isTrue("Fail can read Printer 4"); - - $this->boolean($printer->canEdit($id[0]))->isTrue("Fail can write Printer 1"); - $this->boolean($printer->canEdit($id[1]))->isTrue("Fail can write Printer 2"); - $this->boolean($printer->canEdit($id[2]))->isTrue("Fail can write Printer 3"); - $this->boolean($printer->canEdit($id[3]))->isTrue("Fail can write Printer 4"); - - // See only in main entity - $this->boolean(\Session::changeActiveEntities($ent0))->isTrue(); - - $this->boolean($printer->can($id[0], READ))->isTrue("Fail can read Printer 1"); - $this->boolean($printer->can($id[1], READ))->isTrue("Fail can read Printer 2"); - $this->boolean($printer->can($id[2], READ))->isFalse("Fail can't read Printer 3"); - $this->boolean($printer->can($id[3], READ))->isFalse("Fail can't read Printer 1"); - - $this->boolean($printer->canEdit($id[0]))->isTrue("Fail can write Printer 1"); - $this->boolean($printer->canEdit($id[1]))->isTrue("Fail can write Printer 2"); - $this->boolean($printer->canEdit($id[2]))->isFalse("Fail can't write Printer 1"); - $this->boolean($printer->canEdit($id[3]))->isFalse("Fail can't write Printer 1"); - - // See only in child entity 1 + parent if recursive - $this->boolean(\Session::changeActiveEntities($ent1))->isTrue(); - - $this->boolean($printer->can($id[0], READ))->isFalse("Fail can't read Printer 1"); - $this->boolean($printer->can($id[1], READ))->isTrue("Fail can read Printer 2"); - $this->boolean($printer->can($id[2], READ))->isTrue("Fail can read Printer 3"); - $this->boolean($printer->can($id[3], READ))->isFalse("Fail can't read Printer 4"); - - $this->boolean($printer->canEdit($id[0]))->isFalse("Fail can't write Printer 1"); - $this->boolean($printer->canEdit($id[1]))->isFalse("Fail can't write Printer 2"); - $this->boolean($printer->canEdit($id[2]))->isTrue("Fail can write Printer 2"); - $this->boolean($printer->canEdit($id[3]))->isFalse("Fail can't write Printer 2"); - - // See only in child entity 2 + parent if recursive - $this->boolean(\Session::changeActiveEntities($ent2))->isTrue(); - - $this->boolean($printer->can($id[0], READ))->isFalse("Fail can't read Printer 1"); - $this->boolean($printer->can($id[1], READ))->isTrue("Fail can read Printer 2"); - $this->boolean($printer->can($id[2], READ))->isFalse("Fail can't read Printer 3"); - $this->boolean($printer->can($id[3], READ))->isTrue("Fail can read Printer 4"); - - $this->boolean($printer->canEdit($id[0]))->isFalse("Fail can't write Printer 1"); - $this->boolean($printer->canEdit($id[1]))->isFalse("Fail can't write Printer 2"); - $this->boolean($printer->canEdit($id[2]))->isFalse("Fail can't write Printer 3"); - $this->boolean($printer->canEdit($id[3]))->isTrue("Fail can write Printer 4"); + $this->assertEquals(4, $_SESSION['glpiactiveprofile']['id']); + $this->assertEquals(255, $_SESSION['glpiactiveprofile']['printer']); + + // See all + $this->assertTrue(\Session::changeActiveEntities('all')); + + $this->assertTrue($printer->can($id[0], READ), "Fail can read Printer 1"); + $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); + $this->assertTrue($printer->can($id[2], READ), "Fail can read Printer 3"); + $this->assertTrue($printer->can($id[3], READ), "Fail can read Printer 4"); + + $this->assertTrue($printer->canEdit($id[0]), "Fail can write Printer 1"); + $this->assertTrue($printer->canEdit($id[1]), "Fail can write Printer 2"); + $this->assertTrue($printer->canEdit($id[2]), "Fail can write Printer 3"); + $this->assertTrue($printer->canEdit($id[3]), "Fail can write Printer 4"); + + // See only in main entity + $this->assertTrue(\Session::changeActiveEntities($ent0)); + + $this->assertTrue($printer->can($id[0], READ), "Fail can read Printer 1"); + $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); + $this->assertFalse($printer->can($id[2], READ), "Fail can't read Printer 3"); + $this->assertFalse($printer->can($id[3], READ), "Fail can't read Printer 1"); + + $this->assertTrue($printer->canEdit($id[0]), "Fail can write Printer 1"); + $this->assertTrue($printer->canEdit($id[1]), "Fail can write Printer 2"); + $this->assertFalse($printer->canEdit($id[2]), "Fail can't write Printer 1"); + $this->assertFalse($printer->canEdit($id[3]), "Fail can't write Printer 1"); + + // See only in child entity 1 + parent if recursive + $this->assertTrue(\Session::changeActiveEntities($ent1)); + + $this->assertFalse($printer->can($id[0], READ), "Fail can't read Printer 1"); + $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); + $this->assertTrue($printer->can($id[2], READ), "Fail can read Printer 3"); + $this->assertFalse($printer->can($id[3], READ), "Fail can't read Printer 4"); + + $this->assertFalse($printer->canEdit($id[0]), "Fail can't write Printer 1"); + $this->assertFalse($printer->canEdit($id[1]), "Fail can't write Printer 2"); + $this->assertTrue($printer->canEdit($id[2]), "Fail can write Printer 2"); + $this->assertFalse($printer->canEdit($id[3]), "Fail can't write Printer 2"); + + // See only in child entity 2 + parent if recursive + $this->assertTrue(\Session::changeActiveEntities($ent2)); + + $this->assertFalse($printer->can($id[0], READ), "Fail can't read Printer 1"); + $this->assertTrue($printer->can($id[1], READ), "Fail can read Printer 2"); + $this->assertFalse($printer->can($id[2], READ), "Fail can't read Printer 3"); + $this->assertTrue($printer->can($id[3], READ), "Fail can read Printer 4"); + + $this->assertFalse($printer->canEdit($id[0]), "Fail can't write Printer 1"); + $this->assertFalse($printer->canEdit($id[1]), "Fail can't write Printer 2"); + $this->assertFalse($printer->canEdit($id[2]), "Fail can't write Printer 3"); + $this->assertTrue($printer->canEdit($id[3]), "Fail can write Printer 4"); } /** @@ -548,11 +538,11 @@ public function testContact_Supplier() // Super admin $this->login('glpi', 'glpi'); - $this->variable($_SESSION['glpiactiveprofile']['id'])->isEqualTo(4); - $this->variable($_SESSION['glpiactiveprofile']['contact_enterprise'])->isEqualTo(255); + $this->assertEquals(4, $_SESSION['glpiactiveprofile']['id']); + $this->assertEquals(255, $_SESSION['glpiactiveprofile']['contact_enterprise']); // See all - $this->boolean(\Session::changeActiveEntities('all'))->isTrue(); + $this->assertTrue(\Session::changeActiveEntities('all')); // Create some contacts $contact = new \Contact(); @@ -562,27 +552,27 @@ public function testContact_Supplier() 'entities_id' => $ent0, 'is_recursive' => 0 ]); - $this->integer($idc[0])->isGreaterThan(0); + $this->assertGreaterThan(0, $idc[0]); $idc[1] = (int)$contact->add([ 'name' => "Contact 2", 'entities_id' => $ent0, 'is_recursive' => 1 ]); - $this->integer($idc[1])->isGreaterThan(0); + $this->assertGreaterThan(0, $idc[1]); $idc[2] = (int)$contact->add([ 'name' => "Contact 3", 'entities_id' => $ent1, 'is_recursive' => 1 ]); - $this->integer($idc[2])->isGreaterThan(0); + $this->assertGreaterThan(0, $idc[2]); $idc[3] = (int)$contact->add([ 'name' => "Contact 4", 'entities_id' => $ent2 ]); - $this->integer($idc[3])->isGreaterThan(0); + $this->assertGreaterThan(0, $idc[3]); ; // Create some suppliers @@ -593,26 +583,26 @@ public function testContact_Supplier() 'entities_id' => $ent0, 'is_recursive' => 0 ]); - $this->integer($ids[0])->isGreaterThan(0); + $this->assertGreaterThan(0, $ids[0]); $ids[1] = (int)$supplier->add([ 'name' => "Supplier 2", 'entities_id' => $ent0, 'is_recursive' => 1 ]); - $this->integer($ids[1])->isGreaterThan(0); + $this->assertGreaterThan(0, $ids[1]); $ids[2] = (int)$supplier->add([ 'name' => "Supplier 3", 'entities_id' => $ent1 ]); - $this->integer($ids[2])->isGreaterThan(0); + $this->assertGreaterThan(0, $ids[2]); $ids[3] = (int)$supplier->add([ 'name' => "Supplier 4", 'entities_id' => $ent2 ]); - $this->integer($ids[3])->isGreaterThan(0); + $this->assertGreaterThan(0, $ids[3]); // Relation $rel = new \Contact_Supplier(); @@ -620,176 +610,176 @@ public function testContact_Supplier() 'contacts_id' => $idc[0], // root 'suppliers_id' => $ids[0] //root ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[0] = (int)$rel->add($input); - $this->integer($idr[0])->isGreaterThan(0); - $this->boolean($rel->can($idr[0], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[0]))->isTrue(); + $this->assertGreaterThan(0, $idr[0]); + $this->assertTrue($rel->can($idr[0], READ)); + $this->assertTrue($rel->canEdit($idr[0])); $input = [ 'contacts_id' => $idc[0], // root 'suppliers_id' => $ids[1] // root + rec ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[1] = (int)$rel->add($input); - $this->integer($idr[1])->isGreaterThan(0); - $this->boolean($rel->can($idr[1], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[1]))->isTrue(); + $this->assertGreaterThan(0, $idr[1]); + $this->assertTrue($rel->can($idr[1], READ)); + $this->assertTrue($rel->canEdit($idr[1])); $input = [ 'contacts_id' => $idc[0], // root 'suppliers_id' => $ids[2] // child 1 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[0], // root 'suppliers_id' => $ids[3] // child 2 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[1], // root + rec 'suppliers_id' => $ids[0] // root ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[2] = (int)$rel->add($input); - $this->integer($idr[2])->isGreaterThan(0); - $this->boolean($rel->can($idr[2], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[2]))->isTrue(); + $this->assertGreaterThan(0, $idr[2]); + $this->assertTrue($rel->can($idr[2], READ)); + $this->assertTrue($rel->canEdit($idr[2])); $input = [ 'contacts_id' => $idc[1], // root + rec 'suppliers_id' => $ids[1] // root + rec ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[3] = (int)$rel->add($input); - $this->integer($idr[3])->isGreaterThan(0); - $this->boolean($rel->can($idr[3], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[3]))->isTrue(); + $this->assertGreaterThan(0, $idr[3]); + $this->assertTrue($rel->can($idr[3], READ)); + $this->assertTrue($rel->canEdit($idr[3])); $input = [ 'contacts_id' => $idc[1], // root + rec 'suppliers_id' => $ids[2] // child 1 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[4] = (int)$rel->add($input); - $this->integer($idr[4])->isGreaterThan(0); - $this->boolean($rel->can($idr[4], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[4]))->isTrue(); + $this->assertGreaterThan(0, $idr[4]); + $this->assertTrue($rel->can($idr[4], READ)); + $this->assertTrue($rel->canEdit($idr[4])); $input = [ 'contacts_id' => $idc[1], // root + rec 'suppliers_id' => $ids[3] // child 2 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[5] = (int)$rel->add($input); - $this->integer($idr[5])->isGreaterThan(0); - $this->boolean($rel->can($idr[5], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[5]))->isTrue(); + $this->assertGreaterThan(0, $idr[5]); + $this->assertTrue($rel->can($idr[5], READ)); + $this->assertTrue($rel->canEdit($idr[5])); $input = [ 'contacts_id' => $idc[2], // Child 1 'suppliers_id' => $ids[0] // root ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[2], // Child 1 'suppliers_id' => $ids[1] // root + rec ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[6] = (int)$rel->add($input); - $this->integer($idr[6])->isGreaterThan(0); - $this->boolean($rel->can($idr[6], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[6]))->isTrue(); + $this->assertGreaterThan(0, $idr[6]); + $this->assertTrue($rel->can($idr[6], READ)); + $this->assertTrue($rel->canEdit($idr[6])); $input = [ 'contacts_id' => $idc[2], // Child 1 'suppliers_id' => $ids[2] // Child 1 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[7] = (int)$rel->add($input); - $this->integer($idr[7])->isGreaterThan(0); - $this->boolean($rel->can($idr[7], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[7]))->isTrue(); + $this->assertGreaterThan(0, $idr[7]); + $this->assertTrue($rel->can($idr[7], READ)); + $this->assertTrue($rel->canEdit($idr[7])); $input = [ 'contacts_id' => $idc[2], // Child 1 'suppliers_id' => $ids[3] // Child 2 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); - - // See only in child entity 2 + parent if recursive - $this->boolean(\Session::changeActiveEntities($ent2))->isTrue(); - - $this->boolean($rel->can($idr[0], READ))->isFalse(); // root / root - //$this->boolean($rel->canEdit($idr[0]))->isFalse(); - $this->boolean($rel->can($idr[1], READ))->isFalse(); // root / root rec - //$this->boolean($rel->canEdit($idr[1]))->isFalse(); - $this->boolean($rel->can($idr[2], READ))->isFalse(); // root rec / root - //$this->boolean($rel->canEdit($idr[2]))->isFalse(); - $this->boolean($rel->can($idr[3], READ))->isTrue(); // root rec / root rec - //$this->boolean($rel->canEdit($idr[3]))->isFalse(); - $this->boolean($rel->can($idr[4], READ))->isFalse(); // root rec / child 1 - //$this->boolean($rel->canEdit($idr[4]))->isFalse(); - $this->boolean($rel->can($idr[5], READ))->isTrue(); // root rec / child 2 - $this->boolean($rel->canEdit($idr[5]))->isTrue(); - $this->boolean($rel->can($idr[6], READ))->isFalse(); // child 1 / root rec - //$this->boolean($rel->canEdit($idr[6]))->isFalse(); - $this->boolean($rel->can($idr[7], READ))->isFalse(); // child 1 / child 1 - //$this->boolean($rel->canEdit($idr[7]))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); + + // See only in child entity 2 + parent if recursive + $this->assertTrue(\Session::changeActiveEntities($ent2)); + + $this->assertFalse($rel->can($idr[0], READ)); // root / root + //$this->assertFalse($rel->canEdit($idr[0])); + $this->assertFalse($rel->can($idr[1], READ)); // root / root rec + //$this->assertFalse($rel->canEdit($idr[1])); + $this->assertFalse($rel->can($idr[2], READ)); // root rec / root + //$this->assertFalse($rel->canEdit($idr[2])); + $this->assertTrue($rel->can($idr[3], READ)); // root rec / root rec + //$this->assertFalse($rel->canEdit($idr[3])); + $this->assertFalse($rel->can($idr[4], READ)); // root rec / child 1 + //$this->assertFalse($rel->canEdit($idr[4])); + $this->assertTrue($rel->can($idr[5], READ)); // root rec / child 2 + $this->assertTrue($rel->canEdit($idr[5])); + $this->assertFalse($rel->can($idr[6], READ)); // child 1 / root rec + //$this->assertFalse($rel->canEdit($idr[6])); + $this->assertFalse($rel->can($idr[7], READ)); // child 1 / child 1 + //$this->assertFalse($rel->canEdit($idr[7])); $input = [ 'contacts_id' => $idc[0], // root 'suppliers_id' => $ids[0] // root ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[0],// root 'suppliers_id' => $ids[1] // root + rec ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[1],// root + rec 'suppliers_id' => $ids[0] // root ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[3], // Child 2 'suppliers_id' => $ids[0] // root ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[3],// Child 2 'suppliers_id' => $ids[1] // root + rec ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[7] = (int)$rel->add($input); - $this->integer($idr[7])->isGreaterThan(0); - $this->boolean($rel->can($idr[7], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[7]))->isTrue(); + $this->assertGreaterThan(0, $idr[7]); + $this->assertTrue($rel->can($idr[7], READ)); + $this->assertTrue($rel->canEdit($idr[7])); $input = [ 'contacts_id' => $idc[3], // Child 2 'suppliers_id' => $ids[2] // Child 1 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isFalse(); + $this->assertFalse($rel->can(-1, CREATE, $input)); $input = [ 'contacts_id' => $idc[3], // Child 2 'suppliers_id' => $ids[3] // Child 2 ]; - $this->boolean($rel->can(-1, CREATE, $input))->isTrue(); + $this->assertTrue($rel->can(-1, CREATE, $input)); $idr[8] = (int)$rel->add($input); - $this->integer($idr[8])->isGreaterThan(0); - $this->boolean($rel->can($idr[8], READ))->isTrue(); - $this->boolean($rel->canEdit($idr[8]))->isTrue(); + $this->assertGreaterThan(0, $idr[8]); + $this->assertTrue($rel->can($idr[8], READ)); + $this->assertTrue($rel->canEdit($idr[8])); } /** @@ -808,53 +798,53 @@ public function testEntity() 'name' => '_test_child_2_subchild_1', 'entities_id' => $ent2 ]); - $this->integer($ent3)->isGreaterThan(0); + $this->assertGreaterThan(0, $ent3); $ent4 = (int)$entity->add([ 'name' => '_test_child_2_subchild_2', 'entities_id' => $ent2 ]); - $this->integer($ent4)->isGreaterThan(0); - - $this->boolean(\Session::changeActiveEntities('all'))->isTrue(); - - $this->boolean($entity->can(0, READ))->isTrue("Fail: can't read root entity"); - $this->boolean($entity->can($ent0, READ))->isTrue("Fail: can't read entity 0"); - $this->boolean($entity->can($ent1, READ))->isTrue("Fail: can't read entity 1"); - $this->boolean($entity->can($ent2, READ))->isTrue("Fail: can't read entity 2"); - $this->boolean($entity->can($ent3, READ))->isTrue("Fail: can't read entity 2.1"); - $this->boolean($entity->can($ent4, READ))->isTrue("Fail: can't read entity 2.2"); - $this->boolean($entity->can(99999, READ))->isFalse("Fail: can read not existing entity"); - - $this->boolean($entity->canEdit(0))->isTrue("Fail: can't write root entity"); - $this->boolean($entity->canEdit($ent0))->isTrue("Fail: can't write entity 0"); - $this->boolean($entity->canEdit($ent1))->isTrue("Fail: can't write entity 1"); - $this->boolean($entity->canEdit($ent2))->isTrue("Fail: can't write entity 2"); - $this->boolean($entity->canEdit($ent3))->isTrue("Fail: can't write entity 2.1"); - $this->boolean($entity->canEdit($ent4))->isTrue("Fail: can't write entity 2.2"); - $this->boolean($entity->canEdit(99999))->isFalse("Fail: can write not existing entity"); + $this->assertGreaterThan(0, $ent4); + + $this->assertTrue(\Session::changeActiveEntities('all')); + + $this->assertTrue($entity->can(0, READ), "Fail: can't read root entity"); + $this->assertTrue($entity->can($ent0, READ), "Fail: can't read entity 0"); + $this->assertTrue($entity->can($ent1, READ), "Fail: can't read entity 1"); + $this->assertTrue($entity->can($ent2, READ), "Fail: can't read entity 2"); + $this->assertTrue($entity->can($ent3, READ), "Fail: can't read entity 2.1"); + $this->assertTrue($entity->can($ent4, READ), "Fail: can't read entity 2.2"); + $this->assertFalse($entity->can(99999, READ), "Fail: can read not existing entity"); + + $this->assertTrue($entity->canEdit(0), "Fail: can't write root entity"); + $this->assertTrue($entity->canEdit($ent0), "Fail: can't write entity 0"); + $this->assertTrue($entity->canEdit($ent1), "Fail: can't write entity 1"); + $this->assertTrue($entity->canEdit($ent2), "Fail: can't write entity 2"); + $this->assertTrue($entity->canEdit($ent3), "Fail: can't write entity 2.1"); + $this->assertTrue($entity->canEdit($ent4), "Fail: can't write entity 2.2"); + $this->assertFalse($entity->canEdit(99999), "Fail: can write not existing entity"); $input = ['entities_id' => $ent1]; - $this->boolean($entity->can(-1, CREATE, $input))->isTrue("Fail: can create entity in root"); + $this->assertTrue($entity->can(-1, CREATE, $input), "Fail: can create entity in root"); $input = ['entities_id' => $ent2]; - $this->boolean($entity->can(-1, CREATE, $input))->isTrue("Fail: can't create entity in 2"); + $this->assertTrue($entity->can(-1, CREATE, $input), "Fail: can't create entity in 2"); $input = ['entities_id' => $ent3]; - $this->boolean($entity->can(-1, CREATE, $input))->isTrue("Fail: can't create entity in 2.1"); + $this->assertTrue($entity->can(-1, CREATE, $input), "Fail: can't create entity in 2.1"); $input = ['entities_id' => 99999]; - $this->boolean($entity->can(-1, CREATE, $input))->isFalse("Fail: can create entity in not existing entity"); + $this->assertFalse($entity->can(-1, CREATE, $input), "Fail: can create entity in not existing entity"); $input = ['entities_id' => -1]; - $this->boolean($entity->can(-1, CREATE, $input))->isFalse("Fail: can create entity in not existing entity"); + $this->assertFalse($entity->can(-1, CREATE, $input), "Fail: can create entity in not existing entity"); - $this->boolean(\Session::changeActiveEntities($ent2, false))->isTrue(); + $this->assertTrue(\Session::changeActiveEntities($ent2, false)); $input = ['entities_id' => $ent1]; - $this->boolean($entity->can(-1, CREATE, $input))->isFalse("Fail: can create entity in root"); + $this->assertFalse($entity->can(-1, CREATE, $input), "Fail: can create entity in root"); $input = ['entities_id' => $ent2]; - // next should be false (or not).... but check is done on glpiactiveprofile - // will require to save current state in session - this is probably acceptable - // this allow creation when no child defined yet (no way to select tree in this case) - $this->boolean($entity->can(-1, CREATE, $input))->isTrue("Fail: can't create entity in 2"); + // next should be false (or not).... but check is done on glpiactiveprofile + // will require to save current state in session - this is probably acceptable + // this allow creation when no child defined yet (no way to select tree in this case) + $this->assertTrue($entity->can(-1, CREATE, $input), "Fail: can't create entity in 2"); $input = ['entities_id' => $ent3]; - $this->boolean($entity->can(-1, CREATE, $input))->isFalse("Fail: can create entity in 2.1"); + $this->assertFalse($entity->can(-1, CREATE, $input), "Fail: can create entity in 2.1"); } public function testAdd() @@ -871,32 +861,32 @@ public function testAdd() 'date_mod' => '2018-01-01 22:33:44', 'entities_id' => $ent0 ])); - $this->string($computer->fields['name'])->isIdenticalTo("Computer01 '"); + $this->assertSame("Computer01 '", $computer->fields['name']); - $this->integer($computerID)->isGreaterThan(0); - $this->boolean( + $this->assertGreaterThan(0, $computerID); + $this->assertTrue( $computer->getFromDB($computerID) - )->isTrue(); - // Verify you can override creation and modifcation dates from add - $this->string($computer->fields['date_creation'])->isEqualTo('2018-01-01 11:22:33'); - $this->string($computer->fields['date_mod'])->isEqualTo('2018-01-01 22:33:44'); - $this->string($computer->fields['name'])->isIdenticalTo("Computer01 '"); + ); + // Verify you can override creation and modifcation dates from add + $this->assertEquals('2018-01-01 11:22:33', $computer->fields['date_creation']); + $this->assertEquals('2018-01-01 22:33:44', $computer->fields['date_mod']); + $this->assertSame("Computer01 '", $computer->fields['name']); - //test with default date + //test with default date $computerID = $computer->add(\Toolbox::addslashes_deep([ 'name' => 'Computer01 \'', 'entities_id' => $ent0 ])); - $this->string($computer->fields['name'])->isIdenticalTo("Computer01 '"); + $this->assertSame("Computer01 '", $computer->fields['name']); - $this->integer($computerID)->isGreaterThan(0); - $this->boolean( + $this->assertGreaterThan(0, $computerID); + $this->assertTrue( $computer->getFromDB($computerID) - )->isTrue(); - // Verify default date has been used - $this->string($computer->fields['date_creation'])->isEqualTo('2000-01-01 00:00:00'); - $this->string($computer->fields['date_mod'])->isEqualTo('2000-01-01 00:00:00'); - $this->string($computer->fields['name'])->isIdenticalTo("Computer01 '"); + ); + // Verify default date has been used + $this->assertEquals('2000-01-01 00:00:00', $computer->fields['date_creation']); + $this->assertEquals('2000-01-01 00:00:00', $computer->fields['date_mod']); + $this->assertSame("Computer01 '", $computer->fields['name']); $_SESSION['glpi_currenttime'] = $bkp_current; } @@ -908,41 +898,41 @@ public function testUpdate() $bkp_current = $_SESSION['glpi_currenttime']; $_SESSION['glpi_currenttime'] = '2000-01-01 00:00:00'; - //test with date set + //test with date set $computerID = $computer->add(\Toolbox::addslashes_deep([ 'name' => 'Computer01', 'date_creation' => '2018-01-01 11:22:33', 'date_mod' => '2018-01-01 22:33:44', 'entities_id' => $ent0 ])); - $this->string($computer->fields['name'])->isIdenticalTo("Computer01"); + $this->assertSame("Computer01", $computer->fields['name']); - $this->integer($computerID)->isGreaterThan(0); - $this->boolean( + $this->assertGreaterThan(0, $computerID); + $this->assertTrue( $computer->getFromDB($computerID) - )->isTrue(); - $this->string($computer->fields['name'])->isIdenticalTo("Computer01"); + ); + $this->assertSame("Computer01", $computer->fields['name']); - $this->boolean( + $this->assertTrue( $computer->update(['id' => $computerID, 'name' => \Toolbox::addslashes_deep('Computer01 \'')]) - )->isTrue(); - $this->string($computer->fields['name'])->isIdenticalTo('Computer01 \''); - $this->boolean($computer->getFromDB($computerID))->isTrue(); - $this->string($computer->fields['name'])->isIdenticalTo('Computer01 \''); + ); + $this->assertSame('Computer01 \'', $computer->fields['name']); + $this->assertTrue($computer->getFromDB($computerID)); + $this->assertSame('Computer01 \'', $computer->fields['name']); - $this->boolean( + $this->assertTrue( $computer->update(['id' => $computerID, 'name' => null]) - )->isTrue(); - $this->variable($computer->fields['name'])->isIdenticalTo(null); - $this->boolean($computer->getFromDB($computerID))->isTrue(); - $this->variable($computer->fields['name'])->isIdenticalTo(null); + ); + $this->assertNull($computer->fields['name']); + $this->assertTrue($computer->getFromDB($computerID)); + $this->assertNull($computer->fields['name']); - $this->boolean( + $this->assertTrue( $computer->update(['id' => $computerID, 'name' => 'renamed']) - )->isTrue(); - $this->string($computer->fields['name'])->isIdenticalTo('renamed'); - $this->boolean($computer->getFromDB($computerID))->isTrue(); - $this->string($computer->fields['name'])->isIdenticalTo('renamed'); + ); + $this->assertSame('renamed', $computer->fields['name']); + $this->assertTrue($computer->getFromDB($computerID)); + $this->assertSame('renamed', $computer->fields['name']); } @@ -950,13 +940,13 @@ public function testTimezones() { global $DB; - //check if timezones are available - $this->boolean($DB->use_timezones)->isTrue(); - $this->array($DB->getTimezones())->size->isGreaterThan(0); + //check if timezones are available + $this->assertTrue($DB->use_timezones); + $this->assertGreaterThan(0, count($DB->getTimezones())); - //login with default TZ + //login with default TZ $this->login(); - //add a Compuer with creation and update dates + //add a Computer with creation and update dates $comp = new \Computer(); $cid = $comp->add([ 'name' => 'Computer with timezone', @@ -964,21 +954,21 @@ public function testTimezones() 'date_mod' => '2019-03-04 10:00:00', 'entities_id' => 0 ]); - $this->integer($cid)->isGreaterThan(0); + $this->assertGreaterThan(0, $cid); - $this->boolean($comp->getFromDB($cid)); - $this->string($comp->fields['date_creation'])->isIdenticalTo('2019-03-04 10:00:00'); + $this->assertTrue($comp->getFromDB($cid)); + $this->assertSame('2019-03-04 10:00:00', $comp->fields['date_creation']); $user = getItemByTypeName('User', 'glpi'); - $this->boolean($user->update(['id' => $user->fields['id'], 'timezone' => 'Europe/Paris']))->isTrue(); + $this->assertTrue($user->update(['id' => $user->fields['id'], 'timezone' => 'Europe/Paris'])); //check tz is set - $this->boolean($user->getFromDB($user->fields['id']))->isTrue(); - $this->string($user->fields['timezone'])->isIdenticalTo('Europe/Paris'); + $this->assertTrue($user->getFromDB($user->fields['id'])); + $this->assertSame('Europe/Paris', $user->fields['timezone']); $this->login('glpi', 'glpi'); - $this->boolean($comp->getFromDB($cid)); - $this->string($comp->fields['date_creation'])->matches('/2019-03-04 1[12]:00:00/'); + $this->assertTrue($comp->getFromDB($cid)); + $this->assertMatchesRegularExpression('/2019-03-04 1[12]:00:00/', $comp->fields['date_creation']); } public function testCircularRelation() @@ -988,32 +978,31 @@ public function testCircularRelation() 'name' => 'Project 1', 'auto_percent_done' => 1 ]); - $this->integer((int) $project_id_1)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $project_id_1); $project_id_2 = $project->add([ 'name' => 'Project 2', 'auto_percent_done' => 1, 'projects_id' => $project_id_1 ]); - $this->integer((int) $project_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $project_id_2); $project_id_3 = $project->add([ 'name' => 'Project 3', 'projects_id' => $project_id_2 ]); - $this->integer((int) $project_id_3)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $project_id_3); $project_id_4 = $project->add([ 'name' => 'Project 4', ]); - $this->integer((int) $project_id_4)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $project_id_4); - // This should evaluate as a circular relation - $this->boolean(\Project::checkCircularRelation($project_id_1, $project_id_3))->isTrue(); - // This should not evaluate as a circular relation - $this->boolean(\Project::checkCircularRelation($project_id_4, $project_id_3))->isFalse(); + // This should evaluate as a circular relation + $this->assertTrue(\Project::checkCircularRelation($project_id_1, $project_id_3)); + // This should not evaluate as a circular relation + $this->assertFalse(\Project::checkCircularRelation($project_id_4, $project_id_3)); } protected function relationConfigProvider() { - return [ [ 'relation_itemtype' => \Infocom::getType(), @@ -1049,6 +1038,7 @@ public function testCleanRelationTableBasedOnConfiguredTypes( $config_name, $linked_itemtype = null ) { + /** @var array $CFG_GLPI */ global $CFG_GLPI; $entity_id = getItemByTypeName('Entity', '_test_root_entity', true); @@ -1067,53 +1057,53 @@ public function testCleanRelationTableBasedOnConfiguredTypes( 'entities_id' => $entity_id, ] ); - $this->integer($linked_item_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $linked_item_id); $linked_item_input = [$linked_item->getForeignKeyField() => $linked_item_id]; } - // Create computer for which cleaning will be done. + // Create computer for which cleaning will be done. $computer_1_id = $computer->add( [ 'name' => 'Computer 1', 'entities_id' => $entity_id, ] ); - $this->integer($computer_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $computer_1_id); $relation_item_1_id = $relation_item->add( [ 'itemtype' => $computer->getType(), 'items_id' => $computer_1_id, ] + $linked_item_input ); - $this->integer($relation_item_1_id)->isGreaterThan(0); - $this->boolean($relation_item->getFromDB($relation_item_1_id))->isTrue(); + $this->assertGreaterThan(0, $relation_item_1_id); + $this->assertTrue($relation_item->getFromDB($relation_item_1_id)); - // Create witness computer. + // Create witness computer. $computer_2_id = $computer->add( [ 'name' => 'Computer 2', 'entities_id' => $entity_id, ] ); - $this->integer($computer_2_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $computer_2_id); $relation_item_2_id = $relation_item->add( [ 'itemtype' => $computer->getType(), 'items_id' => $computer_2_id, ] + $linked_item_input ); - $this->integer($relation_item_2_id)->isGreaterThan(0); - $this->boolean($relation_item->getFromDB($relation_item_2_id))->isTrue(); + $this->assertGreaterThan(0, $relation_item_2_id); + $this->assertTrue($relation_item->getFromDB($relation_item_2_id)); $cfg_backup = $CFG_GLPI; $CFG_GLPI[$config_name] = [$computer->getType()]; $computer->delete(['id' => $computer_1_id], true); $CFG_GLPI = $cfg_backup; - // Relation with deleted item has been cleaned - $this->boolean($relation_item->getFromDB($relation_item_1_id))->isFalse(); - // Relation with witness object is still present - $this->boolean($relation_item->getFromDB($relation_item_2_id))->isTrue(); + // Relation with deleted item has been cleaned + $this->assertFalse($relation_item->getFromDB($relation_item_1_id)); + // Relation with witness object is still present + $this->assertTrue($relation_item->getFromDB($relation_item_2_id)); } public function testCleanItemDeviceDBOnItemDelete() @@ -1172,59 +1162,73 @@ public function testCleanItemDeviceDBOnItemDelete() } // Check that only created relations exists - $this->integer( + $this->assertSame( + 6, countElementsInTable(\Item_DeviceBattery::getTable()) - )->isEqualTo(6); - $this->integer( + ); + $this->assertSame( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Computer::class, 'items_id' => $computer_id_1]) - )->isEqualTo(2); - $this->integer( + ); + $this->assertEquals( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Computer::class, 'items_id' => $computer_id_2]) - )->isEqualTo(2); - $this->integer( + ); + $this->assertEquals( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Phone::class, 'items_id' => $phone_id]) - )->isEqualTo(2); + ); $computer_1->delete(['id' => $computer_id_1, 'keep_devices' => 1], true); // Check that only relations to computer were cleaned - $this->integer( + $this->assertEquals( + 6, countElementsInTable(\Item_DeviceBattery::getTable()) - )->isEqualTo(6); // item devices were preserved but detached - $this->integer( + ); // item devices were preserved but detached + $this->assertEquals( + 0, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Computer::class, 'items_id' => $computer_id_1]) - )->isEqualTo(0); - $this->integer( + ); + $this->assertEquals( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => '', 'items_id' => 0]) - )->isEqualTo(2); - $this->integer( + ); + $this->assertEquals( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Computer::class, 'items_id' => $computer_id_2]) - )->isEqualTo(2); - $this->integer( + ); + $this->assertEquals( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Phone::class, 'items_id' => $phone_id]) - )->isEqualTo(2); + ); $computer_2->delete(['id' => $computer_id_2], true); // Check that only relations to computer were cleaned - $this->integer( + $this->assertEquals( + 4, countElementsInTable(\Item_DeviceBattery::getTable()) - )->isEqualTo(4); // item devices were deleted - $this->integer( + ); // item devices were deleted + $this->assertEquals( + 0, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Computer::class, 'items_id' => $computer_id_1]) - )->isEqualTo(0); - $this->integer( + ); + $this->assertEquals( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => '', 'items_id' => 0]) - )->isEqualTo(2); - $this->integer( + ); + $this->assertEquals( + 0, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Computer::class, 'items_id' => $computer_id_2]) - )->isEqualTo(0); - $this->integer( + ); + $this->assertEquals( + 2, countElementsInTable(\Item_DeviceBattery::getTable(), ['itemtype' => \Phone::class, 'items_id' => $phone_id]) - )->isEqualTo(2); + ); } - protected function testCheckTemplateEntityProvider() + public static function testCheckTemplateEntityProvider() { $sv1 = getItemByTypeName('SoftwareVersion', '_test_softver_1'); @@ -1283,9 +1287,9 @@ public function testCheckTemplateEntity( $_SESSION['glpiactiveentities'] = $active_entities; $res = \CommonDBTM::checkTemplateEntity($data, $parent_id, $parent_itemtype); - $this->array($res)->isEqualTo($expected); + $this->assertEquals($expected, $res); - // Reset session + // Reset session unset($_SESSION['glpiactiveentities']); } @@ -1293,38 +1297,38 @@ public function testGetById() { $itemtype = \Computer::class; - // test null ID + // test null ID $output = $itemtype::getById(null); - $this->boolean($output)->isFalse(); + $this->assertFalse($output); - // test existing item + // test existing item $instance = new $itemtype(); $instance->getFromDBByRequest([ 'WHERE' => ['name' => '_test_pc01'], ]); - $this->boolean($instance->isNewItem())->isFalse(); + $this->assertFalse($instance->isNewItem()); $output = $itemtype::getById($instance->getID()); - $this->object($output)->isInstanceOf($itemtype); + $this->assertInstanceOf($itemtype, $output); - // test non-existing item + // test non-existing item $instance = new $itemtype(); $instance->add([ 'name' => 'to be deleted', 'entities_id' => 0, ]); - $this->boolean($instance->isNewItem())->isFalse(); + $this->assertFalse($instance->isNewItem()); $nonExistingId = $instance->getID(); $instance->delete([ 'id' => $nonExistingId, ], 1); - $this->boolean($instance->getFromDB($nonExistingId))->isFalse(); + $this->assertFalse($instance->getFromDB($nonExistingId)); $output = $itemtype::getById($nonExistingId); - $this->boolean($output)->isFalse(); + $this->assertFalse($output); } - protected function textValueProvider(): iterable + public static function textValueProvider(): iterable { $value = 'This is not a long value'; yield [ @@ -1382,16 +1386,18 @@ public function testTextValueTuncation(string $value, string $truncated, int $le { $computer = new \Computer(); - $this->when( - function () use ($computer, $value) { - $this->integer($computer->add(['name' => $value, 'entities_id' => 0]))->isGreaterThan(0); - } - )->error() - ->withType(E_USER_WARNING) - ->withMessage(sprintf('%s exceed 255 characters long (%s), it will be truncated.', $value, $length)) - ->{($value !== $truncated ? 'exists' : 'notExists')}; - - $this->string($computer->fields['name'])->isEqualTo($truncated); + $this->assertGreaterThan(0, $computer->add(['name' => $value, 'entities_id' => 0])); + $this->assertEquals($truncated, $computer->fields['name']); + if ($value !== $truncated) { + $this->hasPhpLogRecordThatContains( + sprintf( + '%s exceed 255 characters long (%s), it will be truncated.', + $value, + $length + ), + Logger::WARNING + ); + } } public function testCheckUnicity() @@ -1399,41 +1405,50 @@ public function testCheckUnicity() $this->login(); $field_unicity = new \FieldUnicity(); - $this->integer($field_unicity->add([ - 'name' => 'uuid uniqueness', - 'itemtype' => 'Computer', - '_fields' => ['uuid'], - 'is_active' => 1, - 'action_refuse' => 1, - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $field_unicity->add([ + 'name' => 'uuid uniqueness', + 'itemtype' => 'Computer', + '_fields' => ['uuid'], + 'is_active' => 1, + 'action_refuse' => 1, + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), + ]) + ); $computer = new \Computer(); - $this->integer($computers_id1 = $computer->add([ - 'name' => __FUNCTION__ . '01', - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), - 'uuid' => '76873749-0813-482f-ac20-eb7102ed3367' - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $computers_id1 = $computer->add([ + 'name' => __FUNCTION__ . '01', + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), + 'uuid' => '76873749-0813-482f-ac20-eb7102ed3367' + ]) + ); - $this->integer($computers_id2 = $computer->add([ - 'name' => __FUNCTION__ . '02', - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), - 'uuid' => '81fb7b20-a404-4d1e-aafa-4255b7614eae' - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $computers_id2 = $computer->add([ + 'name' => __FUNCTION__ . '02', + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), + 'uuid' => '81fb7b20-a404-4d1e-aafa-4255b7614eae' + ]) + ); - $this->variable($computer->update([ + $this->assertFalse($computer->update([ 'id' => $computers_id2, 'uuid' => '76873749-0813-482f-ac20-eb7102ed3367' - ]))->isNotTrue(); + ])); $err_msg = "Impossible record for UUID = 76873749-0813-482f-ac20-eb7102ed3367
Other item exist
[testCheckUnicity01 - ID: {$computers_id1} - Serial number: - Entity: Root entity > _test_root_entity]"; $this->hasSessionMessages(1, [$err_msg]); - $this->variable($computer->add([ + $this->assertFalse($computer->add([ 'name' => __FUNCTION__ . '03', 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true), 'uuid' => '76873749-0813-482f-ac20-eb7102ed3367' - ]))->isNotTrue(); + ])); $this->hasSessionMessages(1, [$err_msg]); } @@ -1466,14 +1481,14 @@ public function testAddFilesWithNewFile() // Check the document exists and is linked to the computer $document_item = new Document_Item(); - $this->boolean( + $this->assertTrue( $document_item->getFromDbByCrit(['itemtype' => $item->getType(), 'items_id' => $item->getID()]) - )->isTrue(); + ); $document = new Document(); - $this->boolean( + $this->assertTrue( $document->getFromDB($document_item->fields['documents_id']) - )->isTrue(); - $this->string($document->fields['filename'])->isEqualTo('foo.txt'); + ); + $this->assertEquals('foo.txt', $document->fields['filename']); } public function testAddFilesSimilarToExistingDocument() @@ -1498,10 +1513,11 @@ public function testAddFilesSimilarToExistingDocument() 0 => '6079908c4be820.58460925', ] ]); + $this->assertGreaterThan(0, $init_document_id); unlink(GLPI_TMP_DIR . '/' . $filename1_txt); - $this->boolean($document->getFromDB($init_document_id))->isTrue(); + $this->assertTrue($document->getFromDB($init_document_id)); // Simulate legit call to `addFiles()` post_addItem / post_updateItem $item = getItemByTypeName(Computer::class, '_test_pc01'); @@ -1528,20 +1544,20 @@ public function testAddFilesSimilarToExistingDocument() // Check the document is linked to the computer $document_item = new Document_Item(); - $this->boolean( + $this->assertTrue( $document_item->getFromDbByCrit(['itemtype' => $item->getType(), 'items_id' => $item->getID()]) - )->isTrue(); + ); // Check that first document has been updated $document = new Document(); - $this->boolean( + $this->assertTrue( $document->getFromDB($document_item->fields['documents_id']) - )->isTrue(); - $this->integer($document->getID())->isEqualTo($init_document_id); - $this->string($document->fields['filename'])->isEqualTo('bar.txt'); + ); + $this->assertEquals($init_document_id, $document->getID()); + $this->assertEquals('bar.txt', $document->fields['filename']); } - protected function updatedInputProvider(): iterable + public static function updatedInputProvider(): iterable { $root_entity_id = getItemByTypeName(\Entity::class, '_test_root_entity', true); @@ -1742,13 +1758,13 @@ public function testUpdatedFields(string $itemtype, array $add_input, array $upd $item = new $itemtype(); $item_id = $item->add(Sanitizer::sanitize($add_input)); - $this->integer($item_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $item_id); $updated = $item->update(['id' => $item_id] + Sanitizer::sanitize($update_input)); - $this->boolean($updated)->isTrue(0); + $this->assertTrue($updated, 0); sort($item->updates); sort($expected_updates); - $this->array($item->updates)->isEqualTo($expected_updates); + $this->assertEquals($expected_updates, $item->updates); } } diff --git a/phpunit/functional/CommonDropdown.php b/phpunit/functional/CommonDropdown.php new file mode 100644 index 00000000000..8863f5de083 --- /dev/null +++ b/phpunit/functional/CommonDropdown.php @@ -0,0 +1,212 @@ +. + * + * --------------------------------------------------------------------- + */ + +namespace tests\units; + +use DbTestCase; + +/* Test for inc/commondropdown.class.php */ + +abstract class CommonDropdown extends DbTestCase +{ + /** + * Get object class name + * + */ + abstract protected function getObjectClass(); + + abstract public static function typenameProvider(); + + /** + * @dataProvider typenameProvider + */ + public function testGetTypeName($string, $expected) + { + $this->assertSame($expected, $string); + } + + public function testMaybeTranslated() + { + $instance = $this->newInstance(); + $this->assertFalse($instance->maybeTranslated()); + } + + public function testGetMenuContent() + { + $class = $this->getObjectClass(); + $this->assertFalse($class::getMenuContent()); + } + + public function testGetAdditionalFields() + { + $instance = $this->newInstance(); + $this->assertSame([], $instance->getAdditionalFields()); + } + + abstract protected function getTabs(); + + public function testDefineTabs() + { + $instance = $this->newInstance(); + $this->assertSame($this->getTabs(), $instance->defineTabs()); + } + + public function testPre_deleteItem() + { + $instance = $this->newInstance(); + $this->assertTrue($instance->pre_deleteItem()); + } + + public function testPrepareInputForAdd() + { + $instance = $this->newInstance(); + + $input = []; + $this->assertSame($input, $instance->prepareInputForAdd($input)); + + $input = ['name' => 'Any name', 'comment' => 'Any comment']; + $this->assertSame($input, $instance->prepareInputForAdd($input)); + + $loc = getItemByTypeName('Location', '_location01'); + $input['locations_id'] = $loc->getID(); + $this->assertSame( + $input + ['entities_id' => $loc->fields['entities_id']], + $instance->prepareInputForAdd($input) + ); + } + + public function testPrepareInputForUpdate() + { + $instance = $this->newInstance(); + + $input = []; + $this->assertSame($input, $instance->prepareInputForUpdate($input)); + + $input = ['name' => 'Any name', 'comment' => 'Any comment']; + $this->assertSame($input, $instance->prepareInputForUpdate($input)); + + $loc = getItemByTypeName('Location', '_location01'); + $input['locations_id'] = $loc->getID(); + //to make sure existing entities_id will not be changed on update + $input['entities_id'] = $loc->fields['entities_id'] + 1; + $this->assertSame( + $input + ['entities_id' => $loc->fields['entities_id']], + $instance->prepareInputForUpdate($input) + ); + } + + /** + * Create new object in database + * + * @return \CommonDBTM + */ + abstract protected function newInstance(): \CommonDBTM; + + public function testGetDropdownName() + { + $instance = $this->newInstance(); + $ret = \Dropdown::getDropdownName($instance::getTable(), $instance->getID()); + $this->assertSame($instance->getName(), $ret); + } + + public function testAddUpdate() + { + $instance = $this->newInstance(); + + $this->assertGreaterThan( + 0, + $instance->add([]) + ); + $this->assertTrue($instance->getFromDB($instance->getID())); + + $keys = ['name', 'comment', 'date_mod', 'date_creation']; + foreach ($keys as $key) { + $this->assertArrayHasKey($key, $instance->fields); + } + + $this->assertNotEquals('', $instance->fields['date_mod']); + $this->assertNotEquals('', $instance->fields['date_creation']); + + $this->assertGreaterThan( + 0, + $instance->add(['name' => 'Tested name']) + ); + $this->assertTrue( + $instance->getFromDB($instance->getID()) + ); + + foreach ($keys as $key) { + $this->assertArrayHasKey($key, $instance->fields); + } + $this->assertSame('Tested name', $instance->fields['name']); + $this->assertNotEquals('', $instance->fields['date_mod']); + $this->assertNotEquals('', $instance->fields['date_creation']); + + $this->assertGreaterThan( + 0, + $instance->add([ + 'name' => 'Another name', + 'comment' => 'A comment on an object' + ]) + ); + $this->assertTrue( + $instance->getFromDB($instance->getID()) + ); + + foreach ($keys as $key) { + $this->assertArrayHasKey($key, $instance->fields); + } + $this->assertSame('Another name', $instance->fields['name']); + $this->assertSame('A comment on an object', $instance->fields['comment']); + $this->assertNotEquals('', $instance->fields['date_mod']); + $this->assertNotEquals('', $instance->fields['date_creation']); + + $this->assertTrue( + $instance->update([ + 'id' => $instance->getID(), + 'name' => 'Changed name' + ]) + ); + $this->assertTrue( + $instance->getFromDB($instance->getID()) + ); + $this->assertSame('Changed name', $instance->fields['name']); + + //cannot update if id is missing + $this->assertFalse( + $instance->update(['name' => 'Will not change']) + ); + } +} diff --git a/tests/functional/Computer.php b/phpunit/functional/ComputerTest.php similarity index 70% rename from tests/functional/Computer.php rename to phpunit/functional/ComputerTest.php index fedc133ec43..7ccbb7acecb 100644 --- a/tests/functional/Computer.php +++ b/phpunit/functional/ComputerTest.php @@ -36,10 +36,11 @@ namespace tests\units; use DbTestCase; +use Monolog\Logger; /* Test for inc/computer.class.php */ -class Computer extends DbTestCase +class ComputerTest extends DbTestCase { protected function getUniqueString() { @@ -56,7 +57,7 @@ private function getNewComputer(): \Computer unset($fields['date_creation']); unset($fields['date_mod']); $fields['name'] = $this->getUniqueString(); - $this->integer((int)$computer->add(\Toolbox::addslashes_deep($fields)))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$computer->add(\Toolbox::addslashes_deep($fields))); return $computer; } @@ -68,7 +69,7 @@ private function getNewPrinter() unset($pfields['date_creation']); unset($pfields['date_mod']); $pfields['name'] = $this->getUniqueString(); - $this->integer((int)$printer->add(\Toolbox::addslashes_deep($pfields)))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$printer->add(\Toolbox::addslashes_deep($pfields))); return $printer; } @@ -86,7 +87,7 @@ public function testUpdate() 'itemtype' => $printer->getType(), 'items_id' => $printer->getID(), ]; - $this->integer((int)$link->add($in))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$link->add($in)); // Change the computer $CFG_GLPI['is_contact_autoupdate'] = 1; @@ -102,15 +103,15 @@ public function testUpdate() 'states_id' => $this->getUniqueInteger(), 'locations_id' => $this->getUniqueInteger(), ]; - $this->boolean($computer->update(\Toolbox::addslashes_deep($in)))->isTrue(); - $this->boolean($computer->getFromDB($computer->getID()))->isTrue(); - $this->boolean($printer->getFromDB($printer->getID()))->isTrue(); + $this->assertTrue($computer->update(\Toolbox::addslashes_deep($in))); + $this->assertTrue($computer->getFromDB($computer->getID())); + $this->assertTrue($printer->getFromDB($printer->getID())); unset($in['id']); foreach ($in as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation occurs - $this->variable($printer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $printer->getField($k)); } //reset values @@ -122,15 +123,15 @@ public function testUpdate() 'states_id' => 0, 'locations_id' => 0, ]; - $this->boolean($computer->update($in))->isTrue(); - $this->boolean($computer->getFromDB($computer->getID()))->isTrue(); - $this->boolean($printer->getFromDB($printer->getID()))->isTrue(); + $this->assertTrue($computer->update($in)); + $this->assertTrue($computer->getFromDB($computer->getID())); + $this->assertTrue($printer->getFromDB($printer->getID())); unset($in['id']); foreach ($in as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation occurs - $this->variable($printer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $printer->getField($k)); } // Change the computer again @@ -147,15 +148,15 @@ public function testUpdate() 'states_id' => $this->getUniqueInteger(), 'locations_id' => $this->getUniqueInteger(), ]; - $this->boolean($computer->update(\Toolbox::addslashes_deep($in2)))->isTrue(); - $this->boolean($computer->getFromDB($computer->getID()))->isTrue(); - $this->boolean($printer->getFromDB($printer->getID()))->isTrue(); + $this->assertTrue($computer->update(\Toolbox::addslashes_deep($in2))); + $this->assertTrue($computer->getFromDB($computer->getID())); + $this->assertTrue($printer->getFromDB($printer->getID())); unset($in2['id']); foreach ($in2 as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation DOES NOT occurs - $this->variable($printer->getField($k))->isEqualTo($in[$k]); + $this->assertEquals($in[$k], $printer->getField($k)); } // Restore configuration @@ -171,7 +172,7 @@ public function testUpdate() ] ); - $this->integer((int)$cpuid)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$cpuid); $link = new \Item_DeviceProcessor(); $linkid = $link->add( @@ -184,7 +185,7 @@ public function testUpdate() ] ); - $this->integer((int)$linkid)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$linkid); // Change the computer $CFG_GLPI['state_autoupdate_mode'] = -1; @@ -193,15 +194,15 @@ public function testUpdate() 'states_id' => $this->getUniqueInteger(), 'locations_id' => $this->getUniqueInteger(), ]; - $this->boolean($computer->update($in))->isTrue(); - $this->boolean($computer->getFromDB($computer->getID()))->isTrue(); - $this->boolean($link->getFromDB($link->getID()))->isTrue(); + $this->assertTrue($computer->update($in)); + $this->assertTrue($computer->getFromDB($computer->getID())); + $this->assertTrue($link->getFromDB($link->getID())); unset($in['id']); foreach ($in as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation occurs - $this->variable($link->getField($k))->isEqualTo($v); + $this->assertEquals($v, $link->getField($k)); } //reset @@ -209,15 +210,15 @@ public function testUpdate() 'states_id' => 0, 'locations_id' => 0, ]; - $this->boolean($computer->update($in))->isTrue(); - $this->boolean($computer->getFromDB($computer->getID()))->isTrue(); - $this->boolean($link->getFromDB($link->getID()))->isTrue(); + $this->assertTrue($computer->update($in)); + $this->assertTrue($computer->getFromDB($computer->getID())); + $this->assertTrue($link->getFromDB($link->getID())); unset($in['id']); foreach ($in as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation occurs - $this->variable($link->getField($k))->isEqualTo($v); + $this->assertEquals($v, $link->getField($k)); } // Change the computer again @@ -227,15 +228,15 @@ public function testUpdate() 'states_id' => $this->getUniqueInteger(), 'locations_id' => $this->getUniqueInteger(), ]; - $this->boolean($computer->update($in2))->isTrue(); - $this->boolean($computer->getFromDB($computer->getID()))->isTrue(); - $this->boolean($link->getFromDB($link->getID()))->isTrue(); + $this->assertTrue($computer->update($in2)); + $this->assertTrue($computer->getFromDB($computer->getID())); + $this->assertTrue($link->getFromDB($link->getID())); unset($in2['id']); foreach ($in2 as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation DOES NOT occurs - $this->variable($link->getField($k))->isEqualTo($in[$k]); + $this->assertEquals($in[$k], $link->getField($k)); } // Restore configuration @@ -269,8 +270,8 @@ public function testCreateLinks() 'states_id' => $this->getUniqueInteger(), 'locations_id' => $this->getUniqueInteger(), ]; - $this->boolean($computer->update(\Toolbox::addslashes_deep($in)))->isTrue(); - $this->boolean($computer->getFromDB($computer->getID()))->isTrue(); + $this->assertTrue($computer->update(\Toolbox::addslashes_deep($in))); + $this->assertTrue($computer->getFromDB($computer->getID())); $printer = new \Printer(); $pid = $printer->add( @@ -280,7 +281,7 @@ public function testCreateLinks() ] ); - $this->integer((int)$pid)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$pid); // Create the link $link = new \Computer_Item(); @@ -288,15 +289,15 @@ public function testCreateLinks() 'itemtype' => $printer->getType(), 'items_id' => $printer->getID(), ]; - $this->integer((int)$link->add($in2))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$link->add($in2)); - $this->boolean($printer->getFromDB($printer->getID()))->isTrue(); + $this->assertTrue($printer->getFromDB($printer->getID())); unset($in['id']); foreach ($in as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation occurs - $this->variable($printer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $printer->getField($k)); } //create devices @@ -308,7 +309,7 @@ public function testCreateLinks() ] ); - $this->integer((int)$cpuid)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$cpuid); $link = new \Item_DeviceProcessor(); $linkid = $link->add( @@ -319,18 +320,18 @@ public function testCreateLinks() ] ); - $this->integer((int)$linkid)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$linkid); $in3 = ['states_id' => $in['states_id'], 'locations_id' => $in['locations_id'], ]; - $this->boolean($link->getFromDB($link->getID()))->isTrue(); + $this->assertTrue($link->getFromDB($link->getID())); foreach ($in3 as $k => $v) { // Check the computer new values - $this->variable($computer->getField($k))->isEqualTo($v); + $this->assertEquals($v, $computer->getField($k)); // Check the printer and test propagation occurs - $this->variable($link->getField($k))->isEqualTo($v); + $this->assertEquals($v, $link->getField($k)); } // Restore configuration @@ -346,29 +347,25 @@ public function testGetFromIter() ]); $prev = false; foreach (\Computer::getFromIter($iter) as $comp) { - $this->object($comp)->isInstanceOf('Computer'); - $this->array($comp->fields) - ->hasKey('name') - ->string['name']->isNotEqualTo($prev); + $this->assertInstanceOf(\Computer::class, $comp); + $this->assertArrayHasKey('name', $comp->fields); + $this->assertNotEquals($prev, $comp->fields['name']); $prev = $comp->fields['name']; } - $this->boolean((bool)$prev)->isTrue(); // we are retrieve something + $this->assertTrue((bool)$prev); // we are retrieve something } public function testGetFromDbByCrit() { $comp = new \Computer(); - $this->boolean($comp->getFromDBByCrit(['name' => '_test_pc01']))->isTrue(); - $this->string($comp->getField('name'))->isIdenticalTo('_test_pc01'); + $this->assertTrue($comp->getFromDBByCrit(['name' => '_test_pc01'])); + $this->assertSame('_test_pc01', $comp->getField('name')); - $this->when( - function () use ($comp) { - $this->boolean($comp->getFromDBByCrit(['name' => ['LIKE', '_test%']]))->isFalse(); - } - )->error() - ->withType(E_USER_WARNING) - ->withMessage('getFromDBByCrit expects to get one result, 9 found in query "SELECT `id` FROM `glpi_computers` WHERE `name` LIKE \'_test%\'".') - ->exists(); + $this->assertFalse($comp->getFromDBByCrit(['name' => ['LIKE', '_test%']])); + $this->hasPhpLogRecordThatContains( + 'getFromDBByCrit expects to get one result, 9 found in query "SELECT `id` FROM `glpi_computers` WHERE `name` LIKE \'_test%\'".', + Logger::WARNING + ); } public function testClone() @@ -385,39 +382,42 @@ public function testClone() //add note $note = new \Notepad(); - $this->integer( + $this->assertGreaterThan( + 0, $note->add([ 'itemtype' => 'Computer', 'items_id' => $id ]) - )->isGreaterThan(0); + ); //add os $os = new \OperatingSystem(); $osid = $os->add([ 'name' => 'My own OS' ]); - $this->integer($osid)->isGreaterThan(0); + $this->assertGreaterThan(0, $osid); $ios = new \Item_OperatingSystem(); - $this->integer( + $this->assertGreaterThan( + 0, $ios->add([ 'operatingsystems_id' => $osid, 'itemtype' => 'Computer', 'items_id' => $id, ]) - )->isGreaterThan(0); + ); - //add infocom + //add infocom $infocom = new \Infocom(); - $this->integer( + $this->assertGreaterThan( + 0, $infocom->add([ 'itemtype' => 'Computer', 'items_id' => $id ]) - )->isGreaterThan(0); + ); - //add device + //add device $cpu = new \DeviceProcessor(); $cpuid = $cpu->add( [ @@ -426,7 +426,7 @@ public function testClone() ] ); - $this->integer((int)$cpuid)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$cpuid); $link = new \Item_DeviceProcessor(); $linkid = $link->add( @@ -436,60 +436,61 @@ public function testClone() 'deviceprocessors_id' => $cpuid ] ); - $this->integer((int)$linkid)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$linkid); - //add document + //add document $document = new \Document(); $docid = (int)$document->add(['name' => 'Test link document']); - $this->integer($docid)->isGreaterThan(0); + $this->assertGreaterThan(0, $docid); $docitem = new \Document_Item(); - $this->integer( + $this->assertGreaterThan( + 0, $docitem->add([ 'documents_id' => $docid, 'itemtype' => 'Computer', 'items_id' => $id ]) - )->isGreaterThan(0); + ); //add antivirus $antivirus = new \ComputerAntivirus(); $antivirus_id = (int)$antivirus->add(['name' => 'Test link antivirus', 'computers_id' => $id]); - $this->integer($antivirus_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $antivirus_id); //clone! $computer = new \Computer(); //$computer->fields contents is already escaped! - $this->boolean($computer->getFromDB($id))->isTrue(); + $this->assertTrue($computer->getFromDB($id)); $added = $computer->clone(); - $this->integer((int)$added)->isGreaterThan(0); - $this->integer($added)->isNotEqualTo($computer->fields['id']); + $this->assertGreaterThan(0, (int)$added); + $this->assertNotEquals($computer->fields['id'], $added); $clonedComputer = new \Computer(); - $this->boolean($clonedComputer->getFromDB($added))->isTrue(); + $this->assertTrue($clonedComputer->getFromDB($added)); $fields = $computer->fields; - // Check the computers values. Id and dates must be different, everything else must be equal + // Check the computers values. Id and dates must be different, everything else must be equal foreach ($fields as $k => $v) { switch ($k) { case 'id': - $this->variable($clonedComputer->getField($k))->isNotEqualTo($computer->getField($k)); + $this->assertNotEquals($computer->getField($k), $clonedComputer->getField($k)); break; case 'date_mod': case 'date_creation': $dateClone = new \DateTime($clonedComputer->getField($k)); $expectedDate = new \DateTime($date); - $this->dateTime($dateClone)->isEqualTo($expectedDate); + $this->assertEquals($expectedDate, $dateClone); break; case 'name': - $this->variable($clonedComputer->getField($k))->isEqualTo("{$computer->getField($k)} (copy)"); + $this->assertEquals("{$computer->getField($k)} (copy)", $clonedComputer->getField($k)); break; default: - $this->variable($clonedComputer->getField($k))->isEqualTo($computer->getField($k)); + $this->assertEquals($computer->getField($k), $clonedComputer->getField($k)); } } - //TODO: would be better to check each Computer::getCloneRelations() ones. + //TODO: would be better to check each Computer::getCloneRelations() ones. $relations = [ \Infocom::class => 1, \Notepad::class => 1, @@ -497,7 +498,8 @@ public function testClone() ]; foreach ($relations as $relation => $expected) { - $this->integer( + $this->assertSame( + $expected, countElementsInTable( $relation::getTable(), [ @@ -505,15 +507,15 @@ public function testClone() 'items_id' => $clonedComputer->fields['id'], ] ) - )->isIdenticalTo($expected); + ); } //check antivirus - $this->boolean($antivirus->getFromDBByCrit(['computers_id' => $clonedComputer->fields['id']]))->isTrue(); + $this->assertTrue($antivirus->getFromDBByCrit(['computers_id' => $clonedComputer->fields['id']])); - //check processor has been cloned - $this->boolean($link->getFromDBByCrit(['itemtype' => 'Computer', 'items_id' => $added]))->isTrue(); - $this->boolean($docitem->getFromDBByCrit(['itemtype' => 'Computer', 'items_id' => $added]))->isTrue(); + //check processor has been cloned + $this->assertTrue($link->getFromDBByCrit(['itemtype' => 'Computer', 'items_id' => $added])); + $this->assertTrue($docitem->getFromDBByCrit(['itemtype' => 'Computer', 'items_id' => $added])); } public function testCloneWithAutoCreateInfocom() @@ -532,7 +534,8 @@ public function testCloneWithAutoCreateInfocom() // add infocom $infocom = new \Infocom(); - $this->integer( + $this->assertGreaterThan( + 0, $infocom->add([ 'itemtype' => 'Computer', 'items_id' => $id, @@ -540,20 +543,20 @@ public function testCloneWithAutoCreateInfocom() 'use_date' => '2021-01-02', 'value' => '800.00' ]) - )->isGreaterThan(0); + ); // clone! $computer = new \Computer(); //$computer->fields contents is already escaped! - $this->boolean($computer->getFromDB($id))->isTrue(); + $this->assertTrue($computer->getFromDB($id)); $infocom_auto_create_original = $CFG_GLPI["infocom_auto_create"] ?? 0; $CFG_GLPI["infocom_auto_create"] = 1; $added = $computer->clone(); $CFG_GLPI["infocom_auto_create"] = $infocom_auto_create_original; - $this->integer((int)$added)->isGreaterThan(0); - $this->integer($added)->isNotEqualTo($computer->fields['id']); + $this->assertGreaterThan(0, (int)$added); + $this->assertNotEquals($computer->fields['id'], $added); $clonedComputer = new \Computer(); - $this->boolean($clonedComputer->getFromDB($added))->isTrue(); + $this->assertTrue($clonedComputer->getFromDB($added)); $iterator = $DB->request([ 'SELECT' => ['buy_date', 'use_date', 'value'], @@ -563,12 +566,15 @@ public function testCloneWithAutoCreateInfocom() 'items_id' => $clonedComputer->fields['id'] ] ]); - $this->integer($iterator->count())->isEqualTo(1); - $this->array($iterator->current())->isIdenticalTo([ - 'buy_date' => '2021-01-01', - 'use_date' => '2021-01-02', - 'value' => '800.0000' //DB stores 4 decimal places - ]); + $this->assertEquals(1, $iterator->count()); + $this->assertSame( + [ + 'buy_date' => '2021-01-01', + 'use_date' => '2021-01-02', + 'value' => '800.0000' //DB stores 4 decimal places + ], + $iterator->current() + ); } public function testCloneWithSpecificName() @@ -578,10 +584,10 @@ public function testCloneWithSpecificName() $clone_id = $computer->clone([ 'name' => 'testCloneWithSpecificName' ]); - $this->integer($clone_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $clone_id); $result = $computer->getFromDB($clone_id); - $this->boolean($result)->isTrue(); - $this->string($computer->fields['name'])->isEqualTo('testCloneWithSpecificName'); + $this->assertTrue($result); + $this->assertEquals('testCloneWithSpecificName', $computer->fields['name']); } public function testClonedRelationNamesFromTemplate() @@ -595,7 +601,7 @@ public function testClonedRelationNamesFromTemplate() 'template_name' => __FUNCTION__ . '_template', 'is_template' => 1 ]); - $this->integer($templates_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $templates_id); // Add a network port to the template $networkPort = new \NetworkPort(); @@ -608,7 +614,7 @@ public function testClonedRelationNamesFromTemplate() 'items_devicenetworkcards_id' => 0, '_create_children' => true ]); - $this->integer($networkports_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networkports_id); // Create computer from template $computer = new \Computer(); @@ -616,15 +622,17 @@ public function testClonedRelationNamesFromTemplate() 'name' => __FUNCTION__, 'id' => $templates_id ]); - $this->integer($computers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $computers_id); // Get network port from computer - $this->boolean($networkPort->getFromDBByCrit([ - 'itemtype' => 'Computer', - 'items_id' => $computers_id, - ]))->isTrue(); + $this->assertTrue( + $networkPort->getFromDBByCrit([ + 'itemtype' => 'Computer', + 'items_id' => $computers_id, + ]) + ); // Network port name should not have a "copy" suffix - $this->string($networkPort->fields['name'])->isEqualTo(__FUNCTION__); + $this->assertEquals(__FUNCTION__, $networkPort->fields['name']); } public function testCloneWithAutoName() @@ -636,10 +644,10 @@ public function testCloneWithAutoName() 'name' => 'testCloneWithAutoName' ]); $clone_id = $computer->clone(); - $this->integer($clone_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $clone_id); $result = $computer->getFromDB($clone_id); - $this->boolean($result)->isTrue(); - $this->string($computer->fields['name'])->isEqualTo('testCloneWithAutoName (copy)'); + $this->assertTrue($result); + $this->assertEquals('testCloneWithAutoName (copy)', $computer->fields['name']); } public function testTransfer() @@ -653,14 +661,14 @@ public function testTransfer() 'name' => 'GLPI', 'entities_id' => $computer->fields['entities_id'] ]); - $this->integer($softwares_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $softwares_id); $version = new \SoftwareVersion(); $versions_id = $version->add([ 'softwares_id' => $softwares_id, 'name' => '9.5' ]); - $this->integer($versions_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $versions_id); $link = new \Item_SoftwareVersion(); $link_id = $link->add([ @@ -668,17 +676,18 @@ public function testTransfer() 'items_id' => $cid, 'softwareversions_id' => $versions_id ]); - $this->integer($link_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $link_id); $entities_id = getItemByTypeName('Entity', '_test_child_2', true); $oentities_id = (int)$computer->fields['entities_id']; - $this->integer($entities_id)->isNotEqualTo($oentities_id); + $this->assertNotEquals($oentities_id, $entities_id); - //transer to another entity + //transfer to another entity $transfer = new \Transfer(); - $this->mockGenerator->orphanize('__construct'); - $ma = new \mock\MassiveAction([], [], 'process'); + $ma = $this->getMockBuilder(\MassiveAction::class) + ->disableOriginalConstructor() + ->getMock(); \MassiveAction::processMassiveActionsForOneItemtype( $ma, @@ -688,11 +697,11 @@ public function testTransfer() $transfer->moveItems(['Computer' => [$cid]], $entities_id, [$cid, 'keep_software' => 1]); unset($_SESSION['glpitransfer_list']); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->integer((int)$computer->fields['entities_id'])->isidenticalTo($entities_id); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertSame($entities_id, (int)$computer->fields['entities_id']); - $this->boolean($soft->getFromDB($softwares_id))->isTrue(); - $this->integer($soft->fields['entities_id'])->isidenticalTo($oentities_id); + $this->assertTrue($soft->getFromDB($softwares_id)); + $this->assertSame($oentities_id, $soft->fields['entities_id']); global $DB; $softwares = $DB->request([ @@ -702,7 +711,7 @@ public function testTransfer() 'items_id' => $cid ] ]); - $this->integer(count($softwares))->isidenticalTo(1); + $this->assertSame(1, count($softwares)); } public function testClearSavedInputAfterUpdate() @@ -720,7 +729,7 @@ public function testClearSavedInputAfterUpdate() 'id' => $cid, 'comment' => 'test' ]); - $this->boolean($result)->isTrue(); + $this->assertTrue($result); // Check that there is no savedInput after update if (isset($_SESSION['saveInput']) && is_array($_SESSION['saveInput'])) { @@ -751,7 +760,7 @@ public function testGetInventoryAgent(): void ); $computer_agent = $computer->getInventoryAgent(); - $this->variable($computer_agent)->isNull(); + $this->assertNull($computer_agent); $agenttype_id = getItemByTypeName(\AgentType::class, 'Core', true); @@ -801,23 +810,23 @@ public function testGetInventoryAgent(): void // most recent agent directly linked $computer_agent = $computer->getInventoryAgent(); - $this->object($computer_agent)->isInstanceOf(\Agent::class); - $this->array($computer_agent->fields)->isEqualTo($agent1->fields); + $this->assertInstanceOf(\Agent::class, $computer_agent); + $this->assertEquals($agent1->fields, $computer_agent->fields); - $this->boolean($agent1->delete(['id' => $agent1->fields['id']]))->isTrue(); + $this->assertTrue($agent1->delete(['id' => $agent1->fields['id']])); // most recent agent directly linked $computer_agent = $computer->getInventoryAgent(); - $this->object($computer_agent)->isInstanceOf(\Agent::class); - $this->array($computer_agent->fields)->isEqualTo($agent2->fields); + $this->assertInstanceOf(\Agent::class, $computer_agent); + $this->assertEquals($agent2->fields, $computer_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 items, as there is no more agent linked directly $computer_agent = $computer->getInventoryAgent(); - $this->object($computer_agent)->isInstanceOf(\Agent::class); + $this->assertInstanceOf(\Agent::class, $computer_agent); $printer1_agent = $printer1->getInventoryAgent(); - $this->object($printer1_agent)->isInstanceOf(\Agent::class); - $this->array($computer_agent->fields)->isEqualTo($printer1_agent->fields); + $this->assertInstanceOf(\Agent::class, $printer1_agent); + $this->assertEquals($printer1_agent->fields, $computer_agent->fields); } } diff --git a/tests/functional/ComputerVirtualMachine.php b/phpunit/functional/ComputerVirtualMachine.php similarity index 71% rename from tests/functional/ComputerVirtualMachine.php rename to phpunit/functional/ComputerVirtualMachine.php index 40d8f1c4f51..d08aad97ced 100644 --- a/tests/functional/ComputerVirtualMachine.php +++ b/phpunit/functional/ComputerVirtualMachine.php @@ -43,38 +43,39 @@ public function testCreateAndGet() { $this->login(); - $this->newTestedInstance(); - $obj = $this->testedInstance; + $obj = new \ComputerVirtualMachine(); $uuid = 'c37f7ce8-af95-4676-b454-0959f2c5e162'; - // Add + // Add $computer = getItemByTypeName('Computer', '_test_pc01'); - $this->object($computer)->isInstanceOf('\Computer'); + $this->assertInstanceOf('\Computer', $computer); - $this->integer( - $id = (int)$obj->add([ + $this->assertGreaterThan( + 0, + $id = $obj->add([ 'computers_id' => $computer->fields['id'], 'name' => 'Virtu Hall', 'uuid' => $uuid, 'vcpu' => 1, 'ram' => 1024 ]) - )->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->string($obj->fields['uuid'])->isIdenticalTo($uuid); + ); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame($uuid, $obj->fields['uuid']); - $this->boolean($obj->findVirtualMachine(['name' => 'Virtu Hall']))->isFalse(); - //n machin exists yet - $this->boolean($obj->findVirtualMachine(['uuid' => $uuid]))->isFalse(); + $this->assertFalse($obj->findVirtualMachine(['name' => 'Virtu Hall'])); + //a machine exists yet + $this->assertFalse($obj->findVirtualMachine(['uuid' => $uuid])); - $this->integer( - $cid = (int)$computer->add([ + $this->assertGreaterThan( + 0, + $cid = $computer->add([ 'name' => 'Virtu Hall', 'uuid' => $uuid, 'entities_id' => 0 ]) - )->isGreaterThan(0); + ); - $this->variable($obj->findVirtualMachine(['uuid' => $uuid]))->isEqualTo($cid); + $this->assertEquals($cid, $obj->findVirtualMachine(['uuid' => $uuid])); } } diff --git a/tests/functional/Config.php b/phpunit/functional/ConfigTest.php similarity index 71% rename from tests/functional/Config.php rename to phpunit/functional/ConfigTest.php index 54f208f5213..cbaf18f4c1f 100644 --- a/tests/functional/Config.php +++ b/phpunit/functional/ConfigTest.php @@ -44,47 +44,48 @@ /* Test for inc/config.class.php */ -class Config extends DbTestCase +class ConfigTest extends DbTestCase { public function testGetTypeName() { - $this->string(\Config::getTypeName())->isIdenticalTo('Setup'); + $this->assertSame('Setup', \Config::getTypeName()); } public function testAcls() { //check ACLs when not logged - $this->boolean(\Config::canView())->isFalse(); - $this->boolean(\Config::canCreate())->isFalse(); + $this->assertFalse(\Config::canView()); + $this->assertFalse(\Config::canCreate()); $conf = new \Config(); - $this->boolean($conf->canViewItem())->isFalse(); + $this->assertFalse($conf->canViewItem()); //check ACLs from superadmin profile $this->login(); - $this->boolean((bool)\Config::canView())->isTrue(); - $this->boolean(\Config::canCreate())->isFalse(); - $this->boolean($conf->canViewItem())->isFalse(); + $this->assertTrue((bool)\Config::canView()); + $this->assertFalse(\Config::canCreate()); + $this->assertFalse($conf->canViewItem()); - $this->boolean($conf->getFromDB(1))->isTrue(); - $this->boolean($conf->canViewItem())->isTrue(); + $this->assertTrue($conf->getFromDB(1)); + $this->assertTrue($conf->canViewItem()); //check ACLs from tech profile $auth = new \Auth(); - $this->boolean((bool)$auth->login('tech', 'tech', true))->isTrue(); - $this->boolean((bool)\Config::canView())->isFalse(); - $this->boolean(\Config::canCreate())->isFalse(); - $this->boolean($conf->canViewItem())->isTrue(); + $this->assertTrue((bool)$auth->login('tech', 'tech', true)); + $this->assertFalse((bool)\Config::canView()); + $this->assertFalse(\Config::canCreate()); + $this->assertTrue($conf->canViewItem()); } public function testGetMenuContent() { - $this->boolean(\Config::getMenuContent())->isFalse(); + $this->assertFalse(\Config::getMenuContent()); $this->login(); - $this->array(\Config::getMenuContent()) - ->hasSize(4) - ->hasKeys(['title', 'page', 'options', 'icon']); + $this->assertEquals( + ['title', 'page', 'icon', 'options'], + array_keys(\Config::getMenuContent()) + ); } public function testDefineTabs() @@ -97,22 +98,18 @@ public function testDefineTabs() 'Config$12' => 'Management', 'GLPINetwork$1' => 'GLPI Network', ]; - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->defineTabs()) - ->isIdenticalTo($expected); - //Standards users do not have extra tabs + $instance = new \Config(); + $this->assertSame($expected, $instance->defineTabs()); + + //Standards users do not have extra tabs $auth = new \Auth(); - $this->boolean((bool)$auth->login('tech', 'tech', true))->isTrue(); - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->defineTabs()) - ->isIdenticalTo($expected); - - //check extra tabs from superadmin profile + $this->assertTrue((bool)$auth->login('tech', 'tech', true)); + + $instance = new \Config(); + $this->assertSame($expected, $instance->defineTabs()); + + //check extra tabs from superadmin profile $this->login(); $expected = [ 'Config$1' => 'General setup', @@ -129,11 +126,9 @@ public function testDefineTabs() 'GLPINetwork$1' => 'GLPI Network', 'Log$1' => 'Historical', ]; - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->defineTabs()) - ->isIdenticalTo($expected); + + $instance = new \Config(); + $this->assertSame($expected, $instance->defineTabs()); } public function testUnsetUndisclosedFields() @@ -146,7 +141,7 @@ public function testUnsetUndisclosedFields() $expected = $input; \Config::unsetUndisclosedFields($input); - $this->array($input)->isIdenticalTo($expected); + $this->assertSame($expected, $input); $input = [ 'context' => 'core', @@ -157,7 +152,7 @@ public function testUnsetUndisclosedFields() unset($expected['value']); \Config::unsetUndisclosedFields($input); - $this->array($input)->isIdenticalTo($expected); + $this->assertSame($expected, $input); $input = [ 'context' => 'core', @@ -168,23 +163,23 @@ public function testUnsetUndisclosedFields() unset($expected['value']); \Config::unsetUndisclosedFields($input); - $this->array($input)->isIdenticalTo($expected); + $this->assertSame($expected, $input); } public function testValidatePassword() { global $CFG_GLPI; - $this->boolean((bool)$CFG_GLPI['use_password_security'])->isFalse(); + $this->assertFalse((bool)$CFG_GLPI['use_password_security']); - $this->boolean(\Config::validatePassword('mypass'))->isTrue(); + $this->assertTrue(\Config::validatePassword('mypass')); $CFG_GLPI['use_password_security'] = 1; - $this->integer((int)$CFG_GLPI['password_min_length'])->isIdenticalTo(8); - $this->integer((int)$CFG_GLPI['password_need_number'])->isIdenticalTo(1); - $this->integer((int)$CFG_GLPI['password_need_letter'])->isIdenticalTo(1); - $this->integer((int)$CFG_GLPI['password_need_caps'])->isIdenticalTo(1); - $this->integer((int)$CFG_GLPI['password_need_symbol'])->isIdenticalTo(1); - $this->boolean(\Config::validatePassword(''))->isFalse(); + $this->assertSame(8, (int)$CFG_GLPI['password_min_length']); + $this->assertSame(1, (int)$CFG_GLPI['password_need_number']); + $this->assertSame(1, (int)$CFG_GLPI['password_need_letter']); + $this->assertSame(1, (int)$CFG_GLPI['password_need_caps']); + $this->assertSame(1, (int)$CFG_GLPI['password_need_symbol']); + $this->assertFalse(\Config::validatePassword('')); $expected = [ 'Password too short!', @@ -199,11 +194,11 @@ public function testValidatePassword() 'Password must include at least a uppercase letter!', 'Password must include at least a symbol!' ]; - $this->boolean(\Config::validatePassword('mypassword'))->isFalse(); + $this->assertFalse(\Config::validatePassword('mypassword')); $this->hasSessionMessages(ERROR, $expected); $CFG_GLPI['password_min_length'] = strlen('mypass'); - $this->boolean(\Config::validatePassword('mypass'))->isFalse(); + $this->assertFalse(\Config::validatePassword('mypass')); $CFG_GLPI['password_min_length'] = 8; //reset $this->hasSessionMessages(ERROR, $expected); @@ -212,30 +207,30 @@ public function testValidatePassword() 'Password must include at least a uppercase letter!', 'Password must include at least a symbol!' ]; - $this->boolean(\Config::validatePassword('my1password'))->isFalse(); + $this->assertFalse(\Config::validatePassword('my1password')); $this->hasSessionMessages(ERROR, $expected); $CFG_GLPI['password_need_number'] = 0; - $this->boolean(\Config::validatePassword('mypassword'))->isFalse(); + $this->assertFalse(\Config::validatePassword('mypassword')); $CFG_GLPI['password_need_number'] = 1; //reset $this->hasSessionMessages(ERROR, $expected); $expected = [ 'Password must include at least a symbol!' ]; - $this->boolean(\Config::validatePassword('my1paSsword'))->isFalse(); + $this->assertFalse(\Config::validatePassword('my1paSsword')); $this->hasSessionMessages(ERROR, $expected); $CFG_GLPI['password_need_caps'] = 0; - $this->boolean(\Config::validatePassword('my1password'))->isFalse(); + $this->assertFalse(\Config::validatePassword('my1password')); $CFG_GLPI['password_need_caps'] = 1; //reset $this->hasSessionMessages(ERROR, $expected); - $this->boolean(\Config::validatePassword('my1paSsw@rd'))->isTrue(); + $this->assertTrue(\Config::validatePassword('my1paSsw@rd')); $this->hasNoSessionMessage(ERROR); $CFG_GLPI['password_need_symbol'] = 0; - $this->boolean(\Config::validatePassword('my1paSsword'))->isTrue(); + $this->assertTrue(\Config::validatePassword('my1paSsword')); $CFG_GLPI['password_need_symbol'] = 1; //reset $this->hasNoSessionMessage(ERROR); } @@ -251,7 +246,7 @@ public function testGetLibraries() } } sort($actual); - $this->array($actual)->isNotEmpty(); + $this->assertNotEmpty($actual); $composer = json_decode(file_get_contents(__DIR__ . '/../../composer.json'), true); foreach (array_keys($composer['require']) as $dep) { // composer names only (skip php, ext-*, ...) @@ -260,31 +255,34 @@ public function testGetLibraries() } } sort($expected); - $this->array($expected)->isNotEmpty(); - $this->array($actual)->isIdenticalTo($expected); + $this->assertNotEmpty($expected); + $this->assertSame($expected, $actual); } public function testGetLibraryDir() { - $this->boolean(\Config::getLibraryDir(''))->isFalse(); - $this->boolean(\Config::getLibraryDir('abcde'))->isFalse(); + $this->assertFalse(\Config::getLibraryDir('')); + $this->assertFalse(\Config::getLibraryDir('abcde')); $expected = realpath(__DIR__ . '/../../vendor/phpmailer/phpmailer/src'); if (is_dir($expected)) { // skip when system library is used - $this->string(\Config::getLibraryDir('PHPMailer\PHPMailer\PHPMailer'))->isIdenticalTo($expected); + $this->assertSame($expected, \Config::getLibraryDir('PHPMailer\PHPMailer\PHPMailer')); $mailer = new PHPMailer(); - $this->string(\Config::getLibraryDir($mailer))->isIdenticalTo($expected); + $this->assertSame($expected, \Config::getLibraryDir($mailer)); } - $expected = realpath(__DIR__ . '/../src/autoload'); - $this->string(\Config::getLibraryDir('getItemByTypeName'))->isIdenticalTo($expected); + $expected = realpath(__DIR__ . '/../../tests/src/autoload'); + $this->assertSame($expected, \Config::getLibraryDir('getItemByTypeName')); } public function testCheckExtensions() { - $this->array(\Config::checkExtensions()) - ->hasKeys(['error', 'good', 'missing', 'may']); + $check = \Config::checkExtensions(); + $this->assertArrayHasKey('error', $check); + $this->assertArrayHasKey('good', $check); + $this->assertArrayHasKey('missing', $check); + $this->assertArrayHasKey('may', $check); $expected = [ 'error' => 0, @@ -295,7 +293,7 @@ public function testCheckExtensions() 'may' => [] ]; - //check extension from class name + //check extension from class name $list = [ 'mysqli' => [ 'required' => true, @@ -303,7 +301,7 @@ public function testCheckExtensions() ] ]; $report = \Config::checkExtensions($list); - $this->array($report)->isIdenticalTo($expected); + $this->assertSame($expected, $report); //check extension from method name $list = [ @@ -313,18 +311,18 @@ public function testCheckExtensions() ] ]; $report = \Config::checkExtensions($list); - $this->array($report)->isIdenticalTo($expected); + $this->assertSame($expected, $report); - //check extension from its name + //check extension from its name $list = [ 'mysqli' => [ 'required' => true ] ]; $report = \Config::checkExtensions($list); - $this->array($report)->isIdenticalTo($expected); + $this->assertSame($expected, $report); - //required, missing extension + //required, missing extension $list['notantext'] = [ 'required' => true ]; @@ -339,9 +337,9 @@ public function testCheckExtensions() ], 'may' => [] ]; - $this->array($report)->isIdenticalTo($expected); + $this->assertSame($expected, $report); - //not required, missing extension + //not required, missing extension unset($list['notantext']); $list['totally_optionnal'] = ['required' => false]; $report = \Config::checkExtensions($list); @@ -355,69 +353,90 @@ public function testCheckExtensions() 'totally_optionnal' => 'totally_optionnal extension is not present' ] ]; - $this->array($report)->isIdenticalTo($expected); + $this->assertSame($expected, $report); } public function testGetConfigurationValues() { $conf = \Config::getConfigurationValues('core'); - $this->array($conf) - ->hasKeys(['version', 'dbversion']) - ->size->isGreaterThan(170); + $this->assertArrayHasKey('version', $conf); + $this->assertArrayHasKey('dbversion', $conf); + $this->assertGreaterThan(170, count($conf)); $conf = \Config::getConfigurationValues('core', ['version', 'dbversion']); - $this->array($conf)->isEqualTo([ - 'dbversion' => GLPI_SCHEMA_VERSION, - 'version' => GLPI_VERSION - ]); + $this->assertEquals( + [ + 'dbversion' => GLPI_SCHEMA_VERSION, + 'version' => GLPI_VERSION + ], + $conf + ); } public function testSetConfigurationValues() { $conf = \Config::getConfigurationValues('core', ['version', 'notification_to_myself']); - $this->array($conf)->isEqualTo([ - 'notification_to_myself' => '1', - 'version' => GLPI_VERSION - ]); + $this->assertEquals( + [ + 'notification_to_myself' => '1', + 'version' => GLPI_VERSION + ], + $conf + ); - //update configuration value + //update configuration value \Config::setConfigurationValues('core', ['notification_to_myself' => 0]); $conf = \Config::getConfigurationValues('core', ['version', 'notification_to_myself']); - $this->array($conf)->isEqualTo([ - 'notification_to_myself' => '0', - 'version' => GLPI_VERSION - ]); + $this->assertEquals( + [ + 'notification_to_myself' => '0', + 'version' => GLPI_VERSION + ], + $conf + ); \Config::setConfigurationValues('core', ['notification_to_myself' => 1]); //reset - //check new configuration key does not exists + //check new configuration key does not exists $conf = \Config::getConfigurationValues('core', ['version', 'new_configuration_key']); - $this->array($conf)->isEqualTo([ - 'version' => GLPI_VERSION - ]); + $this->assertEquals( + [ + 'version' => GLPI_VERSION + ], + $conf + ); - //add new configuration key + //add new configuration key \Config::setConfigurationValues('core', ['new_configuration_key' => 'test']); $conf = \Config::getConfigurationValues('core', ['version', 'new_configuration_key']); - $this->array($conf)->isEqualTo([ - 'new_configuration_key' => 'test', - 'version' => GLPI_VERSION - ]); + $this->assertEquals( + [ + 'new_configuration_key' => 'test', + 'version' => GLPI_VERSION + ], + $conf + ); - //drop new configuration key + //drop new configuration key \Config::deleteConfigurationValues('core', ['new_configuration_key']); $conf = \Config::getConfigurationValues('core', ['version', 'new_configuration_key']); - $this->array($conf)->isEqualTo([ - 'version' => GLPI_VERSION - ]); + $this->assertEquals( + [ + 'version' => GLPI_VERSION + ], + $conf + ); } public function testGetRights() { $conf = new \Config(); - $this->array($conf->getRights())->isIdenticalTo([ - READ => 'Read', - UPDATE => 'Update' - ]); + $this->assertSame( + [ + READ => 'Read', + UPDATE => 'Update' + ], + $conf->getRights() + ); } public function testGetPalettes() @@ -442,11 +461,9 @@ public function testGetPalettes() 'teclib' => 'Teclib', 'vintage' => 'Vintage', ]; - $this - ->if($this->newTestedInstance) - ->then - ->array($this->testedInstance->getPalettes()) - ->isIdenticalTo($expected); + + $instance = new \Config(); + $this->assertSame($expected, $instance->getPalettes()); } /** @@ -454,7 +471,7 @@ public function testGetPalettes() * * @return array */ - protected function dbEngineProvider() + public static function dbEngineProvider() { return [ [ @@ -499,30 +516,30 @@ protected function dbEngineProvider() public function testCheckDbEngine($raw, $version, $compat) { global $DB; - $DB = new \mock\DB(); - $this->calling($DB)->getVersion = $raw; + + $orig_db = clone $DB; + $DB = $this->getMockBuilder(\DB::class) + ->onlyMethods(['getVersion']) + ->getMock(); + $DB->method('getVersion')->willReturn($raw); $result = \Config::checkDbEngine(); - $this->array($result)->isIdenticalTo([$version => $compat]); + $this->assertSame( + [$version => $compat], + $result + ); + + $DB = $orig_db; } public function testGetLanguage() { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getLanguage('fr')) - ->isIdenticalTo('fr_FR') - ->string($this->testedInstance->getLanguage('fr_FR')) - ->isIdenticalTo('fr_FR') - ->string($this->testedInstance->getLanguage('fr-FR')) - ->isIdenticalTo('fr_FR') - ->string($this->testedInstance->getLanguage('Français')) - ->isIdenticalTo('fr_FR') - ->string($this->testedInstance->getLanguage('french')) - ->isIdenticalTo('fr_FR') - ->string($this->testedInstance->getLanguage('notalang')) - ->isIdenticalTo(''); + $instance = new \Config(); + $this->assertSame('fr_FR', $instance->getLanguage('fr')); + $this->assertSame('fr_FR', $instance->getLanguage('fr_FR')); + $this->assertSame('fr_FR', $instance->getLanguage('Français')); + $this->assertSame('fr_FR', $instance->getLanguage('french')); + $this->assertSame('', $instance->getLanguage('notalang')); } /** @@ -530,7 +547,7 @@ public function testGetLanguage() * * @return array */ - protected function itemtypeLinkedToConfigurationProvider() + public static function itemtypeLinkedToConfigurationProvider() { return [ [ @@ -563,24 +580,23 @@ protected function itemtypeLinkedToConfigurationProvider() public function testCleanRelationDataOfLinkedItems($key, $itemtype) { - // Case 1: used item is cleaned without replacement + // Case 1: used item is cleaned without replacement $item = new $itemtype(); $item->fields = ['id' => 15]; \Config::setConfigurationValues('core', [$key => $item->fields['id']]); if (is_a($itemtype, 'CommonDropdown', true)) { - $this->boolean($item->isUsed())->isTrue(); + $this->assertTrue($item->isUsed()); } $item->cleanRelationData(); if (is_a($itemtype, 'CommonDropdown', true)) { - $this->boolean($item->isUsed())->isFalse(); + $this->assertFalse($item->isUsed()); } - $this->array(\Config::getConfigurationValues('core', [$key])) - ->hasKey($key) - ->variable[$key]->isEqualTo(0); + $this->assertArrayHasKey($key, \Config::getConfigurationValues('core', [$key])); + $this->assertEquals(0, \Config::getConfigurationValues('core', [$key])[$key]); - // Case 2: unused item is cleaned without effect + // Case 2: unused item is cleaned without effect $item = new $itemtype(); $item->fields = ['id' => 15]; @@ -589,17 +605,16 @@ public function testCleanRelationDataOfLinkedItems($key, $itemtype) \Config::setConfigurationValues('core', [$key => $random_id]); if (is_a($itemtype, 'CommonDropdown', true)) { - $this->boolean($item->isUsed())->isFalse(); + $this->assertFalse($item->isUsed()); } $item->cleanRelationData(); if (is_a($itemtype, 'CommonDropdown', true)) { - $this->boolean($item->isUsed())->isFalse(); + $this->assertFalse($item->isUsed()); } - $this->array(\Config::getConfigurationValues('core', [$key])) - ->hasKey($key) - ->variable[$key]->isEqualTo($random_id); + $this->assertArrayHasKey($key, \Config::getConfigurationValues('core', [$key])); + $this->assertEquals($random_id, \Config::getConfigurationValues('core', [$key])[$key]); - // Case 3: used item is cleaned with replacement (CommonDropdown only) + // Case 3: used item is cleaned with replacement (CommonDropdown only) if (is_a($itemtype, 'CommonDropdown', true)) { $replacement_item = new $itemtype(); $replacement_item->fields = ['id' => 12]; @@ -610,43 +625,46 @@ public function testCleanRelationDataOfLinkedItems($key, $itemtype) \Config::setConfigurationValues('core', [$key => $item->fields['id']]); - $this->boolean($item->isUsed())->isTrue(); - $this->boolean($replacement_item->isUsed())->isFalse(); + $this->assertTrue($item->isUsed()); + $this->assertFalse($replacement_item->isUsed()); $item->cleanRelationData(); - $this->boolean($item->isUsed())->isFalse(); - $this->boolean($replacement_item->isUsed())->isTrue(); - $this->array(\Config::getConfigurationValues('core', [$key])) - ->hasKey($key) - ->variable[$key] - ->isEqualTo($replacement_item->fields['id']); + $this->assertFalse($item->isUsed()); + $this->assertTrue($replacement_item->isUsed()); + $this->assertArrayHasKey($key, \Config::getConfigurationValues('core', [$key])); + $this->assertEquals($replacement_item->fields['id'], \Config::getConfigurationValues('core', [$key])[$key]); } } public function testDevicesInMenu() { global $CFG_GLPI, $DB; + $bkp_devices_in_menu = $CFG_GLPI['devices_in_menu']; $conf = new \Config(); - $this->array($CFG_GLPI['devices_in_menu'])->isIdenticalTo([ - 'Item_DeviceSimcard' - ]); + $this->assertSame( + ['Item_DeviceSimcard'], + $CFG_GLPI['devices_in_menu'] + ); - //Config::prepareInputForUpdate() always return false. + //Config::prepareInputForUpdate() always return false. $conf->update([ 'id' => 1, '_update_devices_in_menu' => 1, 'devices_in_menu' => ['Item_DeviceSimcard', 'Item_DeviceBattery'] ]); - //check values in db + //check values in db $res = $DB->request([ 'SELECT' => 'value', 'FROM' => $conf->getTable(), 'WHERE' => ['name' => 'devices_in_menu'] ])->current(); - $this->array($res)->isIdenticalTo( - ['value' => exportArrayToDB(['Item_DeviceSimcard', 'Item_DeviceBattery'])] + $this->assertSame( + ['value' => exportArrayToDB(['Item_DeviceSimcard', 'Item_DeviceBattery'])], + $res ); + + $CFG_GLPI['devices_in_menu'] = $bkp_devices_in_menu; } /** @@ -668,7 +686,7 @@ public function testPasswordExpirationDelayUpdate() 'authtype' => $authtype, ] ); - $this->integer($user_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $user_id); } // get count of users using local auth @@ -689,22 +707,24 @@ public function testPasswordExpirationDelayUpdate() // - users from installation data have no value for password_last_update // - crontask is not active $values = \Config::getConfigurationValues('core'); - $this->array($values)->hasKey('password_expiration_delay'); - $this->integer((int)$values['password_expiration_delay'])->isIdenticalTo(-1); - $this->integer( + $this->assertArrayHasKey('password_expiration_delay', $values); + $this->assertSame(-1, (int)$values['password_expiration_delay']); + $this->assertEquals( + $local_users_count, countElementsInTable( \User::getTable(), ['authtype' => \Auth::DB_GLPI, 'password_last_update' => null] ) - )->isEqualTo($local_users_count); - $this->integer( + ); + $this->assertEquals( + $external_users_count, countElementsInTable( \User::getTable(), ['NOT' => ['authtype' => \Auth::DB_GLPI], 'password_last_update' => null] ) - )->isEqualTo($external_users_count); - $this->boolean($crontask->getFromDBbyName(\User::getType(), 'passwordexpiration'))->isTrue(); - $this->integer((int)$crontask->fields['state'])->isIdenticalTo(0); + ); + $this->assertTrue($crontask->getFromDBbyName(\User::getType(), 'passwordexpiration')); + $this->assertSame(0, (int)$crontask->fields['state']); // check that activation of password expiration reset `password_last_update` to current date // for all local users but not for external users @@ -720,25 +740,27 @@ public function testPasswordExpirationDelayUpdate() ); $_SESSION['glpi_currenttime'] = $current_time; $values = \Config::getConfigurationValues('core'); - $this->array($values)->hasKey('password_expiration_delay'); - $this->integer((int)$values['password_expiration_delay'])->isIdenticalTo(30); - $this->integer( + $this->assertArrayHasKey('password_expiration_delay', $values); + $this->assertSame(30, (int)$values['password_expiration_delay']); + $this->assertEquals( + $local_users_count, countElementsInTable( \User::getTable(), ['authtype' => \Auth::DB_GLPI, 'password_last_update' => $update_datetime] ) - )->isEqualTo($local_users_count); - $this->integer( + ); + $this->assertEquals( + $external_users_count, countElementsInTable( \User::getTable(), ['NOT' => ['authtype' => \Auth::DB_GLPI], 'password_last_update' => null] ) - )->isEqualTo($external_users_count); - $this->boolean($crontask->getFromDBbyName(\User::getType(), 'passwordexpiration'))->isTrue(); - $this->integer((int)$crontask->fields['state'])->isIdenticalTo(1); + ); + $this->assertTrue($crontask->getFromDBbyName(\User::getType(), 'passwordexpiration')); + $this->assertSame(1, (int)$crontask->fields['state']); - // check that changing password expiration delay does not reset `password_last_update` to current date - // if password expiration was already active + // check that changing password expiration delay does not reset `password_last_update` to current date + // if password expiration was already active $current_time = $_SESSION['glpi_currenttime']; $new_update_datetime = date('Y-m-d H:i:s', strtotime('-5 days')); // arbitrary date $_SESSION['glpi_currenttime'] = $new_update_datetime; @@ -750,20 +772,22 @@ public function testPasswordExpirationDelayUpdate() ); $_SESSION['glpi_currenttime'] = $current_time; $values = \Config::getConfigurationValues('core'); - $this->array($values)->hasKey('password_expiration_delay'); - $this->integer((int)$values['password_expiration_delay'])->isIdenticalTo(45); - $this->integer( + $this->assertArrayHasKey('password_expiration_delay', $values); + $this->assertSame(45, (int)$values['password_expiration_delay']); + $this->assertEquals( + $local_users_count, countElementsInTable( \User::getTable(), ['authtype' => \Auth::DB_GLPI, 'password_last_update' => $update_datetime] // previous config update ) - )->isEqualTo($local_users_count); - $this->integer( + ); + $this->assertEquals( + $external_users_count, countElementsInTable( \User::getTable(), ['NOT' => ['authtype' => \Auth::DB_GLPI], 'password_last_update' => null] ) - )->isEqualTo($external_users_count); + ); } protected function logConfigChangeProvider() @@ -835,7 +859,7 @@ public function testLogConfigChange(string $context, string $name, bool $is_secu unset($value['id']); }; - // History on first value + // History on first value \Config::setConfigurationValues($context, [$name => 'first value']); $expected_history = [ $history_entry_fields + [ @@ -846,9 +870,9 @@ public function testLogConfigChange(string $context, string $name, bool $is_secu $found_history = array_values(getAllDataFromTable(Log::getTable(), $history_crit)); array_walk($found_history, $clean_ids); - $this->array($found_history)->isEqualTo($expected_history); + $this->assertEquals($expected_history, $found_history); - // History on updated value + // History on updated value \Config::setConfigurationValues($context, [$name => 'new value']); $expected_history[] = $history_entry_fields + [ 'old_value' => $old_value_prefix . ($is_secured ? '********' : 'first value'), @@ -857,9 +881,9 @@ public function testLogConfigChange(string $context, string $name, bool $is_secu $found_history = array_values(getAllDataFromTable(Log::getTable(), $history_crit)); array_walk($found_history, $clean_ids); - $this->array($found_history)->isEqualTo($expected_history); + $this->assertEquals($expected_history, $found_history); - // History on config deletion + // History on config deletion \Config::deleteConfigurationValues($context, [$name]); $expected_history[] = $history_entry_fields + [ 'old_value' => $old_value_prefix . ($is_secured ? '********' : 'new value'), @@ -868,7 +892,7 @@ public function testLogConfigChange(string $context, string $name, bool $is_secu $found_history = array_values(getAllDataFromTable(Log::getTable(), $history_crit)); array_walk($found_history, $clean_ids); - $this->array($found_history)->isEqualTo($expected_history); + $this->assertEquals($expected_history, $found_history); } public function testAutoCreateInfocom() @@ -898,7 +922,7 @@ public function testAutoCreateInfocom() $CFG_GLPI['auto_create_infocoms'] = $infocom_auto_create_original; // Verify an Infocom object exists for the newly created asset $infocom_exists = $infocom->getFromDBforDevice($asset_type, $asset_id); - $this->boolean($infocom_exists)->isTrue(); + $this->assertTrue($infocom_exists); $CFG_GLPI['auto_create_infocoms'] = 0; // Verify an Infocom object does not exist for a newly created asset @@ -911,13 +935,14 @@ public function testAutoCreateInfocom() ]); $CFG_GLPI['auto_create_infocoms'] = $infocom_auto_create_original; $infocom_exists = $infocom->getFromDBforDevice($asset_type, $asset_id2); - $this->boolean($infocom_exists)->isFalse(); + $this->assertFalse($infocom_exists); } } public function testDetectRooDoc(): void { global $CFG_GLPI; + $bkp_root_doc = $CFG_GLPI['root_doc']; $uri_to_scriptname = [ '/' => '/index.php', @@ -938,18 +963,21 @@ public function testDetectRooDoc(): void \Config::detectRootDoc(); $_SERVER = $server_bck; - $this->string($CFG_GLPI['root_doc'])->isEqualTo($prefix); + $this->assertEquals($prefix, $CFG_GLPI['root_doc']); } } + + //reset root_doc + $CFG_GLPI['root_doc'] = $bkp_root_doc; } public function testConfigLogNotEmpty() { $itemtype = 'Config'; $config_id = \Config::getConfigIDForContext('core'); - $this->integer($config_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $config_id); $total_number = countElementsInTable("glpi_logs", ['items_id' => $config_id, 'itemtype' => $itemtype]); - $this->integer($total_number)->isGreaterThan(0); + $this->assertGreaterThan(0, $total_number); } /** @@ -972,7 +1000,7 @@ public function testPrepareInputForUpdate(): void $config->prepareInputForUpdate([ 'lock_lockprofile_id' => getItemByTypeName(Profile::class, "Self-Service", true), ]); - $this->integer((int) $CFG_GLPI['lock_lockprofile_id'])->isEqualTo($default_lock_profile); + $this->assertEquals($default_lock_profile, (int) $CFG_GLPI['lock_lockprofile_id']); $this->hasSessionMessages(ERROR, [ "The specified profile doesn't exist or is not allowed to access the central interface." ]); @@ -981,17 +1009,17 @@ public function testPrepareInputForUpdate(): void $config->prepareInputForUpdate([ 'lock_lockprofile_id' => 674568, ]); - $this->integer((int) $CFG_GLPI['lock_lockprofile_id'])->isEqualTo($default_lock_profile); + $this->assertEquals($default_lock_profile, (int) $CFG_GLPI['lock_lockprofile_id']); $this->hasSessionMessages(ERROR, [ "The specified profile doesn't exist or is not allowed to access the central interface." ]); // Valid profile $super_admin = getItemByTypeName(Profile::class, "Super-Admin", true); - $this->integer((int) $CFG_GLPI['lock_lockprofile_id'])->isNotEqualTo($super_admin); + $this->assertNotEquals($super_admin, (int)$CFG_GLPI['lock_lockprofile_id']); $config->prepareInputForUpdate([ 'lock_lockprofile_id' => $super_admin, ]); - $this->integer((int) $CFG_GLPI['lock_lockprofile_id'])->isEqualTo($super_admin); + $this->assertEquals($super_admin, (int) $CFG_GLPI['lock_lockprofile_id']); } } diff --git a/tests/functional/DbUtils.php b/phpunit/functional/DbUtilsTest.php similarity index 54% rename from tests/functional/DbUtils.php rename to phpunit/functional/DbUtilsTest.php index e8af4750ba8..105e38585b8 100644 --- a/tests/functional/DbUtils.php +++ b/phpunit/functional/DbUtilsTest.php @@ -36,24 +36,26 @@ namespace tests\units; use DbTestCase; +use Monolog\Logger; use org\bovigo\vfs\vfsStream; /* Test for inc/dbutils.class.php */ -class DbUtils extends DbTestCase +class DbUtilsTest extends DbTestCase { - public function setUp() + public function setUp(): void { + /** @var array $CFG_GLPI */ global $CFG_GLPI; - // Clean the cache + // Clean the cache unset($CFG_GLPI['glpiitemtypetables']); unset($CFG_GLPI['glpitablesitemtype']); + parent::setUp(); } - protected function dataTableKey() + public static function dataTableKey() { - return [ ['foo', ''], ['glpi_computers', 'computers_id'], @@ -63,7 +65,7 @@ protected function dataTableKey() ]; } - protected function dataTableForeignKey() + public static function dataTableForeignKey() { return [ @@ -78,14 +80,11 @@ protected function dataTableForeignKey() **/ public function testGetForeignKeyFieldForTable($table, $key) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getForeignKeyFieldForTable($table)) - ->isIdenticalTo($key); + $instance = new \DbUtils(); + $this->assertSame($key, $instance->getForeignKeyFieldForTable($table)); - //keep testing old method from db.function - $this->string(getForeignKeyFieldForTable($table))->isIdenticalTo($key); + //keep testing old method from db.function + $this->assertSame($key, getForeignKeyFieldForTable($table)); } /** @@ -93,62 +92,55 @@ public function testGetForeignKeyFieldForTable($table, $key) **/ public function testIsForeignKeyFieldBase($table, $key) { - $this - ->if($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->isForeignKeyField($key))->isTrue(); + $instance = new \DbUtils(); + $this->assertTrue($instance->isForeignKeyField($key)); - //keep testing old method from db.function - $this->boolean(isForeignKeyField($key))->isTrue(); + //keep testing old method from db.function + $this->assertTrue(isForeignKeyField($key)); } public function testIsForeignKeyFieldMore() { - $this - ->if($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->isForeignKeyField('FakeId'))->isFalse() - ->boolean($this->testedInstance->isForeignKeyField('id_Another_Fake_Id'))->isFalse() - ->boolean($this->testedInstance->isForeignKeyField('users_id_tech'))->isTrue() - ->boolean($this->testedInstance->isForeignKeyField('_id'))->isFalse(); - - //keep testing old method from db.function - $this->boolean(isForeignKeyField('FakeId'))->isFalse(); - $this->boolean(isForeignKeyField('id_Another_Fake_Id'))->isFalse(); - $this->boolean(isForeignKeyField('users_id_tech'))->isTrue(); - $this->boolean(isForeignKeyField('_id'))->isFalse(); - $this->boolean(isForeignKeyField(''))->isFalse(); - $this->boolean(isForeignKeyField(null))->isFalse(); - $this->boolean(isForeignKeyField(false))->isFalse(); - $this->boolean(isForeignKeyField(42))->isFalse(); + $instance = new \DbUtils(); + $this->assertFalse($instance->isForeignKeyField('FakeId')); + $this->assertFalse($instance->isForeignKeyField('id_Another_Fake_Id')); + $this->assertTrue($instance->isForeignKeyField('users_id_tech')); + $this->assertFalse($instance->isForeignKeyField('_id')); + + //keep testing old method from db.function + $this->assertFalse(isForeignKeyField('FakeId')); + $this->assertFalse(isForeignKeyField('id_Another_Fake_Id')); + $this->assertTrue(isForeignKeyField('users_id_tech')); + $this->assertFalse(isForeignKeyField('_id')); + $this->assertFalse(isForeignKeyField('')); + $this->assertFalse(isForeignKeyField(null)); + $this->assertFalse(isForeignKeyField(false)); + $this->assertFalse(isForeignKeyField(42)); } - /** * @dataProvider dataTableForeignKey **/ public function testGetTableNameForForeignKeyField($table, $key) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getTableNameForForeignKeyField($key))->isIdenticalTo($table); + $instance = new \DbUtils(); + $this->assertSame($table, $instance->getTableNameForForeignKeyField($key)); - //keep testing old method from db.function - $this->string(getTableNameForForeignKeyField($key))->isIdenticalTo($table); + //keep testing old method from db.function + $this->assertSame($table, getTableNameForForeignKeyField($key)); } - protected function dataTableType() + public static function dataTableType() { - // Pseudo plugin class for test - require_once __DIR__ . '/../fixtures/another_test.php'; - require_once __DIR__ . '/../fixtures/pluginbarabstractstuff.php'; - require_once __DIR__ . '/../fixtures/pluginbarfoo.php'; - require_once __DIR__ . '/../fixtures/pluginfoobar.php'; - require_once __DIR__ . '/../fixtures/pluginfooservice.php'; - require_once __DIR__ . '/../fixtures/pluginfoo_search_item_filter.php'; - require_once __DIR__ . '/../fixtures/pluginfoo_search_a_b_c_d_e_f_g_bar.php'; - require_once __DIR__ . '/../fixtures/test_a_b.php'; + // 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'; return [ ['glpi_dbmysqls', 'DBmysql', false], // not a CommonGLPI, should not be valid @@ -174,13 +166,11 @@ protected function dataTableType() **/ public function testGetTableForItemType($table, $type, $is_valid_type) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getTableForItemType($type))->isIdenticalTo($table); + $instance = new \DbUtils(); + $this->assertSame($table, $instance->getTableForItemType($type)); - //keep testing old method from db.function - $this->string(getTableForItemType($type))->isIdenticalTo($table); + //keep testing old method from db.function + $this->assertSame($table, getTableForItemType($type)); } /** @@ -188,29 +178,24 @@ public function testGetTableForItemType($table, $type, $is_valid_type) **/ public function testGetItemTypeForTable($table, $type, $is_valid_type) { + $instance = new \DbUtils(); if ($is_valid_type) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getItemTypeForTable($table))->isIdenticalTo($type); + $this->assertSame($type, $instance->getItemTypeForTable($table)); } else { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getItemTypeForTable($table))->isIdenticalTo('UNKNOWN'); + $this->assertSame('UNKNOWN', $instance->getItemTypeForTable($table)); } - //keep testing old method from db.function + //keep testing old method from db.function if ($is_valid_type) { - $this->string(getItemTypeForTable($table))->isIdenticalTo($type); + $this->assertSame($type, getItemTypeForTable($table)); } else { - $this->string(getItemTypeForTable($table))->isIdenticalTo('UNKNOWN'); + $this->assertSame('UNKNOWN', getItemTypeForTable($table)); } } - protected function getItemForItemtypeProvider(): iterable + public static function getItemForItemtypeProvider(): iterable { - foreach ($this->dataTableType() as $test_case) { + foreach (self::dataTableType() as $test_case) { yield [ 'itemtype' => $test_case['1'], 'is_valid' => $test_case['2'], @@ -231,67 +216,70 @@ protected function getItemForItemtypeProvider(): iterable **/ public function testGetItemForItemtype($itemtype, $is_valid, $expected_class) { + $instance = new \DbUtils(); if ($is_valid) { - $this - ->if($this->newTestedInstance) - ->then - ->object($this->testedInstance->getItemForItemtype($itemtype))->isInstanceOf($expected_class); + $this->assertInstanceOf($expected_class, $instance->getItemForItemtype($itemtype)); } else { - $this - ->if($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->getItemForItemtype($itemtype))->isFalse(); + $this->assertFalse($instance->getItemForItemtype($itemtype)); } //keep testing old method from db.function if ($is_valid) { - $this->object(getItemForItemtype($itemtype))->isInstanceOf($expected_class); + $this->assertInstanceOf($expected_class, getItemForItemtype($itemtype)); } else { - $this->boolean(getItemForItemtype($itemtype))->isFalse(); + $this->assertFalse(getItemForItemtype($itemtype)); } } public function testGetItemForItemtypeSanitized() { - require_once __DIR__ . '/../fixtures/pluginbarfoo.php'; - - $this - ->if($this->newTestedInstance) - ->when(function () { - $this->object($this->testedInstance->getItemForItemtype(addslashes('Glpi\Event')))->isInstanceOf('Glpi\Event'); - })->error - ->withType(E_USER_WARNING) - ->withMessage('Unexpected sanitized itemtype "Glpi\\\\Event" encountered.') - ->exists() - ->when(function () { - $this->object($this->testedInstance->getItemForItemtype(addslashes('GlpiPlugin\Bar\Foo')))->isInstanceOf('GlpiPlugin\Bar\Foo'); - })->error - ->withType(E_USER_WARNING) - ->withMessage('Unexpected sanitized itemtype "GlpiPlugin\\\\Bar\\\\Foo" encountered.') - ->exists(); + require_once __DIR__ . '/../../tests/fixtures/pluginbarfoo.php'; + + $instance = new \DbUtils(); + $instance->getItemForItemtype(addslashes('Glpi\Event')); + $this->hasPhpLogRecordThatContains( + 'Unexpected sanitized itemtype "Glpi\\\\Event" encountered.', + Logger::WARNING + ); + } + + public function testGetItemForItemtypeSanitized2() + { + require_once __DIR__ . '/../../tests/fixtures/pluginbarfoo.php'; + + $instance = new \DbUtils(); + $instance->getItemForItemtype(addslashes('GlpiPlugin\Bar\Foo')); + $this->hasPhpLogRecordThatContains( + 'Unexpected sanitized itemtype "GlpiPlugin\\\\Bar\\\\Foo" encountered.', + Logger::WARNING + ); } public function testGetItemForItemtypeAbstract() { - require_once __DIR__ . '/../fixtures/pluginbarabstractstuff.php'; - - $this - ->if($this->newTestedInstance) - ->when(function () { - $this->boolean($this->testedInstance->getItemForItemtype('CommonDevice'))->isFalse(); - })->error - ->withType(E_USER_WARNING) - ->withMessage('Cannot instanciate "CommonDevice" as it is an abstract class.') - ->exists() - ->when(function () { - $this->boolean($this->testedInstance->getItemForItemtype('GlpiPlugin\Bar\AbstractStuff'))->isFalse(); - })->error - ->withType(E_USER_WARNING) - ->withMessage('Cannot instanciate "GlpiPlugin\Bar\AbstractStuff" as it is an abstract class.') - ->exists(); + require_once __DIR__ . '/../../tests/fixtures/pluginbarabstractstuff.php'; + + $instance = new \DbUtils(); + $instance->getItemForItemtype('CommonDevice'); + $this->hasPhpLogRecordThatContains( + 'Cannot instanciate "CommonDevice" as it is an abstract class.', + Logger::WARNING + ); + } + + public function testGetItemForItemtypeAbstract2() + { + require_once __DIR__ . '/../../tests/fixtures/pluginbarabstractstuff.php'; + + $instance = new \DbUtils(); + $instance->getItemForItemtype('GlpiPlugin\Bar\AbstractStuff'); + $this->hasPhpLogRecordThatContains( + 'Cannot instanciate "GlpiPlugin\Bar\AbstractStuff" as it is an abstract class.', + Logger::WARNING + ); } - public function dataPlural() + public static function dataPlural() { return [ @@ -315,21 +303,27 @@ public function dataPlural() */ public function testGetPlural($singular, $plural) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getPlural($singular))->isIdenticalTo($plural) - ->string( - $this->testedInstance->getPlural( - $this->testedInstance->getPlural( - $singular - ) + $instance = new \DbUtils(); + $this->assertSame($plural, $instance->getPlural($singular)); + $this->assertSame( + $plural, + $instance->getPlural( + $instance->getPlural( + $singular ) - )->isIdenticalTo($plural); + ) + ); - //keep testing old method from db.function - $this->string(getPlural($singular))->isIdenticalTo($plural); - $this->string(getPlural(getPlural($singular)))->isIdenticalTo($plural); + //keep testing old method from db.function + $this->assertSame($plural, getPlural($singular)); + $this->assertSame( + $plural, + getPlural( + getPlural( + $singular + ) + ) + ); } /** @@ -337,80 +331,84 @@ public function testGetPlural($singular, $plural) **/ public function testGetSingular($singular, $plural) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getSingular($plural))->isIdenticalTo($singular) - ->string( - $this->testedInstance->getSingular( - $this->testedInstance->getSingular( - $plural - ) + $instance = new \DbUtils(); + $this->assertSame($singular, $instance->getSingular($plural)); + $this->assertSame( + $singular, + $instance->getSingular( + $instance->getSingular( + $plural ) - )->isIdenticalTo($singular); + ) + ); - //keep testing old method from db.function - $this->string(getSingular($plural))->isIdenticalTo($singular); - $this->string(getSingular(getSingular($plural)))->isIdenticalTo($singular); + //keep testing old method from db.function + $this->assertSame($singular, getSingular($plural)); + $this->assertSame( + $singular, + getSingular( + getSingular( + $plural + ) + ) + ); } public function testCountElementsInTable() { - $this - ->if($this->newTestedInstance) - ->then - ->integer($this->testedInstance->countElementsInTable('glpi_configs'))->isGreaterThan(100) - ->integer($this->testedInstance->countElementsInTable(['glpi_configs', 'glpi_users']))->isGreaterThan(100) - ->integer($this->testedInstance->countElementsInTable('glpi_configs', ['context' => 'core']))->isGreaterThan(100) - ->integer($this->testedInstance->countElementsInTable('glpi_configs', ['context' => 'core', 'name' => 'version']))->isIdenticalTo(1) - ->integer($this->testedInstance->countElementsInTable('glpi_configs', ['context' => 'fakecontext']))->isIdenticalTo(0); - - //keep testing old method from db.function - //the case of using an element that is not a table is not handle in the function : - $this->integer(countElementsInTable('glpi_configs'))->isGreaterThan(100); - $this->integer(countElementsInTable(['glpi_configs', 'glpi_users']))->isGreaterThan(100); - $this->integer(countElementsInTable('glpi_configs', ['context' => 'core', 'name' => 'version']))->isIdenticalTo(1); - $this->integer(countElementsInTable('glpi_configs', ['context' => 'core']))->isGreaterThan(100); - $this->integer(countElementsInTable('glpi_configs', ['context' => 'fakecontext']))->isIdenticalTo(0); + $instance = new \DbUtils(); + $this->assertGreaterThan(100, $instance->countElementsInTable('glpi_configs')); + $this->assertGreaterThan(100, $instance->countElementsInTable(['glpi_configs', 'glpi_users'])); + $this->assertGreaterThan(100, $instance->countElementsInTable('glpi_configs', ['context' => 'core'])); + $this->assertSame(1, $instance->countElementsInTable('glpi_configs', ['context' => 'core', 'name' => 'version'])); + $this->assertSame(0, $instance->countElementsInTable('glpi_configs', ['context' => 'fakecontext'])); + + //keep testing old method from db.function + //the case of using an element that is not a table is not handle in the function : + $this->assertGreaterThan(100, countElementsInTable('glpi_configs')); + $this->assertGreaterThan(100, countElementsInTable(['glpi_configs', 'glpi_users'])); + $this->assertGreaterThan(100, countElementsInTable('glpi_configs', ['context' => 'core'])); + $this->assertSame(1, countElementsInTable('glpi_configs', ['context' => 'core', 'name' => 'version'])); + $this->assertSame(0, countElementsInTable('glpi_configs', ['context' => 'fakecontext'])); } public function testCountDistinctElementsInTable() { - $this - ->if($this->newTestedInstance) - ->then - ->integer($this->testedInstance->countDistinctElementsInTable('glpi_configs', 'id'))->isGreaterThan(0) - ->integer($this->testedInstance->countDistinctElementsInTable('glpi_configs', 'context'))->isGreaterThan(0) - ->integer($this->testedInstance->countDistinctElementsInTable('glpi_tickets', 'entities_id'))->isIdenticalTo(2) - ->integer($this->testedInstance->countDistinctElementsInTable('glpi_crontasks', 'itemtype', ['frequency' => '86400']))->isIdenticalTo(17) - ->integer($this->testedInstance->countDistinctElementsInTable('glpi_crontasks', 'id', ['frequency' => '86400']))->isIdenticalTo(20) - ->integer($this->testedInstance->countDistinctElementsInTable('glpi_configs', 'context', ['name' => 'version']))->isIdenticalTo(1) - ->integer($this->testedInstance->countDistinctElementsInTable('glpi_configs', 'id', ['context' => 'fakecontext']))->isIdenticalTo(0); - - //keep testing old method from db.function - //the case of using an element that is not a table is not handle in the function : - //testCountElementsInTable($table, $condition="") - $this->integer(countDistinctElementsInTable('glpi_configs', 'id'))->isGreaterThan(0); - $this->integer(countDistinctElementsInTable('glpi_configs', 'context'))->isGreaterThan(0); - $this->integer( + $instance = new \DbUtils(); + $this->assertGreaterThan(0, $instance->countDistinctElementsInTable('glpi_configs', 'id')); + $this->assertGreaterThan(0, $instance->countDistinctElementsInTable('glpi_configs', 'context')); + $this->assertSame(2, $instance->countDistinctElementsInTable('glpi_tickets', 'entities_id')); + $this->assertSame(17, $instance->countDistinctElementsInTable('glpi_crontasks', 'itemtype', ['frequency' => '86400'])); + $this->assertSame(20, $instance->countDistinctElementsInTable('glpi_crontasks', 'id', ['frequency' => '86400'])); + $this->assertSame(1, $instance->countDistinctElementsInTable('glpi_configs', 'context', ['name' => 'version'])); + $this->assertSame(0, $instance->countDistinctElementsInTable('glpi_configs', 'id', ['context' => 'fakecontext'])); + + //keep testing old method from db.function + //the case of using an element that is not a table is not handle in the function : + //testCountElementsInTable($table, $condition="") + $this->assertGreaterThan(0, countDistinctElementsInTable('glpi_configs', 'id')); + $this->assertGreaterThan(0, countDistinctElementsInTable('glpi_configs', 'context')); + $this->assertSame( + 1, countDistinctElementsInTable( 'glpi_configs', 'context', ['name' => 'version'] ) - )->isIdenticalTo(1); - $this->integer( + ); + $this->assertSame( + 0, countDistinctElementsInTable( 'glpi_configs', 'id', ['context' => 'fakecontext'] ) - )->isIdenticalTo(0); + ); } - protected function dataCountMyEntities() + public static function dataCountMyEntities() { return [ ['_test_root_entity', true, 'glpi_computers', [], 9], @@ -440,16 +438,14 @@ public function testCountElementsInTableForMyEntities( $this->login(); $this->setEntity($entity, $recursive); - $this - ->if($this->newTestedInstance) - ->then - ->integer($this->testedInstance->countElementsInTableForMyEntities($table, $condition))->isIdenticalTo($count); + $instance = new \DbUtils(); + $this->assertSame($count, $instance->countElementsInTableForMyEntities($table, $condition)); - //keep testing old method from db.function - $this->integer(countElementsInTableForMyEntities($table, $condition))->isIdenticalTo($count); + //keep testing old method from db.function + $this->assertSame($count, countElementsInTableForMyEntities($table, $condition)); } - protected function dataCountEntities() + public static function dataCountEntities() { return [ ['_test_root_entity', 'glpi_computers', [], 4], @@ -474,236 +470,290 @@ public function testCountElementsInTableForEntity( ) { $eid = getItemByTypeName('Entity', $entity, true); - $this - ->if($this->newTestedInstance) - ->then - ->integer($this->testedInstance->countElementsInTableForEntity($table, $eid, $condition))->isIdenticalTo($count); + $instance = new \DbUtils(); + $this->assertSame($count, $instance->countElementsInTableForEntity($table, $eid, $condition)); - //keep testing old method from db.function - $this->integer(countElementsInTableForEntity($table, $eid, $condition))->isIdenticalTo($count); + //keep testing old method from db.function + $this->assertSame($count, countElementsInTableForEntity($table, $eid, $condition)); } public function testGetAllDataFromTable() { - $this - ->if($this->newTestedInstance) - ->then - ->array($data = $this->testedInstance->getAllDataFromTable('glpi_configs')) - ->size->isGreaterThan(100); + $instance = new \DbUtils(); + $data = $instance->getAllDataFromTable('glpi_configs'); + $this->assertGreaterThan(100, count($data)); foreach ($data as $key => $array) { - $this->array($array) - ->variable['id']->isEqualTo($key); + $this->assertSame($key, $array['id']); } - $this - ->if($this->newTestedInstance) - ->then - ->array($this->testedInstance->getAllDataFromTable('glpi_configs', ['context' => 'core', 'name' => 'version']))->hasSize(1) - ->array($data = $this->testedInstance->getAllDataFromTable('glpi_configs', ['ORDER' => 'name']))->isNotEmpty(); + $instance = new \DbUtils(); + $this->assertCount(1, $instance->getAllDataFromTable('glpi_configs', ['context' => 'core', 'name' => 'version'])); + $data = $instance->getAllDataFromTable('glpi_configs', ['ORDER' => 'name']); + $this->assertNotEmpty($data); + $previousArrayName = ""; foreach ($data as $key => $array) { - $this->boolean($previousArrayName <= $previousArrayName = $array['name'])->isTrue(); + $this->assertTrue($previousArrayName <= $previousArrayName = $array['name']); } - //TODO: test with cache === true + //TODO: test with cache === true - //keep testing old method from db.function + //keep testing old method from db.function $data = getAllDataFromTable('glpi_configs'); - $this->array($data) - ->size->isGreaterThan(100); + $this->assertGreaterThan(100, count($data)); foreach ($data as $key => $array) { - $this->array($array) - ->variable['id']->isEqualTo($key); + $this->assertSame($key, $array['id']); } $data = getAllDataFromTable('glpi_configs', ['context' => 'core', 'name' => 'version']); - $this->array($data)->hasSize(1); + $this->assertCount(1, $data); $data = getAllDataFromTable('glpi_configs', ['ORDER' => 'name']); - $this->array($data)->isNotEmpty(); + $this->assertNotEmpty($data); $previousArrayName = ""; foreach ($data as $key => $array) { - $this->boolean($previousArrayName <= $previousArrayName = $array['name'])->isTrue(); + $this->assertTrue($previousArrayName <= $previousArrayName = $array['name']); } } public function testIsIndex() { - $this - ->if($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->isIndex('glpi_configs', 'fakeField'))->isFalse() - ->boolean($this->testedInstance->isIndex('glpi_configs', 'name'))->isTrue() - ->boolean($this->testedInstance->isIndex('glpi_configs', 'value'))->isFalse() - ->boolean($this->testedInstance->isIndex('glpi_users', 'locations_id'))->isTrue() - ->boolean($this->testedInstance->isIndex('glpi_users', 'unicityloginauth'))->isTrue() - ->when(function () { - $this->boolean($this->testedInstance->isIndex('fakeTable', 'id'))->isFalse(); - })->error - ->withType(E_USER_WARNING) - ->exists(); + $instance = new \DbUtils(); + $this->assertFalse($instance->isIndex('glpi_configs', 'fakeField')); + $this->assertTrue($instance->isIndex('glpi_configs', 'name')); + $this->assertFalse($instance->isIndex('glpi_configs', 'value')); + $this->assertTrue($instance->isIndex('glpi_users', 'locations_id')); + $this->assertTrue($instance->isIndex('glpi_users', 'unicityloginauth')); + + $this->assertFalse($instance->isIndex('fakeTable', 'id')); + $this->hasPhpLogRecordThatContains('Table fakeTable does not exists', Logger::WARNING); + } - //keep testing old method from db.function - $this->boolean(isIndex('glpi_configs', 'fakeField'))->isFalse(); - $this->boolean(isIndex('glpi_configs', 'name'))->isTrue(); - $this->boolean(isIndex('glpi_users', 'locations_id'))->isTrue(); - $this->boolean(isIndex('glpi_users', 'unicityloginauth'))->isTrue(); - - $this->when(function () { - $this->boolean(isIndex('fakeTable', 'id'))->isFalse(); - })->error - ->withType(E_USER_WARNING) - ->exists(); + public function testProceduralIsIndex() + { + //keep testing old method from db.function + $this->assertFalse(isIndex('glpi_configs', 'fakeField')); + $this->assertTrue(isIndex('glpi_configs', 'name')); + $this->assertFalse(isIndex('glpi_configs', 'value')); + $this->assertTrue(isIndex('glpi_users', 'locations_id')); + $this->assertTrue(isIndex('glpi_users', 'unicityloginauth')); + + $this->assertFalse(isIndex('fakeTable', 'id')); + $this->hasPhpLogRecordThatContains('Table fakeTable does not exists', Logger::WARNING); } public function testGetEntityRestrict() { $this->login(); - $this->newTestedInstance(); + $instance = new \DbUtils(); - // See all, really all + // See all, really all $_SESSION['glpishowallentities'] = 1; // will be restored by setEntity call - $this->string($this->testedInstance->getEntitiesRestrictRequest('AND', 'glpi_computers'))->isEmpty(); + $this->assertEmpty($instance->getEntitiesRestrictRequest('AND', 'glpi_computers')); $it = new \DBmysqlIterator(null); - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql())->isIdenticalTo('SELECT * FROM `glpi_computers`'); + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria('glpi_computers')); + $this->assertSame('SELECT * FROM `glpi_computers`', $it->getSql()); - //keep testing old method from db.function - $this->string(getEntitiesRestrictRequest('AND', 'glpi_computers'))->isEmpty(); + //keep testing old method from db.function + $this->assertEmpty(getEntitiesRestrictRequest('AND', 'glpi_computers')); $it->execute('glpi_computers', getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql())->isIdenticalTo('SELECT * FROM `glpi_computers`'); + $this->assertSame('SELECT * FROM `glpi_computers`', $it->getSql()); - // See all + // See all $this->setEntity('_test_root_entity', true); - $this->string($this->testedInstance->getEntitiesRestrictRequest('WHERE', 'glpi_computers')) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('1', '2', '3') ) "); - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE `glpi_computers`.`entities_id` IN (\'1\', \'2\', \'3\')'); + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('1', '2', '3') ) ", + $instance->getEntitiesRestrictRequest('WHERE', 'glpi_computers') + ); + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria('glpi_computers')); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE `glpi_computers`.`entities_id` IN (\'1\', \'2\', \'3\')', + $it->getSql() + ); - //keep testing old method from db.function - $this->string(getEntitiesRestrictRequest('WHERE', 'glpi_computers')) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('1', '2', '3') ) "); + //keep testing old method from db.function + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('1', '2', '3') ) ", + getEntitiesRestrictRequest('WHERE', 'glpi_computers') + ); $it->execute('glpi_computers', getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'1\', \'2\', \'3\'))'); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'1\', \'2\', \'3\'))', + $it->getSql() + ); - // Root entity + // Root entity $this->setEntity('_test_root_entity', false); - $this->string($this->testedInstance->getEntitiesRestrictRequest('WHERE', 'glpi_computers')) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('1') ) "); - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE `glpi_computers`.`entities_id` IN (\'1\')'); + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('1') ) ", + $instance->getEntitiesRestrictRequest('WHERE', 'glpi_computers') + ); + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria('glpi_computers')); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE `glpi_computers`.`entities_id` IN (\'1\')', + $it->getSql() + ); - //keep testing old method from db.function - $this->string(getEntitiesRestrictRequest('WHERE', 'glpi_computers')) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('1') ) "); + //keep testing old method from db.function + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('1') ) ", + getEntitiesRestrictRequest('WHERE', 'glpi_computers') + ); $it->execute('glpi_computers', getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'1\'))'); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'1\'))', + $it->getSql() + ); - // Child + // Child $this->setEntity('_test_child_1', false); - $this->string($this->testedInstance->getEntitiesRestrictRequest('WHERE', 'glpi_computers')) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('2') ) "); - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE `glpi_computers`.`entities_id` IN (\'2\')'); + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('2') ) ", + $instance->getEntitiesRestrictRequest('WHERE', 'glpi_computers') + ); + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria('glpi_computers')); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE `glpi_computers`.`entities_id` IN (\'2\')', + $it->getSql() + ); - //keep testing old method from db.function - $this->string(getEntitiesRestrictRequest('WHERE', 'glpi_computers')) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('2') ) "); + //keep testing old method from db.function + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('2') ) ", + getEntitiesRestrictRequest('WHERE', 'glpi_computers') + ); $it->execute('glpi_computers', getEntitiesRestrictCriteria('glpi_computers')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'2\'))'); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'2\'))', + $it->getSql() + ); - // Child without table - $this->string($this->testedInstance->getEntitiesRestrictRequest('WHERE')) - ->isIdenticalTo("WHERE ( `entities_id` IN ('2') ) "); - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria()); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE `entities_id` IN (\'2\')'); + // Child without table + $this->assertSame( + "WHERE ( `entities_id` IN ('2') ) ", + $instance->getEntitiesRestrictRequest('WHERE') + ); + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria()); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE `entities_id` IN (\'2\')', + $it->getSql() + ); - //keep testing old method from db.function - $this->string(getEntitiesRestrictRequest('WHERE')) - ->isIdenticalTo("WHERE ( `entities_id` IN ('2') ) "); + //keep testing old method from db.function + $this->assertSame( + "WHERE ( `entities_id` IN ('2') ) ", + getEntitiesRestrictRequest('WHERE') + ); $it->execute('glpi_computers', getEntitiesRestrictCriteria()); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE (`entities_id` IN (\'2\'))'); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE (`entities_id` IN (\'2\'))', + $it->getSql() + ); - // Child + parent + // Child + parent $this->setEntity('_test_child_2', false); - $this->string($this->testedInstance->getEntitiesRestrictRequest('WHERE', 'glpi_computers', '', '', true)) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('3') OR (`glpi_computers`.`is_recursive`='1' AND `glpi_computers`.`entities_id` IN (0, 1)) ) "); - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria('glpi_computers', '', '', true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\')))'); + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('3') OR (`glpi_computers`.`is_recursive`='1' AND `glpi_computers`.`entities_id` IN (0, 1)) ) ", + $instance->getEntitiesRestrictRequest('WHERE', 'glpi_computers', '', '', true) + ); + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria('glpi_computers', '', '', true)); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\')))', + $it->getSql() + ); - //keep testing old method from db.function - $this->string(getEntitiesRestrictRequest('WHERE', 'glpi_computers', '', '', true)) - ->isIdenticalTo("WHERE ( `glpi_computers`.`entities_id` IN ('3') OR (`glpi_computers`.`is_recursive`='1' AND `glpi_computers`.`entities_id` IN (0, 1)) ) "); + //keep testing old method from db.function + $this->assertSame( + "WHERE ( `glpi_computers`.`entities_id` IN ('3') OR (`glpi_computers`.`is_recursive`='1' AND `glpi_computers`.`entities_id` IN (0, 1)) ) ", + getEntitiesRestrictRequest('WHERE', 'glpi_computers', '', '', true) + ); $it->execute('glpi_computers', getEntitiesRestrictCriteria('glpi_computers', '', '', true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE ((`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\'))))'); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE ((`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\'))))', + $it->getSql() + ); - //Child + parent on glpi_entities - $it->execute('glpi_entities', $this->testedInstance->getEntitiesRestrictCriteria('glpi_entities', '', '', true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_entities` WHERE (`glpi_entities`.`id` IN (\'3\', \'0\', \'1\'))'); + //Child + parent on glpi_entities + $it->execute('glpi_entities', $instance->getEntitiesRestrictCriteria('glpi_entities', '', '', true)); + $this->assertSame( + 'SELECT * FROM `glpi_entities` WHERE (`glpi_entities`.`id` IN (\'3\', \'0\', \'1\'))', + $it->getSql() + ); - //keep testing old method from db.function + //keep testing old method from db.function $it->execute('glpi_entities', getEntitiesRestrictCriteria('glpi_entities', '', '', true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_entities` WHERE ((`glpi_entities`.`id` IN (\'3\', \'0\', \'1\')))'); + $this->assertSame( + 'SELECT * FROM `glpi_entities` WHERE ((`glpi_entities`.`id` IN (\'3\', \'0\', \'1\')))', + $it->getSql() + ); - //Child + parent -- automatic recusrivity detection - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria('glpi_computers', '', '', 'auto')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\')))'); + //Child + parent -- automatic recusrivity detection + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria('glpi_computers', '', '', 'auto')); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE (`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\')))', + $it->getSql() + ); - //keep testing old method from db.function + //keep testing old method from db.function $it->execute('glpi_computers', getEntitiesRestrictCriteria('glpi_computers', '', '', 'auto')); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE ((`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\'))))'); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE ((`glpi_computers`.`entities_id` IN (\'3\') OR (`glpi_computers`.`is_recursive` = \'1\' AND `glpi_computers`.`entities_id` IN (\'0\', \'1\'))))', + $it->getSql() + ); - // Child + parent without table - $this->string($this->testedInstance->getEntitiesRestrictRequest('WHERE', '', '', '', true)) - ->isIdenticalTo("WHERE ( `entities_id` IN ('3') OR (`is_recursive`='1' AND `entities_id` IN (0, 1)) ) "); - $it->execute('glpi_computers', $this->testedInstance->getEntitiesRestrictCriteria('', '', '', true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE (`entities_id` IN (\'3\') OR (`is_recursive` = \'1\' AND `entities_id` IN (\'0\', \'1\')))'); + // Child + parent without table + $this->assertSame( + "WHERE ( `entities_id` IN ('3') OR (`is_recursive`='1' AND `entities_id` IN (0, 1)) ) ", + $instance->getEntitiesRestrictRequest('WHERE', '', '', '', true) + ); + $it->execute('glpi_computers', $instance->getEntitiesRestrictCriteria('', '', '', true)); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE (`entities_id` IN (\'3\') OR (`is_recursive` = \'1\' AND `entities_id` IN (\'0\', \'1\')))', + $it->getSql() + ); - $it->execute('glpi_entities', $this->testedInstance->getEntitiesRestrictCriteria('glpi_entities', '', 3, true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_entities` WHERE (`glpi_entities`.`id` IN (\'3\', \'0\', \'1\'))'); + $it->execute('glpi_entities', $instance->getEntitiesRestrictCriteria('glpi_entities', '', 3, true)); + $this->assertSame( + 'SELECT * FROM `glpi_entities` WHERE (`glpi_entities`.`id` IN (\'3\', \'0\', \'1\'))', + $it->getSql() + ); - $it->execute('glpi_entities', $this->testedInstance->getEntitiesRestrictCriteria('glpi_entities', '', 7, true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_entities` WHERE `glpi_entities`.`id` = \'7\''); + $it->execute('glpi_entities', $instance->getEntitiesRestrictCriteria('glpi_entities', '', 7, true)); + $this->assertSame( + 'SELECT * FROM `glpi_entities` WHERE `glpi_entities`.`id` = \'7\'', + $it->getSql() + ); - //keep testing old method from db.function - $this->string(getEntitiesRestrictRequest('WHERE', '', '', '', true)) - ->isIdenticalTo("WHERE ( `entities_id` IN ('3') OR (`is_recursive`='1' AND `entities_id` IN (0, 1)) ) "); + //keep testing old method from db.function + $this->assertSame( + "WHERE ( `entities_id` IN ('3') OR (`is_recursive`='1' AND `entities_id` IN (0, 1)) ) ", + getEntitiesRestrictRequest('WHERE', '', '', '', true) + ); $it->execute('glpi_computers', getEntitiesRestrictCriteria('', '', '', true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_computers` WHERE ((`entities_id` IN (\'3\') OR (`is_recursive` = \'1\' AND `entities_id` IN (\'0\', \'1\'))))'); + $this->assertSame( + 'SELECT * FROM `glpi_computers` WHERE ((`entities_id` IN (\'3\') OR (`is_recursive` = \'1\' AND `entities_id` IN (\'0\', \'1\'))))', + $it->getSql() + ); $it->execute('glpi_entities', getEntitiesRestrictCriteria('glpi_entities', '', 3, true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_entities` WHERE ((`glpi_entities`.`id` IN (\'3\', \'0\', \'1\')))'); + $this->assertSame( + 'SELECT * FROM `glpi_entities` WHERE ((`glpi_entities`.`id` IN (\'3\', \'0\', \'1\')))', + $it->getSql() + ); $it->execute('glpi_entities', getEntitiesRestrictCriteria('glpi_entities', '', 7, true)); - $this->string($it->getSql()) - ->isIdenticalTo('SELECT * FROM `glpi_entities` WHERE (`glpi_entities`.`id` = \'7\')'); + $this->assertSame( + 'SELECT * FROM `glpi_entities` WHERE (`glpi_entities`.`id` = \'7\')', + $it->getSql() + ); } /** @@ -734,112 +784,112 @@ private function runGetAncestorsOf($cache = false, $hit = false) //test on ent0 $expected = [0 => 0]; if ($cache === true && $hit === false) { - $this->boolean($GLPI_CACHE->has($ckey_ent0))->isFalse(); + $this->assertFalse($GLPI_CACHE->has($ckey_ent0)); } else if ($cache === true && $hit === true) { - $this->array($GLPI_CACHE->get($ckey_ent0))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent0)); } $ancestors = getAncestorsOf('glpi_entities', $ent0); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent0))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent0)); } //test on ent1 $expected = [0 => 0, 1 => $ent0]; if ($cache === true && $hit === false) { - $this->boolean($GLPI_CACHE->has($ckey_ent1))->isFalse(); + $this->assertFalse($GLPI_CACHE->has($ckey_ent1)); } else if ($cache === true && $hit === true) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } $ancestors = getAncestorsOf('glpi_entities', $ent1); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } - //test on ent2 + //test on ent2 $expected = [0 => 0, 1 => $ent0]; if ($cache === true && $hit === false) { - $this->boolean($GLPI_CACHE->has($ckey_ent2))->isFalse(); + $this->assertFalse($GLPI_CACHE->has($ckey_ent2)); } else if ($cache === true && $hit === true) { - $this->array($GLPI_CACHE->get($ckey_ent2))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent2)); } $ancestors = getAncestorsOf('glpi_entities', $ent2); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent2))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent2)); } - //test with new sub entity - //Cache tests: - //Cache is updated on entity creation; so even if we do not expect $hit; we got it. + //test with new sub entity + //Cache tests: + //Cache is updated on entity creation; so even if we do not expect $hit; we got it. $new_id = getItemByTypeName('Entity', 'Sub child entity', true); if (!$new_id) { $entity = new \Entity(); - $new_id = (int)$entity->add([ + $new_id = $entity->add([ 'name' => 'Sub child entity', 'entities_id' => $ent1 ]); - $this->integer($new_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $new_id); } $ckey_new_id = 'ancestors_cache_glpi_entities_' . $new_id; $expected = [0 => 0, $ent0 => $ent0, $ent1 => $ent1]; if ($cache === true) { - $this->array($GLPI_CACHE->get($ckey_new_id))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_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($ckey_new_id))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_new_id)); } - //test with another new sub entity + //test with another new sub entity $new_id2 = getItemByTypeName('Entity', 'Sub child entity 2', true); if (!$new_id2) { $entity = new \Entity(); - $new_id2 = (int)$entity->add([ + $new_id2 = $entity->add([ 'name' => 'Sub child entity 2', 'entities_id' => $ent2 ]); - $this->integer($new_id2)->isGreaterThan(0); + $this->assertGreaterThan(0, $new_id2); } $ckey_new_id2 = 'ancestors_cache_glpi_entities_' . $new_id2; $expected = [0 => 0, $ent0 => $ent0, $ent2 => $ent2]; if ($cache === true) { - $this->array($GLPI_CACHE->get($ckey_new_id2))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_new_id2)); } $ancestors = getAncestorsOf('glpi_entities', $new_id2); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_new_id2))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_new_id2)); } //test on multiple entities $expected = [0 => 0, $ent0 => $ent0, $ent1 => $ent1, $ent2 => $ent2]; $ckey_new_all = 'ancestors_cache_glpi_entities_' . md5($new_id . '|' . $new_id2); if ($cache === true && $hit === false) { - $this->boolean($GLPI_CACHE->has($ckey_new_all))->isFalse(); + $this->assertFalse($GLPI_CACHE->has($ckey_new_all)); } else if ($cache === true && $hit === true) { - $this->array($GLPI_CACHE->get($ckey_new_all))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_new_all)); } $ancestors = getAncestorsOf('glpi_entities', [$new_id, $new_id2]); - $this->array($ancestors)->isIdenticalTo($expected); + $this->assertSame($expected, $ancestors); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_new_all))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_new_all)); } } @@ -851,15 +901,16 @@ public function testGetAncestorsOf() $DB->update('glpi_entities', ['ancestors_cache' => null], [true]); $this->runGetAncestorsOf(); - $this->integer( + $this->assertGreaterThan( + 0, countElementsInTable( 'glpi_entities', [ 'NOT' => ['ancestors_cache' => null] ] ) - )->isGreaterThan(0); - //run a second time: db cache must be set + ); + //run a second time: db cache must be set $this->runGetAncestorsOf(); } @@ -870,13 +921,14 @@ public function testGetAncestorsOfCached() { $this->login(); + /** @var \Psr\SimpleCache\CacheInterface $GLPI_CACHE */ global $GLPI_CACHE; $GLPI_CACHE->clear(); // login produce cache, must be cleared - //run with cache - //first run: no cache hit expected + //run with cache + //first run: no cache hit expected $this->runGetAncestorsOf(true); - //second run: cache hit expected + //second run: cache hit expected $this->runGetAncestorsOf(true, true); } @@ -891,70 +943,71 @@ public function testGetAncestorsOfCached() */ private function runGetSonsOf($cache = false, $hit = false) { + /** @var \Psr\SimpleCache\CacheInterface $GLPI_CACHE */ global $GLPI_CACHE; $ent0 = getItemByTypeName('Entity', '_test_root_entity', true); $ent1 = getItemByTypeName('Entity', '_test_child_1', true); $ent2 = getItemByTypeName('Entity', '_test_child_2', true); - $this->newTestedInstance(); + $instance = new \DbUtils(); - //Cache tests: - //- if $cache === 0; we do not expect anything, - //- if $cache === 1; we expect cache to be empty before call, and populated after - //- if $hit === 1; we expect cache to be populated + //Cache tests: + //- if $cache === 0; we do not expect anything, + //- if $cache === 1; we expect cache to be empty before call, and populated after + //- if $hit === 1; we expect cache to be populated $ckey_ent0 = 'sons_cache_glpi_entities_' . $ent0; $ckey_ent1 = 'sons_cache_glpi_entities_' . $ent1; $ckey_ent2 = 'sons_cache_glpi_entities_' . $ent2; - //test on ent0 + //test on ent0 $expected = [$ent0 => $ent0, $ent1 => $ent1, $ent2 => $ent2]; if ($cache === true && $hit === false) { - $this->boolean($GLPI_CACHE->has($ckey_ent0))->isFalse(); + $this->assertFalse($GLPI_CACHE->has($ckey_ent0)); } else if ($cache === true && $hit === true) { - $this->array($GLPI_CACHE->get($ckey_ent0))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent0)); } - $sons = $this->testedInstance->getSonsOf('glpi_entities', $ent0); - $this->array($sons)->isIdenticalTo($expected); + $sons = $instance->getSonsOf('glpi_entities', $ent0); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent0))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent0)); } - //test on ent1 + //test on ent1 $expected = [$ent1 => $ent1]; if ($cache === true && $hit === false) { - $this->boolean($GLPI_CACHE->has($ckey_ent1))->isFalse(); + $this->assertFalse($GLPI_CACHE->has($ckey_ent1)); } else if ($cache === true && $hit === true) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } - $sons = $this->testedInstance->getSonsOf('glpi_entities', $ent1); - $this->array($sons)->isIdenticalTo($expected); + $sons = $instance->getSonsOf('glpi_entities', $ent1); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } - //test on ent2 + //test on ent2 $expected = [$ent2 => $ent2]; if ($cache === true && $hit === false) { - $this->boolean($GLPI_CACHE->has($ckey_ent2))->isFalse(); + $this->assertFalse($GLPI_CACHE->has($ckey_ent2)); } else if ($cache === true && $hit === true) { - $this->array($GLPI_CACHE->get($ckey_ent2))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent2)); } - $sons = $this->testedInstance->getSonsOf('glpi_entities', $ent2); - $this->array($sons)->isIdenticalTo($expected); + $sons = $instance->getSonsOf('glpi_entities', $ent2); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent2))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent2)); } - //test with new sub entity - //Cache tests: - //Cache is updated on entity creation; so even if we do not expect $hit; we got it. + //test with new sub entity + //Cache tests: + //Cache is updated on entity creation; so even if we do not expect $hit; we got it. $new_id = getItemByTypeName('Entity', 'Sub child entity', true); if (!$new_id) { $entity = new \Entity(); @@ -962,22 +1015,22 @@ private function runGetSonsOf($cache = false, $hit = false) 'name' => 'Sub child entity', 'entities_id' => $ent1 ]); - $this->integer($new_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $new_id); } $expected = [$ent1 => $ent1, $new_id => $new_id]; if ($cache === true) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } - $sons = $this->testedInstance->getSonsOf('glpi_entities', $ent1); - $this->array($sons)->isIdenticalTo($expected); + $sons = $instance->getSonsOf('glpi_entities', $ent1); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } - //test with another new sub entity + //test with another new sub entity $new_id2 = getItemByTypeName('Entity', 'Sub child entity 2', true); if (!$new_id2) { $entity = new \Entity(); @@ -985,51 +1038,53 @@ private function runGetSonsOf($cache = false, $hit = false) 'name' => 'Sub child entity 2', 'entities_id' => $ent1 ]); - $this->integer($new_id2)->isGreaterThan(0); + $this->assertGreaterThan(0, $new_id2); } $expected = [$ent1 => $ent1, $new_id => $new_id, $new_id2 => $new_id2]; if ($cache === true) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } - $sons = $this->testedInstance->getSonsOf('glpi_entities', $ent1); - $this->array($sons)->isIdenticalTo($expected); + $sons = $instance->getSonsOf('glpi_entities', $ent1); + $this->assertSame($expected, $sons); if ($cache === true && $hit === false) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } - //drop sub entity + //drop sub entity $expected = [$ent1 => $ent1, $new_id2 => $new_id2]; - $this->boolean($entity->delete(['id' => $new_id], true))->isTrue(); + $this->assertTrue($entity->delete(['id' => $new_id], true)); if ($cache === true) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } $expected = [$ent1 => $ent1]; - $this->boolean($entity->delete(['id' => $new_id2], true))->isTrue(); + $this->assertTrue($entity->delete(['id' => $new_id2], true)); if ($cache === true) { - $this->array($GLPI_CACHE->get($ckey_ent1))->isIdenticalTo($expected); + $this->assertSame($expected, $GLPI_CACHE->get($ckey_ent1)); } } public function testGetSonsOf() { global $DB; + $instance = new \DbUtils(); $this->login(); - //ensure db cache is unset + //ensure db cache is unset $DB->update('glpi_entities', ['sons_cache' => null], [true]); $this->runGetSonsOf(); - $this->integer( - $this->testedInstance->countElementsInTable( + $this->assertGreaterThan( + 0, + $instance->countElementsInTable( 'glpi_entities', [ 'NOT' => ['sons_cache' => null] ] ) - )->isGreaterThan(0); + ); //run a second time: db cache must be set $this->runGetSonsOf(); } @@ -1041,13 +1096,14 @@ public function testGetSonsOfCached() { $this->login(); + /** @var \Psr\SimpleCache\CacheInterface $GLPI_CACHE */ global $GLPI_CACHE; $GLPI_CACHE->clear(); // login produce cache, must be cleared - //run with cache - //first run: no cache hit expected + //run with cache + //first run: no cache hit expected $this->runGetSonsOf(true); - //second run: cache hit expected + //second run: cache hit expected $this->runGetSonsOf(true, true); } @@ -1056,50 +1112,57 @@ public function testGetSonsOfCached() */ public function testRelationsValidity() { + /** @var \DBmysql $DB */ global $DB; - $this->newTestedInstance(); + $instance = new \DbUtils(); - $mapping = $this->testedInstance->getDbRelations(); + $mapping = $instance->getDbRelations(); // Check that target fields exists in database foreach ($mapping as $source_table => $relations) { - $this->boolean($DB->tableExists($source_table)) - ->isTrue(sprintf('Invalid table "%s" in relation mapping.', $source_table)); + $this->assertTrue( + $DB->tableExists($source_table), + sprintf('Invalid table "%s" in relation mapping.', $source_table) + ); foreach ($relations as $target_table_key => $target_fields) { $target_table = preg_replace('/^_/', '', $target_table_key); - $this->boolean($DB->tableExists($target_table)) - ->isTrue(sprintf('Invalid table "%s" in "%s" mapping.', $target_table, $source_table)); + $this->assertTrue( + $DB->tableExists($target_table), + sprintf('Invalid table "%s" in "%s" mapping.', $target_table, $source_table) + ); - $this->array($target_fields); + $this->assertIsArray($target_fields); $fields_to_check = []; foreach ($target_fields as $target_field) { if (is_array($target_field)) { // Polymorphic relation - $this->array($target_field)->size->isEqualTo(2); // has only `itemtype*` and `items_id*` fields + $this->assertCount(2, $target_field); // has only `itemtype*` and `items_id*` fields if ($target_table === 'glpi_ipaddresses') { - $this->array($target_field)->containsValues(['mainitemtype', 'mainitems_id']); + $this->assertContains('mainitemtype', $target_field); + $this->assertContains('mainitems_id', $target_field); } else { - $this->integer(count(preg_grep('/^itemtype/', $target_field)))->isEqualTo(1); - $this->integer(count(preg_grep('/^items_id/', $target_field)))->isEqualTo(1); + $this->assertSame(1, count(preg_grep('/^itemtype/', $target_field))); + $this->assertSame(1, count(preg_grep('/^items_id/', $target_field))); } $fields_to_check = array_merge($fields_to_check, $target_field); } else { // Ensure polymorphic relations are correctly declared in an array with both fields names. $msg = sprintf('Invalid table field "%s.%s" in "%s" mapping.', $target_table, $target_field, $source_table); - $this->string($target_field) - ->notMatches('/^itemtype/', $msg) - ->notMatches('/^items_id/', $msg); + $this->assertDoesNotMatchRegularExpression('/^itemtype/', $target_field, $msg); + $this->assertDoesNotMatchRegularExpression('/^items_id/', $target_field, $msg); $fields_to_check[] = $target_field; } } foreach ($fields_to_check as $field_to_check) { - $this->boolean($DB->fieldExists($target_table, $field_to_check)) - ->isTrue(sprintf('Invalid table field "%s.%s" in "%s" mapping.', $target_table, $field_to_check, $source_table)); + $this->assertTrue( + $DB->fieldExists($target_table, $field_to_check), + sprintf('Invalid table field "%s.%s" in "%s" mapping.', $target_table, $field_to_check, $source_table) + ); } } } @@ -1272,8 +1335,10 @@ public function testRelationsValidity() . implode(PHP_EOL, $mixed_relations) . PHP_EOL; } - $this->boolean(empty($forbiddenly_prefixed_relations) && empty($missing_relations) && empty($duplicated_relations) && empty($mixed_relations)) - ->isTrue($msg); + $this->assertTrue( + empty($forbiddenly_prefixed_relations) && empty($missing_relations) && empty($duplicated_relations) && empty($mixed_relations), + $msg + ); } /** @@ -1283,67 +1348,70 @@ public function testRelationsValidity() */ public function testGetDateCriteria() { - $this->newTestedInstance(); + $instance = new \DbUtils(); - $this->array( - $this->testedInstance->getDateCriteria('date', null, null) - )->isIdenticalTo([]); + $this->assertSame( + [], + $instance->getDateCriteria('date', null, null) + ); - $this->array( - $this->testedInstance->getDateCriteria('date', '', '') - )->isIdenticalTo([]); + $this->assertSame( + [], + $instance->getDateCriteria('date', '', '') + ); - $this->array( - $this->testedInstance->getDateCriteria('date', '2018-11-09', null) - )->isIdenticalTo([ - ['date' => ['>=', '2018-11-09']] - ]); + $this->assertSame( + [['date' => ['>=', '2018-11-09']]], + $instance->getDateCriteria('date', '2018-11-09', null) + ); - $result = $this->testedInstance->getDateCriteria('date', null, '2018-11-09'); - $this->array($result)->hasSize(1); + $result = $instance->getDateCriteria('date', null, '2018-11-09'); + $this->assertCount(1, $result); - $this->array($result[0]['date']) - ->hasSize(2) - ->string[0]->isIdenticalTo('<=') - ->object[1]->isInstanceOf('\QueryExpression'); + $this->assertCount(2, $result[0]['date']); + $this->assertSame('<=', $result[0]['date'][0]); + $this->assertInstanceOf('\QueryExpression', $result[0]['date'][1]); - $this->string( + $this->assertSame( + "ADDDATE('2018-11-09', INTERVAL 1 DAY)", $result[0]['date'][1]->getValue() - )->isIdenticalTo("ADDDATE('2018-11-09', INTERVAL 1 DAY)"); + ); - $result = $this->testedInstance->getDateCriteria('date', '2018-11-08', '2018-11-09'); - $this->array($result)->hasSize(2); + $result = $instance->getDateCriteria('date', '2018-11-08', '2018-11-09'); + $this->assertCount(2, $result); - $this->array($result[0])->isIdenticalTo(['date' => ['>=', '2018-11-08']]); - $this->array($result[1]['date']) - ->hasSize(2) - ->string[0]->isIdenticalTo('<=') - ->object[1]->isInstanceOf('\QueryExpression'); + $this->assertSame(['date' => ['>=', '2018-11-08']], $result[0]); + $this->assertCount(2, $result[1]['date']); + $this->assertSame('<=', $result[1]['date'][0]); + $this->assertInstanceOf('\QueryExpression', $result[1]['date'][1]); - $this->string( + $this->assertSame( + "ADDDATE('2018-11-09', INTERVAL 1 DAY)", $result[1]['date'][1]->getValue() - )->isIdenticalTo("ADDDATE('2018-11-09', INTERVAL 1 DAY)"); - - $result = null; - $this->when(function () use (&$result) { - $result = $this->testedInstance->getDateCriteria('date', '2023-02-19\', INTERVAL 1 DAY)))))', null); - })->error - ->withType(E_USER_WARNING) - ->withMessage('Invalid "2023-02-19\', INTERVAL 1 DAY)))))" date value.') - ->exists(); - $this->array($result)->isIdenticalTo([]); - - $result = null; - $this->when(function () use (&$result) { - $result = $this->testedInstance->getDateCriteria('date', null, '2021-02-19\', INTERVAL 1 DAY)))))'); - })->error - ->withType(E_USER_WARNING) - ->withMessage('Invalid "2021-02-19\', INTERVAL 1 DAY)))))" date value.') - ->exists(); - $this->array($result)->isIdenticalTo([]); + ); + } + + public function testGetDateCriteriaError1() + { + $instance = new \DbUtils(); + $instance->getDateCriteria('date', '2023-02-19\', INTERVAL 1 DAY)))))', null); + $this->hasPhpLogRecordThatContains( + 'Invalid "2023-02-19\', INTERVAL 1 DAY)))))" date value.', + Logger::WARNING + ); } - protected function autoNameProvider() + public function testGetDateCriteriaError2() + { + $instance = new \DbUtils(); + $instance->getDateCriteria('date', null, '2023-02-19\', INTERVAL 1 DAY)))))'); + $this->hasPhpLogRecordThatContains( + 'Invalid "2023-02-19\', INTERVAL 1 DAY)))))" date value.', + Logger::WARNING + ); + } + + public static function autoNameProvider() { return [ //will return name without changes @@ -1477,10 +1545,10 @@ protected function autoNameProvider() */ public function testAutoName($name, $field, $is_template, $itemtype, $entities_id, $expected, bool $deprecated = false) { - $this->newTestedInstance; + $instance = new \DbUtils(); - $call = function () use ($name, $field, $is_template, $itemtype, $entities_id) { - return $this->testedInstance->autoName( + $call = function () use ($name, $field, $is_template, $itemtype, $entities_id, $instance) { + return $instance->autoName( $name, $field, $is_template, @@ -1491,21 +1559,20 @@ public function testAutoName($name, $field, $is_template, $itemtype, $entities_i if (!$deprecated) { $autoname = $call(); } else { - $autoname = null; - $this->when($autoname = $call()) - ->error() - ->withType(E_USER_DEPRECATED) - ->withMessage('Handling of encoded/escaped value in autoName() is deprecated.') - ->exists(); + $autoname = $call(); + $this->hasPhpLogRecordThatContains( + 'Handling of encoded/escaped value in autoName() is deprecated.', + Logger::NOTICE + ); } - $this->string($autoname)->isIdenticalTo($expected); + $this->assertSame($expected, $autoname); } /** * Data provider for self::testGetItemtypeWithFixedCase(). */ - protected function fixItemtypeCaseProvider() + public static function fixItemtypeCaseProvider() { return [ // Bad case classnames matching and existing class file @@ -1563,9 +1630,6 @@ protected function fixItemtypeCaseProvider() */ public function testGetItemtypeWithFixedCase($itemtype, $expected) { - - $this->newTestedInstance(); - vfsStream::setup( 'glpi', null, @@ -1597,8 +1661,8 @@ public function testGetItemtypeWithFixedCase($itemtype, $expected) ], ] ); - - $result = $this->testedInstance->fixItemtypeCase($itemtype, vfsStream::url('glpi')); - $this->variable($result)->isEqualTo($expected); + $instance = new \DbUtils(); + $result = $instance->fixItemtypeCase($itemtype, vfsStream::url('glpi')); + $this->assertEquals($expected, $result); } } diff --git a/tests/functional/DomainRelation.php b/phpunit/functional/DomainRelation.php similarity index 79% rename from tests/functional/DomainRelation.php rename to phpunit/functional/DomainRelation.php index a9cc11e9173..313f80321b3 100644 --- a/tests/functional/DomainRelation.php +++ b/phpunit/functional/DomainRelation.php @@ -44,15 +44,18 @@ public function testDeleteProtectedRelations() $this->login(); $relation = new \DomainRelation(); - $this->integer($unprotected_id = $relation->add([ - 'name' => __FUNCTION__ - ]))->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $unprotected_id = $relation->add([ + 'name' => __FUNCTION__ + ]) + ); // Should not be able to delete the domain relations added to GLPI by default - $this->boolean($relation->delete(['id' => \DomainRelation::BELONGS]))->isFalse(); - $this->boolean($relation->delete(['id' => \DomainRelation::MANAGE]))->isFalse(); + $this->assertFalse($relation->delete(['id' => \DomainRelation::BELONGS])); + $this->assertFalse($relation->delete(['id' => \DomainRelation::MANAGE])); // Should be able to delete the domain relation added by the test - $this->boolean($relation->delete(['id' => $unprotected_id]))->isTrue(); + $this->assertTrue($relation->delete(['id' => $unprotected_id])); } } diff --git a/tests/functional/Domain.php b/phpunit/functional/DomainTest.php similarity index 71% rename from tests/functional/Domain.php rename to phpunit/functional/DomainTest.php index 508c07de462..2e4d83604ca 100644 --- a/tests/functional/Domain.php +++ b/phpunit/functional/DomainTest.php @@ -39,13 +39,13 @@ /* Test for inc/software.class.php */ -class Domain extends DbTestCase +class DomainTest extends DbTestCase { public function testTypeName() { - $this->string(\Domain::getTypeName(1))->isIdenticalTo('Domain'); - $this->string(\Domain::getTypeName(0))->isIdenticalTo('Domains'); - $this->string(\Domain::getTypeName(10))->isIdenticalTo('Domains'); + $this->assertSame('Domain', \Domain::getTypeName(1)); + $this->assertSame('Domains', \Domain::getTypeName(0)); + $this->assertSame('Domains', \Domain::getTypeName(10)); } public function testPrepareInput() @@ -53,9 +53,9 @@ public function testPrepareInput() $domain = new \Domain(); $expected = ['date_creation' => 'NULL', 'date_expiration' => null]; $result = $domain->prepareInputForUpdate(['date_creation' => '', 'date_expiration' => null]); - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); $result = $domain->prepareInputForAdd(['date_creation' => '', 'date_expiration' => null]); - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } public function testCleanDBonPurge() @@ -66,33 +66,35 @@ public function testCleanDBonPurge() $domains_id = (int)$domain->add([ 'name' => 'glpi-project.org' ]); - $this->integer($domains_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $domains_id); $domain_item = new \Domain_Item(); - $this->integer( + $this->assertGreaterThan( + 0, $domain_item->add([ 'domains_id' => $domains_id, 'itemtype' => 'Computer', 'items_id' => getItemByTypeName('Computer', '_test_pc01', true) ]) - )->isGreaterThan(0); + ); $record = new \DomainRecord(); foreach (['www', 'ftp', 'mail'] as $sub) { - $this->integer( - (int)$record->add([ + $this->assertGreaterThan( + 0, + $record->add([ 'name' => $sub, 'data' => 'glpi-project.org.', 'domains_id' => $domains_id ]) - )->isGreaterThan(0); + ); } - $this->integer((int)countElementsInTable($domain_item->getTable(), ['domains_id' => $domains_id]))->isIdenticalTo(1); - $this->integer((int)countElementsInTable($record->getTable(), ['domains_id' => $domains_id]))->isIdenticalTo(3); - $this->boolean($domain->delete(['id' => $domains_id], true))->isTrue(); - $this->integer((int)countElementsInTable($domain_item->getTable(), ['domains_id' => $domains_id]))->isIdenticalTo(0); - $this->integer((int)countElementsInTable($record->getTable(), ['domains_id' => $domains_id]))->isIdenticalTo(0); + $this->assertSame(1, countElementsInTable($domain_item->getTable(), ['domains_id' => $domains_id])); + $this->assertSame(3, countElementsInTable($record->getTable(), ['domains_id' => $domains_id])); + $this->assertTrue($domain->delete(['id' => $domains_id], true)); + $this->assertSame(0, countElementsInTable($domain_item->getTable(), ['domains_id' => $domains_id])); + $this->assertSame(0, countElementsInTable($record->getTable(), ['domains_id' => $domains_id])); } public function testGetEntitiesToNotify() @@ -100,37 +102,42 @@ public function testGetEntitiesToNotify() global $DB; $this->login(); - $this->array(\Entity::getEntitiesToNotify('use_domains_alert'))->isEmpty(); + $this->assertEmpty(\Entity::getEntitiesToNotify('use_domains_alert')); $entity = getItemByTypeName('Entity', '_test_root_entity'); - $this->boolean( + $this->assertTrue( $entity->update([ 'id' => $entity->fields['id'], 'use_domains_alert' => 1, 'send_domains_alert_close_expiries_delay' => 7, 'send_domains_alert_expired_delay' => 1 ]) - )->isTrue(); - $this->boolean($entity->getFromDB($entity->fields['id']))->isTrue(); + ); + $this->assertTrue($entity->getFromDB($entity->fields['id'])); - $this->array(\Entity::getEntitiesToNotify('use_domains_alert'))->isIdenticalTo([ - getItemByTypeName('Entity', '_test_root_entity', true) => 1, - getItemByTypeName('Entity', '_test_child_1', true) => 1, - getItemByTypeName('Entity', '_test_child_2', true) => 1, - ]); + $this->assertSame( + [ + getItemByTypeName('Entity', '_test_root_entity', true) => 1, + getItemByTypeName('Entity', '_test_child_1', true) => 1, + getItemByTypeName('Entity', '_test_child_2', true) => 1, + ], + \Entity::getEntitiesToNotify('use_domains_alert') + ); $iterator = $DB->request(\Domain::expiredDomainsCriteria($entity->fields['id'])); - $this->string($iterator->getSql())->isIdenticalTo( + $this->assertSame( "SELECT * FROM `glpi_domains` WHERE " . "NOT (`date_expiration` IS NULL) AND `entities_id` = '{$entity->fields['id']}' AND `is_deleted` = '0' " . - "AND DATEDIFF(CURDATE(), `date_expiration`) > 1 AND DATEDIFF(CURDATE(), `date_expiration`) > 0" + "AND DATEDIFF(CURDATE(), `date_expiration`) > 1 AND DATEDIFF(CURDATE(), `date_expiration`) > 0", + $iterator->getSql() ); $iterator = $DB->request(\Domain::closeExpiriesDomainsCriteria($entity->fields['id'])); - $this->string($iterator->getSql())->isIdenticalTo( + $this->assertSame( "SELECT * FROM `glpi_domains` WHERE " . "NOT (`date_expiration` IS NULL) AND `entities_id` = '{$entity->fields['id']}' AND `is_deleted` = '0' " . - "AND DATEDIFF(CURDATE(), `date_expiration`) > -7 AND DATEDIFF(CURDATE(), `date_expiration`) < 0" + "AND DATEDIFF(CURDATE(), `date_expiration`) > -7 AND DATEDIFF(CURDATE(), `date_expiration`) < 0", + $iterator->getSql() ); } @@ -141,26 +148,28 @@ public function testTransfer() $domains_id = (int)$domain->add([ 'name' => 'glpi-project.org' ]); - $this->integer($domains_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $domains_id); $record = new \DomainRecord(); foreach (['www', 'ftp', 'mail'] as $sub) { - $this->integer( - (int)$record->add([ + $this->assertGreaterThan( + 0, + $record->add([ 'name' => $sub, 'data' => 'glpi-project.org.', 'domains_id' => $domains_id ]) - )->isGreaterThan(0); + ); } $entities_id = getItemByTypeName('Entity', '_test_child_2', true); - //transer to another entity + //transfer to another entity $transfer = new \Transfer(); - $this->mockGenerator->orphanize('__construct'); - $ma = new \mock\MassiveAction([], [], 'process'); + $ma = $this->getMockBuilder(\MassiveAction::class) + ->disableOriginalConstructor() + ->getMock(); \MassiveAction::processMassiveActionsForOneItemtype( $ma, @@ -170,8 +179,8 @@ public function testTransfer() $transfer->moveItems(['Domain' => [$domains_id]], $entities_id, [$domains_id]); unset($_SESSION['glpitransfer_list']); - $this->boolean($domain->getFromDB($domains_id))->isTrue(); - $this->integer((int)$domain->fields['entities_id'])->isidenticalTo($entities_id); + $this->assertTrue($domain->getFromDB($domains_id)); + $this->assertSame($entities_id, (int)$domain->fields['entities_id']); global $DB; $records = $DB->request([ @@ -179,7 +188,7 @@ public function testTransfer() 'WHERE' => ['domains_id' => $domains_id] ]); foreach ($records as $row) { - $this->integer((int)$row['entities_id'])->isidenticalTo($entities_id); + $this->assertSame($entities_id, (int)$row['entities_id']); } } @@ -202,35 +211,35 @@ public function testCronDomainsAlert() 'entities_id' => $entities_id, 'date_expiration' => date('Y-m-d', time() - MONTH_TIMESTAMP), // expired for a long time (> 7 days) ]); - $this->integer($domain_1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $domain_1_id); $domain_2_id = $domain->add([ 'name' => $this->getUniqueString(), 'entities_id' => $entities_id, 'date_expiration' => date('Y-m-d', time() - DAY_TIMESTAMP), // expired recently (< 7 days) ]); - $this->integer($domain_2_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $domain_2_id); $domain_3_id = $domain->add([ 'name' => $this->getUniqueString(), 'entities_id' => $entities_id, 'date_expiration' => date('Y-m-d', time() + DAY_TIMESTAMP), // will expire soon (< 7 days) ]); - $this->integer($domain_3_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $domain_3_id); $domain_4_id = $domain->add([ 'name' => $this->getUniqueString(), 'entities_id' => $entities_id, 'date_expiration' => date('Y-m-d', time() + MONTH_TIMESTAMP), // will expire in a long time (> 7 days) ]); - $this->integer($domain_4_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $domain_4_id); $domain_5_id = $domain->add([ 'name' => $this->getUniqueString(), 'entities_id' => $entities_id, 'date_expiration' => null, // does not expire ]); - $this->integer($domain_5_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $domain_5_id); // Set root entity config domains alerts $entity = new \Entity(); @@ -240,12 +249,12 @@ public function testCronDomainsAlert() 'send_domains_alert_close_expiries_delay' => 7, // alert on domains that will expire in less than 7 days 'send_domains_alert_expired_delay' => 7, // alert on domains expired since, at least, 7 days ]); - $this->boolean($updated)->isTrue(); + $this->assertTrue($updated); $result = $domain->cronDomainsAlert($crontask); - $this->integer($result)->isEqualTo(1); // 1 = fully processed + $this->assertEquals(1, $result); // 1 = fully processed - $this->integer(countElementsInTable(\Alert::getTable()))->isEqualTo(2); + $this->assertEquals(2, countElementsInTable(\Alert::getTable())); $expired_alerts = $alert->find( [ @@ -255,13 +264,14 @@ public function testCronDomainsAlert() ); $expired_alert = reset($expired_alerts); unset($expired_alert['id']); - $this->array($expired_alert)->isEqualTo( + $this->assertEquals( [ 'date' => $_SESSION["glpi_currenttime"], 'itemtype' => 'Domain', 'items_id' => $domain_1_id, 'type' => \Alert::END, - ] + ], + $expired_alert ); $expiring_alerts = $alert->find( @@ -273,16 +283,17 @@ public function testCronDomainsAlert() $expiring_alert = reset($expiring_alerts); unset($expiring_alert['id']); - $this->array($expiring_alert)->isEqualTo( + $this->assertEquals( [ 'date' => $_SESSION["glpi_currenttime"], 'itemtype' => 'Domain', 'items_id' => $domain_3_id, 'type' => \Alert::NOTICE, - ] + ], + $expiring_alert ); $result = $domain->cronDomainsAlert($crontask); - $this->integer($result)->isEqualTo(0); // 0 = nothing to do (alerts were already sent) + $this->assertEquals(0, $result); // 0 = nothing to do (alerts were already sent) } } diff --git a/tests/functional/Glpi/Agent/Communication/Headers/Common.php b/phpunit/functional/Glpi/Agent/Communication/Headers/Common.php similarity index 73% rename from tests/functional/Glpi/Agent/Communication/Headers/Common.php rename to phpunit/functional/Glpi/Agent/Communication/Headers/Common.php index f180792f3c1..2b15823fe12 100644 --- a/tests/functional/Glpi/Agent/Communication/Headers/Common.php +++ b/phpunit/functional/Glpi/Agent/Communication/Headers/Common.php @@ -41,7 +41,7 @@ class Common extends GLPITestCase { - protected function namesProvider(): array + public static function namesProvider(): array { return [ [ @@ -68,11 +68,11 @@ protected function namesProvider(): array */ public function testHeaders($propname, $headername) { - $this - ->if($this->newTestedInstance) - ->then - ->string($this->testedInstance->getHeaderName($propname)) - ->isIdenticalTo($headername); + $instance = new \Glpi\Agent\Communication\Headers\Common(); + $this->assertSame( + $headername, + $instance->getHeaderName($propname) + ); } /* Useful only when legacy will no longer be the default */ @@ -90,38 +90,36 @@ function() { public function testGetHeaders() { - $instance = $this->newTestedInstance; + $instance = new \Glpi\Agent\Communication\Headers\Common(); $instance->setHeader('Content-Type', 'application/xml'); $instance->setHeader('GLPI-Agent-ID', 'anything'); - $this->array($instance->getHeaders()) - ->hasKeys(['Content-Type', 'Pragma', 'GLPI-Agent-ID']); + $headers = $instance->getHeaders(); + $this->assertArrayHasKey('Content-Type', $headers); + $this->assertArrayHasKey('Pragma', $headers); + $this->assertArrayHasKey('GLPI-Agent-ID', $headers); - $instance = $this->newTestedInstance; + $instance = new \Glpi\Agent\Communication\Headers\Common(); $instance->setHeaders([ 'Content-Type' => 'application/xml', 'GLPI-Agent-ID' => 'anything' ]); - $this->array($instance->getHeaders()) - ->hasKeys(['Content-Type', 'Pragma', 'GLPI-Agent-ID']); + $headers = $instance->getHeaders(); + $this->assertArrayHasKey('Content-Type', $headers); + $this->assertArrayHasKey('Pragma', $headers); + $this->assertArrayHasKey('GLPI-Agent-ID', $headers); } public function testGetRequireds() { - $this - ->if($this->newTestedInstance) - ->then - ->array($this->testedInstance->getRequireds()) - ->hasSize(5); + $instance = new \Glpi\Agent\Communication\Headers\Common(); + $this->assertCount(5, $instance->getRequireds()); } public function testGetHeadersNames() { - $this - ->if($this->newTestedInstance) - ->then - ->array($this->testedInstance->getHeadersNames()) - ->hasSize(1); + $instance = new \Glpi\Agent\Communication\Headers\Common(); + $this->assertCount(1, $instance->getHeadersNames()); } } diff --git a/phpunit/functional/Glpi/Inventory/Assets/ComputerTest.php b/phpunit/functional/Glpi/Inventory/Assets/ComputerTest.php index 39705e5e397..004908f7a83 100644 --- a/phpunit/functional/Glpi/Inventory/Assets/ComputerTest.php +++ b/phpunit/functional/Glpi/Inventory/Assets/ComputerTest.php @@ -1011,7 +1011,7 @@ public function testTransferWithLockedField() //test entities_id $this->assertSame(0, $computer->fields['entities_id']); - //transer to another entity + //transfer to another entity $doTransfer = \Entity::getUsedConfig('transfers_strategy', $computer->fields['entities_id'], 'transfers_id', 0); $transfer = new \Transfer(); $transfer->getFromDB($doTransfer); @@ -1061,7 +1061,7 @@ public function testTransferWithoutLockedField() //test entities_id $this->assertSame(0, $computer->fields['entities_id']); - //transer to another entity + //transfer to another entity $doTransfer = \Entity::getUsedConfig('transfers_strategy', $computer->fields['entities_id'], 'transfers_id', 0); $transfer = new \Transfer(); $transfer->getFromDB($doTransfer); diff --git a/tests/functional/Html.php b/phpunit/functional/HtmlTest.php similarity index 66% rename from tests/functional/Html.php rename to phpunit/functional/HtmlTest.php index 73c6a1602e8..7dbc5910e43 100644 --- a/tests/functional/Html.php +++ b/phpunit/functional/HtmlTest.php @@ -41,77 +41,77 @@ /* Test for inc/html.class.php */ -class Html extends \GLPITestCase +class HtmlTest extends \GLPITestCase { public function testConvDate() { - $this->variable(\Html::convDate(null))->isNull(); - $this->variable(\Html::convDate('NULL'))->isNull(); - $this->variable(\Html::convDate(''))->isNull(); - $this->variable(\Html::convDate('0000-00-00'))->isNull(); - $this->variable(\Html::convDate('0000-00-00 00:00:00'))->isNull(); + $this->assertNull(\Html::convDate(null)); + $this->assertNull(\Html::convDate('NULL')); + $this->assertNull(\Html::convDate('')); + $this->assertNull(\Html::convDate('0000-00-00')); + $this->assertNull(\Html::convDate('0000-00-00 00:00:00')); $mydate = date('Y-m-d H:i:s'); $expected = date('Y-m-d'); unset($_SESSION['glpidate_format']); - $this->string(\Html::convDate($mydate))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDate($mydate)); $_SESSION['glpidate_format'] = 0; - $this->string(\Html::convDate($mydate))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDate($mydate)); - $this->string(\Html::convDate(date('Y-m-d')))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDate(date('Y-m-d'))); $expected = date('d-m-Y'); - $this->string(\Html::convDate($mydate, 1))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDate($mydate, 1)); $expected = date('m-d-Y'); - $this->string(\Html::convDate($mydate, 2))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDate($mydate, 2)); $expected_error = 'Failed to parse time string (not a date) at position 0 (n): The timezone could not be found in the database'; - $this->string(\Html::convDate('not a date', 2))->isIdenticalTo('not a date'); + $this->assertSame('not a date', \Html::convDate('not a date', 2)); $this->hasPhpLogRecordThatContains($expected_error, LogLevel::CRITICAL); } public function testConvDateTime() { - $this->variable(\Html::convDateTime(null))->isNull(); - $this->variable(\Html::convDateTime('NULL'))->isNull; + $this->assertNull(\Html::convDateTime(null)); + $this->assertNull(\Html::convDateTime('NULL')); $timestamp = time(); $mydate = date('Y-m-d H:i:s', $timestamp); $expected = date('Y-m-d H:i', $timestamp); - $this->string(\Html::convDateTime($mydate))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDateTime($mydate)); $expected = date('Y-m-d H:i:s', $timestamp); - $this->string(\Html::convDateTime($mydate, null, true))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDateTime($mydate, null, true)); $expected = date('d-m-Y H:i', $timestamp); - $this->string(\Html::convDateTime($mydate, 1))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDateTime($mydate, 1)); $expected = date('d-m-Y H:i:s', $timestamp); - $this->string(\Html::convDateTime($mydate, 1, true))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDateTime($mydate, 1, true)); $expected = date('m-d-Y H:i', $timestamp); - $this->string(\Html::convDateTime($mydate, 2))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDateTime($mydate, 2)); $expected = date('m-d-Y H:i:s', $timestamp); - $this->string(\Html::convDateTime($mydate, 2, true))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::convDateTime($mydate, 2, true)); } public function testCleanInputText() { $origin = 'This is a \'string\' with some "replacements" needed, but not « others »!'; $expected = 'This is a 'string' with some "replacements" needed, but not « others »!'; - $this->string(\Html::cleanInputText($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::cleanInputText($origin)); } public function cleanParametersURL() { $url = 'http://host/glpi/path/to/file.php?var1=2&var2=3'; $expected = 'http://host/glpi/path/to/file.php'; - $this->string(\Html::cleanParametersURL($url))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::cleanParametersURL($url)); } public function testResume_text() @@ -122,18 +122,18 @@ public function testResume_text() $expected = 'This is a very long string which will be truncated by a dedicated method. ' . 'If the string is not truncated, well... We\'re wrong and got a very serious issue in our codebase!' . 'And if the string has been correctly truncated, well... All is ok then, let\'s show i (...)'; - $this->string(\Html::resume_text($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::resume_text($origin)); $origin = 'A string that is longer than 10 characters.'; $expected = 'A string t (...)'; - $this->string(\Html::resume_text($origin, 10))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::resume_text($origin, 10)); } public function testCleanPostForTextArea() { $origin = "A text that \\\"would\\\" be entered in a \\'textarea\\'\\nWith breakline\\r\\nand breaklines."; $expected = "A text that \"would\" be entered in a 'textarea'\nWith breakline\nand breaklines."; - $this->string(\Html::cleanPostForTextArea($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::cleanPostForTextArea($origin)); $aorigin = [ $origin, @@ -143,7 +143,7 @@ public function testCleanPostForTextArea() $expected, "Another\none!" ]; - $this->array(\Html::cleanPostForTextArea($aorigin))->isIdenticalTo($aexpected); + $this->assertSame($aexpected, \Html::cleanPostForTextArea($aorigin)); } public function testFormatNumber() @@ -151,109 +151,109 @@ public function testFormatNumber() $_SESSION['glpinumber_format'] = 0; $origin = ''; $expected = '0.00'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $origin = '1207.3'; $expected = '1 207.30'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $expected = '1207.30'; - $this->string(\Html::formatNumber($origin, true))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin, true)); $origin = 124556.693; $expected = '124 556.69'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $origin = 120.123456789; $expected = '120.12'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $expected = '120.12346'; - $this->string(\Html::formatNumber($origin, false, 5))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin, false, 5)); $expected = '120'; - $this->string(\Html::formatNumber($origin, false, 0))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin, false, 0)); $origin = 120.999; $expected = '121.00'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $expected = '121'; - $this->string(\Html::formatNumber($origin, false, 0))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin, false, 0)); - $this->string(\Html::formatNumber('-'))->isIdenticalTo('-'); + $this->assertSame('-', \Html::formatNumber('-')); $_SESSION['glpinumber_format'] = 2; $origin = '1207.3'; $expected = '1 207,30'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $_SESSION['glpinumber_format'] = 3; $origin = '1207.3'; $expected = '1207.30'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $_SESSION['glpinumber_format'] = 4; $origin = '1207.3'; $expected = '1207,30'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); $_SESSION['glpinumber_format'] = 1337; $origin = '1207.3'; $expected = '1,207.30'; - $this->string(\Html::formatNumber($origin))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::formatNumber($origin)); } public function testTimestampToString() { $expected = '0 seconds'; - $this->string(\Html::timestampToString(null))->isIdenticalTo($expected); - $this->string(\Html::timestampToString(''))->isIdenticalTo($expected); - $this->string(\Html::timestampToString(0))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString(null)); + $this->assertSame($expected, \Html::timestampToString('')); + $this->assertSame($expected, \Html::timestampToString(0)); $tstamp = 57226; $expected = '15 hours 53 minutes 46 seconds'; - $this->string(\Html::timestampToString($tstamp))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp)); $tstamp = -57226; $expected = '- 15 hours 53 minutes 46 seconds'; - $this->string(\Html::timestampToString($tstamp))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp)); $tstamp = 1337; $expected = '22 minutes 17 seconds'; - $this->string(\Html::timestampToString($tstamp))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp)); $expected = '22 minutes'; - $this->string(\Html::timestampToString($tstamp, false))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp, false)); $tstamp = 54; $expected = '54 seconds'; - $this->string(\Html::timestampToString($tstamp))->isIdenticalTo($expected); - $this->string(\Html::timestampToString($tstamp, false))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp)); + $this->assertSame($expected, \Html::timestampToString($tstamp, false)); $tstamp = 157226; $expected = '1 days 19 hours 40 minutes 26 seconds'; - $this->string(\Html::timestampToString($tstamp))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp)); $expected = '1 days 19 hours 40 minutes'; - $this->string(\Html::timestampToString($tstamp, false))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp, false)); $expected = '43 hours 40 minutes 26 seconds'; - $this->string(\Html::timestampToString($tstamp, true, false))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp, true, false)); $expected = '43 hours 40 minutes'; - $this->string(\Html::timestampToString($tstamp, false, false))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::timestampToString($tstamp, false, false)); } public function testGetMenuInfos() { $menu = \Html::getMenuInfos(); - $this->integer(count($menu))->isIdenticalTo(8); + $this->assertSame(8, count($menu)); $expected = [ 'assets', @@ -265,9 +265,7 @@ public function testGetMenuInfos() 'config', 'preference' ]; - $this->array($menu) - ->hasSize(count($expected)) - ->hasKeys($expected); + $this->assertSame($expected, array_keys($menu)); $expected = [ 'Computer', @@ -287,8 +285,8 @@ public function testGetMenuInfos() 'Cable', 'Item_DeviceSimcard' ]; - $this->string($menu['assets']['title'])->isIdenticalTo('Assets'); - $this->array($menu['assets']['types'])->isIdenticalTo($expected); + $this->assertSame('Assets', $menu['assets']['title']); + $this->assertSame($expected, $menu['assets']['types']); $expected = [ 'Ticket', @@ -299,8 +297,8 @@ public function testGetMenuInfos() 'TicketRecurrent', 'RecurrentChange', ]; - $this->string($menu['helpdesk']['title'])->isIdenticalTo('Assistance'); - $this->array($menu['helpdesk']['types'])->isIdenticalTo($expected); + $this->assertSame('Assistance', $menu['helpdesk']['title']); + $this->assertSame($expected, $menu['helpdesk']['types']); $expected = [ 'SoftwareLicense', @@ -317,8 +315,8 @@ public function testGetMenuInfos() 'Appliance', 'Database' ]; - $this->string($menu['management']['title'])->isIdenticalTo('Management'); - $this->array($menu['management']['types'])->isIdenticalTo($expected); + $this->assertSame('Management', $menu['management']['title']); + $this->assertSame($expected, $menu['management']['types']); $expected = [ 'Project', @@ -331,12 +329,12 @@ public function testGetMenuInfos() 'SavedSearch', 'Impact' ]; - $this->string($menu['tools']['title'])->isIdenticalTo('Tools'); - $this->array($menu['tools']['types'])->isIdenticalTo($expected); + $this->assertSame('Tools', $menu['tools']['title']); + $this->assertSame($expected, $menu['tools']['types']); $expected = []; - $this->string($menu['plugins']['title'])->isIdenticalTo('Plugins'); - $this->array($menu['plugins']['types'])->isIdenticalTo($expected); + $this->assertSame('Plugins', $menu['plugins']['title']); + $this->assertSame($expected, $menu['plugins']['types']); $expected = [ 'User', @@ -348,8 +346,8 @@ public function testGetMenuInfos() 'Glpi\\Event', 'Glpi\Inventory\Inventory' ]; - $this->string($menu['admin']['title'])->isIdenticalTo('Administration'); - $this->array($menu['admin']['types'])->isIdenticalTo($expected); + $this->assertSame('Administration', $menu['admin']['title']); + $this->assertSame($expected, $menu['admin']['types']); $expected = [ 'CommonDropdown', @@ -364,25 +362,23 @@ public function testGetMenuInfos() 'Link', 'Plugin' ]; - $this->string($menu['config']['title'])->isIdenticalTo('Setup'); - $this->array($menu['config']['types'])->isIdenticalTo($expected); + $this->assertSame('Setup', $menu['config']['title']); + $this->assertSame($expected, $menu['config']['types']); - $this->string($menu['preference']['title'])->isIdenticalTo('My settings'); - $this->array($menu['preference'])->notHasKey('types'); - $this->string($menu['preference']['default'])->isIdenticalTo('/front/preference.php'); + $this->assertSame('My settings', $menu['preference']['title']); + $this->assertArrayNotHasKey('types', $menu['preference']); + $this->assertSame('/front/preference.php', $menu['preference']['default']); } public function testGetCopyrightMessage() { $message = \Html::getCopyrightMessage(); - $this->string($message) - ->contains(GLPI_VERSION) - ->contains(GLPI_YEAR); + $this->assertStringContainsString(GLPI_VERSION, $message); + $this->assertStringContainsString(GLPI_YEAR, $message); $message = \Html::getCopyrightMessage(false); - $this->string($message) - ->notContains(GLPI_VERSION) - ->contains(GLPI_YEAR); + $this->assertStringNotContainsString(GLPI_VERSION, $message); + $this->assertStringContainsString(GLPI_YEAR, $message); } public function testCss() @@ -404,7 +400,7 @@ public function testCss() //create test files foreach ($fake_files as $fake_file) { - $this->boolean(touch(GLPI_TMP_DIR . '/' . $fake_file))->isTrue(); + $this->assertTrue(touch(GLPI_TMP_DIR . '/' . $fake_file)); } //expect minified file @@ -413,7 +409,7 @@ public function testCss() ['file.min.css', $base_attrs], $base_expected ); - $this->string(\Html::css($dir . '/file.css'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/file.css')); //explicitely require not minified file $expected = str_replace( @@ -421,7 +417,7 @@ public function testCss() ['file.css', $base_attrs], $base_expected ); - $this->string(\Html::css($dir . '/file.css', [], false))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/file.css', [], false)); //activate debug mode: expect not minified file $_SESSION['glpi_use_mode'] = \Session::DEBUG_MODE; @@ -430,7 +426,7 @@ public function testCss() ['file.css', $base_attrs], $base_expected ); - $this->string(\Html::css($dir . '/file.css'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/file.css')); $_SESSION['glpi_use_mode'] = \Session::NORMAL_MODE; //expect original file @@ -439,7 +435,7 @@ public function testCss() ['nofile.css', $base_attrs], $base_expected ); - $this->string(\Html::css($dir . '/nofile.css'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/nofile.css')); //expect original file $expected = str_replace( @@ -447,7 +443,7 @@ public function testCss() ['other.css', $base_attrs], $base_expected ); - $this->string(\Html::css($dir . '/other.css'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/other.css')); //expect original file $expected = str_replace( @@ -455,7 +451,7 @@ public function testCss() ['other-min.css', $base_attrs], $base_expected ); - $this->string(\Html::css($dir . '/other-min.css'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/other-min.css')); //expect minified file, print media $expected = str_replace( @@ -463,7 +459,7 @@ public function testCss() ['file.min.css', 'media="print"'], $base_expected ); - $this->string(\Html::css($dir . '/file.css', ['media' => 'print']))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/file.css', ['media' => 'print'])); //expect minified file, screen media $expected = str_replace( @@ -471,7 +467,7 @@ public function testCss() ['file.min.css', $base_attrs], $base_expected ); - $this->string(\Html::css($dir . '/file.css', ['media' => '']))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/file.css', ['media' => ''])); //expect minified file and specific version $fake_version = '0.0.1'; @@ -480,7 +476,7 @@ public function testCss() ['file.min.css', $base_attrs, FrontEnd::getVersionCacheKey($fake_version)], $base_expected ); - $this->string(\Html::css($dir . '/file.css', ['version' => $fake_version]))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/file.css', ['version' => $fake_version])); //expect minified file with added attributes $expected = str_replace( @@ -488,7 +484,7 @@ public function testCss() ['file.min.css', 'attribute="one" ' . $base_attrs], $base_expected ); - $this->string($expected, \Html::css($dir . '/file.css', ['attribute' => 'one']))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::css($dir . '/file.css', ['attribute' => 'one'])); //remove test files foreach ($fake_files as $fake_file) { @@ -523,7 +519,7 @@ public function testScript() 'file.min.js', $base_expected ); - $this->string(\Html::script($dir . '/file.js'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::script($dir . '/file.js')); //explicitely require not minified file $expected = str_replace( @@ -531,7 +527,7 @@ public function testScript() 'file.js', $base_expected ); - $this->string(\Html::script($dir . '/file.js', [], false))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::script($dir . '/file.js', [], false)); //activate debug mode: expect not minified file $_SESSION['glpi_use_mode'] = \Session::DEBUG_MODE; @@ -540,7 +536,7 @@ public function testScript() 'file.js', $base_expected ); - $this->string($expected, \Html::script($dir . '/file.js'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::script($dir . '/file.js')); $_SESSION['glpi_use_mode'] = \Session::NORMAL_MODE; //expect original file @@ -549,7 +545,7 @@ public function testScript() 'nofile.js', $base_expected ); - $this->string(\Html::script($dir . '/nofile.js'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::script($dir . '/nofile.js')); //expect original file $expected = str_replace( @@ -557,7 +553,7 @@ public function testScript() 'other.js', $base_expected ); - $this->string(\Html::script($dir . '/other.js'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::script($dir . '/other.js')); //expect original file $expected = str_replace( @@ -565,7 +561,7 @@ public function testScript() 'other-min.js', $base_expected ); - $this->string(\Html::script($dir . '/other-min.js'))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::script($dir . '/other-min.js')); //expect minified file and specific version $fake_version = '0.0.1'; @@ -574,7 +570,7 @@ public function testScript() ['file.min.js', FrontEnd::getVersionCacheKey($fake_version)], $base_expected ); - $this->string(\Html::script($dir . '/file.js', ['version' => $fake_version]))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::script($dir . '/file.js', ['version' => $fake_version])); //remove test files foreach ($fake_files as $fake_file) { @@ -595,69 +591,56 @@ public function testManageRefreshPage() $expected = ''; $message = \Html::manageRefreshPage(); - $this->string($message)->isIdenticalTo($expected); + $this->assertSame($expected, $message); //Set session refresh to one minute $_SESSION['glpirefresh_views'] = 1; $expected = str_replace("##CALLBACK##", "window.location.reload()", $base_script); $expected = str_replace("##TIMER##", 1 * MINUTE_TIMESTAMP * 1000, $expected); $message = \Html::manageRefreshPage(); - $this->string($message)->isIdenticalTo($expected); + $this->assertSame($expected, $message); $expected = str_replace("##CALLBACK##", '$(\'#mydiv\').remove();', $base_script); $expected = str_replace("##TIMER##", 1 * MINUTE_TIMESTAMP * 1000, $expected); $message = \Html::manageRefreshPage(false, '$(\'#mydiv\').remove();'); - $this->string($message)->isIdenticalTo($expected); + $this->assertSame($expected, $message); $expected = str_replace("##CALLBACK##", "window.location.reload()", $base_script); $expected = str_replace("##TIMER##", 3 * MINUTE_TIMESTAMP * 1000, $expected); $message = \Html::manageRefreshPage(3); - $this->string($message)->isIdenticalTo($expected); + $this->assertSame($expected, $message); $expected = str_replace("##CALLBACK##", '$(\'#mydiv\').remove();', $base_script); $expected = str_replace("##TIMER##", 3 * MINUTE_TIMESTAMP * 1000, $expected); $message = \Html::manageRefreshPage(3, '$(\'#mydiv\').remove();'); - $this->string($message)->isIdenticalTo($expected); + $this->assertSame($expected, $message); } public function testGenerateMenuSession() { //login to get session $auth = new \Auth(); - $this->boolean($auth->login(TU_USER, TU_PASS, true))->isTrue(); + $this->assertTrue($auth->login(TU_USER, TU_PASS, true)); $menu = \Html::generateMenuSession(true); - $this->array($_SESSION) - ->hasKey('glpimenu'); + $this->assertArrayHasKey('glpimenu', $_SESSION); - $this->array($menu) - ->isIdenticalTo($_SESSION['glpimenu']) - ->hasKey('assets') - ->hasKey('helpdesk') - ->hasKey('management') - ->hasKey('tools') - ->hasKey('plugins') - ->hasKey('admin') - ->hasKey('config') - ->hasKey('preference'); + $this->assertSame($menu, $_SESSION['glpimenu']); foreach ($menu as $menu_entry) { - $this->array($menu_entry) - ->hasKey('title'); + $this->assertArrayHasKey('title', $menu_entry); if (isset($menu_entry['content'])) { - $this->array($menu_entry) - ->hasKey('types'); + $this->assertArrayHasKey('types', $menu_entry); foreach ($menu_entry['content'] as $submenu_label => $submenu) { if ($submenu_label === 'is_multi_entries') { continue; } - $this->array($submenu) - ->hasKey('title') - ->hasKey('page'); + $this->assertArrayHasKey('title', $submenu); + $this->assertArrayHasKey('page', $submenu); } } } @@ -665,32 +648,26 @@ public function testGenerateMenuSession() public function testFuzzySearch() { - //login to get session + //login to get session $auth = new \Auth(); - $this->boolean($auth->login(TU_USER, TU_PASS, true))->isTrue(); + $this->assertTrue($auth->login(TU_USER, TU_PASS, true)); - // init menu + // init menu \Html::generateMenuSession(true); - // test modal + // test modal $modal = \Html::FuzzySearch('getHtml'); - $this->string($modal) - ->contains('id="fuzzysearch"') - ->matches('/class="results[^"]*"/'); + $this->assertStringContainsString('id="fuzzysearch"', $modal); + $this->assertMatchesRegularExpression('/class="results[^"]*"/', $modal); // test retrieving entries $default = json_decode(\Html::FuzzySearch(), true); $entries = json_decode(\Html::FuzzySearch('getList'), true); - $this->array($default) - ->isNotEmpty() - ->isIdenticalTo($entries) - ->hasKey(0) - ->size->isGreaterThan(5); + $this->assertSame($default, $entries); foreach ($default as $entry) { - $this->array($entry) - ->hasKey('title') - ->hasKey('url'); + $this->assertArrayHasKey('title', $entry); + $this->assertArrayHasKey('url', $entry); } } @@ -699,19 +676,19 @@ public function testEntitiesDeep() $value = 'Should be \' "escaped" éè!'; $expected = 'Should be ' "escaped" éè!'; $result = \Html::entities_deep($value); - $this->string($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); $result = \Html::entities_deep([$value, $value, $value]); - $this->array($result)->isIdenticalTo([$expected, $expected, $expected]); + $this->assertSame([$expected, $expected, $expected], $result); } public function testCleanParametersURL() { $url = 'http://perdu.com'; - $this->string(\Html::cleanParametersURL($url))->isIdenticalTo($url); + $this->assertSame($url, \Html::cleanParametersURL($url)); $purl = $url . '?with=some&args=none'; - $this->string(\Html::cleanParametersURL($url))->isIdenticalTo($url); + $this->assertSame($url, \Html::cleanParametersURL($purl)); } public function testDisplayMessageAfterRedirect() @@ -721,31 +698,35 @@ public function testDisplayMessageAfterRedirect() WARNING => ['Oooops, I did it again!'] ]; - $this->output( - function () { - \Html::displayMessageAfterRedirect(); - } - ) - ->matches('/class="[^"]*bg-danger[^"]*".*Error.*Something went really wrong :\(/s') - ->matches('/class="[^"]*bg-warning[^"]*".*Warning.*Oooops, I did it again!/s'); + ob_start(); + \Html::displayMessageAfterRedirect(); + $output = ob_get_clean(); + + $this->assertMatchesRegularExpression( + '/class="[^"]*bg-danger[^"]*".*Error.*Something went really wrong :\(/s', + $output + ); + + $this->assertMatchesRegularExpression( + '/class="[^"]*bg-warning[^"]*".*Warning.*Oooops, I did it again!/s', + $output + ); - $this->array($_SESSION['MESSAGE_AFTER_REDIRECT'])->isEmpty(); + $this->assertEmpty($_SESSION['MESSAGE_AFTER_REDIRECT']); } public function testDisplayBackLink() { - $this->output( - function () { - \Html::displayBackLink(); - } - )->isIdenticalTo("Back"); + ob_start(); + \Html::displayBackLink(); + $output = ob_get_clean(); + $this->assertSame("Back", $output); $_SERVER['HTTP_REFERER'] = 'originalpage.html'; - $this->output( - function () { - \Html::displayBackLink(); - } - )->isIdenticalTo("Back"); + ob_start(); + \Html::displayBackLink(); + $output = ob_get_clean(); + $this->assertSame("Back", $output); $_SERVER['HTTP_REFERER'] = ''; // reset referer to prevent having this var in test loop mode } @@ -753,52 +734,52 @@ public function testAddConfirmationOnAction() { $string = 'Are U\' OK?'; $expected = 'onclick="if (window.confirm(\'Are U\\\' OK?\')){ ;return true;} else { return false;}"'; - $this->string(\Html::addConfirmationOnAction($string))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::addConfirmationOnAction($string)); $strings = ['Are you', 'OK?']; $expected = 'onclick="if (window.confirm(\'Are you\nOK?\')){ ;return true;} else { return false;}"'; - $this->string(\Html::addConfirmationOnAction($strings))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::addConfirmationOnAction($strings)); $actions = '$("#mydiv").focus();'; $expected = 'onclick="if (window.confirm(\'Are U\\\' OK?\')){ $("#mydiv").focus();return true;} else { return false;}"'; - $this->string(\Html::addConfirmationOnAction($string, $actions))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::addConfirmationOnAction($string, $actions)); } public function testJsFunctions() { - $this->string(\Html::jsHide('myid'))->isIdenticalTo("$('#myid').hide();\n"); - $this->string(\Html::jsShow('myid'))->isIdenticalTo("$('#myid').show();\n"); - $this->string(\Html::jsGetElementbyID('myid'))->isIdenticalTo("$('#myid')"); - $this->string(\Html::jsSetDropdownValue('myid', 'myval'))->isIdenticalTo("$('#myid').trigger('setValue', 'myval');"); - $this->string(\Html::jsGetDropdownValue('myid'))->isIdenticalTo("$('#myid').val()"); + $this->assertSame("$('#myid').hide();\n", \Html::jsHide('myid')); + $this->assertSame("$('#myid').show();\n", \Html::jsShow('myid')); + $this->assertSame("$('#myid')", \Html::jsGetElementbyID('myid')); + $this->assertSame("$('#myid').trigger('setValue', 'myval');", \Html::jsSetDropdownValue('myid', 'myval')); + $this->assertSame("$('#myid').val()", \Html::jsGetDropdownValue('myid')); } public function testCleanId() { $id = 'myid'; - $this->string(\Html::cleanId($id))->isIdenticalTo($id); + $this->assertSame($id, \Html::cleanId($id)); $id = 'array[]'; $expected = 'array__'; - $this->string(\Html::cleanId($id))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::cleanId($id)); } public function testImage() { $path = '/path/to/image.png'; $expected = ''; - $this->string(\Html::image($path))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::image($path)); $options = [ 'title' => 'My title', 'alt' => 'no img text' ]; $expected = 'no img text'; - $this->string(\Html::image($path, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::image($path, $options)); $options = ['url' => 'mypage.php']; $expected = ''; - $this->string(\Html::image($path, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::image($path, $options)); } public function testLink() @@ -807,28 +788,28 @@ public function testLink() $url = 'mylink.php'; $expected = 'My link'; - $this->string(\Html::link($text, $url))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::link($text, $url)); $options = [ 'confirm' => 'U sure?' ]; $expected = 'My link'; - $this->string(\Html::link($text, $url, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::link($text, $url, $options)); $options['confirmaction'] = 'window.close();'; $expected = 'My link'; - $this->string(\Html::link($text, $url, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::link($text, $url, $options)); } public function testHidden() { $name = 'hiddenfield'; $expected = ''; - $this->string(\Html::hidden($name))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::hidden($name)); $options = ['value' => 'myval']; $expected = ''; - $this->string(\Html::hidden($name, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::hidden($name, $options)); $options = [ 'value' => [ @@ -837,7 +818,7 @@ public function testHidden() ] ]; $expected = "\n\n"; - $this->string(\Html::hidden($name, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::hidden($name, $options)); $options = [ 'value' => [ @@ -846,14 +827,14 @@ public function testHidden() ] ]; $expected = "\n\n"; - $this->string(\Html::hidden($name, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::hidden($name, $options)); } public function testInput() { $name = 'in_put'; $expected = ''; - $this->string(\Html::input($name))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::input($name)); $options = [ 'value' => 'myval', @@ -861,7 +842,7 @@ public function testInput() 'data-id' => 12 ]; $expected = ''; - $this->string(\Html::input($name, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::input($name, $options)); $options = [ 'type' => 'number', @@ -869,10 +850,10 @@ public function testInput() 'value' => 'myval', ]; $expected = ''; - $this->string(\Html::input($name, $options))->isIdenticalTo($expected); + $this->assertSame($expected, \Html::input($name, $options)); } - public function providerGetBackUrl() + public static function providerGetBackUrl() { return [ [ @@ -903,7 +884,7 @@ public function providerGetBackUrl() */ public function testGetBackUrl($url_in, $url_out) { - $this->string(\Html::getBackUrl($url_in))->isIdenticalTo($url_out); + $this->assertSame($url_out, \Html::getBackUrl($url_in)); } public function testGetScssFileHash() @@ -951,13 +932,17 @@ public function testGetScssFileHash() 'imports/colors.scss' => md5_file(vfsStream::url('glpi/css/imports/colors.scss')), ]; - // Composite scss file hash corresponds to self md5 suffixed by all imported scss md5 - $this->string(\Html::getScssFileHash(vfsStream::url('glpi/css/all.scss'))) - ->isEqualTo($files_md5['all.scss'] . $files_md5['imports/borders.scss'] . $files_md5['imports/colors.scss']); + // Composite scss file hash corresponds to self md5 suffixed by all imported scss md5 + $this->assertEquals( + $files_md5['all.scss'] . $files_md5['imports/borders.scss'] . $files_md5['imports/colors.scss'], + \Html::getScssFileHash(vfsStream::url('glpi/css/all.scss')) + ); - // Simple scss file hash corresponds to self md5 - $this->string(\Html::getScssFileHash(vfsStream::url('glpi/css/another.scss'))) - ->isEqualTo($files_md5['another.scss']); + // Simple scss file hash corresponds to self md5 + $this->assertEquals( + $files_md5['another.scss'], + \Html::getScssFileHash(vfsStream::url('glpi/css/another.scss')) + ); } @@ -1052,12 +1037,12 @@ public function testGetGenericDateTimeSearchItems( $values = \Html::getGenericDateTimeSearchItems($options); foreach ($check_values as $key => $value) { - $this->array($values)->hasKey($key); - $this->string($values[$key])->isEqualTo($value); + $this->assertArrayHasKey($key, $values); + $this->assertEquals($value, $values[$key]); } foreach ($unwanted as $key) { - $this->array($values)->notHasKey($key); + $this->assertArrayNotHasKey($key, $values); } } } diff --git a/tests/functional/Location.php b/phpunit/functional/LocationTest.php similarity index 60% rename from tests/functional/Location.php rename to phpunit/functional/LocationTest.php index 6928f22fc9d..cf943a99450 100644 --- a/tests/functional/Location.php +++ b/phpunit/functional/LocationTest.php @@ -41,7 +41,7 @@ /* Test for inc/location.class.php */ -class Location extends DbTestCase +class LocationTest extends DbTestCase { public function testInheritGeolocation() { @@ -52,16 +52,16 @@ public function testInheritGeolocation() 'longitude' => '2.3522', 'altitude' => '115' ]); - $this->integer((int) $location1_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $location1_id); $location2 = new \Location(); $location2_id = $location2->add([ 'locations_id' => $location1_id, 'name' => 'inherit_geo_test_child', ]); - $this->integer((int) $location2_id)->isGreaterThan(0); - $this->string($location2->fields['latitude'])->isEqualTo($location1->fields['latitude']); - $this->string($location2->fields['longitude'])->isEqualTo($location1->fields['longitude']); - $this->string($location2->fields['altitude'])->isEqualTo($location1->fields['altitude']); + $this->assertGreaterThan(0, (int) $location2_id); + $this->assertEquals($location1->fields['latitude'], $location2->fields['latitude']); + $this->assertEquals($location1->fields['longitude'], $location2->fields['longitude']); + $this->assertEquals($location1->fields['altitude'], $location2->fields['altitude']); // Make sure we don't overwrite data a user sets $location3 = new \Location(); @@ -72,32 +72,32 @@ public function testInheritGeolocation() 'longitude' => '2.1734', 'altitude' => '39' ]); - $this->integer((int) $location3_id)->isGreaterThan(0); - $this->string($location3->fields['latitude'])->isEqualTo('41.3851'); - $this->string($location3->fields['longitude'])->isEqualTo('2.1734'); - $this->string($location3->fields['altitude'])->isEqualTo('39'); + $this->assertGreaterThan(0, (int) $location3_id); + $this->assertEquals('41.3851', $location3->fields['latitude']); + $this->assertEquals('2.1734', $location3->fields['longitude']); + $this->assertEquals('39', $location3->fields['altitude']); } public function testImportExternal() { $locations_id = \Dropdown::importExternal('Location', 'testImportExternal_1', getItemByTypeName('Entity', '_test_root_entity', true)); - $this->integer((int) $locations_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $locations_id); // Verify that the location was created $location = new \Location(); $location->getFromDB($locations_id); - $this->string($location->fields['name'])->isEqualTo('testImportExternal_1'); + $this->assertEquals('testImportExternal_1', $location->fields['name']); // Try importing a location as a child of the location we just created $locations_id_2 = \Dropdown::importExternal('Location', 'testImportExternal_2', getItemByTypeName('Entity', '_test_root_entity', true), [ 'locations_id' => $locations_id ]); - $this->integer((int) $locations_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $locations_id_2); // Verify that the location was created $location = new \Location(); $location->getFromDB($locations_id_2); - $this->string($location->fields['name'])->isEqualTo('testImportExternal_2'); + $this->assertEquals('testImportExternal_2', $location->fields['name']); // Verify that the location is a child of the location we just created - $this->integer($location->fields['locations_id'])->isEqualTo($locations_id); + $this->assertEquals($locations_id, $location->fields['locations_id']); } public function testFindIDByName() @@ -110,7 +110,7 @@ public function testFindIDByName() 'name' => 'testFindIDByName_1', 'entities_id' => $entities_id, ]); - $this->integer((int) $location_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $location_id); // Find the location by name $params = [ @@ -118,7 +118,7 @@ public function testFindIDByName() 'entities_id' => $entities_id, ]; $found_location_id = $location->findID($params); - $this->integer((int) $found_location_id)->isEqualTo($location_id); + $this->assertEquals($location_id, (int) $found_location_id); // Add child location $location_id_2 = $location->add([ @@ -126,7 +126,7 @@ public function testFindIDByName() 'name' => 'testFindIDByName_2', 'entities_id' => $entities_id, ]); - $this->integer((int) $location_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $location_id_2); // Find the location by name (and locations_id) $params = [ @@ -135,7 +135,7 @@ public function testFindIDByName() 'entities_id' => $entities_id, ]; $found_location_id = $location->findID($params); - $this->integer((int) $found_location_id)->isEqualTo($location_id_2); + $this->assertEquals($location_id_2, (int) $found_location_id); // Verify finding ID with just name won't work for child location $params = [ @@ -143,7 +143,7 @@ public function testFindIDByName() 'entities_id' => $entities_id, ]; $found_location_id = $location->findID($params); - $this->integer((int) $found_location_id)->isEqualTo(-1); + $this->assertEquals(-1, (int) $found_location_id); } public function testFindIDByCompleteName() @@ -156,7 +156,7 @@ public function testFindIDByCompleteName() 'name' => 'testFindIDByCompleteName_1', 'entities_id' => $entities_id, ]); - $this->integer((int) $location_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $location_id); // Find the location by completename $params = [ @@ -164,7 +164,7 @@ public function testFindIDByCompleteName() 'entities_id' => $entities_id, ]; $found_location_id = $location->findID($params); - $this->integer((int) $found_location_id)->isEqualTo($location_id); + $this->assertEquals($location_id, (int) $found_location_id); // Create a child location $location_id_2 = $location->add([ @@ -172,7 +172,7 @@ public function testFindIDByCompleteName() 'name' => 'testFindIDByCompleteName_2', 'entities_id' => $entities_id, ]); - $this->integer((int) $location_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $location_id_2); // Find the location by completename $params = [ @@ -180,7 +180,7 @@ public function testFindIDByCompleteName() 'entities_id' => $entities_id, ]; $found_location_id = $location->findID($params); - $this->integer((int) $found_location_id)->isEqualTo($location_id_2); + $this->assertEquals($location_id_2, (int) $found_location_id); } public function testUnicity() @@ -189,17 +189,17 @@ public function testUnicity() $location1_id = $location1->add([ 'name' => 'Unique location', ]); - $this->integer($location1_id)->isGreaterThan(0); - $this->boolean($location1->getFromDB($location1_id))->isTrue(); - $this->string($location1->fields['completename'])->isEqualTo('Unique location'); + $this->assertGreaterThan(0, $location1_id); + $this->assertTrue($location1->getFromDB($location1_id)); + $this->assertEquals('Unique location', $location1->fields['completename']); $location2 = new \Location(); $location2_id = $location2->add([ 'name' => 'Non unique location', ]); - $this->integer($location2_id)->isGreaterThan(0); - $this->boolean($location2->getFromDB($location2_id))->isTrue(); - $this->string($location2->fields['completename'])->isEqualTo('Non unique location'); + $this->assertGreaterThan(0, $location2_id); + $this->assertTrue($location2->getFromDB($location2_id)); + $this->assertEquals('Non unique location', $location2->fields['completename']); $updated = $location2->update([ 'id' => $location2_id, @@ -207,13 +207,13 @@ public function testUnicity() ]); $this->hasSqlLogRecordThatContains('Unique location\' for key \'', LogLevel::ERROR); - $this->boolean($updated)->isFalse(); - $this->boolean($location2->getFromDB($location2_id))->isTrue(); - $this->string($location2->fields['name'])->isEqualTo('Non unique location'); - $this->string($location2->fields['completename'])->isEqualTo('Non unique location'); + $this->assertFalse($updated); + $this->assertTrue($location2->getFromDB($location2_id)); + $this->assertEquals('Non unique location', $location2->fields['name']); + $this->assertEquals('Non unique location', $location2->fields['completename']); } - protected function importProvider(): iterable + public static function importProvider(): iterable { $root_entity_id = getItemByTypeName(\Entity::class, '_test_root_entity', true); $sub_entity_id = getItemByTypeName(\Entity::class, '_test_child_1', true); @@ -233,6 +233,32 @@ protected function importProvider(): iterable ], ]; } + } + + /** + * @dataProvider importProvider + */ + public function testImport(array $input, array $imported): void + { + $instance = new \Location(); + $count_before_import = countElementsInTable(\Location::getTable()); + $this->assertGreaterThan(0, $instance->import(Sanitizer::sanitize($input))); + $this->assertEquals(count($imported), countElementsInTable(\Location::getTable()) - $count_before_import); + foreach ($imported as $location_data) { + $this->assertEquals( + 1, + countElementsInTable(\Location::getTable(), $location_data), + json_encode($location_data) + ); + } + } + + public function testImportParentVisibleEntity(): void + { + $instance = new \Location(); + + $root_entity_id = getItemByTypeName(\Entity::class, '_test_root_entity', true); + $sub_entity_id = getItemByTypeName(\Entity::class, '_test_child_1', true); // Make sure import can link to parents that are visible in the expected entity $parent_location = $this->createItem( @@ -243,20 +269,38 @@ protected function importProvider(): iterable 'name' => 'Parent location', ] ); - yield [ - 'input' => [ + + $input = [ + 'entities_id' => $sub_entity_id, + 'completename' => 'Parent location > Child name', + ]; + $imported = [ + [ 'entities_id' => $sub_entity_id, - 'completename' => 'Parent location > Child name', - ], - 'imported' => [ - [ - 'entities_id' => $sub_entity_id, - 'name' => 'Child name', - 'locations_id' => $parent_location->getID(), - ] - ], + 'name' => 'Child name', + 'locations_id' => $parent_location->getID(), + ] ]; + $count_before_import = countElementsInTable(\Location::getTable()); + $this->assertGreaterThan(0, $instance->import(Sanitizer::sanitize($input))); + $this->assertEquals(count($imported), countElementsInTable(\Location::getTable()) - $count_before_import); + foreach ($imported as $location_data) { + $this->assertEquals( + 1, + countElementsInTable(\Location::getTable(), $location_data), + json_encode($location_data) + ); + } + } + + public function testImportParentNotVisibleEntity(): void + { + $instance = new \Location(); + + $root_entity_id = getItemByTypeName(\Entity::class, '_test_root_entity', true); + $sub_entity_id = getItemByTypeName(\Entity::class, '_test_child_1', true); + // Make sure import will create the parents that are not visible in the expected entity $l1_location = $this->createItem( \Location::class, @@ -274,46 +318,36 @@ protected function importProvider(): iterable 'name' => 'Location level 2', ] ); - yield [ - 'input' => [ + $input = [ + 'entities_id' => $sub_entity_id, + 'completename' => 'Location level 1 > Location level 2 > Location level 3', + ]; + $imported = [ + [ 'entities_id' => $sub_entity_id, - 'completename' => 'Location level 1 > Location level 2 > Location level 3', + 'name' => 'Location level 1', + 'locations_id' => 0, ], - 'imported' => [ - [ - 'entities_id' => $sub_entity_id, - 'name' => 'Location level 1', - 'locations_id' => 0, - ], - [ - 'entities_id' => $sub_entity_id, - 'name' => 'Location level 2', - ['NOT' => ['locations_id' => $l1_location->getID()]] - ], - [ - 'entities_id' => $sub_entity_id, - 'name' => 'Location level 3', - ['NOT' => ['locations_id' => $l2_location->getID()]] - ] + [ + 'entities_id' => $sub_entity_id, + 'name' => 'Location level 2', + ['NOT' => ['locations_id' => $l1_location->getID()]] ], + [ + 'entities_id' => $sub_entity_id, + 'name' => 'Location level 3', + ['NOT' => ['locations_id' => $l2_location->getID()]] + ] ]; - } - - /** - * @dataProvider importProvider - */ - public function testImport(array $input, array $imported): void - { - $this->newTestedInstance(); - $count_before_import = countElementsInTable(\Location::getTable()); - - $this->integer($this->testedInstance->import(Sanitizer::sanitize($input)))->isGreaterThan(0); - - $this->integer(countElementsInTable(\Location::getTable()) - $count_before_import)->isEqualTo(count($imported)); - + $this->assertGreaterThan(0, $instance->import(Sanitizer::sanitize($input))); + $this->assertEquals(count($imported), countElementsInTable(\Location::getTable()) - $count_before_import); foreach ($imported as $location_data) { - $this->integer(countElementsInTable(\Location::getTable(), $location_data))->isEqualTo(1, json_encode($location_data)); + $this->assertEquals( + 1, + countElementsInTable(\Location::getTable(), $location_data), + json_encode($location_data) + ); } } @@ -323,7 +357,7 @@ public function testMaybeLocated() foreach ($CFG_GLPI['location_types'] as $type) { $item = new $type(); - $this->boolean($item->maybeLocated())->isTrue($type . ' cannot be located!'); + $this->assertTrue($item->maybeLocated(), $type . ' cannot be located!'); } } } diff --git a/tests/functional/Lockedfield.php b/phpunit/functional/Lockedfield.php similarity index 64% rename from tests/functional/Lockedfield.php rename to phpunit/functional/Lockedfield.php index ce511587707..d7fdf3ad98e 100644 --- a/tests/functional/Lockedfield.php +++ b/phpunit/functional/Lockedfield.php @@ -51,52 +51,52 @@ public function testWithComputer() 'entities_id' => 0, 'is_dynamic' => 1 ]); - $this->integer($cid)->isGreaterThan(0); + $this->assertGreaterThan(0, $cid); $lockedfield = new \Lockedfield(); - $this->boolean($lockedfield->isHandled($computer))->isTrue(); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isEmpty(); + $this->assertTrue($lockedfield->isHandled($computer)); + $this->assertEmpty($lockedfield->getLockedValues($computer->getType(), $cid)); //update computer manually, to add a locked field - $this->boolean( - (bool)$computer->update(['id' => $cid, 'otherserial' => 'AZERTY']) - )->isTrue(); + $this->assertTrue( + $computer->update(['id' => $cid, 'otherserial' => 'AZERTY']) + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => null]); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertSame(['otherserial' => null], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure new dynamic update does not override otherserial again - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $cid, 'otherserial' => '789012', 'is_dynamic' => 1 ]) - )->isTrue(); + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['otherserial'])->isEqualTo('AZERTY'); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => '789012']); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('AZERTY', $computer->fields['otherserial']); + $this->assertSame(['otherserial' => '789012'], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure new dynamic update do not set new lock on regular update - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $cid, 'name' => 'Computer name changed', 'is_dynamic' => 1 ]) - )->isTrue(); + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['name'])->isEqualTo('Computer name changed'); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => '789012']); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('Computer name changed', $computer->fields['name']); + $this->assertSame(['otherserial' => '789012'], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure regular update do work on locked field - $this->boolean( - (bool)$computer->update(['id' => $cid, 'otherserial' => 'QWERTY']) - )->isTrue(); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['otherserial'])->isEqualTo('QWERTY'); + $this->assertTrue( + $computer->update(['id' => $cid, 'otherserial' => 'QWERTY']) + ); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('QWERTY', $computer->fields['otherserial']); } public function testGlobalLock() @@ -109,54 +109,55 @@ public function testGlobalLock() 'entities_id' => 0, 'is_dynamic' => 1 ]); - $this->integer($cid)->isGreaterThan(0); + $this->assertGreaterThan(0, $cid); $lockedfield = new \Lockedfield(); - $this->boolean($lockedfield->isHandled($computer))->isTrue(); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isEmpty(); + $this->assertTrue($lockedfield->isHandled($computer)); + $this->assertEmpty($lockedfield->getLockedValues($computer->getType(), $cid)); //add a global lock on otherserial field - $this->integer( + $this->assertGreaterThan( + 0, $lockedfield->add([ 'item' => 'Computer - otherserial' ]) - )->isGreaterThan(0); + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => null]); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertSame(['otherserial' => null], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure new dynamic update does not override otherserial again - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $cid, 'otherserial' => 'changed', 'is_dynamic' => 1 ]) - )->isTrue(); + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['otherserial'])->isEqualTo('789012'); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => null]); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('789012', $computer->fields['otherserial']); + $this->assertSame(['otherserial' => null], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure new dynamic update do not set new lock on regular update - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $cid, 'name' => 'Computer name changed', 'is_dynamic' => 1 ]) - )->isTrue(); + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['name'])->isEqualTo('Computer name changed'); - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => null]); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('Computer name changed', $computer->fields['name']); + $this->assertSame(['otherserial' => null], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure regular update do work on locked field - $this->boolean( - (bool)$computer->update(['id' => $cid, 'otherserial' => 'QWERTY']) - )->isTrue(); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['otherserial'])->isEqualTo('QWERTY'); + $this->assertTrue( + $computer->update(['id' => $cid, 'otherserial' => 'QWERTY']) + ); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('QWERTY', $computer->fields['otherserial']); } /** @@ -167,11 +168,12 @@ public function testGlobalLockAdd() $lockedfield = new \Lockedfield(); //add a global lock on otherserial field - $this->integer( + $this->assertGreaterThan( + 0, $lockedfield->add([ 'item' => 'Computer - otherserial' ]) - )->isGreaterThan(0); + ); $computer = new \Computer(); $cid = (int)$computer->add([ @@ -181,49 +183,49 @@ public function testGlobalLockAdd() 'entities_id' => 0, 'is_dynamic' => 1 ]); - $this->integer($cid)->isGreaterThan(0); + $this->assertGreaterThan(0, $cid); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['otherserial'])->isEqualTo(''); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('', $computer->fields['otherserial']); - $this->boolean($lockedfield->isHandled($computer))->isTrue(); + $this->assertTrue($lockedfield->isHandled($computer)); //lockedfield value must be null because it's a global lock - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => null]); + $this->assertSame(['otherserial' => null], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure new dynamic update does not override otherserial again - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $cid, 'otherserial' => 'changed', 'is_dynamic' => 1 ]) - )->isTrue(); + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['otherserial'])->isEqualTo(''); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('', $computer->fields['otherserial']); //lockedfield must be null because it's a global lock - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => null]); + $this->assertSame(['otherserial' => null], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure new dynamic update do not set new lock on regular update - $this->boolean( - (bool)$computer->update([ + $this->assertTrue( + $computer->update([ 'id' => $cid, 'name' => 'Computer name changed', 'is_dynamic' => 1 ]) - )->isTrue(); + ); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['name'])->isEqualTo('Computer name changed'); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('Computer name changed', $computer->fields['name']); //lockedfield must be null because it's a global lock - $this->array($lockedfield->getLockedValues($computer->getType(), $cid))->isIdenticalTo(['otherserial' => null]); + $this->assertSame(['otherserial' => null], $lockedfield->getLockedValues($computer->getType(), $cid)); //ensure regular update do work on locked field - $this->boolean( - (bool)$computer->update(['id' => $cid, 'otherserial' => 'QWERTY']) - )->isTrue(); - $this->boolean($computer->getFromDB($cid))->isTrue(); - $this->variable($computer->fields['otherserial'])->isEqualTo('QWERTY'); + $this->assertTrue( + $computer->update(['id' => $cid, 'otherserial' => 'QWERTY']) + ); + $this->assertTrue($computer->getFromDB($cid)); + $this->assertEquals('QWERTY', $computer->fields['otherserial']); } public function testNoRelation() @@ -252,11 +254,12 @@ public function testNoRelation() $lockedfield = new \Lockedfield(); //add a global lock on manufacturers_id field - $this->integer( + $this->assertGreaterThan( + 0, $lockedfield->add([ 'item' => 'Computer - manufacturers_id' ]) - )->isGreaterThan(0); + ); $converter = new \Glpi\Inventory\Converter(); $data = $converter->convert($xml); @@ -267,8 +270,8 @@ public function testNoRelation() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); //check matchedlogs $criteria = [ @@ -284,26 +287,25 @@ public function testNoRelation() 'WHERE' => [] ]; $iterator = $DB->request($criteria); - $this->string($iterator->current()['name'])->isIdenticalTo('Computer import (by serial + uuid)'); + $this->assertSame('Computer import (by serial + uuid)', $iterator->current()['name']); //check created agent $agents = $DB->request(['FROM' => \Agent::getTable()]); - $this->integer(count($agents))->isIdenticalTo(1); + $this->assertSame(1, count($agents)); $agent = $agents->current(); - $this->array($agent) - ->string['deviceid']->isIdenticalTo('glpixps.teclib.infra-2018-10-03-08-42-36') - ->string['itemtype']->isIdenticalTo('Computer'); + $this->assertSame('glpixps.teclib.infra-2018-10-03-08-42-36', $agent['deviceid']); + $this->assertSame('Computer', $agent['itemtype']); //check created computer $computers_id = $agent['items_id']; - $this->integer($computers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $computers_id); $computer = new \Computer(); - $this->boolean($computer->getFromDB($computers_id))->isTrue(); - $this->integer($computer->fields['manufacturers_id'])->isEqualTo(0); + $this->assertTrue($computer->getFromDB($computers_id)); + $this->assertEquals(0, $computer->fields['manufacturers_id']); //ensure no new manufacturer has been added - $this->integer(countElementsInTable(\Manufacturer::getTable()))->isIdenticalTo($existing_manufacturers); + $this->assertSame($existing_manufacturers, countElementsInTable(\Manufacturer::getTable())); } public function testNoLocation() @@ -343,8 +345,8 @@ public function testNoLocation() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); //check matchedlogs $criteria = [ @@ -360,27 +362,27 @@ public function testNoLocation() 'WHERE' => [] ]; $iterator = $DB->request($criteria); - $this->string($iterator->current()['name'])->isIdenticalTo('Printer import (by serial)'); + $this->assertSame('Printer import (by serial)', $iterator->current()['name']); $printers_id = $inventory->getItem()->fields['id']; - $this->integer($printers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $printers_id); $printer = new \Printer(); - $this->boolean($printer->getFromDB($printers_id))->isTrue(); - $this->integer($printer->fields['locations_id'])->isEqualTo(0); + $this->assertTrue($printer->getFromDB($printers_id)); + $this->assertEquals(0, $printer->fields['locations_id']); //ensure no new location has been added - $this->integer(countElementsInTable(\Location::getTable()))->isIdenticalTo($existing_locations); + $this->assertSame($existing_locations, countElementsInTable(\Location::getTable())); //manually update to lock locations_id field $locations_id = getItemByTypeName('Location', '_location02', true); - $this->boolean( + $this->assertTrue( $printer->update([ 'id' => $printers_id, 'locations_id' => $locations_id ]) - )->isTrue(); - $this->array($lockedfield->getLockedValues($printer->getType(), $printers_id))->isIdenticalTo(['locations_id' => null]); + ); + $this->assertSame(['locations_id' => null], $lockedfield->getLockedValues($printer->getType(), $printers_id)); //Replay, with a location $xml = " @@ -415,16 +417,16 @@ public function testNoLocation() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); - $this->boolean($printer->getFromDB($printers_id))->isTrue(); - $this->integer($printer->fields['locations_id'])->isEqualTo($locations_id); + $this->assertTrue($printer->getFromDB($printers_id)); + $this->assertEquals($locations_id, $printer->fields['locations_id']); //ensure no new location has been added - $this->integer(countElementsInTable(\Location::getTable()))->isIdenticalTo($existing_locations); + $this->assertSame($existing_locations, countElementsInTable(\Location::getTable())); - $this->array($lockedfield->getLockedValues($printer->getType(), $printers_id))->isIdenticalTo(['locations_id' => 'Greffe Charron']); + $this->assertSame(['locations_id' => 'Greffe Charron'], $lockedfield->getLockedValues($printer->getType(), $printers_id)); } public function testNoLocationGlobal() @@ -458,11 +460,12 @@ public function testNoLocationGlobal() $lockedfield = new \Lockedfield(); //add a global lock on locations_id field - $this->integer( + $this->assertGreaterThan( + 0, $lockedfield->add([ 'item' => 'Printer - locations_id' ]) - )->isGreaterThan(0); + ); $converter = new \Glpi\Inventory\Converter(); $data = $converter->convert($xml); @@ -473,8 +476,8 @@ public function testNoLocationGlobal() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); //check matchedlogs $criteria = [ @@ -490,17 +493,17 @@ public function testNoLocationGlobal() 'WHERE' => [] ]; $iterator = $DB->request($criteria); - $this->string($iterator->current()['name'])->isIdenticalTo('Printer import (by serial)'); + $this->assertSame('Printer import (by serial)', $iterator->current()['name']); $printers_id = $inventory->getItem()->fields['id']; - $this->integer($printers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $printers_id); $printer = new \Printer(); - $this->boolean($printer->getFromDB($printers_id))->isTrue(); - $this->integer($printer->fields['locations_id'])->isEqualTo(0); + $this->assertTrue($printer->getFromDB($printers_id)); + $this->assertEquals(0, $printer->fields['locations_id']); //ensure no new location has been added - $this->integer(countElementsInTable(\Location::getTable()))->isIdenticalTo($existing_locations); + $this->assertSame($existing_locations, countElementsInTable(\Location::getTable())); } public function testLockedDdValue() @@ -543,8 +546,8 @@ public function testLockedDdValue() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); //check matchedlogs $criteria = [ @@ -560,28 +563,28 @@ public function testLockedDdValue() 'WHERE' => [] ]; $iterator = $DB->request($criteria); - $this->string($iterator->current()['name'])->isIdenticalTo('Printer import (by serial)'); + $this->assertSame('Printer import (by serial)', $iterator->current()['name']); $printers_id = $inventory->getItem()->fields['id']; - $this->integer($printers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $printers_id); $printer = new \Printer(); - $this->boolean($printer->getFromDB($printers_id))->isTrue(); - $this->integer($printer->fields['locations_id'])->isGreaterThan(0); + $this->assertTrue($printer->getFromDB($printers_id)); + $this->assertGreaterThan(0, $printer->fields['locations_id']); //ensure new location has been added ++$existing_locations; - $this->integer(countElementsInTable(\Location::getTable()))->isIdenticalTo($existing_locations); + $this->assertSame($existing_locations, countElementsInTable(\Location::getTable())); //manually update to lock locations_id field $locations_id = getItemByTypeName('Location', '_location02', true); - $this->boolean( + $this->assertTrue( $printer->update([ 'id' => $printers_id, 'locations_id' => $locations_id ]) - )->isTrue(); - $this->array($lockedfield->getLockedValues($printer->getType(), $printers_id))->isIdenticalTo(['locations_id' => null]); + ); + $this->assertSame(['locations_id' => null], $lockedfield->getLockedValues($printer->getType(), $printers_id)); //Replay, with a location, to ensure location has not been updated, and locked value is correct. $data = $converter->convert($xml); @@ -592,16 +595,16 @@ public function testLockedDdValue() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); - $this->boolean($printer->getFromDB($printers_id))->isTrue(); - $this->integer($printer->fields['locations_id'])->isEqualTo($locations_id); + $this->assertTrue($printer->getFromDB($printers_id)); + $this->assertEquals($locations_id, $printer->fields['locations_id']); //ensure no new location has been added - $this->integer(countElementsInTable(\Location::getTable()))->isIdenticalTo($existing_locations); + $this->assertSame($existing_locations, countElementsInTable(\Location::getTable())); - $this->array($lockedfield->getLockedValues($printer->getType(), $printers_id))->isIdenticalTo(['locations_id' => 'Greffe Charron']); + $this->assertSame(['locations_id' => 'Greffe Charron'], $lockedfield->getLockedValues($printer->getType(), $printers_id)); } public function testLockedRelations() @@ -662,50 +665,50 @@ public function testLockedRelations() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); $computers_id = $inventory->getItem()->fields['id']; - $this->integer($computers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $computers_id); - $this->boolean($computer->getFromDB($computers_id))->isTrue(); + $this->assertTrue($computer->getFromDB($computers_id)); - $this->boolean($cos->getFromDBByCrit(['items_id' => $computers_id]))->isTrue(); + $this->assertTrue($cos->getFromDBByCrit(['items_id' => $computers_id])); //check OS version - $this->boolean($aos->getFromDBByCrit(['name' => 'x86_64']))->isTrue(); + $this->assertTrue($aos->getFromDBByCrit(['name' => 'x86_64'])); $archs_id = $aos->fields['id']; - $this->integer($cos->fields['operatingsystemarchitectures_id'])->isIdenticalTo($archs_id); + $this->assertSame($archs_id, $cos->fields['operatingsystemarchitectures_id']); //check antivirus manufacturer - $this->boolean($iav->getFromDBByCrit(['computers_id' => $computers_id]))->isTrue(); - $this->boolean($manufacturer->getFromDBByCrit(['name' => 'Microsoft Corporation']))->isTrue(); + $this->assertTrue($iav->getFromDBByCrit(['computers_id' => $computers_id])); + $this->assertTrue($manufacturer->getFromDBByCrit(['name' => 'Microsoft Corporation'])); $manufacturers_id = $manufacturer->fields['id']; - $this->integer($iav->fields['manufacturers_id'])->isIdenticalTo($manufacturers_id); + $this->assertSame($manufacturers_id, $iav->fields['manufacturers_id']); //manually update OS architecture field $newarchs_id = $aos->add(['name' => 'i386']); - $this->integer($newarchs_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $newarchs_id); - $this->boolean( + $this->assertTrue( $cos->update([ 'id' => $cos->fields['id'], 'operatingsystemarchitectures_id' => $newarchs_id ]) - )->isTrue(); - $this->array($lockedfield->getLockedValues($cos->getType(), $cos->fields['id']))->isIdenticalTo(['operatingsystemarchitectures_id' => null]); + ); + $this->assertSame(['operatingsystemarchitectures_id' => null], $lockedfield->getLockedValues($cos->getType(), $cos->fields['id'])); //manually update AV manufacturer field $newmanufacturers_id = $manufacturer->add(['name' => 'Crosoft']); - $this->integer($newmanufacturers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $newmanufacturers_id); - $this->boolean( + $this->assertTrue( $iav->update([ 'id' => $iav->fields['id'], 'manufacturers_id' => $newmanufacturers_id ]) - )->isTrue(); - $this->array($lockedfield->getLockedValues($iav->getType(), $iav->fields['id']))->isIdenticalTo(['manufacturers_id' => null]); + ); + $this->assertSame(['manufacturers_id' => null], $lockedfield->getLockedValues($iav->getType(), $iav->fields['id'])); //replay $data = $converter->convert($xml); @@ -715,20 +718,20 @@ public function testLockedRelations() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); //make sure architecture is still the correct one - $this->boolean($cos->getFromDBByCrit(['items_id' => $computers_id]))->isTrue(); - $this->integer($cos->fields['operatingsystemarchitectures_id'])->isIdenticalTo($newarchs_id); + $this->assertTrue($cos->getFromDBByCrit(['items_id' => $computers_id])); + $this->assertSame($newarchs_id, $cos->fields['operatingsystemarchitectures_id']); - $this->array($lockedfield->getLockedValues($cos->getType(), $cos->fields['id']))->isIdenticalTo(['operatingsystemarchitectures_id' => 'x86_64']); + $this->assertSame(['operatingsystemarchitectures_id' => 'x86_64'], $lockedfield->getLockedValues($cos->getType(), $cos->fields['id'])); //make sure manufacturer is still the correct one - $this->boolean($iav->getFromDBByCrit(['computers_id' => $computers_id]))->isTrue(); - $this->integer($iav->fields['manufacturers_id'])->isIdenticalTo($newmanufacturers_id); + $this->assertTrue($iav->getFromDBByCrit(['computers_id' => $computers_id])); + $this->assertSame($newmanufacturers_id, $iav->fields['manufacturers_id']); - $this->array($lockedfield->getLockedValues($iav->getType(), $iav->fields['id']))->isIdenticalTo(['manufacturers_id' => 'Microsoft Corporation']); + $this->assertSame(['manufacturers_id' => 'Microsoft Corporation'], $lockedfield->getLockedValues($iav->getType(), $iav->fields['id'])); } public function testLockDatabasesManufacturer() @@ -764,8 +767,8 @@ public function testLockDatabasesManufacturer() ]; $rules_id = $rule->add($input); - $this->integer($rules_id)->isGreaterThan(0); - $this->boolean($collection->moveRule($rules_id, 0, $collection::MOVE_BEFORE))->isTrue(); + $this->assertGreaterThan(0, $rules_id); + $this->assertTrue($collection->moveRule($rules_id, 0, $collection::MOVE_BEFORE)); // Add criteria foreach ($criteria as $crit) { @@ -775,7 +778,7 @@ public function testLockDatabasesManufacturer() 'pattern' => $crit['pattern'], 'condition' => $crit['condition'], ]; - $this->integer((int)$rulecriteria->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$rulecriteria->add($input)); } // Add action @@ -786,7 +789,7 @@ public function testLockDatabasesManufacturer() 'field' => $action['field'], 'value' => $action['value'], ]; - $this->integer((int)$ruleaction->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$ruleaction->add($input)); //UPDATE rule $criteria = [ @@ -822,8 +825,8 @@ public function testLockDatabasesManufacturer() $prev_rules_id = $rules_id; $rules_id = $rule->add($input); - $this->integer($rules_id)->isGreaterThan(0); - $this->boolean($collection->moveRule($rules_id, $prev_rules_id, $collection::MOVE_BEFORE))->isTrue(); + $this->assertGreaterThan(0, $rules_id); + $this->assertTrue($collection->moveRule($rules_id, $prev_rules_id, $collection::MOVE_BEFORE)); // Add criteria foreach ($criteria as $crit) { @@ -833,7 +836,7 @@ public function testLockDatabasesManufacturer() 'pattern' => $crit['pattern'], 'condition' => $crit['condition'], ]; - $this->integer((int)$rulecriteria->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$rulecriteria->add($input)); } // Add action @@ -844,7 +847,7 @@ public function testLockDatabasesManufacturer() 'field' => $action['field'], 'value' => $action['value'], ]; - $this->integer((int)$ruleaction->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$ruleaction->add($input)); //keep only postgresql $json = json_decode(file_get_contents(GLPI_ROOT . '/vendor/glpi-project/inventory_format/examples/computer_2_partial_dbs.json')); @@ -856,33 +859,33 @@ public function testLockDatabasesManufacturer() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); //check created databases & instances - $this->integer(countElementsInTable(\DatabaseInstance::getTable()))->isIdenticalTo(1); + $this->assertSame(1, countElementsInTable(\DatabaseInstance::getTable())); //ensure database version has been updated $database = new \DatabaseInstance(); - $this->boolean($database->getFromDBByCrit(['name' => 'PostgreSQL 13']))->isTrue(); - $this->string($database->fields['version'])->isIdenticalTo('13.2.3'); + $this->assertTrue($database->getFromDBByCrit(['name' => 'PostgreSQL 13'])); + $this->assertSame('13.2.3', $database->fields['version']); $manufacturer = new \Manufacturer(); - $this->boolean($manufacturer->getFromDBByCrit(['name' => 'PostgreSQL']))->isTrue(); + $this->assertTrue($manufacturer->getFromDBByCrit(['name' => 'PostgreSQL'])); $manufacturers_id = $manufacturer->fields['id']; - $this->integer($database->fields['manufacturers_id'])->isIdenticalTo($manufacturers_id); + $this->assertSame($manufacturers_id, $database->fields['manufacturers_id']); $newmanufacturers_id = $manufacturer->add(['name' => 'For test']); - $this->integer($newmanufacturers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $newmanufacturers_id); //manually update manufacturer to lock it - $this->boolean( + $this->assertTrue( $database->update([ 'id' => $database->fields['id'], 'manufacturers_id' => $newmanufacturers_id ]) - )->isTrue(); - $this->array($lockedfield->getLockedValues($database->getType(), $database->fields['id']))->isIdenticalTo(['manufacturers_id' => null]); + ); + $this->assertSame(['manufacturers_id' => null], $lockedfield->getLockedValues($database->getType(), $database->fields['id'])); $json = json_decode(file_get_contents(GLPI_ROOT . '/vendor/glpi-project/inventory_format/examples/computer_2_partial_dbs.json')); $pgsql = $json->content->databases_services[1]; @@ -893,17 +896,17 @@ public function testLockDatabasesManufacturer() if ($inventory->inError()) { $this->dump($inventory->getErrors()); } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); + $this->assertFalse($inventory->inError()); + $this->assertEmpty($inventory->getErrors()); //check created databases & instances - $this->integer(countElementsInTable(\DatabaseInstance::getTable()))->isIdenticalTo(1); + $this->assertSame(1, countElementsInTable(\DatabaseInstance::getTable())); //make sure manufacturer is still the correct one $database = new \DatabaseInstance(); - $this->boolean($database->getFromDBByCrit(['name' => 'PostgreSQL 13']))->isTrue(); - $this->string($database->fields['version'])->isIdenticalTo('13.2.3'); - $this->integer($database->fields['manufacturers_id'])->isIdenticalTo($newmanufacturers_id); - $this->array($lockedfield->getLockedValues($database->getType(), $database->fields['id']))->isIdenticalTo(['manufacturers_id' => 'PostgreSQL']); + $this->assertTrue($database->getFromDBByCrit(['name' => 'PostgreSQL 13'])); + $this->assertSame('13.2.3', $database->fields['version']); + $this->assertSame($newmanufacturers_id, $database->fields['manufacturers_id']); + $this->assertSame(['manufacturers_id' => 'PostgreSQL'], $lockedfield->getLockedValues($database->getType(), $database->fields['id'])); } } diff --git a/tests/functional/Log.php b/phpunit/functional/Log.php similarity index 92% rename from tests/functional/Log.php rename to phpunit/functional/Log.php index 3cf0de113cf..1dff0b27bef 100644 --- a/tests/functional/Log.php +++ b/phpunit/functional/Log.php @@ -44,9 +44,10 @@ class Log extends DbTestCase private function createComputer() { $computer = new \Computer(); - $this->integer( - (int)$computer->add(['entities_id' => getItemByTypeName('Entity', '_test_root_entity', true)], [], false) - )->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $computer->add(['entities_id' => getItemByTypeName('Entity', '_test_root_entity', true)], [], false) + ); return $computer; } @@ -72,7 +73,7 @@ private function createLogEntry( unset($log_data['date_mod']); $log = new \Log(); - $this->integer((int)$log->add($log_data))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$log->add($log_data)); return $log; } @@ -83,7 +84,7 @@ public function testGetDistinctUserNamesValuesInItemLog() $user_names = ['Huey', 'Dewey', 'Louie', 'Phooey']; - // Add at least one item per user + // Add at least one item per user foreach ($user_names as $user_name) { $this->createLogEntry( $computer, @@ -94,7 +95,7 @@ public function testGetDistinctUserNamesValuesInItemLog() ); } - // Add 10 items affected randomly to users + // Add 10 items affected randomly to users for ($i = 0; $i < 10; $i++) { $this->createLogEntry( $computer, @@ -108,10 +109,10 @@ public function testGetDistinctUserNamesValuesInItemLog() $expected_user_names = ['Dewey', 'Huey', 'Louie', 'Phooey']; $expected_result = array_combine($expected_user_names, $expected_user_names); - $this->array(\Log::getDistinctUserNamesValuesInItemLog($computer))->isIdenticalTo($expected_result); + $this->assertSame($expected_result, \Log::getDistinctUserNamesValuesInItemLog($computer)); } - protected function dataLogToAffectedField() + public static function dataLogToAffectedField() { $item_related_linked_action_values = implode( ',', @@ -430,7 +431,7 @@ public function testValuesComputationForGetDistinctAffectedFieldValuesInItemLog( $this->createLogEntry($computer, $log_data); - $this->array(\Log::getDistinctAffectedFieldValuesInItemLog($computer))->isIdenticalTo($expected_result); + $this->assertSame($expected_result, \Log::getDistinctAffectedFieldValuesInItemLog($computer)); } public function testValuesSortInGetDistinctAffectedFieldValuesInItemLog() @@ -446,14 +447,14 @@ public function testValuesSortInGetDistinctAffectedFieldValuesInItemLog() $previous_value = null; foreach ($result as $key => $value) { if (null !== $previous_value) { - $this->boolean('Others' === $value || strcmp($previous_value, $value) < 0)->isTrue(); + $this->assertTrue('Others' === $value || strcmp($previous_value, $value) < 0); } $previous_value = $value; } } - protected function dataLinkedActionLabel() + public static function dataLinkedActionLabel() { return [ [0, null], @@ -492,7 +493,7 @@ protected function dataLinkedActionLabel() */ public function testGetLinkedActionLabel($linked_action, $expected_label) { - $this->variable(\Log::getLinkedActionLabel($linked_action))->isIdenticalTo($expected_label); + $this->assertSame($expected_label, \Log::getLinkedActionLabel($linked_action)); } /** @@ -506,16 +507,18 @@ public function testValuesComputationForGetDistinctLinkedActionValuesInItemLog($ $expected_key = $linked_action; if (0 === $linked_action) { - //Special case for field update + //Special case for field update $expected_value = __('Update a field'); } else if (null === $expected_value) { - //Null values fallbacks to 'Others'. + //Null values fallbacks to 'Others'. $expected_key = 'other'; $expected_value = __('Others'); } - $this->array(\Log::getDistinctLinkedActionValuesInItemLog($computer)) - ->isIdenticalTo([$expected_key => $expected_value]); + $this->assertSame( + [$expected_key => $expected_value], + \Log::getDistinctLinkedActionValuesInItemLog($computer) + ); } public function testValuesSortInGetDistinctLinkedActionValuesInItemLog() @@ -531,14 +534,14 @@ public function testValuesSortInGetDistinctLinkedActionValuesInItemLog() $previous_value = null; foreach ($result as $key => $value) { if (null !== $previous_value) { - $this->boolean('Others' === $value || strcmp($previous_value, $value) < 0)->isTrue(); + $this->assertTrue('Others' === $value || strcmp($previous_value, $value) < 0); } $previous_value = $value; } } - protected function dataFiltersValuesToSqlCriteria() + public static function dataFiltersValuesToSqlCriteria() { return [ [ @@ -737,7 +740,7 @@ protected function dataFiltersValuesToSqlCriteria() */ public function testConvertFiltersValuesToSqlCriteria($filters_values, $expected_result) { - $this->array(\Log::convertFiltersValuesToSqlCriteria($filters_values))->isIdenticalTo($expected_result); + $this->assertSame($expected_result, \Log::convertFiltersValuesToSqlCriteria($filters_values)); } protected function userNameFormattingProvider() @@ -769,7 +772,7 @@ public function testUserNameFormatting(string $username, string $password, strin 'ORDER' => 'id DESC', 'LIMIT' => 1 ]); - $this->integer(count($iterator))->isIdenticalTo(1); + $this->assertSame(1, count($iterator)); return $iterator->current(); }; @@ -777,22 +780,22 @@ public function testUserNameFormatting(string $username, string $password, strin // ID should always be displayed regardless of user preferences or server default $_SESSION['glpiis_ids_visible'] = false; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); $_SESSION['glpiis_ids_visible'] = true; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); $CFG_GLPI['is_ids_visible'] = false; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); $CFG_GLPI['is_ids_visible'] = true; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); // Name order should always be realname firstname regardless of user preferences or server default $_SESSION['glpinames_format'] = \User::FIRSTNAME_BEFORE; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); $_SESSION['glpinames_format'] = \User::REALNAME_BEFORE; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); $CFG_GLPI['names_format'] = \User::FIRSTNAME_BEFORE; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); $CFG_GLPI['names_format'] = \User::REALNAME_BEFORE; - $this->string($log_event()['user_name'])->isIdenticalTo($expected_name . " ($user_id)"); + $this->assertSame($expected_name . " ($user_id)", $log_event()['user_name']); } } diff --git a/tests/functional/Monitor.php b/phpunit/functional/MonitorTest.php similarity index 86% rename from tests/functional/Monitor.php rename to phpunit/functional/MonitorTest.php index 55ac7b8c2bf..53a626d7483 100644 --- a/tests/functional/Monitor.php +++ b/phpunit/functional/MonitorTest.php @@ -39,7 +39,7 @@ /* Test for inc/monitor.class.php */ -class Monitor extends DbTestCase +class MonitorTest extends DbTestCase { private static function getMonitorFields($id, $date) { @@ -99,12 +99,12 @@ private function getNewMonitor() $monitor = new \Monitor(); $added = $monitor->add($data); - $this->integer((int)$added)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$added); $monitor = getItemByTypeName('Monitor', '_test_monitor01'); - $expected = Monitor::getMonitorFields($added, $date); - $this->array($monitor->fields)->isEqualTo($expected); + $expected = self::getMonitorFields($added, $date); + $this->assertEquals($expected, $monitor->fields); return $monitor; } @@ -121,16 +121,19 @@ public function testClone() $_SESSION['glpi_currenttime'] = $date; $added = $monitor->clone(); - $this->integer((int)$added)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$added); $clonedMonitor = new \Monitor(); - $this->boolean($clonedMonitor->getFromDB($added))->isTrue(); + $this->assertTrue($clonedMonitor->getFromDB($added)); - $expected = Monitor::getMonitorFields($added, $date); + $expected = self::getMonitorFields($added, $date); - $this->string($clonedMonitor->fields['name'])->isEqualTo("$expected[name] (copy)"); + $this->assertEquals( + "$expected[name] (copy)", + $clonedMonitor->fields['name'] + ); unset($clonedMonitor->fields['name'], $expected['name']); - $this->array($clonedMonitor->fields)->isEqualTo($expected); + $this->assertEquals($expected, $clonedMonitor->fields); } } diff --git a/tests/functional/NetworkEquipment.php b/phpunit/functional/NetworkEquipmentTest.php similarity index 73% rename from tests/functional/NetworkEquipment.php rename to phpunit/functional/NetworkEquipmentTest.php index e1e072ad8e3..310a562157b 100644 --- a/tests/functional/NetworkEquipment.php +++ b/phpunit/functional/NetworkEquipmentTest.php @@ -39,7 +39,7 @@ /* Test for inc/networkequipment.class.php */ -class NetworkEquipment extends DbTestCase +class NetworkEquipmentTest extends DbTestCase { public function testNetEquipmentCRUD() { @@ -52,10 +52,10 @@ public function testNetEquipmentCRUD() 'entities_id' => 0 ]; $netequipments_id = $device->add($input); - $this->integer($netequipments_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $netequipments_id); - $this->boolean($device->getFromDB($netequipments_id))->isTrue(); - $this->string($device->fields['name'])->isIdenticalTo('Test equipment'); + $this->assertTrue($device->getFromDB($netequipments_id)); + $this->assertSame('Test equipment', $device->fields['name']); //create ports attached $netport = new \NetworkPort(); @@ -68,10 +68,10 @@ public function testNetEquipmentCRUD() 'instantiation_type' => 'NetworkPortEthernet' ]; $netports_id = $netport->add($input); - $this->integer($netports_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $netports_id); - $this->boolean($netport->getFromDB($netports_id))->isTrue(); - $this->string($netport->fields['name'])->isIdenticalTo('Test port'); + $this->assertTrue($netport->getFromDB($netports_id)); + $this->assertSame('Test port', $netport->fields['name']); $input = [ 'itemtype' => $device->getType(), @@ -82,17 +82,17 @@ public function testNetEquipmentCRUD() 'instantiation_type' => 'NetworkPortAggregate' ]; $netports_id = $netport->add($input); - $this->integer($netports_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $netports_id); - $this->boolean($netport->getFromDB($netports_id))->isTrue(); - $this->string($netport->fields['name'])->isIdenticalTo('Another test port'); + $this->assertTrue($netport->getFromDB($netports_id)); + $this->assertSame('Another test port', $netport->fields['name']); - $this->integer($netport->countForItem($device))->isIdenticalTo(2); + $this->assertSame(2, $netport->countForItem($device)); //remove network equipment - $this->boolean($device->delete(['id' => $netequipments_id], true))->isTrue(); + $this->assertTrue($device->delete(['id' => $netequipments_id], true)); //see if links are dropped - $this->integer($netport->countForItem($device))->isIdenticalTo(0); + $this->assertSame(0, $netport->countForItem($device)); } } diff --git a/tests/functional/NetworkName.php b/phpunit/functional/NetworkName.php similarity index 90% rename from tests/functional/NetworkName.php rename to phpunit/functional/NetworkName.php index 3448cbf386c..c6b6e9b1195 100644 --- a/tests/functional/NetworkName.php +++ b/phpunit/functional/NetworkName.php @@ -56,8 +56,8 @@ public function testAddSimpleNetworkName() 'addressable' => 0, ]); - $this->integer((int)$ipnetwork_id)->isGreaterThan(0); - $this->boolean($IPNetwork->getFromDB($ipnetwork_id))->isTrue(); + $this->assertGreaterThan(0, (int)$ipnetwork_id); + $this->assertTrue($IPNetwork->getFromDB($ipnetwork_id)); $current_ipnetwork = $IPNetwork->fields; unset($current_ipnetwork['id']); @@ -93,7 +93,7 @@ public function testAddSimpleNetworkName() "comment" => null, "network" => "1.1.1.0 / 255.255.255.0", ]; - $this->array($current_ipnetwork)->isIdenticalTo($expected); + $this->assertSame($expected, $current_ipnetwork); //Second add NetworkName $Networkname = new \NetworkName(); @@ -108,8 +108,8 @@ public function testAddSimpleNetworkName() 'ipnetworks_id' => 0 ]); - $this->integer((int)$networkname_id)->isGreaterThan(0); - $this->boolean($Networkname->getFromDB($networkname_id))->isTrue(); + $this->assertGreaterThan(0, (int)$networkname_id); + $this->assertTrue($Networkname->getFromDB($networkname_id)); $current_networkname = $Networkname->fields; unset($current_networkname['id']); @@ -127,6 +127,6 @@ public function testAddSimpleNetworkName() "is_deleted" => 0, "is_dynamic" => 0, ]; - $this->array($current_networkname)->isIdenticalTo($expected); + $this->assertSame($expected, $current_networkname); } } diff --git a/tests/functional/NetworkPort.php b/phpunit/functional/NetworkPort.php similarity index 84% rename from tests/functional/NetworkPort.php rename to phpunit/functional/NetworkPort.php index 11e4b588183..cb289d5c98a 100644 --- a/tests/functional/NetworkPort.php +++ b/phpunit/functional/NetworkPort.php @@ -60,8 +60,8 @@ public function testAddSimpleNetworkPort() 'instantiation_type' => 'NetworkPortEthernet', 'name' => 'eth1', ]); - $this->integer((int)$new_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, (int)$new_id); + $this->assertGreaterThan($nb_log, (int)countElementsInTable('glpi_logs')); // check data in db $all_netports = getAllDataFromTable('glpi_networkports', ['ORDER' => 'id']); @@ -97,11 +97,11 @@ public function testAddSimpleNetworkPort() 'trunk' => 0, 'lastup' => null ]; - $this->array($current_networkport)->isIdenticalTo($expected); + $this->assertSame($expected, $current_networkport); $all_netportethernets = getAllDataFromTable('glpi_networkportethernets', ['ORDER' => 'id']); $networkportethernet = end($all_netportethernets); - $this->boolean($networkportethernet)->isFalse(); + $this->assertFalse($networkportethernet); // be sure added and have no logs $nb_log = (int)countElementsInTable('glpi_logs'); @@ -113,8 +113,8 @@ public function testAddSimpleNetworkPort() 'mac' => '00:24:81:eb:c6:d1', 'instantiation_type' => 'NetworkPortEthernet', ], [], false); - $this->integer((int)$new_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isIdenticalTo($nb_log); + $this->assertGreaterThan(0, (int)$new_id); + $this->assertSame($nb_log, (int)countElementsInTable('glpi_logs')); } public function testAddCompleteNetworkPort() @@ -148,8 +148,8 @@ public function testAddCompleteNetworkPort() 'NetworkName__ipaddresses' => ['-1' => '192.168.20.1'], '_create_children' => true // automatically add instancation, networkname and ipadresses ]); - $this->integer($new_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $new_id); + $this->assertGreaterThan($nb_log, (int)countElementsInTable('glpi_logs')); // check data in db // 1 -> NetworkPortEthernet @@ -164,7 +164,7 @@ public function testAddCompleteNetworkPort() 'type' => 'T', 'speed' => 1000, ]; - $this->array($networkportethernet)->isIdenticalTo($expected); + $this->assertSame($expected, $networkportethernet); // 2 -> NetworkName $all_networknames = getAllDataFromTable('glpi_networknames', ['ORDER' => 'id']); @@ -184,7 +184,7 @@ public function testAddCompleteNetworkPort() 'is_deleted' => 0, 'is_dynamic' => 0, ]; - $this->array($networkname)->isIdenticalTo($expected); + $this->assertSame($expected, $networkname); // 3 -> IPAddress $all_ipadresses = getAllDataFromTable('glpi_ipaddresses', ['ORDER' => 'id']); @@ -207,7 +207,7 @@ public function testAddCompleteNetworkPort() 'mainitems_id' => $computer1->getID(), 'mainitemtype' => 'Computer', ]; - $this->array($ipadress)->isIdenticalTo($expected); + $this->assertSame($expected, $ipadress); // be sure added and have no logs $nb_log = (int)countElementsInTable('glpi_logs'); @@ -230,8 +230,8 @@ public function testAddCompleteNetworkPort() 'NetworkName_fqdns_id' => 0, 'NetworkName__ipaddresses' => ['-1' => '192.168.20.2'] ], [], false); - $this->integer((int)$new_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isIdenticalTo($nb_log); + $this->assertGreaterThan(0, (int)$new_id); + $this->assertSame($nb_log, (int)countElementsInTable('glpi_logs')); } public function testClone() @@ -269,15 +269,15 @@ public function testClone() 'NetworkName__ipaddresses' => ['-1' => '192.168.20.1'], '_create_children' => true // automatically add instancation, networkname and ipadresses ]); - $this->integer($new_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, $new_id); + $this->assertGreaterThan($nb_log, (int)countElementsInTable('glpi_logs')); // Test item cloning $added = $networkport->clone(); - $this->integer((int)$added)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$added); $clonedNetworkport = new \NetworkPort(); - $this->boolean($clonedNetworkport->getFromDB($added))->isTrue(); + $this->assertTrue($clonedNetworkport->getFromDB($added)); $fields = $networkport->fields; @@ -285,19 +285,22 @@ public function testClone() foreach ($fields as $k => $v) { switch ($k) { case 'id': - $this->variable($clonedNetworkport->getField($k))->isNotEqualTo($networkport->getField($k)); + $this->assertNotEquals( + $networkport->getField($k), + $clonedNetworkport->getField($k) + ); break; case 'date_mod': case 'date_creation': $dateClone = new \DateTime($clonedNetworkport->getField($k)); $expectedDate = new \DateTime($date); - $this->dateTime($dateClone)->isEqualTo($expectedDate); + $this->assertEquals($expectedDate, $dateClone); break; case 'name': - $this->variable($clonedNetworkport->getField($k))->isEqualTo("{$networkport->getField($k)} (copy)"); + $this->assertEquals("{$networkport->getField($k)} (copy)", $clonedNetworkport->getField($k)); break; default: - $this->variable($clonedNetworkport->getField($k))->isEqualTo($networkport->getField($k)); + $this->assertEquals($networkport->getField($k), $clonedNetworkport->getField($k)); } } @@ -309,20 +312,26 @@ public function testClone() foreach ($fields as $k => $v) { switch ($k) { case 'id': - $this->variable($clonedInstantiation->getField($k))->isNotEqualTo($instantiation->getField($k)); + $this->assertNotEquals( + $instantiation->getField($k), + $clonedInstantiation->getField($k) + ); break; case 'networkports_id': - $this->variable($clonedInstantiation->getField($k))->isNotEqualTo($instantiation->getField($k)); - $this->variable($clonedInstantiation->getField($k))->isEqualTo($clonedNetworkport->getID()); + $this->assertNotEquals( + $instantiation->getField($k), + $clonedInstantiation->getField($k) + ); + $this->assertEquals($clonedNetworkport->getID(), $clonedInstantiation->getField($k)); break; case 'date_mod': case 'date_creation': $dateClone = new \DateTime($clonedInstantiation->getField($k)); $expectedDate = new \DateTime($date); - $this->dateTime($dateClone)->isEqualTo($expectedDate); + $this->assertEquals($expectedDate, $dateClone); break; default: - $this->variable($clonedInstantiation->getField($k))->isEqualTo($instantiation->getField($k)); + $this->assertEquals($instantiation->getField($k), $clonedInstantiation->getField($k)); } } } @@ -349,13 +358,13 @@ public function testClearSavedInputAfterUpdate() 'instantiation_type' => 'NetworkPortEthernet', 'name' => 'eth1', ]); - $this->integer((int)$np_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$np_id); $result = $networkport->update([ 'id' => $np_id, 'comment' => 'test', ]); - $this->boolean($result)->isTrue(); + $this->assertTrue($result); // Check that there is no savedInput after update if (isset($_SESSION['saveInput']) && is_array($_SESSION['saveInput'])) { @@ -381,7 +390,7 @@ public function testShowForItem() 'instantiation_type' => 'NetworkPortEthernet', 'name' => 'eth1', ]); - $this->integer((int)$np_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$np_id); // Display all columns $so = $netport->rawSearchOptions(); @@ -394,22 +403,20 @@ public function testShowForItem() 'users_id' => \Session::getLoginUserID(), 'num' => $column['id'], ]; - $this->integer((int) $displaypref->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int) $displaypref->add($input)); $so_display[] = $column; } } // Check that all columns are displayed and correct values foreach (['showForItem', 'displayTabContentForItem'] as $method) { - $result = $this->output( - function () use ($method, $computer1) { - \NetworkPort::$method($computer1); - } - ); + ob_start(); + \NetworkPort::$method($computer1); + $result = ob_get_clean(); foreach ($so_display as $column) { - $result->contains($column['name']); + $this->assertStringContainsString($column['name'], $result); if (isset($netport->fields[$column['field']])) { - $result->contains((string)$netport->fields[$column['field']]); + $this->assertStringContainsString((string)$netport->fields[$column['field']], $result); } } } diff --git a/tests/functional/NetworkPortMetrics.php b/phpunit/functional/NetworkPortMetrics.php similarity index 84% rename from tests/functional/NetworkPortMetrics.php rename to phpunit/functional/NetworkPortMetrics.php index cbc4091ee40..851e5384589 100644 --- a/tests/functional/NetworkPortMetrics.php +++ b/phpunit/functional/NetworkPortMetrics.php @@ -49,7 +49,7 @@ public function testNetworkPortithMetrics() 'name' => 'My network equipment', 'entities_id' => 0 ]); - $this->integer($neteq_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $neteq_id); $port = [ 'name' => 'Gigabit0/1/2', @@ -68,12 +68,12 @@ public function testNetworkPortithMetrics() $netport = new \NetworkPort(); $netports_id = $netport->add($port); - $this->integer($netports_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $netports_id); //create port, check if metrics has been addded $metrics = new \NetworkPortMetrics(); $values = $metrics->getMetrics($netport); - $this->array($values)->hasSize(1); + $this->assertCount(1, $values); $value = array_pop($values); $expected = [ @@ -87,7 +87,7 @@ public function testNetworkPortithMetrics() 'date_creation' => $_SESSION['glpi_currenttime'], 'date_mod' => $_SESSION['glpi_currenttime'], ]; - $this->array($value)->isEqualTo($expected); + $this->assertEquals($expected, $value); //update port, check metrics $port['ifmtu'] = 1500; @@ -96,9 +96,9 @@ public function testNetworkPortithMetrics() $port['ifinerrors'] = 0; $port['ifouterrors'] = 0; - $this->boolean($netport->update($port + ['id' => $netports_id]))->isTrue(); + $this->assertTrue($netport->update($port + ['id' => $netports_id])); $values = $metrics->getMetrics($netport); - $this->array($values)->hasSize(1); // Still 1 row, as there should be only one row per date + $this->assertCount(1, $values); // Still 1 row, as there should be only one row per date $updated_value = array_pop($values); @@ -113,7 +113,7 @@ public function testNetworkPortithMetrics() 'date_creation' => $_SESSION['glpi_currenttime'], 'date_mod' => $_SESSION['glpi_currenttime'], ]; - $this->array($updated_value)->isEqualTo($expected); + $this->assertEquals($expected, $updated_value); //check logs => no bytes nor errors global $DB; @@ -124,11 +124,10 @@ public function testNetworkPortithMetrics() ] ]); - $this->integer(count($iterator))->isIdenticalTo(2); + $this->assertSame(2, count($iterator)); foreach ($iterator as $row) { - $this->integer($row['id_search_option']) - ->isNotEqualTo(34) //ifinbytes SO from NetworkPort - ->isNotEqualTo(35); //ifinerrors SO from NetworkPort + $this->assertNotEquals(34, $row['id_search_option']); + $this->assertNotEquals(35, $row['id_search_option']); } } } diff --git a/tests/functional/NetworkPortType.php b/phpunit/functional/NetworkPortType.php similarity index 95% rename from tests/functional/NetworkPortType.php rename to phpunit/functional/NetworkPortType.php index 626b5bbae3a..c39c234c311 100644 --- a/tests/functional/NetworkPortType.php +++ b/phpunit/functional/NetworkPortType.php @@ -48,13 +48,16 @@ public function testDefaults() $iterator = $DB->request([ 'FROM' => \NetworkPortType::getTable() ]); - $this->integer(count($iterator))->isGreaterThanOrEqualTo(300); + $this->assertGreaterThanOrEqual( + 300, + count($iterator) + ); $iterator = $DB->request([ 'FROM' => \NetworkPortType::getTable(), 'WHERE' => ['is_importable' => true] ]); - $this->integer(count($iterator))->isIdenticalTo(7); + $this->assertSame(7, count($iterator)); $expecteds = [ [ @@ -111,7 +114,7 @@ public function testDefaults() 'date_creation' => $row['date_creation'], 'date_mod' => $row['date_mod'], ]; - $this->array($row)->isEqualTo($expected); + $this->assertEquals($expected, $row); } } } diff --git a/tests/functional/NetworkPort_NetworkPort.php b/phpunit/functional/NetworkPort_NetworkPort.php similarity index 67% rename from tests/functional/NetworkPort_NetworkPort.php rename to phpunit/functional/NetworkPort_NetworkPort.php index ae08ec6de3b..c067730cf23 100644 --- a/tests/functional/NetworkPort_NetworkPort.php +++ b/phpunit/functional/NetworkPort_NetworkPort.php @@ -55,8 +55,8 @@ private function createPort(\CommonDBTM $asset, string $mac): int 'instantiation_type' => 'NetworkPortEthernet', 'name' => 'eth1', ]); - $this->integer((int)$ports_id)->isGreaterThan(0); - $this->integer((int)countElementsInTable('glpi_logs'))->isGreaterThan($nb_log); + $this->assertGreaterThan(0, (int)$ports_id); + $this->assertGreaterThan($nb_log, (int)countElementsInTable('glpi_logs')); return $ports_id; } @@ -72,18 +72,19 @@ public function testWire() $id_2 = $this->createPort($computer2, '00:24:81:eb:c6:d1'); $wired = new \NetworkPort_NetworkPort(); - $this->integer( + $this->assertGreaterThan( + 0, $wired->add([ 'networkports_id_1' => $id_1, 'networkports_id_2' => $id_2 ]) - )->isGreaterThan(0); + ); - $this->boolean($wired->getFromDBForNetworkPort($id_1))->isTrue(); - $this->boolean($wired->getFromDBForNetworkPort($id_2))->isTrue(); + $this->assertTrue($wired->getFromDBForNetworkPort($id_1)); + $this->assertTrue($wired->getFromDBForNetworkPort($id_2)); - $this->integer($wired->getOppositeContact($id_1))->isIdenticalTo($id_2); - $this->integer($wired->getOppositeContact($id_2))->isIdenticalTo($id_1); + $this->assertSame($id_2, $wired->getOppositeContact($id_1)); + $this->assertSame($id_1, $wired->getOppositeContact($id_2)); } public function testHub() @@ -95,24 +96,24 @@ public function testHub() $wired = new \NetworkPort_NetworkPort(); $hubs_id = $wired->createHub($ports_id); - $this->integer($hubs_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $hubs_id); $unmanaged = new \Unmanaged(); - $this->boolean($unmanaged->getFromDB($hubs_id))->isTrue(); + $this->assertTrue($unmanaged->getFromDB($hubs_id)); - $this->integer($unmanaged->fields['hub'])->isIdenticalTo(1); - $this->string($unmanaged->fields['name'])->isIdenticalTo('Hub'); - $this->integer($unmanaged->fields['entities_id'])->isIdenticalTo(0); - $this->string($unmanaged->fields['comment'])->isIdenticalTo('Port: ' . $ports_id); + $this->assertSame(1, $unmanaged->fields['hub']); + $this->assertSame('Hub', $unmanaged->fields['name']); + $this->assertSame(0, $unmanaged->fields['entities_id']); + $this->assertSame('Port: ' . $ports_id, $unmanaged->fields['comment']); $opposites_id = $wired->getOppositeContact($ports_id); - $this->integer($opposites_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $opposites_id); $netport = new \NetworkPort(); - $this->boolean($netport->getFromDB($opposites_id))->isTrue(); + $this->assertTrue($netport->getFromDB($opposites_id)); - $this->integer($netport->fields['items_id'])->isIdenticalTo($hubs_id); - $this->string($netport->fields['itemtype'])->isIdenticalTo($unmanaged->getType()); - $this->string($netport->fields['name'])->isIdenticalTo('Hub link'); - $this->string($netport->fields['instantiation_type'])->isIdenticalTo(\NetworkPortEthernet::getType()); + $this->assertSame($hubs_id, $netport->fields['items_id']); + $this->assertSame($unmanaged->getType(), $netport->fields['itemtype']); + $this->assertSame('Hub link', $netport->fields['name']); + $this->assertSame(\NetworkPortEthernet::getType(), $netport->fields['instantiation_type']); } } diff --git a/tests/functional/OperatingSystem.php b/phpunit/functional/OperatingSystem.php similarity index 85% rename from tests/functional/OperatingSystem.php rename to phpunit/functional/OperatingSystem.php index c867bc14816..b3497311780 100644 --- a/tests/functional/OperatingSystem.php +++ b/phpunit/functional/OperatingSystem.php @@ -46,7 +46,7 @@ public function getObjectClass() return '\OperatingSystem'; } - public function typenameProvider() + public static function typenameProvider() { return [ [\OperatingSystem::getTypeName(), 'Operating systems'], @@ -66,16 +66,19 @@ protected function getTabs() /** * Create new Operating system in database * - * @return void + * @return \CommonDBTM */ - protected function newInstance() + protected function newInstance(): \CommonDBTM { - $this->newTestedInstance(); - $this->integer( - (int)$this->testedInstance->add([ + $instance = new \OperatingSystem(); + $this->assertGreaterThan( + 0, + $instance->add([ 'name' => 'OS name ' . $this->getUniqueString() ]) - )->isGreaterThan(0); - $this->boolean($this->testedInstance->getFromDB($this->testedInstance->getID()))->isTrue(); + ); + $this->assertTrue($instance->getFromDB($instance->getID())); + + return $instance; } } diff --git a/tests/functional/OperatingSystemArchitecture.php b/phpunit/functional/OperatingSystemArchitecture.php similarity index 85% rename from tests/functional/OperatingSystemArchitecture.php rename to phpunit/functional/OperatingSystemArchitecture.php index ae1d14ecdb1..4c057f72a1c 100644 --- a/tests/functional/OperatingSystemArchitecture.php +++ b/phpunit/functional/OperatingSystemArchitecture.php @@ -46,7 +46,7 @@ public function getObjectClass() return '\OperatingSystemArchitecture'; } - public function typenameProvider() + public static function typenameProvider() { return [ [\OperatingSystemArchitecture::getTypeName(), 'Operating system architectures'], @@ -66,16 +66,18 @@ protected function getTabs() /** * Create new Architecture system in database * - * @return void + * @return \CommonDBTM */ - protected function newInstance() + protected function newInstance(): \CommonDBTM { - $this->newTestedInstance(); - $this->integer( - (int)$this->testedInstance->add([ + $instance = new \OperatingSystemArchitecture(); + $this->assertGreaterThan( + 0, + $instance->add([ 'name' => 'Arch name ' . $this->getUniqueString() ]) - )->isGreaterThan(0); - $this->boolean($this->testedInstance->getFromDB($this->testedInstance->getID()))->isTrue(); + ); + $this->assertTrue($instance->getFromDB($instance->getID())); + return $instance; } } diff --git a/tests/functional/OperatingSystemEdition.php b/phpunit/functional/OperatingSystemEdition.php similarity index 81% rename from tests/functional/OperatingSystemEdition.php rename to phpunit/functional/OperatingSystemEdition.php index e380b107f22..08eed466d2b 100644 --- a/tests/functional/OperatingSystemEdition.php +++ b/phpunit/functional/OperatingSystemEdition.php @@ -46,7 +46,7 @@ public function getObjectClass() return '\OperatingSystemEdition'; } - public function typenameProvider() + public static function typenameProvider() { return [ [\OperatingSystemEdition::getTypeName(), 'Editions'], @@ -58,10 +58,8 @@ public function typenameProvider() public function testMaybeTranslated() { - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->maybeTranslated())->isTrue(); + $instance = $this->newInstance(); + $this->assertTrue($instance->maybeTranslated()); } protected function getTabs() @@ -74,16 +72,18 @@ protected function getTabs() /** * Create new Operating system in database * - * @return void + * @return \CommonDBTM */ - protected function newInstance() + protected function newInstance(): \CommonDBTM { - $this->newTestedInstance(); - $this->integer( - (int)$this->testedInstance->add([ + $instance = new \OperatingSystemEdition(); + $this->assertGreaterThan( + 0, + $instance->add([ 'name' => 'OS name ' . $this->getUniqueString() ]) - )->isGreaterThan(0); - $this->boolean($this->testedInstance->getFromDB($this->testedInstance->getID()))->isTrue(); + ); + $this->assertTrue($instance->getFromDB($instance->getID())); + return $instance; } } diff --git a/tests/functional/OperatingSystemKernel.php b/phpunit/functional/OperatingSystemKernel.php similarity index 85% rename from tests/functional/OperatingSystemKernel.php rename to phpunit/functional/OperatingSystemKernel.php index ad7982c6ee8..b5cdd42792b 100644 --- a/tests/functional/OperatingSystemKernel.php +++ b/phpunit/functional/OperatingSystemKernel.php @@ -46,7 +46,7 @@ public function getObjectClass() return '\OperatingSystemKernel'; } - public function typenameProvider() + public static function typenameProvider() { return [ [\OperatingSystemKernel::getTypeName(), 'Kernels'], @@ -66,16 +66,18 @@ protected function getTabs() /** * Create new Kernel in database * - * @return void + * @return \CommonDBTM */ - protected function newInstance() + protected function newInstance(): \CommonDBTM { - $this->newTestedInstance(); - $this->integer( - (int)$this->testedInstance->add([ + $instance = new \OperatingSystemKernel(); + $this->assertGreaterThan( + 0, + $instance->add([ 'name' => 'Kernel name ' . $this->getUniqueString() ]) - )->isGreaterThan(0); - $this->boolean($this->testedInstance->getFromDB($this->testedInstance->getID()))->isTrue(); + ); + $this->assertTrue($instance->getFromDB($instance->getID())); + return $instance; } } diff --git a/tests/functional/OperatingSystemKernelVersion.php b/phpunit/functional/OperatingSystemKernelVersion.php similarity index 75% rename from tests/functional/OperatingSystemKernelVersion.php rename to phpunit/functional/OperatingSystemKernelVersion.php index c6d3a18166e..d4e2458e2fe 100644 --- a/tests/functional/OperatingSystemKernelVersion.php +++ b/phpunit/functional/OperatingSystemKernelVersion.php @@ -46,7 +46,7 @@ public function getObjectClass() return '\OperatingSystemKernelVersion'; } - public function typenameProvider() + public static function typenameProvider() { return [ [\OperatingSystemKernelVersion::getTypeName(), 'Kernel versions'], @@ -58,17 +58,18 @@ public function typenameProvider() public function testGetAdditionalFields() { - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->getAdditionalFields())->isIdenticalTo([ - [ - 'label' => 'Kernel', - 'name' => 'Kernels', - 'list' => true, - 'type' => 'oskernel' - ] - ]); + $instance = $this->newInstance(); + $this->assertSame( + [ + [ + 'label' => 'Kernel', + 'name' => 'Kernels', + 'list' => true, + 'type' => 'oskernel' + ] + ], + $instance->getAdditionalFields() + ); } protected function getTabs() @@ -81,23 +82,26 @@ protected function getTabs() /** * Create new kernel version in database * - * @return void + * @return \CommonDBTM */ - protected function newInstance() + protected function newInstance(): \CommonDBTM { $kernel = new \OperatingSystemKernel(); - $this->integer( - (int)$kernel->add([ + $this->assertGreaterThan( + 0, + $kernel->add([ 'name' => 'linux' ]) ); - $this->newTestedInstance(); - $this->integer( - (int)$this->testedInstance->add([ + $instance = new \OperatingSystemKernelVersion(); + $this->assertGreaterThan( + 0, + $instance->add([ 'name' => 'Version name ' . $this->getUniqueString(), 'operatingsystemkernels_id' => $kernel->getID() ]) - )->isGreaterThan(0); - $this->boolean($this->testedInstance->getFromDB($this->testedInstance->getID()))->isTrue(); + ); + $this->assertTrue($instance->getFromDB($instance->getID())); + return $instance; } } diff --git a/tests/functional/PCIVendor.php b/phpunit/functional/PCIVendor.php similarity index 67% rename from tests/functional/PCIVendor.php rename to phpunit/functional/PCIVendor.php index 5add2e466ab..cb6365953e0 100644 --- a/tests/functional/PCIVendor.php +++ b/phpunit/functional/PCIVendor.php @@ -43,67 +43,81 @@ class PCIVendor extends DbTestCase { public function testGetList() { - global $DB; - $vendors = new \PCIVendor(); $pciids = $vendors->getList(); $nodb_count = count($pciids); - $this->array($pciids)->size->isGreaterThanOrEqualTo(15000); + $this->assertGreaterThan(15000, $nodb_count); - $this->integer( + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => 'Something to test', 'vendorid' => '01ef', 'deviceid' => '02ef' ]) - )->isGreaterThan(0); + ); $pciids = $vendors->getList(); ++$nodb_count; - $this->array($pciids)->size->isIdenticalTo($nodb_count); + $this->assertCount($nodb_count, $pciids); } public function testGetManufacturer() { $vendors = new \PCIVendor(); - $this->boolean($vendors->getManufacturer('one that does not exists'))->isFalse(); - $this->string($vendors->getManufacturer('0010'))->isIdenticalTo("Allied Telesis, Inc (Wrong ID)"); + $this->assertFalse($vendors->getManufacturer('one that does not exists')); + $this->assertSame( + "Allied Telesis, Inc (Wrong ID)", + $vendors->getManufacturer('0010') + ); - //override - $this->integer( + //override + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => addslashes("UnAllied Telesis, Inc (Good ID)"), 'vendorid' => '0010' ]) - )->isGreaterThan(0); - $this->string($vendors->getManufacturer('0010'))->isIdenticalTo("UnAllied Telesis, Inc (Good ID)"); + ); + $this->assertSame( + "UnAllied Telesis, Inc (Good ID)", + $vendors->getManufacturer('0010') + ); } public function testGetProductName() { $vendors = new \PCIVendor(); - $this->boolean($vendors->getProductName('vendor does not exists', '9139'))->isFalse(); - $this->boolean($vendors->getProductName('0010', 'device does not exists'))->isFalse(); - $this->string($vendors->getProductName('0010', '8139'))->isIdenticalTo('AT-2500TX V3 Ethernet'); + $this->assertFalse($vendors->getProductName('vendor does not exists', '9139')); + $this->assertFalse($vendors->getProductName('0010', 'device does not exists')); + $this->assertSame( + 'AT-2500TX V3 Ethernet', + $vendors->getProductName('0010', '8139') + ); - //override - $this->integer( + //override + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => 'not the good one', 'vendorid' => '0002', 'deviceid' => '8139' ]) - )->isGreaterThan(0); - $this->integer( + ); + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => 'Yeah, that works', 'vendorid' => '0010', 'deviceid' => '8139' ]) - )->isGreaterThan(0); - $this->string($vendors->getProductName('0010', '8139'))->isIdenticalTo('Yeah, that works'); + ); + $this->assertSame( + 'Yeah, that works', + $vendors->getProductName('0010', '8139') + ); } } diff --git a/phpunit/functional/PassiveDCEquipment.php b/phpunit/functional/PassiveDCEquipment.php new file mode 100644 index 00000000000..43125e8208c --- /dev/null +++ b/phpunit/functional/PassiveDCEquipment.php @@ -0,0 +1,141 @@ +. + * + * --------------------------------------------------------------------- + */ + +namespace tests\units; + +use DbTestCase; + +/* Test for inc/passiveDCEquipment.class.php */ + +class PassiveDCEquipment extends DbTestCase +{ + public function testAdd() + { + $obj = new \PassiveDCEquipment(); + + // Add + $id = $obj->add([ + 'name' => __METHOD__, + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) + ]); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); + + // getField methods + $this->assertEquals($id, $obj->getField('id')); + $this->assertSame(__METHOD__, $obj->getField('name')); + + // fields property + $this->assertSame($id, $obj->fields['id']); + $this->assertSame(__METHOD__, $obj->fields['name']); + } + + public function testDelete() + { + $obj = new \PassiveDCEquipment(); + $this->assertTrue($obj->maybeDeleted()); + + // Add + $id = $obj->add([ + 'name' => __METHOD__, + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) + ]); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + $this->assertEquals(0, $obj->isDeleted()); + + // Delete + $this->assertTrue($obj->delete(['id' => $id], 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(1, $obj->getField('is_deleted')); + $this->assertEquals(1, $obj->isDeleted()); + + // Restore + $this->assertTrue($obj->restore(['id' => $id], 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + $this->assertEquals(0, $obj->isDeleted()); + + // Purge + $this->assertTrue($obj->delete(['id' => $id], 1)); + $this->assertFalse($obj->getFromDB($id)); + } + + + public function testDeleteByCriteria() + { + $obj = new \PassiveDCEquipment(); + $this->assertTrue($obj->maybeDeleted()); + + // Add + $id = $obj->add([ + 'name' => __METHOD__, + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) + ]); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + ; + $this->assertEquals(0, $obj->isDeleted()); + $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); + + // DeleteByCriteria without history + $this->assertTrue($obj->deleteByCriteria(['name' => __METHOD__], 0, 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(1, $obj->getField('is_deleted')); + $this->assertEquals(1, $obj->isDeleted()); + + $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); + $this->assertSame($nb_after, $nb_after); + + // Restore + $this->assertTrue($obj->restore(['id' => $id], 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + $this->assertEquals(0, $obj->isDeleted()); + + $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); + + // DeleteByCriteria with history + $this->assertTrue($obj->deleteByCriteria(['name' => __METHOD__], 0, 1)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(1, $obj->getField('is_deleted')); + $this->assertEquals(1, $obj->isDeleted()); + + $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); + $this->assertSame($nb_before + 1, $nb_after); + } +} diff --git a/tests/functional/PrinterLog.php b/phpunit/functional/PrinterLog.php similarity index 86% rename from tests/functional/PrinterLog.php rename to phpunit/functional/PrinterLog.php index 4ee24001c75..e3a428d0bd4 100644 --- a/tests/functional/PrinterLog.php +++ b/phpunit/functional/PrinterLog.php @@ -48,7 +48,7 @@ public function testGetMetrics() 'name' => 'Inventoried printer', 'entities_id' => 0 ]); - $this->integer($printers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $printers_id); $now = new \DateTime(); @@ -65,7 +65,7 @@ public function testGetMetrics() 'scanned' => 7846, 'date' => $cdate1->format('Y-m-d') ]; - $this->integer($log->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, $log->add($input)); $cdate2 = clone $now; $cdate2->sub(new \DateInterval('P6M')); @@ -78,7 +78,7 @@ public function testGetMetrics() 'scanned' => 15542, 'date' => $cdate2->format('Y-m-d') ]; - $this->integer($log->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, $log->add($input)); $input = [ 'printers_id' => $printers_id, @@ -89,12 +89,12 @@ public function testGetMetrics() 'scanned' => 28177, 'date' => $now->format('Y-m-d') ]; - $this->integer($log->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, $log->add($input)); //per default, get 1Y old, first not included - $this->array($log->getMetrics($printer))->hasSize(2); + $this->assertCount(2, $log->getMetrics($printer)); //change filter to include first one - $this->array($log->getMetrics($printer, ['date' => ['>=', $cdate1->format('Y-m-d')]]))->hasSize(3); + $this->assertCount(3, $log->getMetrics($printer, ['date' => ['>=', $cdate1->format('Y-m-d')]])); } } diff --git a/phpunit/functional/PrinterTest.php b/phpunit/functional/PrinterTest.php new file mode 100644 index 00000000000..76328450d66 --- /dev/null +++ b/phpunit/functional/PrinterTest.php @@ -0,0 +1,169 @@ +. + * + * --------------------------------------------------------------------- + */ + +namespace tests\units; + +use DbTestCase; + +/* Test for inc/printer.class.php */ + +class PrinterTest extends DbTestCase +{ + public function testAdd() + { + $obj = new \Printer(); + + // Add + $id = $obj->add([ + 'name' => __METHOD__, + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) + ]); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); + + // getField methods + $this->assertEquals($id, $obj->getField('id')); + $this->assertSame(__METHOD__, $obj->getField('name')); + + // fields property + $this->assertSame($id, $obj->fields['id']); + $this->assertSame(__METHOD__, $obj->fields['name']); + } + + public function testDelete() + { + $obj = new \Printer(); + $this->assertTrue($obj->maybeDeleted()); + + // Add + $id = $obj->add([ + 'name' => __METHOD__, + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) + ]); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + $this->assertEquals(0, $obj->isDeleted()); + + // Delete + $this->assertTrue($obj->delete(['id' => $id], 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(1, $obj->getField('is_deleted')); + $this->assertEquals(1, $obj->isDeleted()); + + // Restore + $this->assertTrue($obj->restore(['id' => $id], 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + $this->assertEquals(0, $obj->isDeleted()); + + // Purge + $this->assertTrue($obj->delete(['id' => $id], 1)); + $this->assertFalse($obj->getFromDB($id)); + } + + public function testVisibility() + { + + $this->login(); + + $p = new \Printer(); + + // Visibility from root + tree + $this->setEntity('_test_root_entity', true); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_all', true), READ)); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_ent0', true), READ)); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_ent1', true), READ)); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_ent2', true), READ)); + + // Visibility from root only + $this->setEntity('_test_root_entity', false); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_all', true), READ)); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_ent0', true), READ)); + $this->assertFalse($p->can(getItemByTypeName('Printer', '_test_printer_ent1', true), READ)); + $this->assertFalse($p->can(getItemByTypeName('Printer', '_test_printer_ent2', true), READ)); + + // Visibility from child + $this->setEntity('_test_child_1', false); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_all', true), READ)); + $this->assertFalse($p->can(getItemByTypeName('Printer', '_test_printer_ent0', true), READ)); + $this->assertTrue($p->can(getItemByTypeName('Printer', '_test_printer_ent1', true), READ)); + $this->assertFalse($p->can(getItemByTypeName('Printer', '_test_printer_ent2', true), READ)); + } + + public function testDeleteByCriteria() + { + $obj = new \Printer(); + $this->assertTrue($obj->maybeDeleted()); + + // Add + $id = $obj->add([ + 'name' => __METHOD__, + 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) + ]); + $this->assertGreaterThan(0, (int)$id); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + ; + $this->assertEquals(0, $obj->isDeleted()); + $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); + + // DeleteByCriteria without history + $this->assertTrue($obj->deleteByCriteria(['name' => __METHOD__], 0, 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(1, $obj->getField('is_deleted')); + $this->assertEquals(1, $obj->isDeleted()); + + $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); + $this->assertSame($nb_after, $nb_after); + + // Restore + $this->assertTrue($obj->restore(['id' => $id], 0)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(0, $obj->getField('is_deleted')); + $this->assertEquals(0, $obj->isDeleted()); + + $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); + + // DeleteByCriteria with history + $this->assertTrue($obj->deleteByCriteria(['name' => __METHOD__], 0, 1)); + $this->assertTrue($obj->getFromDB($id)); + $this->assertEquals(1, $obj->getField('is_deleted')); + $this->assertEquals(1, $obj->isDeleted()); + + $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); + $this->assertSame($nb_before + 1, $nb_after); + } +} diff --git a/tests/functional/ShareDashboardDropdown.php b/phpunit/functional/ShareDashboardDropdown.php similarity index 100% rename from tests/functional/ShareDashboardDropdown.php rename to phpunit/functional/ShareDashboardDropdown.php diff --git a/tests/functional/SoftwareLicense.php b/phpunit/functional/SoftwareLicenseTest.php similarity index 71% rename from tests/functional/SoftwareLicense.php rename to phpunit/functional/SoftwareLicenseTest.php index fac90f6ebfc..6ce68ae56c0 100644 --- a/tests/functional/SoftwareLicense.php +++ b/phpunit/functional/SoftwareLicenseTest.php @@ -42,13 +42,13 @@ /** * @engine isolate */ -class SoftwareLicense extends DbTestCase +class SoftwareLicenseTest extends DbTestCase { public function testTypeName() { - $this->string(\SoftwareLicense::getTypeName(1))->isIdenticalTo('License'); - $this->string(\SoftwareLicense::getTypeName(0))->isIdenticalTo('Licenses'); - $this->string(\SoftwareLicense::getTypeName(10))->isIdenticalTo('Licenses'); + $this->assertSame('License', \SoftwareLicense::getTypeName(1)); + $this->assertSame('Licenses', \SoftwareLicense::getTypeName(0)); + $this->assertSame('Licenses', \SoftwareLicense::getTypeName(10)); } public function testPrepareInputForAdd() @@ -60,7 +60,7 @@ public function testPrepareInputForAdd() 'name' => 'not_inserted_software_license', 'entities_id' => 0 ]; - $this->boolean($license->prepareInputForAdd($input))->isFalse(); + $this->assertFalse($license->prepareInputForAdd($input)); $this->hasSessionMessages(ERROR, ['Please select a software for this license']); //With a softwares_id, import ok @@ -70,7 +70,7 @@ public function testPrepareInputForAdd() 'softwarelicenses_id' => 0, 'level' => 1, 'completename' => 'inserted_sofwarelicense' ]; - $this->array($license->prepareInputForAdd($input))->isIdenticalTo($expected); + $this->assertSame($expected, $license->prepareInputForAdd($input)); //withtemplate, empty 'expire' should be ignored. id will be replaced in _oldID $input = [ 'name' => 'other_inserted_sofwarelicense', 'softwares_id' => 1, @@ -81,7 +81,7 @@ public function testPrepareInputForAdd() 'softwarelicenses_id' => 0, 'level' => 1, 'completename' => 'other_inserted_sofwarelicense', '_oldID' => 1 ]; - $this->array($license->prepareInputForAdd($input))->isIdenticalTo($expected); + $this->assertSame($expected, $license->prepareInputForAdd($input)); } /** @@ -97,8 +97,8 @@ private function createSoft() 'is_template' => 0, 'entities_id' => 0 ]); - $this->integer((int)$softwares_id)->isGreaterThan(0); - $this->boolean($software->getFromDB($softwares_id))->isTrue(); + $this->assertGreaterThan(0, (int)$softwares_id); + $this->assertTrue($software->getFromDB($softwares_id)); return $software; } @@ -110,7 +110,7 @@ public function testAdd() $license = new \SoftwareLicense(); $input = [ 'name' => 'not_inserted_software_license_child']; - $this->boolean($license->add($input))->isFalse(); + $this->assertFalse($license->add($input)); $this->hasSessionMessages(ERROR, ['Please select a software for this license']); $software = $this->createSoft(); @@ -121,13 +121,13 @@ public function testAdd() 'softwares_id' => $software->getID(), 'entities_id' => 0 ]); - $this->integer((int)$parentlicense_id)->isGreaterThan(0); - $this->boolean($parentlicense->getFromDB($parentlicense_id))->isTrue(); + $this->assertGreaterThan(0, (int)$parentlicense_id); + $this->assertTrue($parentlicense->getFromDB($parentlicense_id)); - $this->string($parentlicense->fields['completename'])->isIdenticalTo("a_software_license"); - $this->string($parentlicense->fields['name'])->isIdenticalTo('a_software_license'); - $this->variable($parentlicense->fields['expire'])->isNull(); - $this->variable($parentlicense->fields['level'])->isEqualTo(1); + $this->assertSame("a_software_license", $parentlicense->fields['completename']); + $this->assertSame('a_software_license', $parentlicense->fields['name']); + $this->assertNull($parentlicense->fields['expire']); + $this->assertEquals(1, $parentlicense->fields['level']); $input = [ 'softwares_id' => $software->getID(), @@ -137,13 +137,13 @@ public function testAdd() 'entities_id' => $parentlicense->fields['entities_id'] ]; $lic_id = $license->add($input); - $this->integer($lic_id)->isGreaterThan($parentlicense_id); - $this->boolean($license->getFromDB($lic_id))->isTrue(); + $this->assertGreaterThan($parentlicense_id, $lic_id); + $this->assertTrue($license->getFromDB($lic_id)); - $this->string($license->fields['completename'])->isIdenticalTo("a_software_license > a_child_license"); - $this->string($license->fields['name'])->isIdenticalTo('a_child_license'); - $this->string($license->fields['expire'])->isIdenticalTo('2017-01-01'); - $this->variable($license->fields['level'])->isEqualTo(2); + $this->assertSame("a_software_license > a_child_license", $license->fields['completename']); + $this->assertSame('a_child_license', $license->fields['name']); + $this->assertSame('2017-01-01', $license->fields['expire']); + $this->assertEquals(2, $license->fields['level']); } public function testComputeValidityIndicator() @@ -162,8 +162,8 @@ public function testComputeValidityIndicator() 'entities_id' => 0 ]; $lic_id = $license->add($input); - $this->integer((int)$lic_id)->isGreaterThan(0); - $this->boolean($license->getFromDB($lic_id))->isTrue(); + $this->assertGreaterThan(0, (int)$lic_id); + $this->assertTrue($license->getFromDB($lic_id)); $license_computer = new \Item_SoftwareLicense(); $comp1 = getItemByTypeName('Computer', '_test_pc01'); @@ -176,17 +176,17 @@ public function testComputeValidityIndicator() 'is_deleted' => 0, 'is_dynamic' => 0 ]; - $this->integer((int)$license_computer->add($input_comp))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$license_computer->add($input_comp)); //Test if number is illimited - $this->variable(\SoftwareLicense::computeValidityIndicator($lic_id, -1))->isEqualTo(1); - $this->variable(\SoftwareLicense::computeValidityIndicator($lic_id, 0))->isEqualTo(0); + $this->assertEquals(1, \SoftwareLicense::computeValidityIndicator($lic_id, -1)); + $this->assertEquals(0, \SoftwareLicense::computeValidityIndicator($lic_id, 0)); $input_comp['computers_id'] = $comp2->getID(); - $this->integer((int)$license_computer->add($input_comp))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$license_computer->add($input_comp)); - $this->variable(\SoftwareLicense::computeValidityIndicator($lic_id, 2))->isEqualTo(1); - $this->variable(\SoftwareLicense::computeValidityIndicator($lic_id, 1))->isEqualTo(0); + $this->assertEquals(1, \SoftwareLicense::computeValidityIndicator($lic_id, 2)); + $this->assertEquals(0, \SoftwareLicense::computeValidityIndicator($lic_id, 1)); } public function testPrepareInputForUpdate() @@ -205,11 +205,11 @@ public function testPrepareInputForUpdate() 'entities_id' => 0 ]; $lic_id = $license->add($input); - $this->integer((int)$lic_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$lic_id); $input = ['id' => $lic_id, 'number' => 3]; $expected = ['id' => $lic_id, 'number' => 3, 'is_valid' => 1]; - $this->array($license->prepareInputForUpdate($input))->isIdenticalTo($expected); + $this->assertSame($expected, $license->prepareInputForUpdate($input)); } public function testUpdateValidityIndicator() @@ -228,8 +228,8 @@ public function testUpdateValidityIndicator() 'entities_id' => 0 ]; $lic_id = $license->add($input); - $this->integer((int)$lic_id)->isGreaterThan(0); - $this->boolean($license->getFromDB($lic_id))->isTrue(); + $this->assertGreaterThan(0, (int)$lic_id); + $this->assertTrue($license->getFromDB($lic_id)); $this->createLicenseInstall( $license, @@ -243,7 +243,7 @@ public function testUpdateValidityIndicator() 'items_id' => $comp1->getID(), 'itemtype' => 'Computer' ]; - $this->boolean($license_computer->deleteByCriteria($input, true))->isTrue(); + $this->assertTrue($license_computer->deleteByCriteria($input, true)); $orig_number = $license->getField('number'); //Change the number of assets to 1 @@ -252,14 +252,14 @@ public function testUpdateValidityIndicator() 'number' => 1, ]; $license->update($input); - $this->boolean($license->getFromDB($license->getID()))->isTrue(); + $this->assertTrue($license->getFromDB($license->getID())); - $this->integer((int)$license->getID())->isGreaterThan(0); - $this->variable($input['number'])->isEqualTo($license->fields['number']); + $this->assertGreaterThan(0, (int)$license->getID()); + $this->assertEquals($license->fields['number'], $input['number']); //Update validity indicator $license->updateValidityIndicator($license->getID()); - $this->variable($license->fields['is_valid'])->isEqualTo(0); + $this->assertEquals(0, $license->fields['is_valid']); //cleanup $input = [ @@ -270,7 +270,7 @@ public function testUpdateValidityIndicator() //Update validity indicator $license->updateValidityIndicator($license->fields['id']); - $this->variable($license->fields['is_valid'])->isEqualTo(1); + $this->assertEquals(1, $license->fields['is_valid']); } private function createLicenseInstall(\SoftwareLicense $license, $computers) @@ -291,6 +291,6 @@ private function createInstall($licenses_id, $items_id) 'is_dynamic' => 0, 'is_deleted' => 0 ]; - $this->integer((int)$license_computer->add($input))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$license_computer->add($input)); } } diff --git a/tests/functional/Software.php b/phpunit/functional/SoftwareTest.php similarity index 70% rename from tests/functional/Software.php rename to phpunit/functional/SoftwareTest.php index 590afb03468..3d714b08db6 100644 --- a/tests/functional/Software.php +++ b/phpunit/functional/SoftwareTest.php @@ -39,18 +39,18 @@ /* Test for inc/software.class.php */ -class Software extends DbTestCase +class SoftwareTest extends DbTestCase { public function testTypeName() { - $this->string(\Software::getTypeName(1))->isIdenticalTo('Software'); - $this->string(\Software::getTypeName(0))->isIdenticalTo('Software'); - $this->string(\Software::getTypeName(10))->isIdenticalTo('Software'); + $this->assertSame('Software', \Software::getTypeName(1)); + $this->assertSame('Software', \Software::getTypeName(0)); + $this->assertSame('Software', \Software::getTypeName(10)); } public function testGetMenuShorcut() { - $this->string(\Software::getMenuShorcut())->isIdenticalTo('s'); + $this->assertSame('s', \Software::getMenuShorcut()); } public function testGetTabNameForItem() @@ -63,9 +63,9 @@ public function testGetTabNameForItem() 'is_recursive' => 1 ]; $softwares_id = $software->add($input); - $this->integer((int)$softwares_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softwares_id); $software->getFromDB($softwares_id); - $this->string($software->getTabNameForItem($software, 1))->isEmpty(); + $this->assertEmpty($software->getTabNameForItem($software, 1)); } public function defineTabs() @@ -74,30 +74,30 @@ public function defineTabs() $software = new \Software(); $tabs = $software->defineTabs(); - $this->array($tabs)->hasSize(16); + $this->assertCount(16, $tabs); $_SESSION['glpiactiveprofile']['license'] = 0; $tabs = $software->defineTabs(); - $this->array($tabs)->hasSize(15); + $this->assertCount(15, $tabs); $_SESSION['glpiactiveprofile']['link'] = 0; $tabs = $software->defineTabs(); - $this->array($tabs)->hasSize(14); + $this->assertCount(14, $tabs); $_SESSION['glpiactiveprofile']['infocom'] = 0; $tabs = $software->defineTabs(); - $this->array($tabs)->hasSize(13); + $this->assertCount(13, $tabs); $_SESSION['glpiactiveprofile']['document'] = 0; $tabs = $software->defineTabs(); - $this->array($tabs)->hasSize(12); + $this->assertCount(12, $tabs); } public function testPrepareInputForUpdate() { $software = new \Software(); $result = $software->prepareInputForUpdate(['is_update' => 0]); - $this->array($result)->isIdenticalTo(['is_update' => 0, 'softwares_id' => 0]); + $this->assertSame(['is_update' => 0, 'softwares_id' => 0], $result); } public function testPrepareInputForAdd() @@ -108,13 +108,13 @@ public function testPrepareInputForAdd() $result = $software->prepareInputForAdd($input); $expected = ['name' => 'A name', 'is_update' => 0, 'softwares_id' => 0, '_oldID' => 3, 'softwarecategories_id' => 0]; - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); $input = ['name' => 'A name', 'is_update' => 0, 'withtemplate' => 0]; $result = $software->prepareInputForAdd($input); $expected = ['name' => 'A name', 'is_update' => 0, 'softwares_id' => 0, 'softwarecategories_id' => 0]; - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); $input = ['is_update' => 0, 'withtemplate' => 0, @@ -126,7 +126,7 @@ public function testPrepareInputForAdd() 'softwares_id' => 0 ]; - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } public function testPrepareInputForAddWithCategory() @@ -135,7 +135,7 @@ public function testPrepareInputForAddWithCategory() $criteria = new \RuleCriteria(); $action = new \RuleAction(); - //Create a software category + //Create a software category $category = new \SoftwareCategory(); $categories_id = $category->importExternal('Application'); @@ -147,24 +147,26 @@ public function testPrepareInputForAddWithCategory() 'condition' => 0, 'description' => '' ]); - $this->integer((int)$rules_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$rules_id); - $this->integer( - (int)$criteria->add([ + $this->assertGreaterThan( + 0, + $criteria->add([ 'rules_id' => $rules_id, 'criteria' => 'name', 'condition' => \Rule::PATTERN_IS, 'pattern' => 'MySoft' ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)$action->add(['rules_id' => $rules_id, + $this->assertGreaterThan( + 0, + $action->add(['rules_id' => $rules_id, 'action_type' => 'assign', 'field' => 'softwarecategories_id', 'value' => $categories_id ]) - )->isGreaterThan(0); + ); $input = ['name' => 'MySoft', 'is_update' => 0, @@ -183,7 +185,7 @@ public function testPrepareInputForAddWithCategory() 'softwarecategories_id' => "$categories_id" ]; - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); } public function testPost_addItem() @@ -198,16 +200,16 @@ public function testPost_addItem() 'is_template' => 0, 'entities_id' => 0 ]); - $this->integer((int)$softwares_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softwares_id); - $this->variable($software->fields['is_template'])->isEqualTo(0); - $this->string($software->fields['name'])->isIdenticalTo('MySoft'); + $this->assertEquals(0, $software->fields['is_template']); + $this->assertSame('MySoft', $software->fields['name']); $query = ['itemtype' => 'Software', 'items_id' => $softwares_id]; - $this->integer((int)countElementsInTable('glpi_infocoms', $query))->isIdenticalTo(0); - $this->integer((int)countElementsInTable('glpi_contracts_items', $query))->isIdenticalTo(0); + $this->assertSame(0, (int)countElementsInTable('glpi_infocoms', $query)); + $this->assertSame(0, (int)countElementsInTable('glpi_contracts_items', $query)); - //Force creation of infocom when an asset is added + //Force creation of infocom when an asset is added $CFG_GLPI['auto_create_infocoms'] = 1; $softwares_id = $software->add([ @@ -215,10 +217,10 @@ public function testPost_addItem() 'is_template' => 0, 'entities_id' => 0 ]); - $this->integer((int)$softwares_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softwares_id); $query = ['itemtype' => 'Software', 'items_id' => $softwares_id]; - $this->integer((int)countElementsInTable('glpi_infocoms', $query))->isIdenticalTo(1); + $this->assertSame(1, (int)countElementsInTable('glpi_infocoms', $query)); } public function testPost_addItemWithTemplate() @@ -231,47 +233,52 @@ public function testPost_addItemWithTemplate() 'is_template' => 1, 'template_name' => 'template' ]); - $this->integer((int)$softwares_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $softwares_id); $infocom = new \Infocom(); - $this->integer( - (int)$infocom->add([ + //No idea why, but infocom already exists with phpunit + $infocom->getFromDBByCrit(['itemtype' => 'Software', 'items_id' => $softwares_id]); + $infocom->delete(['id' => $infocom->getID()], true); + $this->assertGreaterThan( + 0, + $infocom->add([ 'itemtype' => 'Software', 'items_id' => $softwares_id, 'value' => '500' ]) - )->isGreaterThan(0); + ); $contract = new \Contract(); $contracts_id = $contract->add([ 'name' => 'contract01', 'entities_id' => 0 ]); - $this->integer((int)$contracts_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$contracts_id); $contract_item = new \Contract_Item(); - $this->integer( - (int)$contract_item->add([ + $this->assertGreaterThan( + 0, + $contract_item->add([ 'itemtype' => 'Software', 'items_id' => $softwares_id, 'contracts_id' => $contracts_id ]) - )->isGreaterThan(0); + ); $softwares_id_2 = $software->add([ 'name' => 'MySoft', 'id' => $softwares_id, 'entities_id' => 0 ]); - $this->integer((int)$softwares_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softwares_id_2); - $this->boolean($software->getFromDB($softwares_id_2))->isTrue(); - $this->variable($software->fields['is_template'])->isEqualTo(0); - $this->string($software->fields['name'])->isIdenticalTo('MySoft'); + $this->assertTrue($software->getFromDB($softwares_id_2)); + $this->assertEquals(0, $software->fields['is_template']); + $this->assertSame('MySoft', $software->fields['name']); $query = ['itemtype' => 'Software', 'items_id' => $softwares_id_2]; - $this->integer((int)countElementsInTable('glpi_infocoms', $query))->isIdenticalTo(1); - $this->integer((int)countElementsInTable('glpi_contracts_items', $query))->isIdenticalTo(1); + $this->assertSame(1, (int)countElementsInTable('glpi_infocoms', $query)); + $this->assertSame(1, (int)countElementsInTable('glpi_contracts_items', $query)); } public function testCleanDBonPurge() @@ -279,7 +286,7 @@ public function testCleanDBonPurge() global $CFG_GLPI; $this->login(); - //Force creation of infocom when an asset is added + //Force creation of infocom when an asset is added $CFG_GLPI['auto_create_infocoms'] = 1; $software = new \Software(); @@ -288,28 +295,29 @@ public function testCleanDBonPurge() 'is_template' => 0, 'entities_id' => 0 ]); - $this->integer((int)$softwares_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$softwares_id); $contract = new \Contract(); $contracts_id = $contract->add([ 'name' => 'contract02', 'entities_id' => 0 ]); - $this->integer((int)$contracts_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$contracts_id); $contract_item = new \Contract_Item(); - $this->integer( - (int)$contract_item->add([ + $this->assertGreaterThan( + 0, + $contract_item->add([ 'itemtype' => 'Software', 'items_id' => $softwares_id, 'contracts_id' => $contracts_id ]) - )->isGreaterThan(0); + ); - $this->boolean($software->delete(['id' => $softwares_id], true))->isTrue(); + $this->assertTrue($software->delete(['id' => $softwares_id], true)); $query = ['itemtype' => 'Software', 'items_id' => $softwares_id]; - $this->integer((int)countElementsInTable('glpi_infocoms', $query))->isIdenticalTo(0); - $this->integer((int)countElementsInTable('glpi_contracts_items', $query))->isIdenticalTo(0); + $this->assertSame(0, (int)countElementsInTable('glpi_infocoms', $query)); + $this->assertSame(0, (int)countElementsInTable('glpi_contracts_items', $query)); //TODO : test Change_Item, Item_Problem, Item_Project } @@ -327,8 +335,8 @@ private function createSoft() 'is_template' => 0, 'entities_id' => 0 ]); - $this->integer((int)$softwares_id)->isGreaterThan(0); - $this->boolean($software->getFromDB($softwares_id))->isTrue(); + $this->assertGreaterThan(0, (int)$softwares_id); + $this->assertTrue($software->getFromDB($softwares_id)); return $software; } @@ -337,7 +345,7 @@ public function testUpdateValidityIndicatorIncreaseDecrease() { $software = $this->createSoft(); - //create a license with 3 installations + //create a license with 3 installations $license = new \SoftwareLicense(); $license_id = $license->add([ 'name' => 'a_software_license', @@ -345,9 +353,9 @@ public function testUpdateValidityIndicatorIncreaseDecrease() 'entities_id' => 0, 'number' => 3 ]); - $this->integer((int)$license_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$license_id); - //attach 2 licenses + //attach 2 licenses $license_computer = new \Item_SoftwareLicense(); foreach (['_test_pc01', '_test_pc02'] as $pcid) { $computer = getItemByTypeName('Computer', $pcid); @@ -358,29 +366,29 @@ public function testUpdateValidityIndicatorIncreaseDecrease() 'is_deleted' => 0, 'is_dynamic' => 0 ]; - $this->integer((int)$license_computer->add($input_comp))->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$license_computer->add($input_comp)); } - $this->boolean($software->getFromDB($software->getID()))->isTrue(); - $this->variable($software->fields['is_valid'])->isEqualTo(1); + $this->assertTrue($software->getFromDB($software->getID())); + $this->assertEquals(1, $software->fields['is_valid']); - //Descrease number to one - $this->boolean( + //Decrease number to one + $this->assertTrue( $license->update(['id' => $license->getID(), 'number' => 1]) - )->isTrue(); + ); \Software::updateValidityIndicator($software->getID()); $software->getFromDB($software->getID()); - $this->variable($software->fields['is_valid'])->isEqualTo(0); + $this->assertEquals(0, $software->fields['is_valid']); - //Increase number to ten - $this->boolean( + //Increase number to ten + $this->assertTrue( $license->update(['id' => $license->getID(), 'number' => 10]) - )->isTrue(); + ); \Software::updateValidityIndicator($software->getID()); $software->getFromDB($software->getID()); - $this->variable($software->fields['is_valid'])->isEqualTo(1); + $this->assertEquals(1, $software->fields['is_valid']); } public function testGetEmpty() @@ -390,12 +398,12 @@ public function testGetEmpty() $software = new \Software(); $CFG_GLPI['default_software_helpdesk_visible'] = 0; $software->getEmpty(); - $this->variable($software->fields['is_helpdesk_visible'])->isEqualTo(0); + $this->assertEquals(0, $software->fields['is_helpdesk_visible']); $CFG_GLPI['default_software_helpdesk_visible'] = 1; $software->getEmpty(); - $this->variable($software->fields['is_helpdesk_visible'])->isEqualTo(1); + $this->assertEquals(1, $software->fields['is_helpdesk_visible']); } public function testGetSpecificMassiveActions() @@ -404,36 +412,36 @@ public function testGetSpecificMassiveActions() $software = new \Software(); $result = $software->getSpecificMassiveActions(); - $this->array($result)->hasSize(5); + $this->assertCount(5, $result); $all_rights = $_SESSION['glpiactiveprofile']['software']; $_SESSION['glpiactiveprofile']['software'] = 0; $result = $software->getSpecificMassiveActions(); - $this->array($result)->isEmpty(); + $this->assertEmpty($result); $_SESSION['glpiactiveprofile']['software'] = READ; $result = $software->getSpecificMassiveActions(); - $this->array($result)->isEmpty(); + $this->assertEmpty($result); $_SESSION['glpiactiveprofile']['software'] = $all_rights; $_SESSION['glpiactiveprofile']['knowbase'] = 0; $result = $software->getSpecificMassiveActions(); - $this->array($result)->hasSize(4); + $this->assertCount(4, $result); $_SESSION['glpiactiveprofile']['rule_dictionnary_software'] = 0; $result = $software->getSpecificMassiveActions(); - $this->array($result)->hasSize(4); + $this->assertCount(4, $result); } public function testGetSearchOptionsNew() { $software = new \Software(); $result = $software->rawSearchOptions(); - $this->array($result)->hasSize(43); + $this->assertCount(43, $result); $this->login(); $result = $software->rawSearchOptions(); - $this->array($result)->hasSize(59); + $this->assertCount(59, $result); } } diff --git a/tests/functional/SoftwareVersion.php b/phpunit/functional/SoftwareVersion.php similarity index 90% rename from tests/functional/SoftwareVersion.php rename to phpunit/functional/SoftwareVersion.php index 008a0028d56..45f975b6879 100644 --- a/tests/functional/SoftwareVersion.php +++ b/phpunit/functional/SoftwareVersion.php @@ -44,10 +44,10 @@ class SoftwareVersion extends DbTestCase { public function testDropdownForOneSoftware() { - $this - ->string(CoreSoftwareVersion::dropdownForOneSoftware([ - "display" => false - ])) - ->isNotEmpty(); + $this->assertNotEmpty( + CoreSoftwareVersion::dropdownForOneSoftware([ + "display" => false + ]) + ); } } diff --git a/tests/functional/Telemetry.php b/phpunit/functional/Telemetry.php similarity index 73% rename from tests/functional/Telemetry.php rename to phpunit/functional/Telemetry.php index 3fce4601a78..bfcac1c4d38 100644 --- a/tests/functional/Telemetry.php +++ b/phpunit/functional/Telemetry.php @@ -69,73 +69,80 @@ public function testGrabGlpiInfos() ]; $result = \Telemetry::grabGlpiInfos(); - $this->string($result['uuid']) - ->hasLength(40); + $this->assertEquals(40, strlen($result['uuid'])); $expected['uuid'] = $result['uuid']; $expected['plugins'] = $result['plugins']; - $this->array($result)->isIdenticalTo($expected); + $this->assertSame($expected, $result); $plugins = new \Plugin(); - $this->integer((int)$plugins->add(['directory' => 'testplugin', - 'name' => 'testplugin', - 'version' => '0.x.z' - ])) - ->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $plugins->add(['directory' => 'testplugin', + 'name' => 'testplugin', + 'version' => '0.x.z' + ]) + ); $expected['plugins'][] = [ 'key' => 'testplugin', 'version' => '0.x.z' ]; - $this->array(\Telemetry::grabGlpiInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabGlpiInfos()); - //enable ldap server + //enable ldap server $ldap = getItemByTypeName('AuthLDAP', '_local_ldap'); - $this->boolean($ldap->update([ - 'id' => $ldap->getID(), - 'is_active' => true - ]))->isTrue(); + $this->assertTrue( + $ldap->update([ + 'id' => $ldap->getID(), + 'is_active' => true + ]) + ); $expected['usage']['ldap_enabled'] = true; - $this->array(\Telemetry::grabGlpiInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabGlpiInfos()); $groups = new \Group(); for ($i = 0; $i < 501; $i++) { - $this->integer( - (int)$groups->add(['name' => 'Tele test']) - )->isGreaterThan(0); + $this->assertGreaterThan( + 0, + $groups->add(['name' => 'Tele test']) + ); } $expected['usage']['avg_groups'] = '500-1000'; - $this->array(\Telemetry::grabGlpiInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabGlpiInfos()); global $CFG_GLPI; $CFG_GLPI['use_notifications'] = 1; - $this->array(\Telemetry::grabGlpiInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabGlpiInfos()); $CFG_GLPI['notifications_mailing'] = 1; $CFG_GLPI['notifications_ajax'] = 1; $expected['usage']['notifications'] = ['mailing', 'ajax']; - $this->array(\Telemetry::grabGlpiInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabGlpiInfos()); $collector = new \MailCollector(); - $this->integer( - (int)$collector->add([ + $this->assertGreaterThan( + 0, + $collector->add([ 'name' => 'Collector1', 'is_active' => 1 ]) - )->isGreaterThan(0); + ); $expected['usage']['mailcollector_enabled'] = true; - $this->array(\Telemetry::grabGlpiInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabGlpiInfos()); - $this->boolean($collector->update([ - 'id' => $collector->getID(), - 'is_active' => false - ]))->isTrue(); + $this->assertTrue( + $collector->update([ + 'id' => $collector->getID(), + 'is_active' => false + ]) + ); $expected['usage']['mailcollector_enabled'] = false; - $this->array(\Telemetry::grabGlpiInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabGlpiInfos()); } public function testGrabDbInfos() @@ -152,9 +159,9 @@ public function testGrabDbInfos() 'sql_mode' => $dbinfos['Server SQL Mode'] ]; $infos = \Telemetry::grabDbInfos(); - $this->string($infos['size'])->isNotEmpty(); + $this->assertNotEmpty($infos['size']); $expected['size'] = $infos['size']; - $this->array($infos)->isIdenticalTo($expected); + $this->assertSame($expected, $infos); } public function testGrabPhpInfos() @@ -172,17 +179,14 @@ public function testGrabPhpInfos() ] ]; - $this->array(\Telemetry::grabPhpInfos())->isIdenticalTo($expected); + $this->assertSame($expected, \Telemetry::grabPhpInfos()); } public function testGrabOsInfos() { - $expected = [ - 'family', - 'distribution', - 'version' - ]; $osinfos = \Telemetry::grabOsInfos(); - $this->array($osinfos)->hasKeys($expected); + $this->assertArrayHasKey('family', $osinfos); + $this->assertArrayHasKey('distribution', $osinfos); + $this->assertArrayHasKey('version', $osinfos); } } diff --git a/tests/functional/Toolbox.php b/phpunit/functional/ToolboxTest.php similarity index 81% rename from tests/functional/Toolbox.php rename to phpunit/functional/ToolboxTest.php index 911af81e74c..cfa9308ad7b 100644 --- a/tests/functional/Toolbox.php +++ b/phpunit/functional/ToolboxTest.php @@ -51,26 +51,26 @@ /* Test for inc/toolbox.class.php */ -class Toolbox extends DbTestCase +class ToolboxTest extends DbTestCase { public function testGetRandomString() { for ($len = 20; $len < 50; $len += 5) { // Low strength $str = \Toolbox::getRandomString($len); - $this->integer(strlen($str))->isIdenticalTo($len); - $this->boolean(ctype_alnum($str))->isTrue(); + $this->assertSame($len, strlen($str)); + $this->assertTrue(ctype_alnum($str)); } } - protected function slugifyProvider() + public static function slugifyProvider() { return [ [ 'string' => 'My - string èé Ê À ß', 'expected' => 'my-string-ee-e-a-ss' ], [ - //https://github.com/glpi-project/glpi/issues/2946 + //https://github.com/glpi-project/glpi/issues/2946 'string' => 'Έρευνα ικανοποίησης - Αιτήματα', 'expected' => 'ereuna-ikanopoieses-aitemata' ], [ @@ -85,17 +85,17 @@ protected function slugifyProvider() */ public function testSlugify($string, $expected) { - $this->string(\Toolbox::slugify($string))->isIdenticalTo($expected); + $this->assertSame($expected, \Toolbox::slugify($string)); } - protected function filenameProvider() + public static function filenameProvider() { return [ [ 'name' => '00-logoteclib.png', 'expected' => '00-logoteclib.png', ], [ - // Space is missing between "France" and "très" due to a bug in laminas-mail + // Space is missing between "France" and "très" due to a bug in laminas-mail 'name' => '01-Screenshot-2018-4-12 Observatoire - Francetrès haut débit.png', 'expected' => '01-screenshot-2018-4-12-observatoire-francetres-haut-debit.png', ], [ @@ -137,11 +137,11 @@ protected function filenameProvider() */ public function testFilename($name, $expected) { - $this->string(\Toolbox::filename($name))->isIdenticalTo($expected); - $this->integer(strlen($expected))->isLessThanOrEqualTo(255); + $this->assertSame($expected, \Toolbox::filename($name)); + $this->assertLessThanOrEqual(255, strlen($expected)); } - public function dataGetSize() + public static function dataGetSize() { return [ [1, '1 o'], @@ -160,31 +160,37 @@ public function dataGetSize() */ public function testGetSize($input, $expected) { - $this->string(\Toolbox::getSize($input))->isIdenticalTo($expected); + $this->assertSame($expected, \Toolbox::getSize($input)); } public function testGetIPAddress() { - // Save values + // Save values $saveServer = $_SERVER; - // Test REMOTE_ADDR + // Test REMOTE_ADDR $_SERVER['REMOTE_ADDR'] = '123.123.123.123'; $ip = \Toolbox::getRemoteIpAddress(); - $this->variable($ip)->isEqualTo('123.123.123.123'); + $this->assertEquals('123.123.123.123', $ip); - // Restore values + // Restore values $_SERVER = $saveServer; } public function testFormatOutputWebLink() { - $this->string(\Toolbox::formatOutputWebLink('www.glpi-project.org/')) - ->isIdenticalTo('http://www.glpi-project.org/'); - $this->string(\Toolbox::formatOutputWebLink('http://www.glpi-project.org/')) - ->isIdenticalTo('http://www.glpi-project.org/'); - $this->string(\Toolbox::formatOutputWebLink('https://www.glpi-project.org/')) - ->isIdenticalTo('https://www.glpi-project.org/'); + $this->assertSame( + 'http://www.glpi-project.org/', + \Toolbox::formatOutputWebLink('www.glpi-project.org/') + ); + $this->assertSame( + 'http://www.glpi-project.org/', + \Toolbox::formatOutputWebLink('http://www.glpi-project.org/') + ); + $this->assertSame( + 'https://www.glpi-project.org/', + \Toolbox::formatOutputWebLink('https://www.glpi-project.org/') + ); } public function testgetBijectiveIndex() @@ -200,11 +206,11 @@ public function testgetBijectiveIndex() 703 => 'AAA', ] as $number => $bij_string ) { - $this->string(\Toolbox::getBijectiveIndex($number))->isIdenticalTo($bij_string); + $this->assertSame($bij_string, \Toolbox::getBijectiveIndex($number)); } } - protected function cleanIntegerProvider() + public static function cleanIntegerProvider() { return [ [1, '1'], @@ -220,10 +226,10 @@ protected function cleanIntegerProvider() */ public function testCleanInteger($value, $expected) { - $this->variable(\Toolbox::cleanInteger($value))->isIdenticalTo($expected); + $this->assertSame($expected, \Toolbox::cleanInteger($value)); } - protected function jsonDecodeProvider() + public static function jsonDecodeProvider() { return [ [ @@ -244,13 +250,11 @@ protected function jsonDecodeProvider() */ public function testJsonDecode($json, $expected) { - $this - ->variable(\Toolbox::jsonDecode($json, true)) - ->isIdenticalTo($expected); + $this->assertSame($expected, \Toolbox::jsonDecode($json, true)); } - protected function isJSONProvider() + public static function isJSONProvider() { return [ [ @@ -287,11 +291,12 @@ protected function isJSONProvider() /** * @dataProvider isJsonProvider */ - public function testIsJSON($json, $expected) + public function testIsJSON($json, bool $expected) { - $this - ->variable(\Toolbox::isJSON($json, true)) - ->isIdenticalTo($expected); + $this->assertSame( + $expected, + \Toolbox::isJSON($json) + ); } @@ -299,11 +304,11 @@ public function testIsJSON($json, $expected) public function testInvalidJsonDecode() { $invalid = '"Monitor":"6","Computer":"35"'; - $this->variable(\Toolbox::jsonDecode($invalid, true))->isIdenticalTo($invalid); + $this->assertSame($invalid, \Toolbox::jsonDecode($invalid, true)); $this->hasPhpLogRecordThatContains('Unable to decode JSON string! Is this really JSON?', LogLevel::NOTICE); } - protected function ucProvider() + public static function ucProvider() { return [ ['hello you', 'Hello you'], @@ -318,10 +323,10 @@ protected function ucProvider() */ public function testUcfirst($in, $out) { - $this->string(\Toolbox::ucfirst($in))->isIdenticalTo($out); + $this->assertSame($out, \Toolbox::ucfirst($in)); } - protected function shortcutProvider() + public static function shortcutProvider() { return [ ['My menu', 'm', 'My menu'], @@ -336,10 +341,10 @@ protected function shortcutProvider() */ public function testShortcut($string, $letter, $expected) { - $this->string(\Toolbox::shortcut($string, $letter))->isIdenticalTo($expected); + $this->assertSame($expected, \Toolbox::shortcut($string, $letter)); } - protected function strposProvider() + public static function strposProvider() { return [ ['Where is Charlie?', 'W', 0, 0], @@ -359,10 +364,13 @@ protected function strposProvider() */ public function testStrpos($string, $search, $offset, $expected) { - $this->variable(\Toolbox::strpos($string, $search, $offset))->isIdenticalTo($expected); + $this->assertSame( + $expected, + \Toolbox::strpos($string, $search, $offset) + ); } - protected function padProvider() + public static function padProvider() { return [ ['GLPI', 10, " ", STR_PAD_RIGHT, 'GLPI '], @@ -380,11 +388,13 @@ protected function padProvider() */ public function testStr_pad($string, $length, $char, $pad, $expected) { - $this->string(\Toolbox::str_pad($string, $length, $char, $pad)) - ->isIdenticalTo($expected); + $this->assertSame( + $expected, + \Toolbox::str_pad($string, $length, $char, $pad) + ); } - protected function strlenProvider() + public static function strlenProvider() { return [ ['GLPI', 4], @@ -397,10 +407,10 @@ protected function strlenProvider() */ public function testStrlen($string, $length) { - $this->integer(\Toolbox::strlen($string))->isIdenticalTo($length); + $this->assertSame($length, \Toolbox::strlen($string)); } - protected function substrProvider() + public static function substrProvider() { return [ ['I want a substring', 0, -1, 'I want a substring'], @@ -417,11 +427,13 @@ protected function substrProvider() */ public function testSubstr($string, $start, $length, $expected) { - $this->string(\Toolbox::substr($string, $start, $length)) - ->isIdenticalTo($expected); + $this->assertSame( + $expected, + \Toolbox::substr($string, $start, $length) + ); } - protected function lowercaseProvider() + public static function lowercaseProvider() { return [ ['GLPI', 'glpi'], @@ -435,10 +447,10 @@ protected function lowercaseProvider() */ public function testStrtolower($upper, $lower) { - $this->string(\Toolbox::strtolower($upper))->isIdenticalTo($lower); + $this->assertSame($lower, \Toolbox::strtolower($upper)); } - protected function uppercaseProvider() + public static function uppercaseProvider() { return [ ['glpi', 'GLPI'], @@ -452,10 +464,10 @@ protected function uppercaseProvider() */ public function testStrtoupper($lower, $upper) { - $this->string(\Toolbox::strtoupper($lower))->isIdenticalTo($upper); + $this->assertSame($upper, \Toolbox::strtoupper($lower)); } - protected function utfProvider() + public static function utfProvider() { return [ ['a simple string', true], @@ -470,37 +482,37 @@ protected function utfProvider() */ public function testSeems_utf8($string, $utf) { - $this->boolean(\Toolbox::seems_utf8($string))->isIdenticalTo($utf); + $this->assertSame($utf, \Toolbox::seems_utf8($string)); } public function testSaveAndDeletePicture() { - // Save an image twice + // Save an image twice $test_file = __DIR__ . '/../files/test.png'; copy(__DIR__ . '/../../pics/add_dropdown.png', $test_file); // saved image will be removed from FS $first_pict = \Toolbox::savePicture($test_file); - $this->string($first_pict)->matches('#[^/]+/.+\.png#'); // generated random name inside subdir + $this->assertMatchesRegularExpression('#[^/]+/.+\.png#', $first_pict); // generated random name inside subdir copy(__DIR__ . '/../../pics/add_dropdown.png', $test_file); // saved image will be removed from FS $second_pict = \Toolbox::savePicture($test_file); - $this->string($second_pict)->matches('#[^/]+/.+\.png#'); // generated random name inside subdir + $this->assertMatchesRegularExpression('#[^/]+/.+\.png#', $second_pict); // generated random name inside subdir - // Check that second saving of same image is not overriding first saved image. - $this->string($first_pict)->isNotEqualTo($second_pict); + // Check that second saving of same image is not overriding first saved image. + $this->assertNotEquals($second_pict, $first_pict); - // Delete saved images - $this->boolean(\Toolbox::deletePicture($first_pict))->isTrue(); - $this->boolean(\Toolbox::deletePicture($second_pict))->isTrue(); + // Delete saved images + $this->assertTrue(\Toolbox::deletePicture($first_pict)); + $this->assertTrue(\Toolbox::deletePicture($second_pict)); - // Save not an image - $this->boolean(\Toolbox::savePicture(__DIR__ . '/../notanimage.jpg'))->isFalse(); + // Save not an image + $this->assertFalse(\Toolbox::savePicture(__DIR__ . '/../notanimage.jpg')); - // Save and delete unexisting files - $this->boolean(\Toolbox::savePicture('notafile.jpg'))->isFalse(); - $this->boolean(\Toolbox::deletePicture('notafile.jpg'))->isFalse(); + // Save and delete nonexistent files + $this->assertFalse(\Toolbox::savePicture('notafile.jpg')); + $this->assertFalse(\Toolbox::deletePicture('notafile.jpg')); } - protected function getPictureUrlProvider() + public static function getPictureUrlProvider() { global $CFG_GLPI; @@ -525,7 +537,7 @@ protected function getPictureUrlProvider() */ public function testGetPictureUrl($path, $url) { - $this->variable(\Toolbox::getPictureUrl($path))->isIdenticalTo($url); + $this->assertSame($url, \Toolbox::getPictureUrl($path)); } /** @@ -596,26 +608,29 @@ public function testConvertTagToImage($item, $expected_url) 'mime' => 'image/png', 'tag' => $img_tag, ]); - $this->integer((int)$doc_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id); $content_text = ''; $expected_url = str_replace('{docid}', $doc_id, $expected_url); $expected_result = '' . $img_tag . ''; // Processed data is expected to be sanitized, and expected result should remain sanitized - $this->string( + $this->assertEquals( + Sanitizer::sanitize($expected_result), \Toolbox::convertTagToImage(Sanitizer::sanitize($content_text), $item, [$doc_id => ['tag' => $img_tag]]) - )->isEqualTo(Sanitizer::sanitize($expected_result)); + ); // Processed data may also be escaped using Toolbox::addslashes_deep(), and expected result should be escaped too - $this->string( + $this->assertEquals( + \Toolbox::addslashes_deep($expected_result), \Toolbox::convertTagToImage(\Toolbox::addslashes_deep($content_text), $item, [$doc_id => ['tag' => $img_tag]]) - )->isEqualTo(\Toolbox::addslashes_deep($expected_result)); + ); // Processed data may also be not sanitized, and expected result should not be sanitized - $this->string( + $this->assertEquals( + $expected_result, \Toolbox::convertTagToImage($content_text, $item, [$doc_id => ['tag' => $img_tag]]) - )->isEqualTo($expected_result); + ); } /** @@ -654,7 +669,7 @@ public function testBaseUrlInConvertTagToImage($url_base, $item, $expected_url) $img_tag = uniqid('', true); - // Create document in DB + // Create document in DB $document = new \Document(); $doc_id = $document->add([ 'name' => 'basic document', @@ -662,25 +677,25 @@ public function testBaseUrlInConvertTagToImage($url_base, $item, $expected_url) 'mime' => 'image/png', 'tag' => $img_tag, ]); - $this->integer((int)$doc_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id); $content_text = ''; $expected_url = str_replace('{docid}', $doc_id, $expected_url); $expected_result = '' . $img_tag . ''; - // Save old config + // Save old config global $CFG_GLPI; $old_url_base = $CFG_GLPI['url_base']; - // Get result + // Get result $CFG_GLPI['url_base'] = $url_base; $result = \Toolbox::convertTagToImage($content_text, $item, [$doc_id => ['tag' => $img_tag]]); - // Restore config + // Restore config $CFG_GLPI['url_base'] = $old_url_base; - // Validate result - $this->string($result)->isEqualTo($expected_result); + // Validate result + $this->assertEquals($expected_result, $result); } /** @@ -704,7 +719,7 @@ public function testConvertTagToImageWithMultipleInlinedImg() 'mime' => 'image/png', 'tag' => $img_tag_1, ]); - $this->integer((int)$doc_id_1)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id_1); $document = new \Document(); $doc_id_2 = $document->add([ @@ -713,7 +728,7 @@ public function testConvertTagToImageWithMultipleInlinedImg() 'mime' => 'image/png', 'tag' => $img_tag_2, ]); - $this->integer((int)$doc_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id_2); $document = new \Document(); $doc_id_3 = $document->add([ @@ -722,7 +737,7 @@ public function testConvertTagToImageWithMultipleInlinedImg() 'mime' => 'image/png', 'tag' => $img_tag_3, ]); - $this->integer((int)$doc_id_3)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id_3); $doc_data = [ $doc_id_1 => ['tag' => $img_tag_1], @@ -741,19 +756,22 @@ public function testConvertTagToImageWithMultipleInlinedImg() } // Processed data is expected to be sanitized, and expected result should remain sanitized - $this->string( + $this->assertEquals( + Sanitizer::sanitize($expected_result), \Toolbox::convertTagToImage(Sanitizer::sanitize($content_text), $item, $doc_data) - )->isEqualTo(Sanitizer::sanitize($expected_result)); + ); // Processed data may also be escaped using Toolbox::addslashes_deep(), and expected result should be escaped too - $this->string( + $this->assertEquals( + \Toolbox::addslashes_deep($expected_result), \Toolbox::convertTagToImage(\Toolbox::addslashes_deep($content_text), $item, $doc_data) - )->isEqualTo(\Toolbox::addslashes_deep($expected_result)); + ); // Processed data may also be not sanitized, and expected result should not be sanitized - $this->string( + $this->assertEquals( + $expected_result, \Toolbox::convertTagToImage($content_text, $item, $doc_data) - )->isEqualTo($expected_result); + ); } /** @@ -775,7 +793,7 @@ public function testConvertTagToImageWithMultipleDocMatchesSameTag() 'mime' => 'image/png', 'tag' => $img_tag, ]); - $this->integer((int)$doc_id_1)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id_1); $document = new \Document(); $doc_id_2 = $document->add([ @@ -784,7 +802,7 @@ public function testConvertTagToImageWithMultipleDocMatchesSameTag() 'mime' => 'image/png', 'tag' => $img_tag, ]); - $this->integer((int)$doc_id_2)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id_2); $content_text = ''; $expected_url_1 = '/front/document.send.php?docid=' . $doc_id_1; @@ -798,28 +816,34 @@ public function testConvertTagToImageWithMultipleDocMatchesSameTag() // Processed data is expected to be sanitized, and expected result should remain sanitized - $this->string( + $this->assertEquals( + Sanitizer::sanitize($expected_result_1), \Toolbox::convertTagToImage(Sanitizer::sanitize($content_text), $item, [$doc_id_1 => ['tag' => $img_tag]]) - )->isEqualTo(Sanitizer::sanitize($expected_result_1)); - $this->string( + ); + $this->assertEquals( + Sanitizer::sanitize($expected_result_2), \Toolbox::convertTagToImage(Sanitizer::sanitize($content_text), $item, [$doc_id_2 => ['tag' => $img_tag]]) - )->isEqualTo(Sanitizer::sanitize($expected_result_2)); + ); // Processed data may also be escaped using Toolbox::addslashes_deep(), and expected result should be escaped too - $this->string( + $this->assertEquals( + \Toolbox::addslashes_deep($expected_result_1), \Toolbox::convertTagToImage(\Toolbox::addslashes_deep($content_text), $item, [$doc_id_1 => ['tag' => $img_tag]]) - )->isEqualTo(\Toolbox::addslashes_deep($expected_result_1)); - $this->string( + ); + $this->assertEquals( + \Toolbox::addslashes_deep($expected_result_2), \Toolbox::convertTagToImage(\Toolbox::addslashes_deep($content_text), $item, [$doc_id_2 => ['tag' => $img_tag]]) - )->isEqualTo(\Toolbox::addslashes_deep($expected_result_2)); + ); // Processed data may also be not sanitized, and expected result should not be sanitized - $this->string( + $this->assertEquals( + $expected_result_1, \Toolbox::convertTagToImage($content_text, $item, [$doc_id_1 => ['tag' => $img_tag]]) - )->isEqualTo($expected_result_1); - $this->string( + ); + $this->assertEquals( + $expected_result_2, \Toolbox::convertTagToImage($content_text, $item, [$doc_id_2 => ['tag' => $img_tag]]) - )->isEqualTo($expected_result_2); + ); } /** @@ -841,7 +865,7 @@ public function testConvertTagToImageWithDuplicatedInlinedImg() 'mime' => 'image/png', 'tag' => $img_tag, ]); - $this->integer((int)$doc_id)->isGreaterThan(0); + $this->assertGreaterThan(0, (int)$doc_id); $content_text = ''; $content_text .= $content_text; @@ -852,19 +876,22 @@ public function testConvertTagToImageWithDuplicatedInlinedImg() $expected_result .= $expected_result; // Processed data is expected to be sanitized, and expected result should remain sanitized - $this->string( + $this->assertEquals( + Sanitizer::sanitize($expected_result), \Toolbox::convertTagToImage(Sanitizer::sanitize($content_text), $item, [$doc_id => ['tag' => $img_tag]]) - )->isEqualTo(Sanitizer::sanitize($expected_result)); + ); // Processed data may also be escaped using Toolbox::addslashes_deep(), and expected result should be escaped too - $this->string( + $this->assertEquals( + \Toolbox::addslashes_deep($expected_result), \Toolbox::convertTagToImage(\Toolbox::addslashes_deep($content_text), $item, [$doc_id => ['tag' => $img_tag]]) - )->isEqualTo(\Toolbox::addslashes_deep($expected_result)); + ); // Processed data may also be not sanitized, and expected result should not be sanitized - $this->string( + $this->assertEquals( + $expected_result, \Toolbox::convertTagToImage($content_text, $item, [$doc_id => ['tag' => $img_tag]]) - )->isEqualTo($expected_result); + ); } protected function shortenNumbers() @@ -911,11 +938,13 @@ protected function shortenNumbers() */ public function testShortenNumber($number, int $precision, string $expected) { - $this->string(\Toolbox::shortenNumber($number, $precision, false)) - ->isEqualTo($expected); + $this->assertEquals( + $expected, + \Toolbox::shortenNumber($number, $precision, false) + ); } - protected function colors() + public static function colors() { return [ [ @@ -943,11 +972,13 @@ protected function colors() */ public function testGetFgColor(string $bg_color, int $offset, string $fg_color) { - $this->string(\Toolbox::getFgColor($bg_color, $offset)) - ->isEqualTo($fg_color); + $this->assertEquals( + $fg_color, + \Toolbox::getFgColor($bg_color, $offset) + ); } - protected function testIsCommonDBTMProvider() + public static function testIsCommonDBTMProvider() { return [ [ @@ -974,10 +1005,13 @@ protected function testIsCommonDBTMProvider() */ public function testIsCommonDBTM(string $class, bool $is_commondbtm) { - $this->boolean(\Toolbox::isCommonDBTM($class))->isEqualTo($is_commondbtm); + $this->assertSame( + $is_commondbtm, + \Toolbox::isCommonDBTM($class) + ); } - protected function testIsAPIDeprecatedProvider() + public static function testIsAPIDeprecatedProvider() { return [ [ @@ -1004,10 +1038,13 @@ protected function testIsAPIDeprecatedProvider() */ public function testIsAPIDeprecated(string $class, bool $is_deprecated) { - $this->boolean(\Toolbox::isAPIDeprecated($class))->isEqualTo($is_deprecated); + $this->assertSame( + $is_deprecated, + \Toolbox::isAPIDeprecated($class) + ); } - protected function urlProvider() + public static function urlProvider() { return [ ['http://localhost', true], @@ -1058,53 +1095,52 @@ protected function urlProvider() /** * @dataProvider urlProvider */ - public function testIsValidWebUrl($url, $result) + public function testIsValidWebUrl(string $url, bool $result) { - $this->boolean(\Toolbox::isValidWebUrl($url))->isIdenticalTo((bool)$result, $url); + $this->assertSame( + $result, + \Toolbox::isValidWebUrl($url), + $url + ); } public function testDeprecated() { - $this->when( - function () { - \Toolbox::deprecated('Calling this function is deprecated'); - } - )->error() - ->withType(E_USER_DEPRECATED) - ->withMessage('Calling this function is deprecated') - ->exists(); + \Toolbox::deprecated('Calling this function is deprecated'); + $this->hasPhpLogRecordThatContains( + 'Calling this function is deprecated', + LogLevel::NOTICE + ); + } + public function testDeprecatedPast() + { // Test planned deprecation in the past - $this->when( - function () { - \Toolbox::deprecated('Calling this function is deprecated', true, '10.0'); - } - )->error() - ->withType(E_USER_DEPRECATED) - ->withMessage('Calling this function is deprecated') - ->exists(); + \Toolbox::deprecated('Calling this function is deprecated', true, '10.0'); + $this->hasPhpLogRecordThatContains( + 'Calling this function is deprecated', + LogLevel::NOTICE + ); + } + public function testDeprecatedCurrent() + { // Test planned deprecation in current version - $this->when( - function () { - \Toolbox::deprecated('Calling this function is deprecated', true, GLPI_VERSION); - } - )->error() - ->withType(E_USER_DEPRECATED) - ->withMessage('Calling this function is deprecated') - ->exists(); - - // Test planned deprecation in the future - $this->when( - function () { - \Toolbox::deprecated('Calling this function is deprecated', true, '99.0'); - } - )->error() - ->withType(E_USER_DEPRECATED) - ->withMessage('Calling this function is deprecated') - ->notExists(); + \Toolbox::deprecated('Calling this function is deprecated', true, GLPI_VERSION); + $this->hasPhpLogRecordThatContains( + 'Calling this function is deprecated', + LogLevel::NOTICE + ); + } + + public function testFutureDeprecated() + { + // Test planned deprecation in the future does NOT throw an error + \Toolbox::deprecated('Calling this function is deprecated', true, '99.0'); + $this->assertTrue(true); //non empty test } + public function hasTraitProvider() { return [ @@ -1125,20 +1161,20 @@ public function hasTraitProvider() /** * @dataProvider hasTraitProvider */ - public function testHasTrait($class, $trait, $result) + public function testHasTrait(string $class, string $trait, bool $result) { - $this->boolean(\Toolbox::hasTrait($class, $trait))->isIdenticalTo((bool)$result); + $this->assertSame($result, \Toolbox::hasTrait($class, $trait)); } public function testGetDocumentsFromTag() { // No tag provided in the tested text $output = \Toolbox::getDocumentsFromTag(''); - $this->array($output)->hasSize(0); + $this->AssertCount(0, $output); // Create a document to emulate a document upload $filename = 'foo.png'; - copy(__DIR__ . '/../fixtures/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); + copy(__DIR__ . '/../../tests/fixtures/uploads/foo.png', GLPI_TMP_DIR . '/' . $filename); $tag = \Rule::getUuid(); $input = [ 'filename' => 'foo.png', @@ -1154,10 +1190,10 @@ public function testGetDocumentsFromTag() ]; $document = new \Document(); $document->add($input); - $this->boolean($document->isnewItem())->isFalse(); + $this->assertFalse($document->isnewItem()); $output = \Toolbox::getDocumentsFromTag("foo #$tag# bar "); - $this->array($output)->hasSize(1); + $this->AssertCount(1, $output); } public function appendParametersProvider() @@ -1214,7 +1250,7 @@ public function appendParametersProvider() */ public function testAppendParameters(array $params, string $separator, string $expected) { - $this->string(\Toolbox::append_params($params, $separator))->isEqualTo($expected); + $this->assertEquals($expected, \Toolbox::append_params($params, $separator)); } /** @@ -1286,7 +1322,7 @@ protected function testIsFloatProvider(): Generator /** * Tests for Toolbox::IsFloat() * - * @dataprovider testIsFloatProvider + * @dataProvider testIsFloatProvider * * @param mixed $value * @param bool $expected @@ -1296,21 +1332,14 @@ protected function testIsFloatProvider(): Generator */ public function testIsFloat($value, bool $expected, ?string $warning = null): void { - $result = null; - - if (! is_null($warning)) { - $this->when(function () use ($value, &$result) { - $result = \Toolbox::isFloat($value); - }) - ->error() - ->withType(E_USER_WARNING) - ->withMessage($warning) - ->exists(); - } else { - $result = \Toolbox::isFloat($value); + $result = \Toolbox::isFloat($value); + $this->assertEquals($expected, $result); + if (!is_null($warning)) { + $this->hasPhpLogRecordThatContains( + $warning, + LogLevel::WARNING + ); } - - $this->boolean($result)->isEqualTo($expected); } /** @@ -1377,7 +1406,7 @@ protected function testgetDecimalNumbersProvider(): Generator /** * Tests for Toolbox::getDecimalNumbers() * - * @dataprovider testgetDecimalNumbersProvider + * @dataProvider testgetDecimalNumbersProvider * * @param mixed $value * @param int $decimals @@ -1387,21 +1416,14 @@ protected function testgetDecimalNumbersProvider(): Generator */ public function testGetDecimalNumbers($value, int $decimals, ?string $warning = null): void { - $result = null; - - if (! is_null($warning)) { - $this->when(function () use ($value, &$result) { - $result = \Toolbox::getDecimalNumbers($value); - }) - ->error() - ->withType(E_USER_WARNING) - ->withMessage($warning) - ->exists(); - } else { - $result = \Toolbox::getDecimalNumbers($value); + $result = \Toolbox::getDecimalNumbers($value); + $this->assertEquals($decimals, $result); + if (!is_null($warning)) { + $this->hasPhpLogRecordThatContains( + $warning, + LogLevel::WARNING + ); } - - $this->integer($result)->isEqualTo($decimals); } /** @@ -1470,7 +1492,7 @@ protected function testGetMioSizeFromStringProvider(): Generator /** * Tests for Toolbox::getMioSizeFromString() * - * @dataprovider testGetMioSizeFromStringProvider + * @dataProvider testGetMioSizeFromStringProvider * * @param string $value * @param mixed $expected @@ -1480,7 +1502,7 @@ protected function testGetMioSizeFromStringProvider(): Generator public function testGetMioSizeFromString(string $size, $expected): void { $result = \Toolbox::getMioSizeFromString($size); - $this->variable($result)->isEqualTo($expected); + $this->assertEquals($expected, $result); } protected function safeUrlProvider(): iterable @@ -1565,6 +1587,6 @@ public function testIsUrlSafe(string $url, bool $expected, ?array $allowlist = n if ($allowlist !== null) { $params[] = $allowlist; } - $this->boolean(call_user_func_array('Toolbox::isUrlSafe', $params))->isEqualTo($expected); + $this->assertSame($expected, call_user_func_array('Toolbox::isUrlSafe', $params)); } } diff --git a/tests/functional/Transfer.php b/phpunit/functional/Transfer.php similarity index 69% rename from tests/functional/Transfer.php rename to phpunit/functional/Transfer.php index 82be989b25c..d7c49f650e7 100644 --- a/tests/functional/Transfer.php +++ b/phpunit/functional/Transfer.php @@ -51,9 +51,9 @@ public function testTransfer() { $this->login(); - //Original entity + //Original entity $fentity = (int)getItemByTypeName('Entity', '_test_root_entity', true); - //Destination entity + //Destination entity $dentity = (int)getItemByTypeName('Entity', '_test_child_2', true); $location_id = getItemByTypeName('Location', '_location01', true); @@ -66,25 +66,25 @@ public function testTransfer() '/^DB.*/', '/^SlaLevel.*/', '/^OlaLevel.*/', - 'Event', - 'Glpi\\Event', - 'KnowbaseItem', + '/^Event$/', + '/^Glpi\\Event$/', + '/^KnowbaseItem$/', '/SavedSearch.*/', '/.*Notification.*/', '/^Device.*/', '/^Network.*/', - 'IPNetwork', - 'FQDN', + '/^IPNetwork$/', + '/^FQDN$/', '/^SoftwareVersion.*/', '/^SoftwareLicense.*/', - 'FieldUnicity', - 'PurgeLogs', - 'TicketRecurrent', - 'Agent', - 'USBVendor', - 'PCIVendor', - 'PendingReasonCron', - 'Netpoint', + '/^FieldUnicity$/', + '/^PurgeLogs$/', + '/^TicketRecurrent$/', + '/^Agent$/', + '/^USBVendor$/', + '/^PCIVendor$/', + '/^PendingReasonCron$/', + '/^Netpoint$/', ] ); @@ -100,7 +100,7 @@ public function testTransfer() $count = 0; foreach ($itemtypeslist as $itemtype) { if (is_a($itemtype, \CommonDBConnexity::class, true)) { - // Do not check transfer of child items, they are not supposed to be transfered directly. + // Do not check transfer of child items, they are not supposed to be transferred directly. continue; } @@ -114,7 +114,7 @@ public function testTransfer() continue; } - // Add + // Add $input = []; foreach ($fields_values as $field => $value) { if ($obj->isField($field)) { @@ -127,14 +127,19 @@ public function testTransfer() } $id = $obj->add($input); - $this->integer((int)$id)->isGreaterThan(0, "Cannot add $itemtype"); - $this->boolean($obj->getFromDB($id))->isTrue(); + $this->assertGreaterThan( + 0, + $id, + "Cannot add $itemtype" + ); + $this->assertTrue($obj->getFromDB($id)); - //transer to another entity + //transfer to another entity $transfer = new \Transfer(); - $this->mockGenerator->orphanize('__construct'); - $ma = new \mock\MassiveAction([], [], 'process'); + $ma = $this->getMockBuilder(\MassiveAction::class) + ->disableOriginalConstructor() + ->getMock(); \MassiveAction::processMassiveActionsForOneItemtype( $ma, @@ -144,8 +149,12 @@ public function testTransfer() $transfer->moveItems([$itemtype => [$id]], $dentity, [$id]); unset($_SESSION['glpitransfer_list']); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->integer((int)$obj->fields['entities_id'])->isidenticalTo($dentity, "Transfer has failed on $itemtype"); + $this->assertTrue($obj->getFromDB($id)); + $this->assertSame( + $dentity, + $obj->fields['entities_id'], + "Transfer has failed on $itemtype" + ); ++$count; } @@ -155,12 +164,12 @@ public function testDomainTransfer() { $this->login(); - //Original entity + //Original entity $fentity = (int)getItemByTypeName('Entity', '_test_root_entity', true); - //Destination entity + //Destination entity $dentity = (int)getItemByTypeName('Entity', '_test_child_2', true); - //records types + //records types $type_a = (int)getItemByTypeName('DomainRecordType', 'A', true); $type_cname = (int)getItemByTypeName('DomainRecordType', 'CNAME', true); @@ -171,44 +180,48 @@ public function testDomainTransfer() 'name' => 'glpi-project.org', 'entities_id' => $fentity ]); - $this->integer($did)->isGreaterThan(0); - $this->boolean($domain->getFromDB($did))->isTrue(); + $this->assertGreaterThan(0, $did); + $this->assertTrue($domain->getFromDB($did)); - $this->integer( - (int)$record->add([ + $this->assertGreaterThan( + 0, + $record->add([ 'name' => 'glpi-project.org.', 'type' => $type_a, 'data' => '127.0.1.1', 'entities_id' => $fentity, 'domains_id' => $did ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)$record->add([ + $this->assertGreaterThan( + 0, + $record->add([ 'name' => 'www.glpi-project.org.', 'type' => $type_cname, 'data' => 'glpi-project.org.', 'entities_id' => $fentity, 'domains_id' => $did ]) - )->isGreaterThan(0); + ); - $this->integer( - (int)$record->add([ + $this->assertGreaterThan( + 0, + $record->add([ 'name' => 'doc.glpi-project.org.', 'type' => $type_cname, 'data' => 'glpi-doc.rtfd.io', 'entities_id' => $fentity, 'domains_id' => $did ]) - )->isGreaterThan(0); + ); - //transer to another entity + //transfer to another entity $transfer = new \Transfer(); - $this->mockGenerator->orphanize('__construct'); - $ma = new \mock\MassiveAction([], [], 'process'); + $ma = $this->getMockBuilder(\MassiveAction::class) + ->disableOriginalConstructor() + ->getMock(); \MassiveAction::processMassiveActionsForOneItemtype( $ma, @@ -218,8 +231,8 @@ public function testDomainTransfer() $transfer->moveItems(['Domain' => [$did]], $dentity, [$did]); unset($_SESSION['glpitransfer_list']); - $this->boolean($domain->getFromDB($did))->isTrue(); - $this->integer((int)$domain->fields['entities_id'])->isidenticalTo($dentity); + $this->assertTrue($domain->getFromDB($did)); + $this->assertSame($dentity, (int)$domain->fields['entities_id']); global $DB; $records = $DB->request([ @@ -229,17 +242,17 @@ public function testDomainTransfer() ] ]); - $this->integer(count($records))->isidenticalTo(3); + $this->assertSame(3, count($records)); foreach ($records as $rec) { - $this->integer((int)$rec['entities_id'])->isidenticalTo($dentity); + $this->assertSame($dentity, (int)$rec['entities_id']); } } - protected function testKeepSoftwareOptionProvider(): array + private function testKeepSoftwareOptionData(): array { $test_entity = getItemByTypeName('Entity', '_test_root_entity', true); - // Create test computers + // Create test computers $computers_to_create = [ 'test_transfer_pc_1', 'test_transfer_pc_2', @@ -252,10 +265,10 @@ protected function testKeepSoftwareOptionProvider(): array 'name' => $computer_name, 'entities_id' => $test_entity, ]); - $this->integer($computers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $computers_id); } - // Create test software + // Create test software $softwares_to_create = [ 'test_transfer_software_1', 'test_transfer_software_2', @@ -267,10 +280,10 @@ protected function testKeepSoftwareOptionProvider(): array 'name' => $software_name, 'entities_id' => $test_entity, ]); - $this->integer($softwares_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $softwares_id); } - // Create test software versions + // Create test software versions $softwareversion_ids = []; $software_versions_to_create = [ 'test_transfer_software_1' => ['V1', 'V2'], @@ -285,12 +298,12 @@ protected function testKeepSoftwareOptionProvider(): array 'softwares_id' => getItemByTypeName('Software', $software_name, true), 'entities_id' => $test_entity, ]); - $this->integer($softwareversions_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $softwareversions_id); $softwareversion_ids[] = $softwareversions_id; } } - // Link softwares and computers + // Link software and computers $item_softwareversion_ids = []; $item_softwareversion_to_create = [ 'test_transfer_pc_1' => ['test_transfer_software_1::V1', 'test_transfer_software_2::V1'], @@ -307,7 +320,7 @@ protected function testKeepSoftwareOptionProvider(): array 'softwareversions_id' => getItemByTypeName('SoftwareVersion', $version, true), 'entities_id' => $test_entity, ]); - $this->integer($item_softwareversions_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $item_softwareversions_id); $item_softwareversion_ids[] = $item_softwareversions_id; } } @@ -372,59 +385,59 @@ protected function testKeepSoftwareOptionProvider(): array ]; } - /** - * @dataProvider testKeepSoftwareOptionProvider - */ - public function testKeepSoftwareOption( - array $items, - int $entities_id_destination, - array $transfer_options, - array $expected_softwares_after_transfer, - array $expected_softwares_version_after_transfer - ): void { - $tranfer = new \Transfer(); - $tranfer->moveItems($items, $entities_id_destination, $transfer_options); - - foreach ($items as $itemtype => $ids) { - foreach ($ids as $id) { - //check item_software - $item_softwareversion = new Item_SoftwareVersion(); - $data = $item_softwareversion->find([ - 'items_id' => $id, - 'itemtype' => $itemtype - ]); - - $found_ids = array_column($data, 'id'); - $this->array($found_ids)->isEqualTo($expected_softwares_after_transfer[$itemtype][$id]); - - if (!empty($data)) { - foreach ($data as $db_field) { - //check entity foreach Item_SoftwareVersion - $this->integer($db_field['entities_id'])->isEqualTo($entities_id_destination); - - //check SoftwareVersion attached to Item_SoftwareVersion - $softwareversion = new SoftwareVersion(); - $softwareversion->getFromDB($db_field['softwareversions_id']); - - $softversion_id = $softwareversion->fields['id']; - $soft_id = $softwareversion->fields['softwares_id']; - - //check SoftwareVersion exist from expected - $this->array($expected_softwares_version_after_transfer['Software'][$soft_id])->contains($softversion_id); - //check entity for SoftwareVersion - $this->integer($softwareversion->fields['entities_id'])->isEqualTo($entities_id_destination); + public function testKeepSoftwareOption(): void + { + $data = $this->testKeepSoftwareOptionData(); + foreach ($data as $test_row) { + $items = $test_row['items']; + $entities_id_destination = $test_row['entities_id_destination']; + $transfer_options = $test_row['transfer_options']; + $expected_softwares_after_transfer = $test_row['expected_softwares_after_transfer']; + $expected_softwares_version_after_transfer = $test_row['expected_softwares_version_after_transfer']; + + $tranfer = new \Transfer(); + $tranfer->moveItems($items, $entities_id_destination, $transfer_options); + + foreach ($items as $itemtype => $ids) { + foreach ($ids as $id) { + //check item_software + $item_softwareversion = new Item_SoftwareVersion(); + $data = $item_softwareversion->find([ + 'items_id' => $id, + 'itemtype' => $itemtype + ]); + + $found_ids = array_column($data, 'id'); + $this->assertEquals($expected_softwares_after_transfer[$itemtype][$id], $found_ids); + + if (!empty($data)) { + foreach ($data as $db_field) { + //check entity foreach Item_SoftwareVersion + $this->assertEquals($entities_id_destination, $db_field['entities_id']); + + //check SoftwareVersion attached to Item_SoftwareVersion + $softwareversion = new SoftwareVersion(); + $softwareversion->getFromDB($db_field['softwareversions_id']); + + $softversion_id = $softwareversion->fields['id']; + $soft_id = $softwareversion->fields['softwares_id']; + + //check SoftwareVersion exist from expected + $this->assertTrue(in_array($softversion_id, $expected_softwares_version_after_transfer['Software'][$soft_id])); + //check entity for SoftwareVersion + $this->assertEquals($entities_id_destination, $softwareversion->fields['entities_id']); + } } } } } } - - protected function testKeepCertificateOptionProvider(): array + protected function testKeepCertificateOptionData(): array { $test_entity = getItemByTypeName('Entity', '_test_root_entity', true); - // Create test computers + // Create test computers $computers_to_create = [ 'test_transfer_pc_1', 'test_transfer_pc_2', @@ -437,10 +450,10 @@ protected function testKeepCertificateOptionProvider(): array 'name' => $computer_name, 'entities_id' => $test_entity, ]); - $this->integer($computers_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $computers_id); } - // Create test certificates + // Create test certificates $certificates_to_create = [ 'test_transfer_certificate_1', 'test_transfer_certificate_2', @@ -453,10 +466,10 @@ protected function testKeepCertificateOptionProvider(): array 'name' => $certificate_name, 'entities_id' => $test_entity, ]); - $this->integer($certificates_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $certificates_id); } - // Link certificates and computers + // Link certificates and computers $certificate_item_ids = []; $certificate_item_to_create = [ 'test_transfer_pc_1' => 'test_transfer_certificate_1', @@ -471,7 +484,7 @@ protected function testKeepCertificateOptionProvider(): array 'itemtype' => 'Computer', 'certificates_id' => getItemByTypeName('Certificate', $certificate, true) ]); - $this->integer($certificate_items_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $certificate_items_id); $certificate_item_ids[] = $certificate_items_id; } @@ -515,27 +528,31 @@ protected function testKeepCertificateOptionProvider(): array ]; } - /** - * @dataProvider testKeepCertificateOptionProvider - */ - public function testKeepCertificateOption( - array $items, - int $entities_id_destination, - array $transfer_options, - array $expected_certificates_after_transfer - ): void { - $tranfer = new \Transfer(); - $tranfer->moveItems($items, $entities_id_destination, $transfer_options); - - foreach ($items as $itemtype => $ids) { - foreach ($ids as $id) { - $certificate_item = new Certificate_Item(); - $data = $certificate_item->find([ - 'items_id' => $id, - 'itemtype' => $itemtype - ]); - $found_ids = array_column($data, 'id'); - $this->array($found_ids)->isEqualTo($expected_certificates_after_transfer[$itemtype][$id]); + public function testKeepCertificateOption(): void + { + $data = $this->testKeepCertificateOptionData(); + foreach ($data as $test_row) { + $items = $test_row['items']; + $entities_id_destination = $test_row['entities_id_destination']; + $transfer_options = $test_row['transfer_options']; + $expected_certificates_after_transfer = $test_row['expected_certificates_after_transfer']; + + $tranfer = new \Transfer(); + $tranfer->moveItems($items, $entities_id_destination, $transfer_options); + + foreach ($items as $itemtype => $ids) { + foreach ($ids as $id) { + $certificate_item = new Certificate_Item(); + $data = $certificate_item->find([ + 'items_id' => $id, + 'itemtype' => $itemtype + ]); + $found_ids = array_column($data, 'id'); + $this->assertEquals( + $expected_certificates_after_transfer[$itemtype][$id], + $found_ids + ); + } } } } @@ -545,9 +562,9 @@ public function testKeepLocationTransfer() { $this->login(); - //Original entity + //Original entity $fentity = (int)getItemByTypeName('Entity', '_test_root_entity', true); - //Destination entity + //Destination entity $dentity = (int)getItemByTypeName('Entity', '_test_child_2', true); $location = new \Location(); @@ -556,9 +573,8 @@ public function testKeepLocationTransfer() 'entities_id' => $fentity, 'is_recursive' => 1 ]); - $this->integer($location_id)->isGreaterThan(0); - $this->boolean($location->getFromDB($location_id))->isTrue(); - + $this->assertGreaterThan(0, $location_id); + $this->assertTrue($location->getFromDB($location_id)); $ticket = new \Ticket(); $ticket_id = (int)$ticket->add([ @@ -567,33 +583,32 @@ public function testKeepLocationTransfer() 'locations_id' => $location_id, 'entities_id' => $fentity ]); - $this->integer($ticket_id)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($ticket_id))->isTrue(); - + $this->assertGreaterThan(0, $ticket_id); + $this->assertTrue($ticket->getFromDB($ticket_id)); - //transer to another entity + //transfer to another entity $transfer = new \Transfer(); - $this->boolean($transfer->getFromDB(1))->isTrue(); + $this->assertTrue($transfer->getFromDB(1)); //update transfer model to keep location $transfer->fields["keep_location"] = 1; - $this->boolean($transfer->update($transfer->fields))->isTrue(); + $this->assertTrue($transfer->update($transfer->fields)); $item_to_transfer = ["ticket" => [$ticket_id => $ticket_id]]; $transfer->moveItems($item_to_transfer, $dentity, $transfer->fields); //reload ticket - $this->boolean($ticket->getFromDB($ticket_id))->isTrue(); - $this->integer($ticket->fields['locations_id'])->isEqualTo($location_id); + $this->assertTrue($ticket->getFromDB($ticket_id)); + $this->assertEquals($location_id, $ticket->fields['locations_id']); } public function testEmptyLocationTransfer() { $this->login(); - //Original entity + //Original entity $fentity = (int)getItemByTypeName('Entity', '_test_root_entity', true); - //Destination entity + //Destination entity $dentity = (int)getItemByTypeName('Entity', '_test_child_2', true); $location = new \Location(); @@ -602,8 +617,8 @@ public function testEmptyLocationTransfer() 'entities_id' => $fentity, 'is_recursive' => 1 ]); - $this->integer($location_id)->isGreaterThan(0); - $this->boolean($location->getFromDB($location_id))->isTrue(); + $this->assertGreaterThan(0, $location_id); + $this->assertTrue($location->getFromDB($location_id)); $ticket = new \Ticket(); @@ -613,23 +628,23 @@ public function testEmptyLocationTransfer() 'locations_id' => $location_id, 'entities_id' => $fentity ]); - $this->integer($ticket_id)->isGreaterThan(0); - $this->boolean($ticket->getFromDB($ticket_id))->isTrue(); + $this->assertGreaterThan(0, $ticket_id); + $this->assertTrue($ticket->getFromDB($ticket_id)); - //transer to another entity + //transfer to another entity $transfer = new \Transfer(); - $this->boolean($transfer->getFromDB(1))->isTrue(); + $this->assertTrue($transfer->getFromDB(1)); //update transfer model to empty location $transfer->fields["keep_location"] = 0; - $this->boolean($transfer->update($transfer->fields))->isTrue(); + $this->assertTrue($transfer->update($transfer->fields)); $item_to_transfer = ["ticket" => [$ticket_id => $ticket_id]]; $transfer->moveItems($item_to_transfer, $dentity, $transfer->fields); //reload ticket - $this->boolean($ticket->getFromDB($ticket_id))->isTrue(); - $this->integer($ticket->fields['locations_id'])->isEqualTo(0); + $this->assertTrue($ticket->getFromDB($ticket_id)); + $this->assertEquals(0, $ticket->fields['locations_id']); } } diff --git a/tests/functional/USBVendor.php b/phpunit/functional/USBVendor.php similarity index 61% rename from tests/functional/USBVendor.php rename to phpunit/functional/USBVendor.php index 2265cf138ed..03744bd5248 100644 --- a/tests/functional/USBVendor.php +++ b/phpunit/functional/USBVendor.php @@ -43,70 +43,93 @@ class USBVendor extends DbTestCase { public function testGetList() { - global $DB; - $vendors = new \USBVendor(); $usbids = $vendors->getList(); $nodb_count = count($usbids); - $this->array($usbids)->size->isGreaterThanOrEqualTo(20000); + $this->assertGreaterThanOrEqual(20000, $nodb_count); - $this->integer( + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => 'Something to test', 'vendorid' => '01ef', 'deviceid' => '02ef' ]) - )->isGreaterThan(0); + ); $usbids = $vendors->getList(); ++$nodb_count; - $this->array($usbids)->size->isIdenticalTo($nodb_count); + $this->assertCount($nodb_count, $usbids); } public function testGetManufacturer() { $vendors = new \USBVendor(); - $this->boolean($vendors->getManufacturer('one that does not exists'))->isFalse(); - $this->string($vendors->getManufacturer('0001'))->isIdenticalTo("Fry's Electronics"); - $this->string($vendors->getManufacturer('17e9'))->isIdenticalTo("DisplayLink"); - $this->string($vendors->getManufacturer('17E9'))->isIdenticalTo("DisplayLink"); + $this->assertFalse($vendors->getManufacturer('one that does not exists')); + $this->assertSame( + "Fry's Electronics", + $vendors->getManufacturer('0001') + ); + $this->assertSame( + "DisplayLink", + $vendors->getManufacturer('17e9') + ); + $this->assertSame( + "DisplayLink", + $vendors->getManufacturer('17E9') + ); - //override - $this->integer( + //override + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => addslashes("Farnsworth's Electronics"), 'vendorid' => '0001' ]) - )->isGreaterThan(0); - $this->string($vendors->getManufacturer('0001'))->isIdenticalTo("Farnsworth's Electronics"); + ); + $this->assertSame( + "Farnsworth's Electronics", + $vendors->getManufacturer('0001') + ); } public function testGetProductName() { $vendors = new \USBVendor(); - $this->boolean($vendors->getProductName('vendor does not exists', '7778'))->isFalse(); - $this->boolean($vendors->getProductName('0001', 'device does not exists'))->isFalse(); - $this->string($vendors->getProductName('0001', '7778'))->isIdenticalTo('Counterfeit flash drive [Kingston]'); - $this->string($vendors->getProductName('0bdb', '1926'))->isIdenticalTo('H5321 gw Mobile Broadband Module'); + $this->assertFalse($vendors->getProductName('vendor does not exists', '7778')); + $this->assertFalse($vendors->getProductName('0001', 'device does not exists')); + $this->assertSame( + 'Counterfeit flash drive [Kingston]', + $vendors->getProductName('0001', '7778') + ); + $this->assertSame( + 'H5321 gw Mobile Broadband Module', + $vendors->getProductName('0bdb', '1926') + ); - //override - $this->integer( + //override + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => 'not the good one', 'vendorid' => '0002', 'deviceid' => '7778' ]) - )->isGreaterThan(0); - $this->integer( + ); + $this->assertGreaterThan( + 0, $vendors->add([ 'name' => 'Yeah, that works', 'vendorid' => '0001', 'deviceid' => '7778' ]) - )->isGreaterThan(0); - $this->string($vendors->getProductName('0001', '7778'))->isIdenticalTo('Yeah, that works'); + ); + $this->assertSame( + 'Yeah, that works', + $vendors->getProductName('0001', '7778') + ); } } diff --git a/tests/functional/Unmanaged.php b/phpunit/functional/Unmanaged.php similarity index 87% rename from tests/functional/Unmanaged.php rename to phpunit/functional/Unmanaged.php index 3fa34607725..7a705e654f9 100644 --- a/tests/functional/Unmanaged.php +++ b/phpunit/functional/Unmanaged.php @@ -107,7 +107,7 @@ public function testUnmanagedToManaged() 'serial' => 'FOC147UJEU4', 'entities_id' => 0 ]); - $this->integer($networkequipments_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networkequipments_id); $converter = new \Glpi\Inventory\Converter(); $data = json_decode($converter->convert($net_xml_source)); @@ -120,10 +120,10 @@ public function testUnmanagedToManaged() var_dump($error); } } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isIdenticalTo([]); + $this->assertFalse($inventory->inError()); + $this->assertSame([], $inventory->getErrors()); - $this->integer(count($networkEquipment->find(['NOT' => ['name' => ['LIKE', '_test_%']]])))->isIdenticalTo(1); + $this->assertSame(1, count($networkEquipment->find(['NOT' => ['name' => ['LIKE', '_test_%']]]))); //inventory computer $comp_xml_source = " @@ -168,8 +168,8 @@ public function testUnmanagedToManaged() var_dump($error); } } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isIdenticalTo([]); + $this->assertFalse($inventory->inError()); + $this->assertSame([], $inventory->getErrors()); $networkPort = new \NetworkPort(); $networkports = $networkPort->find(['mac' => 'cc:f9:54:a1:03:35']); @@ -184,18 +184,20 @@ public function testUnmanagedToManaged() $networkports = $networkPort->find(['mac' => 'cc:f9:54:a1:03:35']); - $this->integer(count($networkports))->isIdenticalTo( + $this->assertSame( 1, + count($networkports), "The MAC address cc:f9:54:a1:03:35 must be tied to only one port" ); $a_networkport = current($networkports); - $this->integer($a_networkport['id'])->isIdenticalTo( + $this->assertSame( $networkports_id, + $a_networkport['id'], 'The networkport ID is not the same between the unknown device and the computer' ); - $this->string($a_networkport['itemtype'])->isIdenticalTo('Computer'); + $this->assertSame('Computer', $a_networkport['itemtype']); } /** @@ -216,7 +218,7 @@ public function testConvert() 'serial' => 'XXS6BEF3', 'comment' => 'with a comment' ]); - $this->integer($unmanageds_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $unmanageds_id); // * Add networkport $netport = new \NetworkPort(); @@ -228,7 +230,7 @@ public function testConvert() 'mac' => '00:00:00:43:ae:0f', 'is_dynamic' => 1 ]); - $this->integer($networkports_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networkports_id); $netname = new \NetworkName(); $networknames_id = $netname->add([ @@ -237,10 +239,11 @@ public function testConvert() 'name' => '', 'is_dynamic' => 1 ]); - $this->integer($networknames_id)->isGreaterThan(0); + $this->assertGreaterThan(0, $networknames_id); $ip = new \IPAddress(); - $this->integer( + $this->assertGreaterThan( + 0, $ip->add([ 'entities_id' => 0, 'itemtype' => $netname->getType(), @@ -248,28 +251,30 @@ public function testConvert() 'name' => '192.168.20.1', 'is_dynamic' => 1 ]) - )->isGreaterThan(0); + ); //convert to NetworkEquipment $unmanaged->convert($unmanageds_id); - $this->integer( + $this->assertSame( + 1, countElementsInTable(\NetworkEquipment::getTable(), ['NOT' => ['name' => ['LIKE', '_test_%']]]), 'No NetworkEquipment added' - )->isIdenticalTo(1); + ); - $this->integer( + $this->assertSame( + 0, countElementsInTable(\Unmanaged::getTable(), ['NOT' => ['name' => ['LIKE', '_test_%']]]), 'Unmanaged has not been deleted' - )->isIdenticalTo(0); + ); $neteq = new \NetworkEquipment(); - $this->boolean($neteq->getFromDBByCrit(['name' => 'switch']))->isTrue(); + $this->assertTrue($neteq->getFromDBByCrit(['name' => 'switch'])); - $this->string($neteq->fields['serial'])->isIdenticalTo('XXS6BEF3'); - $this->integer($neteq->fields['is_dynamic'])->isIdenticalTo(1); - $this->string($neteq->fields['comment'])->isIdenticalTo('with a comment'); - $this->string($neteq->fields['sysdescr'])->isIdenticalTo('Any Cisco equipment'); + $this->assertSame('XXS6BEF3', $neteq->fields['serial']); + $this->assertSame(1, $neteq->fields['is_dynamic']); + $this->assertSame('with a comment', $neteq->fields['comment']); + $this->assertSame('Any Cisco equipment', $neteq->fields['sysdescr']); $netport->getFromDBByCrit([]); unset($netport->fields['date_mod']); @@ -304,7 +309,7 @@ public function testConvert() 'trunk' => 0, 'lastup' => null ]; - $this->array($netport->fields)->isEqualTo($expected); + $this->assertEquals($expected, $netport->fields); $netname->getFromDBByCrit(['items_id' => $networkports_id]); unset($netname->fields['date_mod']); @@ -322,7 +327,7 @@ public function testConvert() 'is_deleted' => 0, 'is_dynamic' => 1, ]; - $this->array($netname->fields)->isEqualTo($expected); + $this->assertEquals($expected, $netname->fields); $ip->getFromDBByCrit(['name' => '192.168.20.1']); $expected = [ @@ -341,6 +346,6 @@ public function testConvert() 'mainitemtype' => 'NetworkEquipment' ]; unset($ip->fields['id']); - $this->array($ip->fields)->isEqualTo($expected); + $this->assertEquals($expected, $ip->fields); } } diff --git a/src/AbstractRightsDropdown.php b/src/AbstractRightsDropdown.php index 964b44de307..728c3f873c8 100644 --- a/src/AbstractRightsDropdown.php +++ b/src/AbstractRightsDropdown.php @@ -284,7 +284,7 @@ protected static function getGroups(string $text): array * 3 => 'groups_id-78', * 4 => 'profiles_id-1', * ] - * into an array containings the ids of the specified $class parameter: + * into an array containing the ids of the specified $class parameter: * $class = User -> [3, 14] * $class = Group -> [2, 78] * $class = Profile -> [1] @@ -302,7 +302,7 @@ public static function getPostedIds(array $values, string $class): array // Split fkey and ids $parsed_values = explode("-", $value); $fkey = $parsed_values[0]; - $value = $parsed_values[1]; + $value = (int)$parsed_values[1]; if ($fkey == $class::getForeignKeyField()) { $inflated_values[] = $value; diff --git a/src/Application/ErrorHandler.php b/src/Application/ErrorHandler.php index c24d55cffe0..c7edff1d028 100644 --- a/src/Application/ErrorHandler.php +++ b/src/Application/ErrorHandler.php @@ -225,8 +225,10 @@ public function setOutputHandler(OutputInterface $output_handler): void public function register(): void { set_error_handler([$this, 'handleError']); - set_exception_handler([$this, 'handleException']); - register_shutdown_function([$this, 'handleFatalError']); + if (!defined('TU_USER')) { + set_exception_handler([$this, 'handleException']); + register_shutdown_function([$this, 'handleFatalError']); + } $this->reserved_memory = str_repeat('x', 50 * 1024); // reserve 50 kB of memory space } diff --git a/src/DbUtils.php b/src/DbUtils.php index 2b8f44ff056..2671cf3bdbb 100644 --- a/src/DbUtils.php +++ b/src/DbUtils.php @@ -387,12 +387,14 @@ public function fixItemtypeCase(string $itemtype, $root_dir = GLPI_ROOT) } if ( - ( - $mapping[$context] !== null - && ($_SESSION['glpi_use_mode'] ?? null) !== Session::DEBUG_MODE - && !defined('TU_USER') + !defined('TU_USER') + && ( + ( + $mapping[$context] !== null + && ($_SESSION['glpi_use_mode'] ?? null) !== Session::DEBUG_MODE + ) + || in_array($context, $already_scanned) ) - || in_array($context, $already_scanned) ) { // Do not scan class files if mapping was already cached, unless debug mode is used. // diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 24182f1457c..4d5fc964397 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -92,11 +92,10 @@ // There is no need to pollute the output with error messages. ini_set('display_errors', 'Off'); ErrorHandler::getInstance()->disableOutput(); -// To ensure that errors/exceptions will be catched by `atoum`, unregister GLPI error/exception handlers. +// To prevent errors caught by `error` asserter to also generate logs, unregister GLPI error handler. // Errors that are pushed directly to logs (SQL errors/warnings for instance) will still have to be explicitely // validated by `$this->has*LogRecord*()` asserters, otherwise it will make make test fails. set_error_handler(null); -set_exception_handler(null); include_once __DIR__ . '/GLPITestCase.php'; include_once __DIR__ . '/DbTestCase.php'; @@ -114,6 +113,4 @@ die("\nDevelopment dependencies not found\n\nrun: composer install -o\n\n"); } - - loadDataset(); diff --git a/tests/functional/Agent.php b/tests/functional/Agent.php deleted file mode 100644 index cbc027df24d..00000000000 --- a/tests/functional/Agent.php +++ /dev/null @@ -1,500 +0,0 @@ -. - * - * --------------------------------------------------------------------- - */ - -namespace tests\units; - -use DbTestCase; - -class Agent extends DbTestCase -{ - const INV_FIXTURES = GLPI_ROOT . '/vendor/glpi-project/inventory_format/examples/'; - - public function testDefineTabs() - { - $expected = [ - 'Agent$main' => 'Agent', - 'RuleMatchedLog$0' => 'Import information', - ]; - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->defineTabs()) - ->isIdenticalTo($expected); - } - - public function testHandleAgent() - { - $metadata = [ - 'deviceid' => 'glpixps-2018-07-09-09-07-13', - 'version' => 'FusionInventory-Agent_v2.5.2-1.fc31', - 'itemtype' => 'Computer', - 'tag' => '000005', - 'port' => '62354', - 'enabled-tasks' => [ - "inventory", - "netdiscovery", - "netinventory", - "remoteinventory", - "wakeonlan", - ] - ]; - - $this - ->given($this->newTestedInstance) - ->then - ->integer($this->testedInstance->handleAgent($metadata)) - ->isGreaterThan(0); - - // This should also work when inventory type is different than agent linked item type - $metadata['itemtype'] = 'Printer'; - - $this - ->given($this->newTestedInstance) - ->then - ->integer($this->testedInstance->handleAgent($metadata)) - ->isGreaterThan(0); - - // In the case the agent is used to submit another item type, we still - // need to have access to agent tag but no item should be linked - $tag = $this->testedInstance->fields['tag']; - $port = $this->testedInstance->fields['port']; - $items_id = $this->testedInstance->fields['items_id']; - $this->string($tag)->isIdenticalTo('000005'); - $this->string($port)->isIdenticalTo('62354'); - - $this->integer($this->testedInstance->fields['use_module_computer_inventory'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_network_discovery'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_network_inventory'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_remote_inventory'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_wake_on_lan'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_esx_remote_inventory'])->isIdenticalTo(0); - $this->integer($this->testedInstance->fields['use_module_package_deployment'])->isIdenticalTo(0); - $this->integer($this->testedInstance->fields['use_module_collect_data'])->isIdenticalTo(0); - } - - public function testHandleAgentWOType() - { - global $DB; - - //explicitly remove agent type - $this->boolean( - $DB->delete( - \AgentType::getTable(), - [ - 'name' => 'Core' - ] - ) - )->isTrue(); - //then rerun tests - $this->testHandleAgent(); - } - - public function testHandleAgentOnUpdate() - { - $metadata = [ - 'deviceid' => 'glpixps-2018-07-09-09-07-13', - 'version' => 'FusionInventory-Agent_v2.5.2-1.fc31', - 'itemtype' => 'Computer', - 'tag' => '000006', - 'port' => '62354', - 'enabled-tasks' => [ - "inventory", - "remoteinventory", - "wakeonlan", - "collect", - "esx", - ] - ]; - - $this - ->given($this->newTestedInstance) - ->then - ->integer($this->testedInstance->handleAgent($metadata)) - ->isGreaterThan(0); - - // This should also work when inventory type is different than agent linked item type - $metadata['itemtype'] = 'Printer'; - - $this - ->given($this->newTestedInstance) - ->then - ->integer($this->testedInstance->handleAgent($metadata)) - ->isGreaterThan(0); - - // In the case the agent is used to submit another item type, we still - // need to have access to agent tag but no item should be linked - $tag = $this->testedInstance->fields['tag']; - $port = $this->testedInstance->fields['port']; - $items_id = $this->testedInstance->fields['items_id']; - $this->string($tag)->isIdenticalTo('000006'); - $this->string($port)->isIdenticalTo('62354'); - - $this->integer($this->testedInstance->fields['use_module_computer_inventory'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_network_discovery'])->isIdenticalTo(0); - $this->integer($this->testedInstance->fields['use_module_network_inventory'])->isIdenticalTo(0); - $this->integer($this->testedInstance->fields['use_module_remote_inventory'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_wake_on_lan'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_esx_remote_inventory'])->isIdenticalTo(1); - $this->integer($this->testedInstance->fields['use_module_package_deployment'])->isIdenticalTo(0); - $this->integer($this->testedInstance->fields['use_module_collect_data'])->isIdenticalTo(1); - } - - public function testAgentFeaturesFromItem() - { - //run an inventory - $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); - $inventory = new \Glpi\Inventory\Inventory($json); - - if ($inventory->inError()) { - foreach ($inventory->getErrors() as $error) { - var_dump($error); - } - } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); - - //check inventory metadata - $metadata = $inventory->getMetadata(); - $this->array($metadata)->hasSize(7) - ->string['deviceid']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['version']->isIdenticalTo('FusionInventory-Agent_v2.5.2-1.fc31') - ->string['itemtype']->isIdenticalTo('Computer') - ->string['action']->isIdenticalTo('inventory') - ->variable['port']->isIdenticalTo(null) - ->string['tag']->isIdenticalTo('000005'); - $this->array($metadata['provider'])->hasSize(10); - - global $DB; - //check created agent - $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); - $agents = $DB->request(['FROM' => \Agent::getTable()]); - $this->integer(count($agents))->isIdenticalTo(1); - $agent = $agents->current(); - $this->array($agent) - ->string['deviceid']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['name']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['version']->isIdenticalTo('2.5.2-1.fc31') - ->string['itemtype']->isIdenticalTo('Computer') - ->integer['agenttypes_id']->isIdenticalTo($agenttype['id']); - - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->getFromDB($agent['id'])) - ->isTrue(); - - $item = $this->testedInstance->getLinkedItem(); - $this->object($item)->isInstanceOf('Computer'); - - $this->array($this->testedInstance->guessAddresses())->isIdenticalTo([ - 'glpixps', - '192.168.1.142', - '[fe80::b283:4fa3:d3f2:96b1]', - '192.168.1.118', - '[fe80::92a4:26c6:99dd:2d60]', - '192.168.122.1' - ]); - - $this->array($this->testedInstance->getAgentURLs())->isIdenticalTo([ - 'http://glpixps:62354', - 'http://192.168.1.142:62354', - 'http://[fe80::b283:4fa3:d3f2:96b1]:62354', - 'http://192.168.1.118:62354', - 'http://[fe80::92a4:26c6:99dd:2d60]:62354', - 'http://192.168.122.1:62354', - 'https://glpixps:62354', - 'https://192.168.1.142:62354', - 'https://[fe80::b283:4fa3:d3f2:96b1]:62354', - 'https://192.168.1.118:62354', - 'https://[fe80::92a4:26c6:99dd:2d60]:62354', - 'https://192.168.122.1:62354' - ]); - - //link a domain to item and see if adresses are still ok - $domain = new \Domain(); - $did = $domain->add([ - 'name' => 'glpi-project.org' - ]); - $this->integer($did)->isGreaterThan(0); - - $ditem = new \Domain_Item(); - $this->integer( - $ditem->add([ - 'itemtype' => $item->getType(), - 'items_id' => $item->getID(), - 'domains_id' => $did - ]) - )->isGreaterThan(0); - - $this->array($this->testedInstance->guessAddresses())->isIdenticalTo([ - 'glpixps', - '192.168.1.142', - '[fe80::b283:4fa3:d3f2:96b1]', - '192.168.1.118', - '[fe80::92a4:26c6:99dd:2d60]', - '192.168.122.1', - 'glpixps.glpi-project.org' - ]); - } - - public function testAgentHasChanged() - { - //run an inventory - $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); - $inventory = new \Glpi\Inventory\Inventory($json); - - if ($inventory->inError()) { - foreach ($inventory->getErrors() as $error) { - var_dump($error); - } - } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); - - //check inventory metadata - $metadata = $inventory->getMetadata(); - $this->array($metadata)->hasSize(7) - ->string['deviceid']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['version']->isIdenticalTo('FusionInventory-Agent_v2.5.2-1.fc31') - ->string['itemtype']->isIdenticalTo('Computer') - ->string['action']->isIdenticalTo('inventory') - ->variable['port']->isIdenticalTo(null) - ->string['tag']->isIdenticalTo('000005'); - $this->array($metadata['provider'])->hasSize(10); - - global $DB; - //check created agent - $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); - $agents = $DB->request(['FROM' => \Agent::getTable()]); - $this->integer(count($agents))->isIdenticalTo(1); - $agent = $agents->current(); - $this->array($agent) - ->string['deviceid']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['name']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['version']->isIdenticalTo('2.5.2-1.fc31') - ->string['itemtype']->isIdenticalTo('Computer') - ->string['tag']->isIdenticalTo('000005') - ->integer['agenttypes_id']->isIdenticalTo($agenttype['id']); - $old_agents_id = $agent['id']; - - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->getFromDB($agent['id'])) - ->isTrue(); - - $item = $this->testedInstance->getLinkedItem(); - $this->object($item)->isInstanceOf('Computer'); - - //play an update with changes - $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); - - //change agent and therefore deviceid - $json->content->versionclient = 'GLPI-Agent_v1'; - $json->deviceid = 'glpixps-2022-01-17-11-36-53'; - - $CFG_GLPI["is_contact_autoupdate"] = 0; - $inventory = new \Glpi\Inventory\Inventory($json); - $CFG_GLPI["is_contact_autoupdate"] = 1; //reset to default - - if ($inventory->inError()) { - foreach ($inventory->getErrors() as $error) { - var_dump($error); - } - } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); - - //check inventory metadata - $metadata = $inventory->getMetadata(); - $this->array($metadata)->hasSize(7) - ->string['deviceid']->isIdenticalTo('glpixps-2022-01-17-11-36-53') - ->string['version']->isIdenticalTo('GLPI-Agent_v1') - ->string['itemtype']->isIdenticalTo('Computer') - ->string['action']->isIdenticalTo('inventory') - ->variable['port']->isIdenticalTo(null) - ->string['tag']->isIdenticalTo('000005'); - $this->array($metadata['provider'])->hasSize(10); - - //check old agent has been dropped - $agent = new \Agent(); - $this->boolean($agent->getFromDB($old_agents_id))->isFalse('Old Agent still exists!'); - } - - public function testTagFromXML() - { - //run an inventory - $xml = " - - - - glpixps - 25C1BB60-5BCB-11D9-B18F-5404A6A534C4 - - - 640HP72 - 000 - - - TAG - 000005 - - FusionInventory-Inventory_v2.4.1-2.fc28 - - glpixps.teclib.infra-2018-10-03-08-42-36 - INVENTORY - "; - - $converter = new \Glpi\Inventory\Converter(); - $data = $converter->convert($xml); - $json = json_decode($data); - - $inventory = new \Glpi\Inventory\Inventory($json); - - if ($inventory->inError()) { - foreach ($inventory->getErrors() as $error) { - var_dump($error); - } - } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); - - //check inventory metadata - $metadata = $inventory->getMetadata(); - $this->array($metadata)->hasSize(6) - ->string['itemtype']->isIdenticalTo('Computer') - ->string['action']->isIdenticalTo('inventory') - ->variable['port']->isIdenticalTo(null) - ->string['tag']->isIdenticalTo('000005'); - - global $DB; - //check created agent - $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); - $agents = $DB->request(['FROM' => \Agent::getTable()]); - $this->integer(count($agents))->isIdenticalTo(1); - $agent = $agents->current(); - $this->array($agent) - ->string['itemtype']->isIdenticalTo('Computer') - ->string['tag']->isIdenticalTo('000005') - ->integer['agenttypes_id']->isIdenticalTo($agenttype['id']); - } - - public function testStaleActions() - { - //run an inventory - $json = json_decode(file_get_contents(self::INV_FIXTURES . 'computer_1.json')); - $inventory = new \Glpi\Inventory\Inventory($json); - - if ($inventory->inError()) { - foreach ($inventory->getErrors() as $error) { - var_dump($error); - } - } - $this->boolean($inventory->inError())->isFalse(); - $this->array($inventory->getErrors())->isEmpty(); - - //check inventory metadata - $metadata = $inventory->getMetadata(); - $this->array($metadata)->hasSize(7) - ->string['deviceid']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['version']->isIdenticalTo('FusionInventory-Agent_v2.5.2-1.fc31') - ->string['itemtype']->isIdenticalTo('Computer') - ->string['action']->isIdenticalTo('inventory') - ->variable['port']->isIdenticalTo(null) - ->string['tag']->isIdenticalTo('000005'); - $this->array($metadata['provider'])->hasSize(10); - - global $DB; - //check created agent - $agenttype = $DB->request(['FROM' => \AgentType::getTable(), 'WHERE' => ['name' => 'Core']])->current(); - $agents = $DB->request(['FROM' => \Agent::getTable()]); - $this->integer(count($agents))->isIdenticalTo(1); - $agent = $agents->current(); - $this->array($agent) - ->string['deviceid']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['name']->isIdenticalTo('glpixps-2018-07-09-09-07-13') - ->string['version']->isIdenticalTo('2.5.2-1.fc31') - ->string['itemtype']->isIdenticalTo('Computer') - ->string['tag']->isIdenticalTo('000005') - ->integer['agenttypes_id']->isIdenticalTo($agenttype['id']); - $old_agents_id = $agent['id']; - - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->getFromDB($agent['id'])) - ->isTrue(); - - $item = $this->testedInstance->getLinkedItem(); - $this->object($item)->isInstanceOf('Computer'); - - //check default status - $this->integer($item->fields['states_id'])->isIdenticalTo(0); - - //create new status - $state = new \State(); - $states_id = $state->add(['name' => 'Stale']); - $this->integer($states_id)->isGreaterThan(0); - - //set last agent contact far ago - $DB->update( - \Agent::getTable(), - ['last_contact' => date('Y-m-d H:i:s', strtotime('-1 year'))], - ['id' => $agent['id']] - ); - - //define sale agents actions - \Config::setConfigurationValues( - 'inventory', - [ - 'stale_agents_delay' => 1, - 'stale_agents_action' => exportArrayToDB([ - \Glpi\Inventory\Conf::STALE_AGENT_ACTION_STATUS, - \Glpi\Inventory\Conf::STALE_AGENT_ACTION_TRASHBIN - ]), - 'stale_agents_status' => $states_id - ] - ); - - //run crontask - $task = new \CronTask(); - $this->integer(\Agent::cronCleanoldagents($task))->isIdenticalTo(1); - - //check item has been updated - $this->boolean($item->getFromDB($item->fields['id']))->isTrue(); - $this->integer($item->fields['is_deleted'])->isIdenticalTo(1); - $this->integer($item->fields['states_id'])->isIdenticalTo($states_id); - } -} diff --git a/tests/functional/CleanSoftwareCron.php b/tests/functional/CleanSoftwareCron.php deleted file mode 100644 index 8f0f2f38872..00000000000 --- a/tests/functional/CleanSoftwareCron.php +++ /dev/null @@ -1,133 +0,0 @@ -. - * - * --------------------------------------------------------------------- - */ - -namespace tests\units; - -use DbTestCase; - -class CleanSoftwareCron extends DbTestCase -{ - public function testRun() - { - global $DB; - - $this->login(); - - $software = new \Software(); - $software_version = new \SoftwareVersion(); - - // Delete all existing software and versions - $always_true = [ - new \QueryExpression('1 = 1') - ]; - $this->boolean($software->deleteByCriteria($always_true, 1))->isTrue(); - $this->boolean($software_version->deleteByCriteria($always_true, 1))->isTrue(); - - // verify all deleted - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \Software::getTable() - ])->current()['cpt'])->isIdenticalTo(0); - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \SoftwareVersion::getTable() - ])->current()['cpt'])->isIdenticalTo(0); - - // Create 100 software with 10 versions each - $entities_id = getItemByTypeName('Entity', '_test_root_entity', true); - for ($i = 0; $i < 100; $i++) { - $software->add([ - 'name' => "Software $i", - 'entities_id' => $entities_id, - ]); - $softwareId = $software->getID(); - for ($j = 0; $j < 10; $j++) { - $software_version->add([ - 'name' => "Version $j", - 'softwares_id' => $softwareId, - ]); - } - } - - // verify all created - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \Software::getTable() - ])->current()['cpt'])->isIdenticalTo(100); - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \SoftwareVersion::getTable() - ])->current()['cpt'])->isIdenticalTo(1000); - - // Run cron - \CleanSoftwareCron::run(5); - // Verify only 5 versions were deleted and no software - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \Software::getTable() - ])->current()['cpt'])->isIdenticalTo(100); - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \SoftwareVersion::getTable() - ])->current()['cpt'])->isIdenticalTo(995); - - // Run cron again - \CleanSoftwareCron::run(990); - // Verify only 990 versions were deleted and no software - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \Software::getTable() - ])->current()['cpt'])->isIdenticalTo(100); - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \SoftwareVersion::getTable() - ])->current()['cpt'])->isIdenticalTo(5); - - // Run cron again - \CleanSoftwareCron::run(50); - // All versions should be deleted now and 45 software should be deleted as well - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \Software::getTable(), - 'WHERE' => [ - 'is_deleted' => 0 // cleanup only trashes software, not purges them - ] - ])->current()['cpt'])->isIdenticalTo(55); - $this->integer((int) $DB->request([ - 'COUNT' => 'cpt', - 'FROM' => \SoftwareVersion::getTable() - ])->current()['cpt'])->isIdenticalTo(0); - } -} diff --git a/tests/functional/CommonDropdown.php b/tests/functional/CommonDropdown.php deleted file mode 100644 index 01c9346a006..00000000000 --- a/tests/functional/CommonDropdown.php +++ /dev/null @@ -1,213 +0,0 @@ -. - * - * --------------------------------------------------------------------- - */ - -namespace tests\units; - -use DbTestCase; - -/* Test for inc/commondropdown.class.php */ - -abstract class CommonDropdown extends DbTestCase -{ - /** - * Get object class name - * - */ - abstract protected function getObjectClass(); - - abstract protected function typenameProvider(); - - /** - * @dataprovider typenameProvider - */ - public function testGetTypeName($string, $expected) - { - $this->string($string)->isIdenticalTo($expected); - } - - public function testMaybeTranslated() - { - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->maybeTranslated())->isFalse(); - } - - public function testGetMenuContent() - { - $class = $this->getObjectClass(); - $this->boolean($class::getMenuContent())->isFalse(); - } - - public function testGetAdditionalFields() - { - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->getAdditionalFields())->isIdenticalTo([]); - } - - abstract protected function getTabs(); - - public function testDefineTabs() - { - $this - ->given($this->newTestedInstance) - ->then - ->array($this->testedInstance->defineTabs()) - ->isIdenticalTo($this->getTabs()); - } - - public function testPre_deleteItem() - { - $this - ->given($this->newTestedInstance) - ->then - ->boolean($this->testedInstance->pre_deleteItem())->isTrue(); - } - - public function testPrepareInputForAdd() - { - $this->newTestedInstance; - - $input = []; - $this->array($this->testedInstance->prepareInputForAdd($input))->isIdenticalTo($input); - - $input = ['name' => 'Any name', 'comment' => 'Any comment']; - $this->array($this->testedInstance->prepareInputForAdd($input))->isIdenticalTo($input); - - $loc = getItemByTypeName('Location', '_location01'); - $input['locations_id'] = $loc->getID(); - $this->array($this->testedInstance->prepareInputForAdd($input)) - ->isIdenticalTo($input + ['entities_id' => $loc->fields['entities_id']]); - } - - public function testPrepareInputForUpdate() - { - $this->newTestedInstance; - - $input = []; - $this->array($this->testedInstance->prepareInputForUpdate($input))->isIdenticalTo($input); - - $input = ['name' => 'Any name', 'comment' => 'Any comment']; - $this->array($this->testedInstance->prepareInputForUpdate($input))->isIdenticalTo($input); - - $loc = getItemByTypeName('Location', '_location01'); - $input['locations_id'] = $loc->getID(); - //to make sure existing entities_id will not be changed on update - $input['entities_id'] = $loc->fields['entities_id'] + 1; - $this->array($this->testedInstance->prepareInputForUpdate($input)) - ->isIdenticalTo($input + ['entities_id' => $input['entities_id']]); - } - - /** - * Create new object in database - * - * @return void - */ - abstract protected function newInstance(); - - public function testGetDropdownName() - { - $this->newInstance(); - $instance = $this->testedInstance; - $ret = \Dropdown::getDropdownName($instance::getTable(), $this->testedInstance->getID()); - $this->string($ret)->isIdenticalTo($this->testedInstance->getName()); - } - - public function testAddUpdate() - { - $this->newTestedInstance(); - - $this->integer( - (int)$this->testedInstance->add([]) - )->isGreaterThan(0); - $this->boolean( - $this->testedInstance->getFromDB($this->testedInstance->getID()) - )->isTrue(); - - $keys = ['name', 'comment', 'date_mod', 'date_creation']; - $this->array($this->testedInstance->fields) - ->hasKeys($keys) - ->string['date_mod']->isNotEqualTo('') - ->string['date_creation']->isNotEqualTo(''); - - $this->integer( - (int)$this->testedInstance->add(['name' => 'Tested name']) - )->isGreaterThan(0); - $this->boolean( - $this->testedInstance->getFromDB($this->testedInstance->getID()) - )->isTrue(); - - $this->array($this->testedInstance->fields) - ->hasKeys($keys) - ->string['name']->isIdenticalTo('Tested name') - ->string['date_mod']->isNotEqualTo('') - ->string['date_creation']->isNotEqualTo(''); - - $this->integer( - (int)$this->testedInstance->add([ - 'name' => 'Another name', - 'comment' => 'A comment on an object' - ]) - )->isGreaterThan(0); - $this->boolean( - $this->testedInstance->getFromDB($this->testedInstance->getID()) - )->isTrue(); - - $this->array($this->testedInstance->fields) - ->hasKeys($keys) - ->string['name']->isIdenticalTo('Another name') - ->string['comment']->isIdenticalTo('A comment on an object') - ->string['date_mod']->isNotEqualTo('') - ->string['date_creation']->isNotEqualTo(''); - - $this->boolean( - $this->testedInstance->update([ - 'id' => $this->testedInstance->getID(), - 'name' => 'Changed name' - ]) - )->isTrue(); - $this->boolean( - $this->testedInstance->getFromDB($this->testedInstance->getID()) - )->isTrue(); - $this->string($this->testedInstance->fields['name'])->isIdenticalTo('Changed name'); - - //cannot update if id is missing - $this->boolean( - $this->testedInstance->update(['name' => 'Will not change']) - )->isFalse(); - } -} diff --git a/tests/functional/PassiveDCEquipment.php b/tests/functional/PassiveDCEquipment.php deleted file mode 100644 index 0e33af3f9a3..00000000000 --- a/tests/functional/PassiveDCEquipment.php +++ /dev/null @@ -1,142 +0,0 @@ -. - * - * --------------------------------------------------------------------- - */ - -namespace tests\units; - -use DbTestCase; - -/* Test for inc/passiveDCEquipment.class.php */ - -class PassiveDCEquipment extends DbTestCase -{ - public function testAdd() - { - $obj = new \PassiveDCEquipment(); - - // Add - $id = $obj->add([ - 'name' => __METHOD__, - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ]); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - - // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); - $this->string($obj->getField('name'))->isidenticalTo(__METHOD__); - - // fields property - $this->array($obj->fields) - ->integer['id']->isEqualTo($id) - ->string['name']->isidenticalTo(__METHOD__); - } - - public function testDelete() - { - $obj = new \PassiveDCEquipment(); - $this->boolean($obj->maybeDeleted())->isTrue(); - - // Add - $id = $obj->add([ - 'name' => __METHOD__, - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ]); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - $this->variable($obj->isDeleted())->isEqualTo(0); - - // Delete - $this->boolean($obj->delete(['id' => $id], 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(1); - $this->variable($obj->isDeleted())->isEqualTo(1); - - // Restore - $this->boolean($obj->restore(['id' => $id], 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - $this->variable($obj->isDeleted())->isEqualTo(0); - - // Purge - $this->boolean($obj->delete(['id' => $id], 1))->isTrue(); - $this->boolean($obj->getFromDB($id))->isFalse(); - } - - - public function testDeleteByCriteria() - { - $obj = new \PassiveDCEquipment(); - $this->boolean($obj->maybeDeleted())->isTrue(); - - // Add - $id = $obj->add([ - 'name' => __METHOD__, - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ]); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - ; - $this->variable($obj->isDeleted())->isEqualTo(0); - $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); - - // DeleteByCriteria without history - $this->boolean($obj->deleteByCriteria(['name' => __METHOD__], 0, 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(1); - $this->variable($obj->isDeleted())->isEqualTo(1); - - $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); - $this->integer($nb_after)->isidenticalTo($nb_after); - - // Restore - $this->boolean($obj->restore(['id' => $id], 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - $this->variable($obj->isDeleted())->isEqualTo(0); - - $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); - - // DeleteByCriteria with history - $this->boolean($obj->deleteByCriteria(['name' => __METHOD__], 0, 1))->isTrue; - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(1); - $this->variable($obj->isDeleted())->isEqualTo(1); - - $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'PassiveDCEquipment', 'items_id' => $id]); - $this->integer($nb_after)->isidenticalTo($nb_before + 1); - } -} diff --git a/tests/functional/Printer.php b/tests/functional/Printer.php deleted file mode 100644 index 2b214dbbec3..00000000000 --- a/tests/functional/Printer.php +++ /dev/null @@ -1,170 +0,0 @@ -. - * - * --------------------------------------------------------------------- - */ - -namespace tests\units; - -use DbTestCase; - -/* Test for inc/printer.class.php */ - -class Printer extends DbTestCase -{ - public function testAdd() - { - $obj = new \Printer(); - - // Add - $id = $obj->add([ - 'name' => __METHOD__, - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ]); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - - // getField methods - $this->variable($obj->getField('id'))->isEqualTo($id); - $this->string($obj->getField('name'))->isidenticalTo(__METHOD__); - - // fields property - $this->array($obj->fields) - ->integer['id']->isEqualTo($id) - ->string['name']->isidenticalTo(__METHOD__); - } - - public function testDelete() - { - $obj = new \Printer(); - $this->boolean($obj->maybeDeleted())->isTrue(); - - // Add - $id = $obj->add([ - 'name' => __METHOD__, - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ]); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - $this->variable($obj->isDeleted())->isEqualTo(0); - - // Delete - $this->boolean($obj->delete(['id' => $id], 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(1); - $this->variable($obj->isDeleted())->isEqualTo(1); - - // Restore - $this->boolean($obj->restore(['id' => $id], 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - $this->variable($obj->isDeleted())->isEqualTo(0); - - // Purge - $this->boolean($obj->delete(['id' => $id], 1))->isTrue(); - $this->boolean($obj->getFromDB($id))->isFalse(); - } - - public function testVisibility() - { - - $this->login(); - - $p = new \Printer(); - - // Visibility from root + tree - $this->setEntity('_test_root_entity', true); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_all', true), READ))->isTrue(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent0', true), READ))->isTrue(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent1', true), READ))->isTrue(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent2', true), READ))->isTrue(); - - // Visibility from root only - $this->setEntity('_test_root_entity', false); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_all', true), READ))->isTrue(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent0', true), READ))->isTrue(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent1', true), READ))->isFalse(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent2', true), READ))->isFalse(); - - // Visibility from child - $this->setEntity('_test_child_1', false); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_all', true), READ))->isTrue(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent0', true), READ))->isFalse(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent1', true), READ))->isTrue(); - $this->boolean($p->can(getItemByTypeName('Printer', '_test_printer_ent2', true), READ))->isFalse(); - } - - public function testDeleteByCriteria() - { - $obj = new \Printer(); - $this->boolean($obj->maybeDeleted())->isTrue(); - - // Add - $id = $obj->add([ - 'name' => __METHOD__, - 'entities_id' => getItemByTypeName('Entity', '_test_root_entity', true) - ]); - $this->integer((int)$id)->isGreaterThan(0); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - ; - $this->variable($obj->isDeleted())->isEqualTo(0); - $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); - - // DeleteByCriteria without history - $this->boolean($obj->deleteByCriteria(['name' => __METHOD__], 0, 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(1); - $this->variable($obj->isDeleted())->isEqualTo(1); - - $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); - $this->integer($nb_after)->isidenticalTo($nb_after); - - // Restore - $this->boolean($obj->restore(['id' => $id], 0))->isTrue(); - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(0); - $this->variable($obj->isDeleted())->isEqualTo(0); - - $nb_before = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); - - // DeleteByCriteria with history - $this->boolean($obj->deleteByCriteria(['name' => __METHOD__], 0, 1))->isTrue; - $this->boolean($obj->getFromDB($id))->isTrue(); - $this->variable($obj->getField('is_deleted'))->isEqualTo(1); - $this->variable($obj->isDeleted())->isEqualTo(1); - - $nb_after = (int)countElementsInTable('glpi_logs', ['itemtype' => 'Printer', 'items_id' => $id]); - $this->integer($nb_after)->isidenticalTo($nb_before + 1); - } -}